editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod commit_tooltip;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod jsx_tag_auto_close;
   32mod linked_editing_ranges;
   33mod lsp_ext;
   34mod mouse_context_menu;
   35pub mod movement;
   36mod persistence;
   37mod proposed_changes_editor;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45#[cfg(test)]
   46mod inline_completion_tests;
   47mod signature_help;
   48#[cfg(any(test, feature = "test-support"))]
   49pub mod test;
   50
   51pub(crate) use actions::*;
   52pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   53use aho_corasick::AhoCorasick;
   54use anyhow::{anyhow, Context as _, Result};
   55use blink_manager::BlinkManager;
   56use buffer_diff::DiffHunkStatus;
   57use client::{Collaborator, ParticipantIndex};
   58use clock::ReplicaId;
   59use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   60use convert_case::{Case, Casing};
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   65};
   66pub use editor_settings_controls::*;
   67use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use futures::{
   72    future::{self, Shared},
   73    FutureExt,
   74};
   75use fuzzy::StringMatchCandidate;
   76
   77use ::git::Restore;
   78use code_context_menus::{
   79    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   80    CompletionsMenu, ContextMenuOrigin,
   81};
   82use git::blame::GitBlame;
   83use gpui::{
   84    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   85    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   86    ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler,
   87    EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
   88    HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
   89    ParentElement, Pixels, Render, SharedString, Size, Stateful, Styled, StyledText, Subscription,
   90    Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   91    WeakEntity, WeakFocusHandle, Window,
   92};
   93use highlight_matching_bracket::refresh_matching_bracket_highlights;
   94use hover_popover::{hide_hover, HoverState};
   95use indent_guides::ActiveIndentGuidesState;
   96use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   97pub use inline_completion::Direction;
   98use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   99pub use items::MAX_TAB_TITLE_LEN;
  100use itertools::Itertools;
  101use language::{
  102    language_settings::{
  103        self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
  104    },
  105    point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
  106    Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, EditPredictionsMode,
  107    EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
  108    Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
  109};
  110use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  111use linked_editing_ranges::refresh_linked_ranges;
  112use mouse_context_menu::MouseContextMenu;
  113use persistence::DB;
  114pub use proposed_changes_editor::{
  115    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  116};
  117use smallvec::smallvec;
  118use std::iter::Peekable;
  119use task::{ResolvedTask, TaskTemplate, TaskVariables};
  120
  121use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  122pub use lsp::CompletionContext;
  123use lsp::{
  124    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  125    InsertTextFormat, LanguageServerId, LanguageServerName,
  126};
  127
  128use language::BufferSnapshot;
  129use movement::TextLayoutDetails;
  130pub use multi_buffer::{
  131    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  132    ToOffset, ToPoint,
  133};
  134use multi_buffer::{
  135    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  136    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  137};
  138use project::{
  139    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  140    project_settings::{GitGutterSetting, ProjectSettings},
  141    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  142    PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  143};
  144use rand::prelude::*;
  145use rpc::{proto::*, ErrorExt};
  146use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  147use selections_collection::{
  148    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  149};
  150use serde::{Deserialize, Serialize};
  151use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  152use smallvec::SmallVec;
  153use snippet::Snippet;
  154use std::{
  155    any::TypeId,
  156    borrow::Cow,
  157    cell::RefCell,
  158    cmp::{self, Ordering, Reverse},
  159    mem,
  160    num::NonZeroU32,
  161    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  162    path::{Path, PathBuf},
  163    rc::Rc,
  164    sync::Arc,
  165    time::{Duration, Instant},
  166};
  167pub use sum_tree::Bias;
  168use sum_tree::TreeMap;
  169use text::{BufferId, OffsetUtf16, Rope};
  170use theme::{
  171    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  172    ThemeColors, ThemeSettings,
  173};
  174use ui::{
  175    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  176    Tooltip,
  177};
  178use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  179use workspace::{
  180    item::{ItemHandle, PreviewTabsSettings},
  181    ItemId, RestoreOnStartupBehavior,
  182};
  183use workspace::{
  184    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  185    WorkspaceSettings,
  186};
  187use workspace::{
  188    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  189};
  190use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  191
  192use crate::hover_links::{find_url, find_url_from_range};
  193use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  194
  195pub const FILE_HEADER_HEIGHT: u32 = 2;
  196pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  197pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  198pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  199const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  200const MAX_LINE_LEN: usize = 1024;
  201const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  202const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  203pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  204#[doc(hidden)]
  205pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  206
  207pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  208pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  209pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  210
  211pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  212pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  213
  214const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  215    alt: true,
  216    shift: true,
  217    control: false,
  218    platform: false,
  219    function: false,
  220};
  221
  222#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  223pub enum InlayId {
  224    InlineCompletion(usize),
  225    Hint(usize),
  226}
  227
  228impl InlayId {
  229    fn id(&self) -> usize {
  230        match self {
  231            Self::InlineCompletion(id) => *id,
  232            Self::Hint(id) => *id,
  233        }
  234    }
  235}
  236
  237enum DocumentHighlightRead {}
  238enum DocumentHighlightWrite {}
  239enum InputComposition {}
  240enum SelectedTextHighlight {}
  241
  242#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  243pub enum Navigated {
  244    Yes,
  245    No,
  246}
  247
  248impl Navigated {
  249    pub fn from_bool(yes: bool) -> Navigated {
  250        if yes {
  251            Navigated::Yes
  252        } else {
  253            Navigated::No
  254        }
  255    }
  256}
  257
  258#[derive(Debug, Clone, PartialEq, Eq)]
  259enum DisplayDiffHunk {
  260    Folded {
  261        display_row: DisplayRow,
  262    },
  263    Unfolded {
  264        diff_base_byte_range: Range<usize>,
  265        display_row_range: Range<DisplayRow>,
  266        multi_buffer_range: Range<Anchor>,
  267        status: DiffHunkStatus,
  268    },
  269}
  270
  271pub fn init_settings(cx: &mut App) {
  272    EditorSettings::register(cx);
  273}
  274
  275pub fn init(cx: &mut App) {
  276    init_settings(cx);
  277
  278    workspace::register_project_item::<Editor>(cx);
  279    workspace::FollowableViewRegistry::register::<Editor>(cx);
  280    workspace::register_serializable_item::<Editor>(cx);
  281
  282    cx.observe_new(
  283        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  284            workspace.register_action(Editor::new_file);
  285            workspace.register_action(Editor::new_file_vertical);
  286            workspace.register_action(Editor::new_file_horizontal);
  287            workspace.register_action(Editor::cancel_language_server_work);
  288        },
  289    )
  290    .detach();
  291
  292    cx.on_action(move |_: &workspace::NewFile, cx| {
  293        let app_state = workspace::AppState::global(cx);
  294        if let Some(app_state) = app_state.upgrade() {
  295            workspace::open_new(
  296                Default::default(),
  297                app_state,
  298                cx,
  299                |workspace, window, cx| {
  300                    Editor::new_file(workspace, &Default::default(), window, cx)
  301                },
  302            )
  303            .detach();
  304        }
  305    });
  306    cx.on_action(move |_: &workspace::NewWindow, cx| {
  307        let app_state = workspace::AppState::global(cx);
  308        if let Some(app_state) = app_state.upgrade() {
  309            workspace::open_new(
  310                Default::default(),
  311                app_state,
  312                cx,
  313                |workspace, window, cx| {
  314                    cx.activate(true);
  315                    Editor::new_file(workspace, &Default::default(), window, cx)
  316                },
  317            )
  318            .detach();
  319        }
  320    });
  321}
  322
  323pub struct SearchWithinRange;
  324
  325trait InvalidationRegion {
  326    fn ranges(&self) -> &[Range<Anchor>];
  327}
  328
  329#[derive(Clone, Debug, PartialEq)]
  330pub enum SelectPhase {
  331    Begin {
  332        position: DisplayPoint,
  333        add: bool,
  334        click_count: usize,
  335    },
  336    BeginColumnar {
  337        position: DisplayPoint,
  338        reset: bool,
  339        goal_column: u32,
  340    },
  341    Extend {
  342        position: DisplayPoint,
  343        click_count: usize,
  344    },
  345    Update {
  346        position: DisplayPoint,
  347        goal_column: u32,
  348        scroll_delta: gpui::Point<f32>,
  349    },
  350    End,
  351}
  352
  353#[derive(Clone, Debug)]
  354pub enum SelectMode {
  355    Character,
  356    Word(Range<Anchor>),
  357    Line(Range<Anchor>),
  358    All,
  359}
  360
  361#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  362pub enum EditorMode {
  363    SingleLine { auto_width: bool },
  364    AutoHeight { max_lines: usize },
  365    Full,
  366}
  367
  368#[derive(Copy, Clone, Debug)]
  369pub enum SoftWrap {
  370    /// Prefer not to wrap at all.
  371    ///
  372    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  373    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  374    GitDiff,
  375    /// Prefer a single line generally, unless an overly long line is encountered.
  376    None,
  377    /// Soft wrap lines that exceed the editor width.
  378    EditorWidth,
  379    /// Soft wrap lines at the preferred line length.
  380    Column(u32),
  381    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  382    Bounded(u32),
  383}
  384
  385#[derive(Clone)]
  386pub struct EditorStyle {
  387    pub background: Hsla,
  388    pub local_player: PlayerColor,
  389    pub text: TextStyle,
  390    pub scrollbar_width: Pixels,
  391    pub syntax: Arc<SyntaxTheme>,
  392    pub status: StatusColors,
  393    pub inlay_hints_style: HighlightStyle,
  394    pub inline_completion_styles: InlineCompletionStyles,
  395    pub unnecessary_code_fade: f32,
  396}
  397
  398impl Default for EditorStyle {
  399    fn default() -> Self {
  400        Self {
  401            background: Hsla::default(),
  402            local_player: PlayerColor::default(),
  403            text: TextStyle::default(),
  404            scrollbar_width: Pixels::default(),
  405            syntax: Default::default(),
  406            // HACK: Status colors don't have a real default.
  407            // We should look into removing the status colors from the editor
  408            // style and retrieve them directly from the theme.
  409            status: StatusColors::dark(),
  410            inlay_hints_style: HighlightStyle::default(),
  411            inline_completion_styles: InlineCompletionStyles {
  412                insertion: HighlightStyle::default(),
  413                whitespace: HighlightStyle::default(),
  414            },
  415            unnecessary_code_fade: Default::default(),
  416        }
  417    }
  418}
  419
  420pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  421    let show_background = language_settings::language_settings(None, None, cx)
  422        .inlay_hints
  423        .show_background;
  424
  425    HighlightStyle {
  426        color: Some(cx.theme().status().hint),
  427        background_color: show_background.then(|| cx.theme().status().hint_background),
  428        ..HighlightStyle::default()
  429    }
  430}
  431
  432pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  433    InlineCompletionStyles {
  434        insertion: HighlightStyle {
  435            color: Some(cx.theme().status().predictive),
  436            ..HighlightStyle::default()
  437        },
  438        whitespace: HighlightStyle {
  439            background_color: Some(cx.theme().status().created_background),
  440            ..HighlightStyle::default()
  441        },
  442    }
  443}
  444
  445type CompletionId = usize;
  446
  447pub(crate) enum EditDisplayMode {
  448    TabAccept,
  449    DiffPopover,
  450    Inline,
  451}
  452
  453enum InlineCompletion {
  454    Edit {
  455        edits: Vec<(Range<Anchor>, String)>,
  456        edit_preview: Option<EditPreview>,
  457        display_mode: EditDisplayMode,
  458        snapshot: BufferSnapshot,
  459    },
  460    Move {
  461        target: Anchor,
  462        snapshot: BufferSnapshot,
  463    },
  464}
  465
  466struct InlineCompletionState {
  467    inlay_ids: Vec<InlayId>,
  468    completion: InlineCompletion,
  469    completion_id: Option<SharedString>,
  470    invalidation_range: Range<Anchor>,
  471}
  472
  473enum EditPredictionSettings {
  474    Disabled,
  475    Enabled {
  476        show_in_menu: bool,
  477        preview_requires_modifier: bool,
  478    },
  479}
  480
  481enum InlineCompletionHighlight {}
  482
  483#[derive(Debug, Clone)]
  484struct InlineDiagnostic {
  485    message: SharedString,
  486    group_id: usize,
  487    is_primary: bool,
  488    start: Point,
  489    severity: DiagnosticSeverity,
  490}
  491
  492pub enum MenuInlineCompletionsPolicy {
  493    Never,
  494    ByProvider,
  495}
  496
  497pub enum EditPredictionPreview {
  498    /// Modifier is not pressed
  499    Inactive { released_too_fast: bool },
  500    /// Modifier pressed
  501    Active {
  502        since: Instant,
  503        previous_scroll_position: Option<ScrollAnchor>,
  504    },
  505}
  506
  507impl EditPredictionPreview {
  508    pub fn released_too_fast(&self) -> bool {
  509        match self {
  510            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  511            EditPredictionPreview::Active { .. } => false,
  512        }
  513    }
  514
  515    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  516        if let EditPredictionPreview::Active {
  517            previous_scroll_position,
  518            ..
  519        } = self
  520        {
  521            *previous_scroll_position = scroll_position;
  522        }
  523    }
  524}
  525
  526#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  527struct EditorActionId(usize);
  528
  529impl EditorActionId {
  530    pub fn post_inc(&mut self) -> Self {
  531        let answer = self.0;
  532
  533        *self = Self(answer + 1);
  534
  535        Self(answer)
  536    }
  537}
  538
  539// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  540// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  541
  542type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  543type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  544
  545#[derive(Default)]
  546struct ScrollbarMarkerState {
  547    scrollbar_size: Size<Pixels>,
  548    dirty: bool,
  549    markers: Arc<[PaintQuad]>,
  550    pending_refresh: Option<Task<Result<()>>>,
  551}
  552
  553impl ScrollbarMarkerState {
  554    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  555        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  556    }
  557}
  558
  559#[derive(Clone, Debug)]
  560struct RunnableTasks {
  561    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  562    offset: multi_buffer::Anchor,
  563    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  564    column: u32,
  565    // Values of all named captures, including those starting with '_'
  566    extra_variables: HashMap<String, String>,
  567    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  568    context_range: Range<BufferOffset>,
  569}
  570
  571impl RunnableTasks {
  572    fn resolve<'a>(
  573        &'a self,
  574        cx: &'a task::TaskContext,
  575    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  576        self.templates.iter().filter_map(|(kind, template)| {
  577            template
  578                .resolve_task(&kind.to_id_base(), cx)
  579                .map(|task| (kind.clone(), task))
  580        })
  581    }
  582}
  583
  584#[derive(Clone)]
  585struct ResolvedTasks {
  586    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  587    position: Anchor,
  588}
  589#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  590struct BufferOffset(usize);
  591
  592// Addons allow storing per-editor state in other crates (e.g. Vim)
  593pub trait Addon: 'static {
  594    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  595
  596    fn render_buffer_header_controls(
  597        &self,
  598        _: &ExcerptInfo,
  599        _: &Window,
  600        _: &App,
  601    ) -> Option<AnyElement> {
  602        None
  603    }
  604
  605    fn to_any(&self) -> &dyn std::any::Any;
  606}
  607
  608#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  609pub enum IsVimMode {
  610    Yes,
  611    No,
  612}
  613
  614/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  615///
  616/// See the [module level documentation](self) for more information.
  617pub struct Editor {
  618    focus_handle: FocusHandle,
  619    last_focused_descendant: Option<WeakFocusHandle>,
  620    /// The text buffer being edited
  621    buffer: Entity<MultiBuffer>,
  622    /// Map of how text in the buffer should be displayed.
  623    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  624    pub display_map: Entity<DisplayMap>,
  625    pub selections: SelectionsCollection,
  626    pub scroll_manager: ScrollManager,
  627    /// When inline assist editors are linked, they all render cursors because
  628    /// typing enters text into each of them, even the ones that aren't focused.
  629    pub(crate) show_cursor_when_unfocused: bool,
  630    columnar_selection_tail: Option<Anchor>,
  631    add_selections_state: Option<AddSelectionsState>,
  632    select_next_state: Option<SelectNextState>,
  633    select_prev_state: Option<SelectNextState>,
  634    selection_history: SelectionHistory,
  635    autoclose_regions: Vec<AutocloseRegion>,
  636    snippet_stack: InvalidationStack<SnippetState>,
  637    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  638    ime_transaction: Option<TransactionId>,
  639    active_diagnostics: Option<ActiveDiagnosticGroup>,
  640    show_inline_diagnostics: bool,
  641    inline_diagnostics_update: Task<()>,
  642    inline_diagnostics_enabled: bool,
  643    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  644    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  645
  646    // TODO: make this a access method
  647    pub project: Option<Entity<Project>>,
  648    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  649    completion_provider: Option<Box<dyn CompletionProvider>>,
  650    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  651    blink_manager: Entity<BlinkManager>,
  652    show_cursor_names: bool,
  653    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  654    pub show_local_selections: bool,
  655    mode: EditorMode,
  656    show_breadcrumbs: bool,
  657    show_gutter: bool,
  658    show_scrollbars: bool,
  659    show_line_numbers: Option<bool>,
  660    use_relative_line_numbers: Option<bool>,
  661    show_git_diff_gutter: Option<bool>,
  662    show_code_actions: Option<bool>,
  663    show_runnables: Option<bool>,
  664    show_wrap_guides: Option<bool>,
  665    show_indent_guides: Option<bool>,
  666    placeholder_text: Option<Arc<str>>,
  667    highlight_order: usize,
  668    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  669    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  670    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  671    scrollbar_marker_state: ScrollbarMarkerState,
  672    active_indent_guides_state: ActiveIndentGuidesState,
  673    nav_history: Option<ItemNavHistory>,
  674    context_menu: RefCell<Option<CodeContextMenu>>,
  675    mouse_context_menu: Option<MouseContextMenu>,
  676    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  677    signature_help_state: SignatureHelpState,
  678    auto_signature_help: Option<bool>,
  679    find_all_references_task_sources: Vec<Anchor>,
  680    next_completion_id: CompletionId,
  681    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  682    code_actions_task: Option<Task<Result<()>>>,
  683    selection_highlight_task: Option<Task<()>>,
  684    document_highlights_task: Option<Task<()>>,
  685    linked_editing_range_task: Option<Task<Option<()>>>,
  686    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  687    pending_rename: Option<RenameState>,
  688    searchable: bool,
  689    cursor_shape: CursorShape,
  690    current_line_highlight: Option<CurrentLineHighlight>,
  691    collapse_matches: bool,
  692    autoindent_mode: Option<AutoindentMode>,
  693    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  694    input_enabled: bool,
  695    use_modal_editing: bool,
  696    read_only: bool,
  697    leader_peer_id: Option<PeerId>,
  698    remote_id: Option<ViewId>,
  699    hover_state: HoverState,
  700    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  701    gutter_hovered: bool,
  702    hovered_link_state: Option<HoveredLinkState>,
  703    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  704    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  705    active_inline_completion: Option<InlineCompletionState>,
  706    /// Used to prevent flickering as the user types while the menu is open
  707    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  708    edit_prediction_settings: EditPredictionSettings,
  709    inline_completions_hidden_for_vim_mode: bool,
  710    show_inline_completions_override: Option<bool>,
  711    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  712    edit_prediction_preview: EditPredictionPreview,
  713    edit_prediction_indent_conflict: bool,
  714    edit_prediction_requires_modifier_in_indent_conflict: bool,
  715    inlay_hint_cache: InlayHintCache,
  716    next_inlay_id: usize,
  717    _subscriptions: Vec<Subscription>,
  718    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  719    gutter_dimensions: GutterDimensions,
  720    style: Option<EditorStyle>,
  721    text_style_refinement: Option<TextStyleRefinement>,
  722    next_editor_action_id: EditorActionId,
  723    editor_actions:
  724        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  725    use_autoclose: bool,
  726    use_auto_surround: bool,
  727    auto_replace_emoji_shortcode: bool,
  728    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  729    show_git_blame_gutter: bool,
  730    show_git_blame_inline: bool,
  731    show_git_blame_inline_delay_task: Option<Task<()>>,
  732    git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
  733    git_blame_inline_enabled: bool,
  734    serialize_dirty_buffers: bool,
  735    show_selection_menu: Option<bool>,
  736    blame: Option<Entity<GitBlame>>,
  737    blame_subscription: Option<Subscription>,
  738    custom_context_menu: Option<
  739        Box<
  740            dyn 'static
  741                + Fn(
  742                    &mut Self,
  743                    DisplayPoint,
  744                    &mut Window,
  745                    &mut Context<Self>,
  746                ) -> Option<Entity<ui::ContextMenu>>,
  747        >,
  748    >,
  749    last_bounds: Option<Bounds<Pixels>>,
  750    last_position_map: Option<Rc<PositionMap>>,
  751    expect_bounds_change: Option<Bounds<Pixels>>,
  752    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  753    tasks_update_task: Option<Task<()>>,
  754    in_project_search: bool,
  755    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  756    breadcrumb_header: Option<String>,
  757    focused_block: Option<FocusedBlock>,
  758    next_scroll_position: NextScrollCursorCenterTopBottom,
  759    addons: HashMap<TypeId, Box<dyn Addon>>,
  760    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  761    load_diff_task: Option<Shared<Task<()>>>,
  762    selection_mark_mode: bool,
  763    toggle_fold_multiple_buffers: Task<()>,
  764    _scroll_cursor_center_top_bottom_task: Task<()>,
  765    serialize_selections: Task<()>,
  766}
  767
  768#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  769enum NextScrollCursorCenterTopBottom {
  770    #[default]
  771    Center,
  772    Top,
  773    Bottom,
  774}
  775
  776impl NextScrollCursorCenterTopBottom {
  777    fn next(&self) -> Self {
  778        match self {
  779            Self::Center => Self::Top,
  780            Self::Top => Self::Bottom,
  781            Self::Bottom => Self::Center,
  782        }
  783    }
  784}
  785
  786#[derive(Clone)]
  787pub struct EditorSnapshot {
  788    pub mode: EditorMode,
  789    show_gutter: bool,
  790    show_line_numbers: Option<bool>,
  791    show_git_diff_gutter: Option<bool>,
  792    show_code_actions: Option<bool>,
  793    show_runnables: Option<bool>,
  794    git_blame_gutter_max_author_length: Option<usize>,
  795    pub display_snapshot: DisplaySnapshot,
  796    pub placeholder_text: Option<Arc<str>>,
  797    is_focused: bool,
  798    scroll_anchor: ScrollAnchor,
  799    ongoing_scroll: OngoingScroll,
  800    current_line_highlight: CurrentLineHighlight,
  801    gutter_hovered: bool,
  802}
  803
  804const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  805
  806#[derive(Default, Debug, Clone, Copy)]
  807pub struct GutterDimensions {
  808    pub left_padding: Pixels,
  809    pub right_padding: Pixels,
  810    pub width: Pixels,
  811    pub margin: Pixels,
  812    pub git_blame_entries_width: Option<Pixels>,
  813}
  814
  815impl GutterDimensions {
  816    /// The full width of the space taken up by the gutter.
  817    pub fn full_width(&self) -> Pixels {
  818        self.margin + self.width
  819    }
  820
  821    /// The width of the space reserved for the fold indicators,
  822    /// use alongside 'justify_end' and `gutter_width` to
  823    /// right align content with the line numbers
  824    pub fn fold_area_width(&self) -> Pixels {
  825        self.margin + self.right_padding
  826    }
  827}
  828
  829#[derive(Debug)]
  830pub struct RemoteSelection {
  831    pub replica_id: ReplicaId,
  832    pub selection: Selection<Anchor>,
  833    pub cursor_shape: CursorShape,
  834    pub peer_id: PeerId,
  835    pub line_mode: bool,
  836    pub participant_index: Option<ParticipantIndex>,
  837    pub user_name: Option<SharedString>,
  838}
  839
  840#[derive(Clone, Debug)]
  841struct SelectionHistoryEntry {
  842    selections: Arc<[Selection<Anchor>]>,
  843    select_next_state: Option<SelectNextState>,
  844    select_prev_state: Option<SelectNextState>,
  845    add_selections_state: Option<AddSelectionsState>,
  846}
  847
  848enum SelectionHistoryMode {
  849    Normal,
  850    Undoing,
  851    Redoing,
  852}
  853
  854#[derive(Clone, PartialEq, Eq, Hash)]
  855struct HoveredCursor {
  856    replica_id: u16,
  857    selection_id: usize,
  858}
  859
  860impl Default for SelectionHistoryMode {
  861    fn default() -> Self {
  862        Self::Normal
  863    }
  864}
  865
  866#[derive(Default)]
  867struct SelectionHistory {
  868    #[allow(clippy::type_complexity)]
  869    selections_by_transaction:
  870        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  871    mode: SelectionHistoryMode,
  872    undo_stack: VecDeque<SelectionHistoryEntry>,
  873    redo_stack: VecDeque<SelectionHistoryEntry>,
  874}
  875
  876impl SelectionHistory {
  877    fn insert_transaction(
  878        &mut self,
  879        transaction_id: TransactionId,
  880        selections: Arc<[Selection<Anchor>]>,
  881    ) {
  882        self.selections_by_transaction
  883            .insert(transaction_id, (selections, None));
  884    }
  885
  886    #[allow(clippy::type_complexity)]
  887    fn transaction(
  888        &self,
  889        transaction_id: TransactionId,
  890    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  891        self.selections_by_transaction.get(&transaction_id)
  892    }
  893
  894    #[allow(clippy::type_complexity)]
  895    fn transaction_mut(
  896        &mut self,
  897        transaction_id: TransactionId,
  898    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  899        self.selections_by_transaction.get_mut(&transaction_id)
  900    }
  901
  902    fn push(&mut self, entry: SelectionHistoryEntry) {
  903        if !entry.selections.is_empty() {
  904            match self.mode {
  905                SelectionHistoryMode::Normal => {
  906                    self.push_undo(entry);
  907                    self.redo_stack.clear();
  908                }
  909                SelectionHistoryMode::Undoing => self.push_redo(entry),
  910                SelectionHistoryMode::Redoing => self.push_undo(entry),
  911            }
  912        }
  913    }
  914
  915    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  916        if self
  917            .undo_stack
  918            .back()
  919            .map_or(true, |e| e.selections != entry.selections)
  920        {
  921            self.undo_stack.push_back(entry);
  922            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  923                self.undo_stack.pop_front();
  924            }
  925        }
  926    }
  927
  928    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  929        if self
  930            .redo_stack
  931            .back()
  932            .map_or(true, |e| e.selections != entry.selections)
  933        {
  934            self.redo_stack.push_back(entry);
  935            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  936                self.redo_stack.pop_front();
  937            }
  938        }
  939    }
  940}
  941
  942struct RowHighlight {
  943    index: usize,
  944    range: Range<Anchor>,
  945    color: Hsla,
  946    should_autoscroll: bool,
  947}
  948
  949#[derive(Clone, Debug)]
  950struct AddSelectionsState {
  951    above: bool,
  952    stack: Vec<usize>,
  953}
  954
  955#[derive(Clone)]
  956struct SelectNextState {
  957    query: AhoCorasick,
  958    wordwise: bool,
  959    done: bool,
  960}
  961
  962impl std::fmt::Debug for SelectNextState {
  963    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  964        f.debug_struct(std::any::type_name::<Self>())
  965            .field("wordwise", &self.wordwise)
  966            .field("done", &self.done)
  967            .finish()
  968    }
  969}
  970
  971#[derive(Debug)]
  972struct AutocloseRegion {
  973    selection_id: usize,
  974    range: Range<Anchor>,
  975    pair: BracketPair,
  976}
  977
  978#[derive(Debug)]
  979struct SnippetState {
  980    ranges: Vec<Vec<Range<Anchor>>>,
  981    active_index: usize,
  982    choices: Vec<Option<Vec<String>>>,
  983}
  984
  985#[doc(hidden)]
  986pub struct RenameState {
  987    pub range: Range<Anchor>,
  988    pub old_name: Arc<str>,
  989    pub editor: Entity<Editor>,
  990    block_id: CustomBlockId,
  991}
  992
  993struct InvalidationStack<T>(Vec<T>);
  994
  995struct RegisteredInlineCompletionProvider {
  996    provider: Arc<dyn InlineCompletionProviderHandle>,
  997    _subscription: Subscription,
  998}
  999
 1000#[derive(Debug, PartialEq, Eq)]
 1001struct ActiveDiagnosticGroup {
 1002    primary_range: Range<Anchor>,
 1003    primary_message: String,
 1004    group_id: usize,
 1005    blocks: HashMap<CustomBlockId, Diagnostic>,
 1006    is_valid: bool,
 1007}
 1008
 1009#[derive(Serialize, Deserialize, Clone, Debug)]
 1010pub struct ClipboardSelection {
 1011    /// The number of bytes in this selection.
 1012    pub len: usize,
 1013    /// Whether this was a full-line selection.
 1014    pub is_entire_line: bool,
 1015    /// The indentation of the first line when this content was originally copied.
 1016    pub first_line_indent: u32,
 1017}
 1018
 1019#[derive(Debug)]
 1020pub(crate) struct NavigationData {
 1021    cursor_anchor: Anchor,
 1022    cursor_position: Point,
 1023    scroll_anchor: ScrollAnchor,
 1024    scroll_top_row: u32,
 1025}
 1026
 1027#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1028pub enum GotoDefinitionKind {
 1029    Symbol,
 1030    Declaration,
 1031    Type,
 1032    Implementation,
 1033}
 1034
 1035#[derive(Debug, Clone)]
 1036enum InlayHintRefreshReason {
 1037    ModifiersChanged(bool),
 1038    Toggle(bool),
 1039    SettingsChange(InlayHintSettings),
 1040    NewLinesShown,
 1041    BufferEdited(HashSet<Arc<Language>>),
 1042    RefreshRequested,
 1043    ExcerptsRemoved(Vec<ExcerptId>),
 1044}
 1045
 1046impl InlayHintRefreshReason {
 1047    fn description(&self) -> &'static str {
 1048        match self {
 1049            Self::ModifiersChanged(_) => "modifiers changed",
 1050            Self::Toggle(_) => "toggle",
 1051            Self::SettingsChange(_) => "settings change",
 1052            Self::NewLinesShown => "new lines shown",
 1053            Self::BufferEdited(_) => "buffer edited",
 1054            Self::RefreshRequested => "refresh requested",
 1055            Self::ExcerptsRemoved(_) => "excerpts removed",
 1056        }
 1057    }
 1058}
 1059
 1060pub enum FormatTarget {
 1061    Buffers,
 1062    Ranges(Vec<Range<MultiBufferPoint>>),
 1063}
 1064
 1065pub(crate) struct FocusedBlock {
 1066    id: BlockId,
 1067    focus_handle: WeakFocusHandle,
 1068}
 1069
 1070#[derive(Clone)]
 1071enum JumpData {
 1072    MultiBufferRow {
 1073        row: MultiBufferRow,
 1074        line_offset_from_top: u32,
 1075    },
 1076    MultiBufferPoint {
 1077        excerpt_id: ExcerptId,
 1078        position: Point,
 1079        anchor: text::Anchor,
 1080        line_offset_from_top: u32,
 1081    },
 1082}
 1083
 1084pub enum MultibufferSelectionMode {
 1085    First,
 1086    All,
 1087}
 1088
 1089impl Editor {
 1090    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1091        let buffer = cx.new(|cx| Buffer::local("", cx));
 1092        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1093        Self::new(
 1094            EditorMode::SingleLine { auto_width: false },
 1095            buffer,
 1096            None,
 1097            false,
 1098            window,
 1099            cx,
 1100        )
 1101    }
 1102
 1103    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1104        let buffer = cx.new(|cx| Buffer::local("", cx));
 1105        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1106        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1107    }
 1108
 1109    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1110        let buffer = cx.new(|cx| Buffer::local("", cx));
 1111        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1112        Self::new(
 1113            EditorMode::SingleLine { auto_width: true },
 1114            buffer,
 1115            None,
 1116            false,
 1117            window,
 1118            cx,
 1119        )
 1120    }
 1121
 1122    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1123        let buffer = cx.new(|cx| Buffer::local("", cx));
 1124        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1125        Self::new(
 1126            EditorMode::AutoHeight { max_lines },
 1127            buffer,
 1128            None,
 1129            false,
 1130            window,
 1131            cx,
 1132        )
 1133    }
 1134
 1135    pub fn for_buffer(
 1136        buffer: Entity<Buffer>,
 1137        project: Option<Entity<Project>>,
 1138        window: &mut Window,
 1139        cx: &mut Context<Self>,
 1140    ) -> Self {
 1141        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1142        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1143    }
 1144
 1145    pub fn for_multibuffer(
 1146        buffer: Entity<MultiBuffer>,
 1147        project: Option<Entity<Project>>,
 1148        show_excerpt_controls: bool,
 1149        window: &mut Window,
 1150        cx: &mut Context<Self>,
 1151    ) -> Self {
 1152        Self::new(
 1153            EditorMode::Full,
 1154            buffer,
 1155            project,
 1156            show_excerpt_controls,
 1157            window,
 1158            cx,
 1159        )
 1160    }
 1161
 1162    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1163        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1164        let mut clone = Self::new(
 1165            self.mode,
 1166            self.buffer.clone(),
 1167            self.project.clone(),
 1168            show_excerpt_controls,
 1169            window,
 1170            cx,
 1171        );
 1172        self.display_map.update(cx, |display_map, cx| {
 1173            let snapshot = display_map.snapshot(cx);
 1174            clone.display_map.update(cx, |display_map, cx| {
 1175                display_map.set_state(&snapshot, cx);
 1176            });
 1177        });
 1178        clone.selections.clone_state(&self.selections);
 1179        clone.scroll_manager.clone_state(&self.scroll_manager);
 1180        clone.searchable = self.searchable;
 1181        clone
 1182    }
 1183
 1184    pub fn new(
 1185        mode: EditorMode,
 1186        buffer: Entity<MultiBuffer>,
 1187        project: Option<Entity<Project>>,
 1188        show_excerpt_controls: bool,
 1189        window: &mut Window,
 1190        cx: &mut Context<Self>,
 1191    ) -> Self {
 1192        let style = window.text_style();
 1193        let font_size = style.font_size.to_pixels(window.rem_size());
 1194        let editor = cx.entity().downgrade();
 1195        let fold_placeholder = FoldPlaceholder {
 1196            constrain_width: true,
 1197            render: Arc::new(move |fold_id, fold_range, cx| {
 1198                let editor = editor.clone();
 1199                div()
 1200                    .id(fold_id)
 1201                    .bg(cx.theme().colors().ghost_element_background)
 1202                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1203                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1204                    .rounded_xs()
 1205                    .size_full()
 1206                    .cursor_pointer()
 1207                    .child("")
 1208                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1209                    .on_click(move |_, _window, cx| {
 1210                        editor
 1211                            .update(cx, |editor, cx| {
 1212                                editor.unfold_ranges(
 1213                                    &[fold_range.start..fold_range.end],
 1214                                    true,
 1215                                    false,
 1216                                    cx,
 1217                                );
 1218                                cx.stop_propagation();
 1219                            })
 1220                            .ok();
 1221                    })
 1222                    .into_any()
 1223            }),
 1224            merge_adjacent: true,
 1225            ..Default::default()
 1226        };
 1227        let display_map = cx.new(|cx| {
 1228            DisplayMap::new(
 1229                buffer.clone(),
 1230                style.font(),
 1231                font_size,
 1232                None,
 1233                show_excerpt_controls,
 1234                FILE_HEADER_HEIGHT,
 1235                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1236                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1237                fold_placeholder,
 1238                cx,
 1239            )
 1240        });
 1241
 1242        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1243
 1244        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1245
 1246        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1247            .then(|| language_settings::SoftWrap::None);
 1248
 1249        let mut project_subscriptions = Vec::new();
 1250        if mode == EditorMode::Full {
 1251            if let Some(project) = project.as_ref() {
 1252                if buffer.read(cx).is_singleton() {
 1253                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1254                        cx.emit(EditorEvent::TitleChanged);
 1255                    }));
 1256                }
 1257                project_subscriptions.push(cx.subscribe_in(
 1258                    project,
 1259                    window,
 1260                    |editor, _, event, window, cx| {
 1261                        if let project::Event::RefreshInlayHints = event {
 1262                            editor
 1263                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1264                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1265                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1266                                let focus_handle = editor.focus_handle(cx);
 1267                                if focus_handle.is_focused(window) {
 1268                                    let snapshot = buffer.read(cx).snapshot();
 1269                                    for (range, snippet) in snippet_edits {
 1270                                        let editor_range =
 1271                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1272                                        editor
 1273                                            .insert_snippet(
 1274                                                &[editor_range],
 1275                                                snippet.clone(),
 1276                                                window,
 1277                                                cx,
 1278                                            )
 1279                                            .ok();
 1280                                    }
 1281                                }
 1282                            }
 1283                        }
 1284                    },
 1285                ));
 1286                if let Some(task_inventory) = project
 1287                    .read(cx)
 1288                    .task_store()
 1289                    .read(cx)
 1290                    .task_inventory()
 1291                    .cloned()
 1292                {
 1293                    project_subscriptions.push(cx.observe_in(
 1294                        &task_inventory,
 1295                        window,
 1296                        |editor, _, window, cx| {
 1297                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1298                        },
 1299                    ));
 1300                }
 1301            }
 1302        }
 1303
 1304        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1305
 1306        let inlay_hint_settings =
 1307            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1308        let focus_handle = cx.focus_handle();
 1309        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1310            .detach();
 1311        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1312            .detach();
 1313        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1314            .detach();
 1315        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1316            .detach();
 1317
 1318        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1319            Some(false)
 1320        } else {
 1321            None
 1322        };
 1323
 1324        let mut code_action_providers = Vec::new();
 1325        let mut load_uncommitted_diff = None;
 1326        if let Some(project) = project.clone() {
 1327            load_uncommitted_diff = Some(
 1328                get_uncommitted_diff_for_buffer(
 1329                    &project,
 1330                    buffer.read(cx).all_buffers(),
 1331                    buffer.clone(),
 1332                    cx,
 1333                )
 1334                .shared(),
 1335            );
 1336            code_action_providers.push(Rc::new(project) as Rc<_>);
 1337        }
 1338
 1339        let mut this = Self {
 1340            focus_handle,
 1341            show_cursor_when_unfocused: false,
 1342            last_focused_descendant: None,
 1343            buffer: buffer.clone(),
 1344            display_map: display_map.clone(),
 1345            selections,
 1346            scroll_manager: ScrollManager::new(cx),
 1347            columnar_selection_tail: None,
 1348            add_selections_state: None,
 1349            select_next_state: None,
 1350            select_prev_state: None,
 1351            selection_history: Default::default(),
 1352            autoclose_regions: Default::default(),
 1353            snippet_stack: Default::default(),
 1354            select_larger_syntax_node_stack: Vec::new(),
 1355            ime_transaction: Default::default(),
 1356            active_diagnostics: None,
 1357            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1358            inline_diagnostics_update: Task::ready(()),
 1359            inline_diagnostics: Vec::new(),
 1360            soft_wrap_mode_override,
 1361            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1362            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1363            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1364            project,
 1365            blink_manager: blink_manager.clone(),
 1366            show_local_selections: true,
 1367            show_scrollbars: true,
 1368            mode,
 1369            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1370            show_gutter: mode == EditorMode::Full,
 1371            show_line_numbers: None,
 1372            use_relative_line_numbers: None,
 1373            show_git_diff_gutter: None,
 1374            show_code_actions: None,
 1375            show_runnables: None,
 1376            show_wrap_guides: None,
 1377            show_indent_guides,
 1378            placeholder_text: None,
 1379            highlight_order: 0,
 1380            highlighted_rows: HashMap::default(),
 1381            background_highlights: Default::default(),
 1382            gutter_highlights: TreeMap::default(),
 1383            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1384            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1385            nav_history: None,
 1386            context_menu: RefCell::new(None),
 1387            mouse_context_menu: None,
 1388            completion_tasks: Default::default(),
 1389            signature_help_state: SignatureHelpState::default(),
 1390            auto_signature_help: None,
 1391            find_all_references_task_sources: Vec::new(),
 1392            next_completion_id: 0,
 1393            next_inlay_id: 0,
 1394            code_action_providers,
 1395            available_code_actions: Default::default(),
 1396            code_actions_task: Default::default(),
 1397            selection_highlight_task: Default::default(),
 1398            document_highlights_task: Default::default(),
 1399            linked_editing_range_task: Default::default(),
 1400            pending_rename: Default::default(),
 1401            searchable: true,
 1402            cursor_shape: EditorSettings::get_global(cx)
 1403                .cursor_shape
 1404                .unwrap_or_default(),
 1405            current_line_highlight: None,
 1406            autoindent_mode: Some(AutoindentMode::EachLine),
 1407            collapse_matches: false,
 1408            workspace: None,
 1409            input_enabled: true,
 1410            use_modal_editing: mode == EditorMode::Full,
 1411            read_only: false,
 1412            use_autoclose: true,
 1413            use_auto_surround: true,
 1414            auto_replace_emoji_shortcode: false,
 1415            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1416            leader_peer_id: None,
 1417            remote_id: None,
 1418            hover_state: Default::default(),
 1419            pending_mouse_down: None,
 1420            hovered_link_state: Default::default(),
 1421            edit_prediction_provider: None,
 1422            active_inline_completion: None,
 1423            stale_inline_completion_in_menu: None,
 1424            edit_prediction_preview: EditPredictionPreview::Inactive {
 1425                released_too_fast: false,
 1426            },
 1427            inline_diagnostics_enabled: mode == EditorMode::Full,
 1428            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1429
 1430            gutter_hovered: false,
 1431            pixel_position_of_newest_cursor: None,
 1432            last_bounds: None,
 1433            last_position_map: None,
 1434            expect_bounds_change: None,
 1435            gutter_dimensions: GutterDimensions::default(),
 1436            style: None,
 1437            show_cursor_names: false,
 1438            hovered_cursors: Default::default(),
 1439            next_editor_action_id: EditorActionId::default(),
 1440            editor_actions: Rc::default(),
 1441            inline_completions_hidden_for_vim_mode: false,
 1442            show_inline_completions_override: None,
 1443            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1444            edit_prediction_settings: EditPredictionSettings::Disabled,
 1445            edit_prediction_indent_conflict: false,
 1446            edit_prediction_requires_modifier_in_indent_conflict: true,
 1447            custom_context_menu: None,
 1448            show_git_blame_gutter: false,
 1449            show_git_blame_inline: false,
 1450            show_selection_menu: None,
 1451            show_git_blame_inline_delay_task: None,
 1452            git_blame_inline_tooltip: None,
 1453            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1454            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1455                .session
 1456                .restore_unsaved_buffers,
 1457            blame: None,
 1458            blame_subscription: None,
 1459            tasks: Default::default(),
 1460            _subscriptions: vec![
 1461                cx.observe(&buffer, Self::on_buffer_changed),
 1462                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1463                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1464                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1465                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1466                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1467                cx.observe_window_activation(window, |editor, window, cx| {
 1468                    let active = window.is_window_active();
 1469                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1470                        if active {
 1471                            blink_manager.enable(cx);
 1472                        } else {
 1473                            blink_manager.disable(cx);
 1474                        }
 1475                    });
 1476                }),
 1477            ],
 1478            tasks_update_task: None,
 1479            linked_edit_ranges: Default::default(),
 1480            in_project_search: false,
 1481            previous_search_ranges: None,
 1482            breadcrumb_header: None,
 1483            focused_block: None,
 1484            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1485            addons: HashMap::default(),
 1486            registered_buffers: HashMap::default(),
 1487            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1488            selection_mark_mode: false,
 1489            toggle_fold_multiple_buffers: Task::ready(()),
 1490            serialize_selections: Task::ready(()),
 1491            text_style_refinement: None,
 1492            load_diff_task: load_uncommitted_diff,
 1493        };
 1494        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1495        this._subscriptions.extend(project_subscriptions);
 1496
 1497        this.end_selection(window, cx);
 1498        this.scroll_manager.show_scrollbar(window, cx);
 1499        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1500
 1501        if mode == EditorMode::Full {
 1502            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1503            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1504
 1505            if this.git_blame_inline_enabled {
 1506                this.git_blame_inline_enabled = true;
 1507                this.start_git_blame_inline(false, window, cx);
 1508            }
 1509
 1510            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1511                if let Some(project) = this.project.as_ref() {
 1512                    let handle = project.update(cx, |project, cx| {
 1513                        project.register_buffer_with_language_servers(&buffer, cx)
 1514                    });
 1515                    this.registered_buffers
 1516                        .insert(buffer.read(cx).remote_id(), handle);
 1517                }
 1518            }
 1519        }
 1520
 1521        this.report_editor_event("Editor Opened", None, cx);
 1522        this
 1523    }
 1524
 1525    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1526        self.mouse_context_menu
 1527            .as_ref()
 1528            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1529    }
 1530
 1531    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1532        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1533    }
 1534
 1535    fn key_context_internal(
 1536        &self,
 1537        has_active_edit_prediction: bool,
 1538        window: &Window,
 1539        cx: &App,
 1540    ) -> KeyContext {
 1541        let mut key_context = KeyContext::new_with_defaults();
 1542        key_context.add("Editor");
 1543        let mode = match self.mode {
 1544            EditorMode::SingleLine { .. } => "single_line",
 1545            EditorMode::AutoHeight { .. } => "auto_height",
 1546            EditorMode::Full => "full",
 1547        };
 1548
 1549        if EditorSettings::jupyter_enabled(cx) {
 1550            key_context.add("jupyter");
 1551        }
 1552
 1553        key_context.set("mode", mode);
 1554        if self.pending_rename.is_some() {
 1555            key_context.add("renaming");
 1556        }
 1557
 1558        match self.context_menu.borrow().as_ref() {
 1559            Some(CodeContextMenu::Completions(_)) => {
 1560                key_context.add("menu");
 1561                key_context.add("showing_completions");
 1562            }
 1563            Some(CodeContextMenu::CodeActions(_)) => {
 1564                key_context.add("menu");
 1565                key_context.add("showing_code_actions")
 1566            }
 1567            None => {}
 1568        }
 1569
 1570        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1571        if !self.focus_handle(cx).contains_focused(window, cx)
 1572            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1573        {
 1574            for addon in self.addons.values() {
 1575                addon.extend_key_context(&mut key_context, cx)
 1576            }
 1577        }
 1578
 1579        if let Some(extension) = self
 1580            .buffer
 1581            .read(cx)
 1582            .as_singleton()
 1583            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1584        {
 1585            key_context.set("extension", extension.to_string());
 1586        }
 1587
 1588        if has_active_edit_prediction {
 1589            if self.edit_prediction_in_conflict() {
 1590                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1591            } else {
 1592                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1593                key_context.add("copilot_suggestion");
 1594            }
 1595        }
 1596
 1597        if self.selection_mark_mode {
 1598            key_context.add("selection_mode");
 1599        }
 1600
 1601        key_context
 1602    }
 1603
 1604    pub fn edit_prediction_in_conflict(&self) -> bool {
 1605        if !self.show_edit_predictions_in_menu() {
 1606            return false;
 1607        }
 1608
 1609        let showing_completions = self
 1610            .context_menu
 1611            .borrow()
 1612            .as_ref()
 1613            .map_or(false, |context| {
 1614                matches!(context, CodeContextMenu::Completions(_))
 1615            });
 1616
 1617        showing_completions
 1618            || self.edit_prediction_requires_modifier()
 1619            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1620            // bindings to insert tab characters.
 1621            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1622    }
 1623
 1624    pub fn accept_edit_prediction_keybind(
 1625        &self,
 1626        window: &Window,
 1627        cx: &App,
 1628    ) -> AcceptEditPredictionBinding {
 1629        let key_context = self.key_context_internal(true, window, cx);
 1630        let in_conflict = self.edit_prediction_in_conflict();
 1631
 1632        AcceptEditPredictionBinding(
 1633            window
 1634                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1635                .into_iter()
 1636                .filter(|binding| {
 1637                    !in_conflict
 1638                        || binding
 1639                            .keystrokes()
 1640                            .first()
 1641                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1642                })
 1643                .rev()
 1644                .min_by_key(|binding| {
 1645                    binding
 1646                        .keystrokes()
 1647                        .first()
 1648                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1649                }),
 1650        )
 1651    }
 1652
 1653    pub fn new_file(
 1654        workspace: &mut Workspace,
 1655        _: &workspace::NewFile,
 1656        window: &mut Window,
 1657        cx: &mut Context<Workspace>,
 1658    ) {
 1659        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1660            "Failed to create buffer",
 1661            window,
 1662            cx,
 1663            |e, _, _| match e.error_code() {
 1664                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1665                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1666                e.error_tag("required").unwrap_or("the latest version")
 1667            )),
 1668                _ => None,
 1669            },
 1670        );
 1671    }
 1672
 1673    pub fn new_in_workspace(
 1674        workspace: &mut Workspace,
 1675        window: &mut Window,
 1676        cx: &mut Context<Workspace>,
 1677    ) -> Task<Result<Entity<Editor>>> {
 1678        let project = workspace.project().clone();
 1679        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1680
 1681        cx.spawn_in(window, |workspace, mut cx| async move {
 1682            let buffer = create.await?;
 1683            workspace.update_in(&mut cx, |workspace, window, cx| {
 1684                let editor =
 1685                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1686                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1687                editor
 1688            })
 1689        })
 1690    }
 1691
 1692    fn new_file_vertical(
 1693        workspace: &mut Workspace,
 1694        _: &workspace::NewFileSplitVertical,
 1695        window: &mut Window,
 1696        cx: &mut Context<Workspace>,
 1697    ) {
 1698        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1699    }
 1700
 1701    fn new_file_horizontal(
 1702        workspace: &mut Workspace,
 1703        _: &workspace::NewFileSplitHorizontal,
 1704        window: &mut Window,
 1705        cx: &mut Context<Workspace>,
 1706    ) {
 1707        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1708    }
 1709
 1710    fn new_file_in_direction(
 1711        workspace: &mut Workspace,
 1712        direction: SplitDirection,
 1713        window: &mut Window,
 1714        cx: &mut Context<Workspace>,
 1715    ) {
 1716        let project = workspace.project().clone();
 1717        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1718
 1719        cx.spawn_in(window, |workspace, mut cx| async move {
 1720            let buffer = create.await?;
 1721            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1722                workspace.split_item(
 1723                    direction,
 1724                    Box::new(
 1725                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1726                    ),
 1727                    window,
 1728                    cx,
 1729                )
 1730            })?;
 1731            anyhow::Ok(())
 1732        })
 1733        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1734            match e.error_code() {
 1735                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1736                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1737                e.error_tag("required").unwrap_or("the latest version")
 1738            )),
 1739                _ => None,
 1740            }
 1741        });
 1742    }
 1743
 1744    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1745        self.leader_peer_id
 1746    }
 1747
 1748    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1749        &self.buffer
 1750    }
 1751
 1752    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1753        self.workspace.as_ref()?.0.upgrade()
 1754    }
 1755
 1756    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1757        self.buffer().read(cx).title(cx)
 1758    }
 1759
 1760    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1761        let git_blame_gutter_max_author_length = self
 1762            .render_git_blame_gutter(cx)
 1763            .then(|| {
 1764                if let Some(blame) = self.blame.as_ref() {
 1765                    let max_author_length =
 1766                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1767                    Some(max_author_length)
 1768                } else {
 1769                    None
 1770                }
 1771            })
 1772            .flatten();
 1773
 1774        EditorSnapshot {
 1775            mode: self.mode,
 1776            show_gutter: self.show_gutter,
 1777            show_line_numbers: self.show_line_numbers,
 1778            show_git_diff_gutter: self.show_git_diff_gutter,
 1779            show_code_actions: self.show_code_actions,
 1780            show_runnables: self.show_runnables,
 1781            git_blame_gutter_max_author_length,
 1782            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1783            scroll_anchor: self.scroll_manager.anchor(),
 1784            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1785            placeholder_text: self.placeholder_text.clone(),
 1786            is_focused: self.focus_handle.is_focused(window),
 1787            current_line_highlight: self
 1788                .current_line_highlight
 1789                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1790            gutter_hovered: self.gutter_hovered,
 1791        }
 1792    }
 1793
 1794    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1795        self.buffer.read(cx).language_at(point, cx)
 1796    }
 1797
 1798    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1799        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1800    }
 1801
 1802    pub fn active_excerpt(
 1803        &self,
 1804        cx: &App,
 1805    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1806        self.buffer
 1807            .read(cx)
 1808            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1809    }
 1810
 1811    pub fn mode(&self) -> EditorMode {
 1812        self.mode
 1813    }
 1814
 1815    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1816        self.collaboration_hub.as_deref()
 1817    }
 1818
 1819    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1820        self.collaboration_hub = Some(hub);
 1821    }
 1822
 1823    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1824        self.in_project_search = in_project_search;
 1825    }
 1826
 1827    pub fn set_custom_context_menu(
 1828        &mut self,
 1829        f: impl 'static
 1830            + Fn(
 1831                &mut Self,
 1832                DisplayPoint,
 1833                &mut Window,
 1834                &mut Context<Self>,
 1835            ) -> Option<Entity<ui::ContextMenu>>,
 1836    ) {
 1837        self.custom_context_menu = Some(Box::new(f))
 1838    }
 1839
 1840    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1841        self.completion_provider = provider;
 1842    }
 1843
 1844    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1845        self.semantics_provider.clone()
 1846    }
 1847
 1848    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1849        self.semantics_provider = provider;
 1850    }
 1851
 1852    pub fn set_edit_prediction_provider<T>(
 1853        &mut self,
 1854        provider: Option<Entity<T>>,
 1855        window: &mut Window,
 1856        cx: &mut Context<Self>,
 1857    ) where
 1858        T: EditPredictionProvider,
 1859    {
 1860        self.edit_prediction_provider =
 1861            provider.map(|provider| RegisteredInlineCompletionProvider {
 1862                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1863                    if this.focus_handle.is_focused(window) {
 1864                        this.update_visible_inline_completion(window, cx);
 1865                    }
 1866                }),
 1867                provider: Arc::new(provider),
 1868            });
 1869        self.update_edit_prediction_settings(cx);
 1870        self.refresh_inline_completion(false, false, window, cx);
 1871    }
 1872
 1873    pub fn placeholder_text(&self) -> Option<&str> {
 1874        self.placeholder_text.as_deref()
 1875    }
 1876
 1877    pub fn set_placeholder_text(
 1878        &mut self,
 1879        placeholder_text: impl Into<Arc<str>>,
 1880        cx: &mut Context<Self>,
 1881    ) {
 1882        let placeholder_text = Some(placeholder_text.into());
 1883        if self.placeholder_text != placeholder_text {
 1884            self.placeholder_text = placeholder_text;
 1885            cx.notify();
 1886        }
 1887    }
 1888
 1889    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1890        self.cursor_shape = cursor_shape;
 1891
 1892        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1893        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1894
 1895        cx.notify();
 1896    }
 1897
 1898    pub fn set_current_line_highlight(
 1899        &mut self,
 1900        current_line_highlight: Option<CurrentLineHighlight>,
 1901    ) {
 1902        self.current_line_highlight = current_line_highlight;
 1903    }
 1904
 1905    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1906        self.collapse_matches = collapse_matches;
 1907    }
 1908
 1909    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1910        let buffers = self.buffer.read(cx).all_buffers();
 1911        let Some(project) = self.project.as_ref() else {
 1912            return;
 1913        };
 1914        project.update(cx, |project, cx| {
 1915            for buffer in buffers {
 1916                self.registered_buffers
 1917                    .entry(buffer.read(cx).remote_id())
 1918                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1919            }
 1920        })
 1921    }
 1922
 1923    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1924        if self.collapse_matches {
 1925            return range.start..range.start;
 1926        }
 1927        range.clone()
 1928    }
 1929
 1930    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1931        if self.display_map.read(cx).clip_at_line_ends != clip {
 1932            self.display_map
 1933                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1934        }
 1935    }
 1936
 1937    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1938        self.input_enabled = input_enabled;
 1939    }
 1940
 1941    pub fn set_inline_completions_hidden_for_vim_mode(
 1942        &mut self,
 1943        hidden: bool,
 1944        window: &mut Window,
 1945        cx: &mut Context<Self>,
 1946    ) {
 1947        if hidden != self.inline_completions_hidden_for_vim_mode {
 1948            self.inline_completions_hidden_for_vim_mode = hidden;
 1949            if hidden {
 1950                self.update_visible_inline_completion(window, cx);
 1951            } else {
 1952                self.refresh_inline_completion(true, false, window, cx);
 1953            }
 1954        }
 1955    }
 1956
 1957    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1958        self.menu_inline_completions_policy = value;
 1959    }
 1960
 1961    pub fn set_autoindent(&mut self, autoindent: bool) {
 1962        if autoindent {
 1963            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1964        } else {
 1965            self.autoindent_mode = None;
 1966        }
 1967    }
 1968
 1969    pub fn read_only(&self, cx: &App) -> bool {
 1970        self.read_only || self.buffer.read(cx).read_only()
 1971    }
 1972
 1973    pub fn set_read_only(&mut self, read_only: bool) {
 1974        self.read_only = read_only;
 1975    }
 1976
 1977    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1978        self.use_autoclose = autoclose;
 1979    }
 1980
 1981    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1982        self.use_auto_surround = auto_surround;
 1983    }
 1984
 1985    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1986        self.auto_replace_emoji_shortcode = auto_replace;
 1987    }
 1988
 1989    pub fn toggle_edit_predictions(
 1990        &mut self,
 1991        _: &ToggleEditPrediction,
 1992        window: &mut Window,
 1993        cx: &mut Context<Self>,
 1994    ) {
 1995        if self.show_inline_completions_override.is_some() {
 1996            self.set_show_edit_predictions(None, window, cx);
 1997        } else {
 1998            let show_edit_predictions = !self.edit_predictions_enabled();
 1999            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2000        }
 2001    }
 2002
 2003    pub fn set_show_edit_predictions(
 2004        &mut self,
 2005        show_edit_predictions: Option<bool>,
 2006        window: &mut Window,
 2007        cx: &mut Context<Self>,
 2008    ) {
 2009        self.show_inline_completions_override = show_edit_predictions;
 2010        self.update_edit_prediction_settings(cx);
 2011
 2012        if let Some(false) = show_edit_predictions {
 2013            self.discard_inline_completion(false, cx);
 2014        } else {
 2015            self.refresh_inline_completion(false, true, window, cx);
 2016        }
 2017    }
 2018
 2019    fn inline_completions_disabled_in_scope(
 2020        &self,
 2021        buffer: &Entity<Buffer>,
 2022        buffer_position: language::Anchor,
 2023        cx: &App,
 2024    ) -> bool {
 2025        let snapshot = buffer.read(cx).snapshot();
 2026        let settings = snapshot.settings_at(buffer_position, cx);
 2027
 2028        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2029            return false;
 2030        };
 2031
 2032        scope.override_name().map_or(false, |scope_name| {
 2033            settings
 2034                .edit_predictions_disabled_in
 2035                .iter()
 2036                .any(|s| s == scope_name)
 2037        })
 2038    }
 2039
 2040    pub fn set_use_modal_editing(&mut self, to: bool) {
 2041        self.use_modal_editing = to;
 2042    }
 2043
 2044    pub fn use_modal_editing(&self) -> bool {
 2045        self.use_modal_editing
 2046    }
 2047
 2048    fn selections_did_change(
 2049        &mut self,
 2050        local: bool,
 2051        old_cursor_position: &Anchor,
 2052        show_completions: bool,
 2053        window: &mut Window,
 2054        cx: &mut Context<Self>,
 2055    ) {
 2056        window.invalidate_character_coordinates();
 2057
 2058        // Copy selections to primary selection buffer
 2059        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2060        if local {
 2061            let selections = self.selections.all::<usize>(cx);
 2062            let buffer_handle = self.buffer.read(cx).read(cx);
 2063
 2064            let mut text = String::new();
 2065            for (index, selection) in selections.iter().enumerate() {
 2066                let text_for_selection = buffer_handle
 2067                    .text_for_range(selection.start..selection.end)
 2068                    .collect::<String>();
 2069
 2070                text.push_str(&text_for_selection);
 2071                if index != selections.len() - 1 {
 2072                    text.push('\n');
 2073                }
 2074            }
 2075
 2076            if !text.is_empty() {
 2077                cx.write_to_primary(ClipboardItem::new_string(text));
 2078            }
 2079        }
 2080
 2081        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2082            self.buffer.update(cx, |buffer, cx| {
 2083                buffer.set_active_selections(
 2084                    &self.selections.disjoint_anchors(),
 2085                    self.selections.line_mode,
 2086                    self.cursor_shape,
 2087                    cx,
 2088                )
 2089            });
 2090        }
 2091        let display_map = self
 2092            .display_map
 2093            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2094        let buffer = &display_map.buffer_snapshot;
 2095        self.add_selections_state = None;
 2096        self.select_next_state = None;
 2097        self.select_prev_state = None;
 2098        self.select_larger_syntax_node_stack.clear();
 2099        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2100        self.snippet_stack
 2101            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2102        self.take_rename(false, window, cx);
 2103
 2104        let new_cursor_position = self.selections.newest_anchor().head();
 2105
 2106        self.push_to_nav_history(
 2107            *old_cursor_position,
 2108            Some(new_cursor_position.to_point(buffer)),
 2109            cx,
 2110        );
 2111
 2112        if local {
 2113            let new_cursor_position = self.selections.newest_anchor().head();
 2114            let mut context_menu = self.context_menu.borrow_mut();
 2115            let completion_menu = match context_menu.as_ref() {
 2116                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2117                _ => {
 2118                    *context_menu = None;
 2119                    None
 2120                }
 2121            };
 2122            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2123                if !self.registered_buffers.contains_key(&buffer_id) {
 2124                    if let Some(project) = self.project.as_ref() {
 2125                        project.update(cx, |project, cx| {
 2126                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2127                                return;
 2128                            };
 2129                            self.registered_buffers.insert(
 2130                                buffer_id,
 2131                                project.register_buffer_with_language_servers(&buffer, cx),
 2132                            );
 2133                        })
 2134                    }
 2135                }
 2136            }
 2137
 2138            if let Some(completion_menu) = completion_menu {
 2139                let cursor_position = new_cursor_position.to_offset(buffer);
 2140                let (word_range, kind) =
 2141                    buffer.surrounding_word(completion_menu.initial_position, true);
 2142                if kind == Some(CharKind::Word)
 2143                    && word_range.to_inclusive().contains(&cursor_position)
 2144                {
 2145                    let mut completion_menu = completion_menu.clone();
 2146                    drop(context_menu);
 2147
 2148                    let query = Self::completion_query(buffer, cursor_position);
 2149                    cx.spawn(move |this, mut cx| async move {
 2150                        completion_menu
 2151                            .filter(query.as_deref(), cx.background_executor().clone())
 2152                            .await;
 2153
 2154                        this.update(&mut cx, |this, cx| {
 2155                            let mut context_menu = this.context_menu.borrow_mut();
 2156                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2157                            else {
 2158                                return;
 2159                            };
 2160
 2161                            if menu.id > completion_menu.id {
 2162                                return;
 2163                            }
 2164
 2165                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2166                            drop(context_menu);
 2167                            cx.notify();
 2168                        })
 2169                    })
 2170                    .detach();
 2171
 2172                    if show_completions {
 2173                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2174                    }
 2175                } else {
 2176                    drop(context_menu);
 2177                    self.hide_context_menu(window, cx);
 2178                }
 2179            } else {
 2180                drop(context_menu);
 2181            }
 2182
 2183            hide_hover(self, cx);
 2184
 2185            if old_cursor_position.to_display_point(&display_map).row()
 2186                != new_cursor_position.to_display_point(&display_map).row()
 2187            {
 2188                self.available_code_actions.take();
 2189            }
 2190            self.refresh_code_actions(window, cx);
 2191            self.refresh_document_highlights(cx);
 2192            self.refresh_selected_text_highlights(window, cx);
 2193            refresh_matching_bracket_highlights(self, window, cx);
 2194            self.update_visible_inline_completion(window, cx);
 2195            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2196            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2197            if self.git_blame_inline_enabled {
 2198                self.start_inline_blame_timer(window, cx);
 2199            }
 2200        }
 2201
 2202        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2203        cx.emit(EditorEvent::SelectionsChanged { local });
 2204
 2205        let selections = &self.selections.disjoint;
 2206        if selections.len() == 1 {
 2207            cx.emit(SearchEvent::ActiveMatchChanged)
 2208        }
 2209        if local
 2210            && self.is_singleton(cx)
 2211            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2212        {
 2213            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2214                let background_executor = cx.background_executor().clone();
 2215                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2216                let snapshot = self.buffer().read(cx).snapshot(cx);
 2217                let selections = selections.clone();
 2218                self.serialize_selections = cx.background_spawn(async move {
 2219                    background_executor.timer(Duration::from_millis(100)).await;
 2220                    let selections = selections
 2221                        .iter()
 2222                        .map(|selection| {
 2223                            (
 2224                                selection.start.to_offset(&snapshot),
 2225                                selection.end.to_offset(&snapshot),
 2226                            )
 2227                        })
 2228                        .collect();
 2229                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2230                        .await
 2231                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2232                        .log_err();
 2233                });
 2234            }
 2235        }
 2236
 2237        cx.notify();
 2238    }
 2239
 2240    pub fn sync_selections(
 2241        &mut self,
 2242        other: Entity<Editor>,
 2243        cx: &mut Context<Self>,
 2244    ) -> gpui::Subscription {
 2245        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2246        self.selections.change_with(cx, |selections| {
 2247            selections.select_anchors(other_selections);
 2248        });
 2249
 2250        let other_subscription =
 2251            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2252                EditorEvent::SelectionsChanged { local: true } => {
 2253                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2254                    if other_selections.is_empty() {
 2255                        return;
 2256                    }
 2257                    this.selections.change_with(cx, |selections| {
 2258                        selections.select_anchors(other_selections);
 2259                    });
 2260                }
 2261                _ => {}
 2262            });
 2263
 2264        let this_subscription =
 2265            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2266                EditorEvent::SelectionsChanged { local: true } => {
 2267                    let these_selections = this.selections.disjoint.to_vec();
 2268                    if these_selections.is_empty() {
 2269                        return;
 2270                    }
 2271                    other.update(cx, |other_editor, cx| {
 2272                        other_editor.selections.change_with(cx, |selections| {
 2273                            selections.select_anchors(these_selections);
 2274                        })
 2275                    });
 2276                }
 2277                _ => {}
 2278            });
 2279
 2280        Subscription::join(other_subscription, this_subscription)
 2281    }
 2282
 2283    pub fn change_selections<R>(
 2284        &mut self,
 2285        autoscroll: Option<Autoscroll>,
 2286        window: &mut Window,
 2287        cx: &mut Context<Self>,
 2288        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2289    ) -> R {
 2290        self.change_selections_inner(autoscroll, true, window, cx, change)
 2291    }
 2292
 2293    fn change_selections_inner<R>(
 2294        &mut self,
 2295        autoscroll: Option<Autoscroll>,
 2296        request_completions: bool,
 2297        window: &mut Window,
 2298        cx: &mut Context<Self>,
 2299        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2300    ) -> R {
 2301        let old_cursor_position = self.selections.newest_anchor().head();
 2302        self.push_to_selection_history();
 2303
 2304        let (changed, result) = self.selections.change_with(cx, change);
 2305
 2306        if changed {
 2307            if let Some(autoscroll) = autoscroll {
 2308                self.request_autoscroll(autoscroll, cx);
 2309            }
 2310            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2311
 2312            if self.should_open_signature_help_automatically(
 2313                &old_cursor_position,
 2314                self.signature_help_state.backspace_pressed(),
 2315                cx,
 2316            ) {
 2317                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2318            }
 2319            self.signature_help_state.set_backspace_pressed(false);
 2320        }
 2321
 2322        result
 2323    }
 2324
 2325    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2326    where
 2327        I: IntoIterator<Item = (Range<S>, T)>,
 2328        S: ToOffset,
 2329        T: Into<Arc<str>>,
 2330    {
 2331        if self.read_only(cx) {
 2332            return;
 2333        }
 2334
 2335        self.buffer
 2336            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2337    }
 2338
 2339    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2340    where
 2341        I: IntoIterator<Item = (Range<S>, T)>,
 2342        S: ToOffset,
 2343        T: Into<Arc<str>>,
 2344    {
 2345        if self.read_only(cx) {
 2346            return;
 2347        }
 2348
 2349        self.buffer.update(cx, |buffer, cx| {
 2350            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2351        });
 2352    }
 2353
 2354    pub fn edit_with_block_indent<I, S, T>(
 2355        &mut self,
 2356        edits: I,
 2357        original_indent_columns: Vec<Option<u32>>,
 2358        cx: &mut Context<Self>,
 2359    ) where
 2360        I: IntoIterator<Item = (Range<S>, T)>,
 2361        S: ToOffset,
 2362        T: Into<Arc<str>>,
 2363    {
 2364        if self.read_only(cx) {
 2365            return;
 2366        }
 2367
 2368        self.buffer.update(cx, |buffer, cx| {
 2369            buffer.edit(
 2370                edits,
 2371                Some(AutoindentMode::Block {
 2372                    original_indent_columns,
 2373                }),
 2374                cx,
 2375            )
 2376        });
 2377    }
 2378
 2379    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2380        self.hide_context_menu(window, cx);
 2381
 2382        match phase {
 2383            SelectPhase::Begin {
 2384                position,
 2385                add,
 2386                click_count,
 2387            } => self.begin_selection(position, add, click_count, window, cx),
 2388            SelectPhase::BeginColumnar {
 2389                position,
 2390                goal_column,
 2391                reset,
 2392            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2393            SelectPhase::Extend {
 2394                position,
 2395                click_count,
 2396            } => self.extend_selection(position, click_count, window, cx),
 2397            SelectPhase::Update {
 2398                position,
 2399                goal_column,
 2400                scroll_delta,
 2401            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2402            SelectPhase::End => self.end_selection(window, cx),
 2403        }
 2404    }
 2405
 2406    fn extend_selection(
 2407        &mut self,
 2408        position: DisplayPoint,
 2409        click_count: usize,
 2410        window: &mut Window,
 2411        cx: &mut Context<Self>,
 2412    ) {
 2413        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2414        let tail = self.selections.newest::<usize>(cx).tail();
 2415        self.begin_selection(position, false, click_count, window, cx);
 2416
 2417        let position = position.to_offset(&display_map, Bias::Left);
 2418        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2419
 2420        let mut pending_selection = self
 2421            .selections
 2422            .pending_anchor()
 2423            .expect("extend_selection not called with pending selection");
 2424        if position >= tail {
 2425            pending_selection.start = tail_anchor;
 2426        } else {
 2427            pending_selection.end = tail_anchor;
 2428            pending_selection.reversed = true;
 2429        }
 2430
 2431        let mut pending_mode = self.selections.pending_mode().unwrap();
 2432        match &mut pending_mode {
 2433            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2434            _ => {}
 2435        }
 2436
 2437        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2438            s.set_pending(pending_selection, pending_mode)
 2439        });
 2440    }
 2441
 2442    fn begin_selection(
 2443        &mut self,
 2444        position: DisplayPoint,
 2445        add: bool,
 2446        click_count: usize,
 2447        window: &mut Window,
 2448        cx: &mut Context<Self>,
 2449    ) {
 2450        if !self.focus_handle.is_focused(window) {
 2451            self.last_focused_descendant = None;
 2452            window.focus(&self.focus_handle);
 2453        }
 2454
 2455        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2456        let buffer = &display_map.buffer_snapshot;
 2457        let newest_selection = self.selections.newest_anchor().clone();
 2458        let position = display_map.clip_point(position, Bias::Left);
 2459
 2460        let start;
 2461        let end;
 2462        let mode;
 2463        let mut auto_scroll;
 2464        match click_count {
 2465            1 => {
 2466                start = buffer.anchor_before(position.to_point(&display_map));
 2467                end = start;
 2468                mode = SelectMode::Character;
 2469                auto_scroll = true;
 2470            }
 2471            2 => {
 2472                let range = movement::surrounding_word(&display_map, position);
 2473                start = buffer.anchor_before(range.start.to_point(&display_map));
 2474                end = buffer.anchor_before(range.end.to_point(&display_map));
 2475                mode = SelectMode::Word(start..end);
 2476                auto_scroll = true;
 2477            }
 2478            3 => {
 2479                let position = display_map
 2480                    .clip_point(position, Bias::Left)
 2481                    .to_point(&display_map);
 2482                let line_start = display_map.prev_line_boundary(position).0;
 2483                let next_line_start = buffer.clip_point(
 2484                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2485                    Bias::Left,
 2486                );
 2487                start = buffer.anchor_before(line_start);
 2488                end = buffer.anchor_before(next_line_start);
 2489                mode = SelectMode::Line(start..end);
 2490                auto_scroll = true;
 2491            }
 2492            _ => {
 2493                start = buffer.anchor_before(0);
 2494                end = buffer.anchor_before(buffer.len());
 2495                mode = SelectMode::All;
 2496                auto_scroll = false;
 2497            }
 2498        }
 2499        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2500
 2501        let point_to_delete: Option<usize> = {
 2502            let selected_points: Vec<Selection<Point>> =
 2503                self.selections.disjoint_in_range(start..end, cx);
 2504
 2505            if !add || click_count > 1 {
 2506                None
 2507            } else if !selected_points.is_empty() {
 2508                Some(selected_points[0].id)
 2509            } else {
 2510                let clicked_point_already_selected =
 2511                    self.selections.disjoint.iter().find(|selection| {
 2512                        selection.start.to_point(buffer) == start.to_point(buffer)
 2513                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2514                    });
 2515
 2516                clicked_point_already_selected.map(|selection| selection.id)
 2517            }
 2518        };
 2519
 2520        let selections_count = self.selections.count();
 2521
 2522        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2523            if let Some(point_to_delete) = point_to_delete {
 2524                s.delete(point_to_delete);
 2525
 2526                if selections_count == 1 {
 2527                    s.set_pending_anchor_range(start..end, mode);
 2528                }
 2529            } else {
 2530                if !add {
 2531                    s.clear_disjoint();
 2532                } else if click_count > 1 {
 2533                    s.delete(newest_selection.id)
 2534                }
 2535
 2536                s.set_pending_anchor_range(start..end, mode);
 2537            }
 2538        });
 2539    }
 2540
 2541    fn begin_columnar_selection(
 2542        &mut self,
 2543        position: DisplayPoint,
 2544        goal_column: u32,
 2545        reset: bool,
 2546        window: &mut Window,
 2547        cx: &mut Context<Self>,
 2548    ) {
 2549        if !self.focus_handle.is_focused(window) {
 2550            self.last_focused_descendant = None;
 2551            window.focus(&self.focus_handle);
 2552        }
 2553
 2554        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2555
 2556        if reset {
 2557            let pointer_position = display_map
 2558                .buffer_snapshot
 2559                .anchor_before(position.to_point(&display_map));
 2560
 2561            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2562                s.clear_disjoint();
 2563                s.set_pending_anchor_range(
 2564                    pointer_position..pointer_position,
 2565                    SelectMode::Character,
 2566                );
 2567            });
 2568        }
 2569
 2570        let tail = self.selections.newest::<Point>(cx).tail();
 2571        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2572
 2573        if !reset {
 2574            self.select_columns(
 2575                tail.to_display_point(&display_map),
 2576                position,
 2577                goal_column,
 2578                &display_map,
 2579                window,
 2580                cx,
 2581            );
 2582        }
 2583    }
 2584
 2585    fn update_selection(
 2586        &mut self,
 2587        position: DisplayPoint,
 2588        goal_column: u32,
 2589        scroll_delta: gpui::Point<f32>,
 2590        window: &mut Window,
 2591        cx: &mut Context<Self>,
 2592    ) {
 2593        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2594
 2595        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2596            let tail = tail.to_display_point(&display_map);
 2597            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2598        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2599            let buffer = self.buffer.read(cx).snapshot(cx);
 2600            let head;
 2601            let tail;
 2602            let mode = self.selections.pending_mode().unwrap();
 2603            match &mode {
 2604                SelectMode::Character => {
 2605                    head = position.to_point(&display_map);
 2606                    tail = pending.tail().to_point(&buffer);
 2607                }
 2608                SelectMode::Word(original_range) => {
 2609                    let original_display_range = original_range.start.to_display_point(&display_map)
 2610                        ..original_range.end.to_display_point(&display_map);
 2611                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2612                        ..original_display_range.end.to_point(&display_map);
 2613                    if movement::is_inside_word(&display_map, position)
 2614                        || original_display_range.contains(&position)
 2615                    {
 2616                        let word_range = movement::surrounding_word(&display_map, position);
 2617                        if word_range.start < original_display_range.start {
 2618                            head = word_range.start.to_point(&display_map);
 2619                        } else {
 2620                            head = word_range.end.to_point(&display_map);
 2621                        }
 2622                    } else {
 2623                        head = position.to_point(&display_map);
 2624                    }
 2625
 2626                    if head <= original_buffer_range.start {
 2627                        tail = original_buffer_range.end;
 2628                    } else {
 2629                        tail = original_buffer_range.start;
 2630                    }
 2631                }
 2632                SelectMode::Line(original_range) => {
 2633                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2634
 2635                    let position = display_map
 2636                        .clip_point(position, Bias::Left)
 2637                        .to_point(&display_map);
 2638                    let line_start = display_map.prev_line_boundary(position).0;
 2639                    let next_line_start = buffer.clip_point(
 2640                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2641                        Bias::Left,
 2642                    );
 2643
 2644                    if line_start < original_range.start {
 2645                        head = line_start
 2646                    } else {
 2647                        head = next_line_start
 2648                    }
 2649
 2650                    if head <= original_range.start {
 2651                        tail = original_range.end;
 2652                    } else {
 2653                        tail = original_range.start;
 2654                    }
 2655                }
 2656                SelectMode::All => {
 2657                    return;
 2658                }
 2659            };
 2660
 2661            if head < tail {
 2662                pending.start = buffer.anchor_before(head);
 2663                pending.end = buffer.anchor_before(tail);
 2664                pending.reversed = true;
 2665            } else {
 2666                pending.start = buffer.anchor_before(tail);
 2667                pending.end = buffer.anchor_before(head);
 2668                pending.reversed = false;
 2669            }
 2670
 2671            self.change_selections(None, window, cx, |s| {
 2672                s.set_pending(pending, mode);
 2673            });
 2674        } else {
 2675            log::error!("update_selection dispatched with no pending selection");
 2676            return;
 2677        }
 2678
 2679        self.apply_scroll_delta(scroll_delta, window, cx);
 2680        cx.notify();
 2681    }
 2682
 2683    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2684        self.columnar_selection_tail.take();
 2685        if self.selections.pending_anchor().is_some() {
 2686            let selections = self.selections.all::<usize>(cx);
 2687            self.change_selections(None, window, cx, |s| {
 2688                s.select(selections);
 2689                s.clear_pending();
 2690            });
 2691        }
 2692    }
 2693
 2694    fn select_columns(
 2695        &mut self,
 2696        tail: DisplayPoint,
 2697        head: DisplayPoint,
 2698        goal_column: u32,
 2699        display_map: &DisplaySnapshot,
 2700        window: &mut Window,
 2701        cx: &mut Context<Self>,
 2702    ) {
 2703        let start_row = cmp::min(tail.row(), head.row());
 2704        let end_row = cmp::max(tail.row(), head.row());
 2705        let start_column = cmp::min(tail.column(), goal_column);
 2706        let end_column = cmp::max(tail.column(), goal_column);
 2707        let reversed = start_column < tail.column();
 2708
 2709        let selection_ranges = (start_row.0..=end_row.0)
 2710            .map(DisplayRow)
 2711            .filter_map(|row| {
 2712                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2713                    let start = display_map
 2714                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2715                        .to_point(display_map);
 2716                    let end = display_map
 2717                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2718                        .to_point(display_map);
 2719                    if reversed {
 2720                        Some(end..start)
 2721                    } else {
 2722                        Some(start..end)
 2723                    }
 2724                } else {
 2725                    None
 2726                }
 2727            })
 2728            .collect::<Vec<_>>();
 2729
 2730        self.change_selections(None, window, cx, |s| {
 2731            s.select_ranges(selection_ranges);
 2732        });
 2733        cx.notify();
 2734    }
 2735
 2736    pub fn has_pending_nonempty_selection(&self) -> bool {
 2737        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2738            Some(Selection { start, end, .. }) => start != end,
 2739            None => false,
 2740        };
 2741
 2742        pending_nonempty_selection
 2743            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2744    }
 2745
 2746    pub fn has_pending_selection(&self) -> bool {
 2747        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2748    }
 2749
 2750    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2751        self.selection_mark_mode = false;
 2752
 2753        if self.clear_expanded_diff_hunks(cx) {
 2754            cx.notify();
 2755            return;
 2756        }
 2757        if self.dismiss_menus_and_popups(true, window, cx) {
 2758            return;
 2759        }
 2760
 2761        if self.mode == EditorMode::Full
 2762            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2763        {
 2764            return;
 2765        }
 2766
 2767        cx.propagate();
 2768    }
 2769
 2770    pub fn dismiss_menus_and_popups(
 2771        &mut self,
 2772        is_user_requested: bool,
 2773        window: &mut Window,
 2774        cx: &mut Context<Self>,
 2775    ) -> bool {
 2776        if self.take_rename(false, window, cx).is_some() {
 2777            return true;
 2778        }
 2779
 2780        if hide_hover(self, cx) {
 2781            return true;
 2782        }
 2783
 2784        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2785            return true;
 2786        }
 2787
 2788        if self.hide_context_menu(window, cx).is_some() {
 2789            return true;
 2790        }
 2791
 2792        if self.mouse_context_menu.take().is_some() {
 2793            return true;
 2794        }
 2795
 2796        if is_user_requested && self.discard_inline_completion(true, cx) {
 2797            return true;
 2798        }
 2799
 2800        if self.snippet_stack.pop().is_some() {
 2801            return true;
 2802        }
 2803
 2804        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2805            self.dismiss_diagnostics(cx);
 2806            return true;
 2807        }
 2808
 2809        false
 2810    }
 2811
 2812    fn linked_editing_ranges_for(
 2813        &self,
 2814        selection: Range<text::Anchor>,
 2815        cx: &App,
 2816    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2817        if self.linked_edit_ranges.is_empty() {
 2818            return None;
 2819        }
 2820        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2821            selection.end.buffer_id.and_then(|end_buffer_id| {
 2822                if selection.start.buffer_id != Some(end_buffer_id) {
 2823                    return None;
 2824                }
 2825                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2826                let snapshot = buffer.read(cx).snapshot();
 2827                self.linked_edit_ranges
 2828                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2829                    .map(|ranges| (ranges, snapshot, buffer))
 2830            })?;
 2831        use text::ToOffset as TO;
 2832        // find offset from the start of current range to current cursor position
 2833        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2834
 2835        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2836        let start_difference = start_offset - start_byte_offset;
 2837        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2838        let end_difference = end_offset - start_byte_offset;
 2839        // Current range has associated linked ranges.
 2840        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2841        for range in linked_ranges.iter() {
 2842            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2843            let end_offset = start_offset + end_difference;
 2844            let start_offset = start_offset + start_difference;
 2845            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2846                continue;
 2847            }
 2848            if self.selections.disjoint_anchor_ranges().any(|s| {
 2849                if s.start.buffer_id != selection.start.buffer_id
 2850                    || s.end.buffer_id != selection.end.buffer_id
 2851                {
 2852                    return false;
 2853                }
 2854                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2855                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2856            }) {
 2857                continue;
 2858            }
 2859            let start = buffer_snapshot.anchor_after(start_offset);
 2860            let end = buffer_snapshot.anchor_after(end_offset);
 2861            linked_edits
 2862                .entry(buffer.clone())
 2863                .or_default()
 2864                .push(start..end);
 2865        }
 2866        Some(linked_edits)
 2867    }
 2868
 2869    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2870        let text: Arc<str> = text.into();
 2871
 2872        if self.read_only(cx) {
 2873            return;
 2874        }
 2875
 2876        let selections = self.selections.all_adjusted(cx);
 2877        let mut bracket_inserted = false;
 2878        let mut edits = Vec::new();
 2879        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2880        let mut new_selections = Vec::with_capacity(selections.len());
 2881        let mut new_autoclose_regions = Vec::new();
 2882        let snapshot = self.buffer.read(cx).read(cx);
 2883
 2884        for (selection, autoclose_region) in
 2885            self.selections_with_autoclose_regions(selections, &snapshot)
 2886        {
 2887            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2888                // Determine if the inserted text matches the opening or closing
 2889                // bracket of any of this language's bracket pairs.
 2890                let mut bracket_pair = None;
 2891                let mut is_bracket_pair_start = false;
 2892                let mut is_bracket_pair_end = false;
 2893                if !text.is_empty() {
 2894                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2895                    //  and they are removing the character that triggered IME popup.
 2896                    for (pair, enabled) in scope.brackets() {
 2897                        if !pair.close && !pair.surround {
 2898                            continue;
 2899                        }
 2900
 2901                        if enabled && pair.start.ends_with(text.as_ref()) {
 2902                            let prefix_len = pair.start.len() - text.len();
 2903                            let preceding_text_matches_prefix = prefix_len == 0
 2904                                || (selection.start.column >= (prefix_len as u32)
 2905                                    && snapshot.contains_str_at(
 2906                                        Point::new(
 2907                                            selection.start.row,
 2908                                            selection.start.column - (prefix_len as u32),
 2909                                        ),
 2910                                        &pair.start[..prefix_len],
 2911                                    ));
 2912                            if preceding_text_matches_prefix {
 2913                                bracket_pair = Some(pair.clone());
 2914                                is_bracket_pair_start = true;
 2915                                break;
 2916                            }
 2917                        }
 2918                        if pair.end.as_str() == text.as_ref() {
 2919                            bracket_pair = Some(pair.clone());
 2920                            is_bracket_pair_end = true;
 2921                            break;
 2922                        }
 2923                    }
 2924                }
 2925
 2926                if let Some(bracket_pair) = bracket_pair {
 2927                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 2928                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2929                    let auto_surround =
 2930                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2931                    if selection.is_empty() {
 2932                        if is_bracket_pair_start {
 2933                            // If the inserted text is a suffix of an opening bracket and the
 2934                            // selection is preceded by the rest of the opening bracket, then
 2935                            // insert the closing bracket.
 2936                            let following_text_allows_autoclose = snapshot
 2937                                .chars_at(selection.start)
 2938                                .next()
 2939                                .map_or(true, |c| scope.should_autoclose_before(c));
 2940
 2941                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2942                                && bracket_pair.start.len() == 1
 2943                            {
 2944                                let target = bracket_pair.start.chars().next().unwrap();
 2945                                let current_line_count = snapshot
 2946                                    .reversed_chars_at(selection.start)
 2947                                    .take_while(|&c| c != '\n')
 2948                                    .filter(|&c| c == target)
 2949                                    .count();
 2950                                current_line_count % 2 == 1
 2951                            } else {
 2952                                false
 2953                            };
 2954
 2955                            if autoclose
 2956                                && bracket_pair.close
 2957                                && following_text_allows_autoclose
 2958                                && !is_closing_quote
 2959                            {
 2960                                let anchor = snapshot.anchor_before(selection.end);
 2961                                new_selections.push((selection.map(|_| anchor), text.len()));
 2962                                new_autoclose_regions.push((
 2963                                    anchor,
 2964                                    text.len(),
 2965                                    selection.id,
 2966                                    bracket_pair.clone(),
 2967                                ));
 2968                                edits.push((
 2969                                    selection.range(),
 2970                                    format!("{}{}", text, bracket_pair.end).into(),
 2971                                ));
 2972                                bracket_inserted = true;
 2973                                continue;
 2974                            }
 2975                        }
 2976
 2977                        if let Some(region) = autoclose_region {
 2978                            // If the selection is followed by an auto-inserted closing bracket,
 2979                            // then don't insert that closing bracket again; just move the selection
 2980                            // past the closing bracket.
 2981                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2982                                && text.as_ref() == region.pair.end.as_str();
 2983                            if should_skip {
 2984                                let anchor = snapshot.anchor_after(selection.end);
 2985                                new_selections
 2986                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2987                                continue;
 2988                            }
 2989                        }
 2990
 2991                        let always_treat_brackets_as_autoclosed = snapshot
 2992                            .language_settings_at(selection.start, cx)
 2993                            .always_treat_brackets_as_autoclosed;
 2994                        if always_treat_brackets_as_autoclosed
 2995                            && is_bracket_pair_end
 2996                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2997                        {
 2998                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2999                            // and the inserted text is a closing bracket and the selection is followed
 3000                            // by the closing bracket then move the selection past the closing bracket.
 3001                            let anchor = snapshot.anchor_after(selection.end);
 3002                            new_selections.push((selection.map(|_| anchor), text.len()));
 3003                            continue;
 3004                        }
 3005                    }
 3006                    // If an opening bracket is 1 character long and is typed while
 3007                    // text is selected, then surround that text with the bracket pair.
 3008                    else if auto_surround
 3009                        && bracket_pair.surround
 3010                        && is_bracket_pair_start
 3011                        && bracket_pair.start.chars().count() == 1
 3012                    {
 3013                        edits.push((selection.start..selection.start, text.clone()));
 3014                        edits.push((
 3015                            selection.end..selection.end,
 3016                            bracket_pair.end.as_str().into(),
 3017                        ));
 3018                        bracket_inserted = true;
 3019                        new_selections.push((
 3020                            Selection {
 3021                                id: selection.id,
 3022                                start: snapshot.anchor_after(selection.start),
 3023                                end: snapshot.anchor_before(selection.end),
 3024                                reversed: selection.reversed,
 3025                                goal: selection.goal,
 3026                            },
 3027                            0,
 3028                        ));
 3029                        continue;
 3030                    }
 3031                }
 3032            }
 3033
 3034            if self.auto_replace_emoji_shortcode
 3035                && selection.is_empty()
 3036                && text.as_ref().ends_with(':')
 3037            {
 3038                if let Some(possible_emoji_short_code) =
 3039                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3040                {
 3041                    if !possible_emoji_short_code.is_empty() {
 3042                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3043                            let emoji_shortcode_start = Point::new(
 3044                                selection.start.row,
 3045                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3046                            );
 3047
 3048                            // Remove shortcode from buffer
 3049                            edits.push((
 3050                                emoji_shortcode_start..selection.start,
 3051                                "".to_string().into(),
 3052                            ));
 3053                            new_selections.push((
 3054                                Selection {
 3055                                    id: selection.id,
 3056                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3057                                    end: snapshot.anchor_before(selection.start),
 3058                                    reversed: selection.reversed,
 3059                                    goal: selection.goal,
 3060                                },
 3061                                0,
 3062                            ));
 3063
 3064                            // Insert emoji
 3065                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3066                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3067                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3068
 3069                            continue;
 3070                        }
 3071                    }
 3072                }
 3073            }
 3074
 3075            // If not handling any auto-close operation, then just replace the selected
 3076            // text with the given input and move the selection to the end of the
 3077            // newly inserted text.
 3078            let anchor = snapshot.anchor_after(selection.end);
 3079            if !self.linked_edit_ranges.is_empty() {
 3080                let start_anchor = snapshot.anchor_before(selection.start);
 3081
 3082                let is_word_char = text.chars().next().map_or(true, |char| {
 3083                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3084                    classifier.is_word(char)
 3085                });
 3086
 3087                if is_word_char {
 3088                    if let Some(ranges) = self
 3089                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3090                    {
 3091                        for (buffer, edits) in ranges {
 3092                            linked_edits
 3093                                .entry(buffer.clone())
 3094                                .or_default()
 3095                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3096                        }
 3097                    }
 3098                }
 3099            }
 3100
 3101            new_selections.push((selection.map(|_| anchor), 0));
 3102            edits.push((selection.start..selection.end, text.clone()));
 3103        }
 3104
 3105        drop(snapshot);
 3106
 3107        self.transact(window, cx, |this, window, cx| {
 3108            let initial_buffer_versions =
 3109                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3110
 3111            this.buffer.update(cx, |buffer, cx| {
 3112                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3113            });
 3114            for (buffer, edits) in linked_edits {
 3115                buffer.update(cx, |buffer, cx| {
 3116                    let snapshot = buffer.snapshot();
 3117                    let edits = edits
 3118                        .into_iter()
 3119                        .map(|(range, text)| {
 3120                            use text::ToPoint as TP;
 3121                            let end_point = TP::to_point(&range.end, &snapshot);
 3122                            let start_point = TP::to_point(&range.start, &snapshot);
 3123                            (start_point..end_point, text)
 3124                        })
 3125                        .sorted_by_key(|(range, _)| range.start)
 3126                        .collect::<Vec<_>>();
 3127                    buffer.edit(edits, None, cx);
 3128                })
 3129            }
 3130            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3131            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3132            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3133            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3134                .zip(new_selection_deltas)
 3135                .map(|(selection, delta)| Selection {
 3136                    id: selection.id,
 3137                    start: selection.start + delta,
 3138                    end: selection.end + delta,
 3139                    reversed: selection.reversed,
 3140                    goal: SelectionGoal::None,
 3141                })
 3142                .collect::<Vec<_>>();
 3143
 3144            let mut i = 0;
 3145            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3146                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3147                let start = map.buffer_snapshot.anchor_before(position);
 3148                let end = map.buffer_snapshot.anchor_after(position);
 3149                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3150                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3151                        Ordering::Less => i += 1,
 3152                        Ordering::Greater => break,
 3153                        Ordering::Equal => {
 3154                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3155                                Ordering::Less => i += 1,
 3156                                Ordering::Equal => break,
 3157                                Ordering::Greater => break,
 3158                            }
 3159                        }
 3160                    }
 3161                }
 3162                this.autoclose_regions.insert(
 3163                    i,
 3164                    AutocloseRegion {
 3165                        selection_id,
 3166                        range: start..end,
 3167                        pair,
 3168                    },
 3169                );
 3170            }
 3171
 3172            let had_active_inline_completion = this.has_active_inline_completion();
 3173            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3174                s.select(new_selections)
 3175            });
 3176
 3177            if !bracket_inserted {
 3178                if let Some(on_type_format_task) =
 3179                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3180                {
 3181                    on_type_format_task.detach_and_log_err(cx);
 3182                }
 3183            }
 3184
 3185            let editor_settings = EditorSettings::get_global(cx);
 3186            if bracket_inserted
 3187                && (editor_settings.auto_signature_help
 3188                    || editor_settings.show_signature_help_after_edits)
 3189            {
 3190                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3191            }
 3192
 3193            let trigger_in_words =
 3194                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3195            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3196            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3197            this.refresh_inline_completion(true, false, window, cx);
 3198            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3199        });
 3200    }
 3201
 3202    fn find_possible_emoji_shortcode_at_position(
 3203        snapshot: &MultiBufferSnapshot,
 3204        position: Point,
 3205    ) -> Option<String> {
 3206        let mut chars = Vec::new();
 3207        let mut found_colon = false;
 3208        for char in snapshot.reversed_chars_at(position).take(100) {
 3209            // Found a possible emoji shortcode in the middle of the buffer
 3210            if found_colon {
 3211                if char.is_whitespace() {
 3212                    chars.reverse();
 3213                    return Some(chars.iter().collect());
 3214                }
 3215                // If the previous character is not a whitespace, we are in the middle of a word
 3216                // and we only want to complete the shortcode if the word is made up of other emojis
 3217                let mut containing_word = String::new();
 3218                for ch in snapshot
 3219                    .reversed_chars_at(position)
 3220                    .skip(chars.len() + 1)
 3221                    .take(100)
 3222                {
 3223                    if ch.is_whitespace() {
 3224                        break;
 3225                    }
 3226                    containing_word.push(ch);
 3227                }
 3228                let containing_word = containing_word.chars().rev().collect::<String>();
 3229                if util::word_consists_of_emojis(containing_word.as_str()) {
 3230                    chars.reverse();
 3231                    return Some(chars.iter().collect());
 3232                }
 3233            }
 3234
 3235            if char.is_whitespace() || !char.is_ascii() {
 3236                return None;
 3237            }
 3238            if char == ':' {
 3239                found_colon = true;
 3240            } else {
 3241                chars.push(char);
 3242            }
 3243        }
 3244        // Found a possible emoji shortcode at the beginning of the buffer
 3245        chars.reverse();
 3246        Some(chars.iter().collect())
 3247    }
 3248
 3249    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3250        self.transact(window, cx, |this, window, cx| {
 3251            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3252                let selections = this.selections.all::<usize>(cx);
 3253                let multi_buffer = this.buffer.read(cx);
 3254                let buffer = multi_buffer.snapshot(cx);
 3255                selections
 3256                    .iter()
 3257                    .map(|selection| {
 3258                        let start_point = selection.start.to_point(&buffer);
 3259                        let mut indent =
 3260                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3261                        indent.len = cmp::min(indent.len, start_point.column);
 3262                        let start = selection.start;
 3263                        let end = selection.end;
 3264                        let selection_is_empty = start == end;
 3265                        let language_scope = buffer.language_scope_at(start);
 3266                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3267                            &language_scope
 3268                        {
 3269                            let insert_extra_newline =
 3270                                insert_extra_newline_brackets(&buffer, start..end, language)
 3271                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3272
 3273                            // Comment extension on newline is allowed only for cursor selections
 3274                            let comment_delimiter = maybe!({
 3275                                if !selection_is_empty {
 3276                                    return None;
 3277                                }
 3278
 3279                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3280                                    return None;
 3281                                }
 3282
 3283                                let delimiters = language.line_comment_prefixes();
 3284                                let max_len_of_delimiter =
 3285                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3286                                let (snapshot, range) =
 3287                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3288
 3289                                let mut index_of_first_non_whitespace = 0;
 3290                                let comment_candidate = snapshot
 3291                                    .chars_for_range(range)
 3292                                    .skip_while(|c| {
 3293                                        let should_skip = c.is_whitespace();
 3294                                        if should_skip {
 3295                                            index_of_first_non_whitespace += 1;
 3296                                        }
 3297                                        should_skip
 3298                                    })
 3299                                    .take(max_len_of_delimiter)
 3300                                    .collect::<String>();
 3301                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3302                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3303                                })?;
 3304                                let cursor_is_placed_after_comment_marker =
 3305                                    index_of_first_non_whitespace + comment_prefix.len()
 3306                                        <= start_point.column as usize;
 3307                                if cursor_is_placed_after_comment_marker {
 3308                                    Some(comment_prefix.clone())
 3309                                } else {
 3310                                    None
 3311                                }
 3312                            });
 3313                            (comment_delimiter, insert_extra_newline)
 3314                        } else {
 3315                            (None, false)
 3316                        };
 3317
 3318                        let capacity_for_delimiter = comment_delimiter
 3319                            .as_deref()
 3320                            .map(str::len)
 3321                            .unwrap_or_default();
 3322                        let mut new_text =
 3323                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3324                        new_text.push('\n');
 3325                        new_text.extend(indent.chars());
 3326                        if let Some(delimiter) = &comment_delimiter {
 3327                            new_text.push_str(delimiter);
 3328                        }
 3329                        if insert_extra_newline {
 3330                            new_text = new_text.repeat(2);
 3331                        }
 3332
 3333                        let anchor = buffer.anchor_after(end);
 3334                        let new_selection = selection.map(|_| anchor);
 3335                        (
 3336                            (start..end, new_text),
 3337                            (insert_extra_newline, new_selection),
 3338                        )
 3339                    })
 3340                    .unzip()
 3341            };
 3342
 3343            this.edit_with_autoindent(edits, cx);
 3344            let buffer = this.buffer.read(cx).snapshot(cx);
 3345            let new_selections = selection_fixup_info
 3346                .into_iter()
 3347                .map(|(extra_newline_inserted, new_selection)| {
 3348                    let mut cursor = new_selection.end.to_point(&buffer);
 3349                    if extra_newline_inserted {
 3350                        cursor.row -= 1;
 3351                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3352                    }
 3353                    new_selection.map(|_| cursor)
 3354                })
 3355                .collect();
 3356
 3357            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3358                s.select(new_selections)
 3359            });
 3360            this.refresh_inline_completion(true, false, window, cx);
 3361        });
 3362    }
 3363
 3364    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3365        let buffer = self.buffer.read(cx);
 3366        let snapshot = buffer.snapshot(cx);
 3367
 3368        let mut edits = Vec::new();
 3369        let mut rows = Vec::new();
 3370
 3371        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3372            let cursor = selection.head();
 3373            let row = cursor.row;
 3374
 3375            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3376
 3377            let newline = "\n".to_string();
 3378            edits.push((start_of_line..start_of_line, newline));
 3379
 3380            rows.push(row + rows_inserted as u32);
 3381        }
 3382
 3383        self.transact(window, cx, |editor, window, cx| {
 3384            editor.edit(edits, cx);
 3385
 3386            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3387                let mut index = 0;
 3388                s.move_cursors_with(|map, _, _| {
 3389                    let row = rows[index];
 3390                    index += 1;
 3391
 3392                    let point = Point::new(row, 0);
 3393                    let boundary = map.next_line_boundary(point).1;
 3394                    let clipped = map.clip_point(boundary, Bias::Left);
 3395
 3396                    (clipped, SelectionGoal::None)
 3397                });
 3398            });
 3399
 3400            let mut indent_edits = Vec::new();
 3401            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3402            for row in rows {
 3403                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3404                for (row, indent) in indents {
 3405                    if indent.len == 0 {
 3406                        continue;
 3407                    }
 3408
 3409                    let text = match indent.kind {
 3410                        IndentKind::Space => " ".repeat(indent.len as usize),
 3411                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3412                    };
 3413                    let point = Point::new(row.0, 0);
 3414                    indent_edits.push((point..point, text));
 3415                }
 3416            }
 3417            editor.edit(indent_edits, cx);
 3418        });
 3419    }
 3420
 3421    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3422        let buffer = self.buffer.read(cx);
 3423        let snapshot = buffer.snapshot(cx);
 3424
 3425        let mut edits = Vec::new();
 3426        let mut rows = Vec::new();
 3427        let mut rows_inserted = 0;
 3428
 3429        for selection in self.selections.all_adjusted(cx) {
 3430            let cursor = selection.head();
 3431            let row = cursor.row;
 3432
 3433            let point = Point::new(row + 1, 0);
 3434            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3435
 3436            let newline = "\n".to_string();
 3437            edits.push((start_of_line..start_of_line, newline));
 3438
 3439            rows_inserted += 1;
 3440            rows.push(row + rows_inserted);
 3441        }
 3442
 3443        self.transact(window, cx, |editor, window, cx| {
 3444            editor.edit(edits, cx);
 3445
 3446            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3447                let mut index = 0;
 3448                s.move_cursors_with(|map, _, _| {
 3449                    let row = rows[index];
 3450                    index += 1;
 3451
 3452                    let point = Point::new(row, 0);
 3453                    let boundary = map.next_line_boundary(point).1;
 3454                    let clipped = map.clip_point(boundary, Bias::Left);
 3455
 3456                    (clipped, SelectionGoal::None)
 3457                });
 3458            });
 3459
 3460            let mut indent_edits = Vec::new();
 3461            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3462            for row in rows {
 3463                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3464                for (row, indent) in indents {
 3465                    if indent.len == 0 {
 3466                        continue;
 3467                    }
 3468
 3469                    let text = match indent.kind {
 3470                        IndentKind::Space => " ".repeat(indent.len as usize),
 3471                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3472                    };
 3473                    let point = Point::new(row.0, 0);
 3474                    indent_edits.push((point..point, text));
 3475                }
 3476            }
 3477            editor.edit(indent_edits, cx);
 3478        });
 3479    }
 3480
 3481    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3482        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3483            original_indent_columns: Vec::new(),
 3484        });
 3485        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3486    }
 3487
 3488    fn insert_with_autoindent_mode(
 3489        &mut self,
 3490        text: &str,
 3491        autoindent_mode: Option<AutoindentMode>,
 3492        window: &mut Window,
 3493        cx: &mut Context<Self>,
 3494    ) {
 3495        if self.read_only(cx) {
 3496            return;
 3497        }
 3498
 3499        let text: Arc<str> = text.into();
 3500        self.transact(window, cx, |this, window, cx| {
 3501            let old_selections = this.selections.all_adjusted(cx);
 3502            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3503                let anchors = {
 3504                    let snapshot = buffer.read(cx);
 3505                    old_selections
 3506                        .iter()
 3507                        .map(|s| {
 3508                            let anchor = snapshot.anchor_after(s.head());
 3509                            s.map(|_| anchor)
 3510                        })
 3511                        .collect::<Vec<_>>()
 3512                };
 3513                buffer.edit(
 3514                    old_selections
 3515                        .iter()
 3516                        .map(|s| (s.start..s.end, text.clone())),
 3517                    autoindent_mode,
 3518                    cx,
 3519                );
 3520                anchors
 3521            });
 3522
 3523            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3524                s.select_anchors(selection_anchors);
 3525            });
 3526
 3527            cx.notify();
 3528        });
 3529    }
 3530
 3531    fn trigger_completion_on_input(
 3532        &mut self,
 3533        text: &str,
 3534        trigger_in_words: bool,
 3535        window: &mut Window,
 3536        cx: &mut Context<Self>,
 3537    ) {
 3538        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3539            self.show_completions(
 3540                &ShowCompletions {
 3541                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3542                },
 3543                window,
 3544                cx,
 3545            );
 3546        } else {
 3547            self.hide_context_menu(window, cx);
 3548        }
 3549    }
 3550
 3551    fn is_completion_trigger(
 3552        &self,
 3553        text: &str,
 3554        trigger_in_words: bool,
 3555        cx: &mut Context<Self>,
 3556    ) -> bool {
 3557        let position = self.selections.newest_anchor().head();
 3558        let multibuffer = self.buffer.read(cx);
 3559        let Some(buffer) = position
 3560            .buffer_id
 3561            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3562        else {
 3563            return false;
 3564        };
 3565
 3566        if let Some(completion_provider) = &self.completion_provider {
 3567            completion_provider.is_completion_trigger(
 3568                &buffer,
 3569                position.text_anchor,
 3570                text,
 3571                trigger_in_words,
 3572                cx,
 3573            )
 3574        } else {
 3575            false
 3576        }
 3577    }
 3578
 3579    /// If any empty selections is touching the start of its innermost containing autoclose
 3580    /// region, expand it to select the brackets.
 3581    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3582        let selections = self.selections.all::<usize>(cx);
 3583        let buffer = self.buffer.read(cx).read(cx);
 3584        let new_selections = self
 3585            .selections_with_autoclose_regions(selections, &buffer)
 3586            .map(|(mut selection, region)| {
 3587                if !selection.is_empty() {
 3588                    return selection;
 3589                }
 3590
 3591                if let Some(region) = region {
 3592                    let mut range = region.range.to_offset(&buffer);
 3593                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3594                        range.start -= region.pair.start.len();
 3595                        if buffer.contains_str_at(range.start, &region.pair.start)
 3596                            && buffer.contains_str_at(range.end, &region.pair.end)
 3597                        {
 3598                            range.end += region.pair.end.len();
 3599                            selection.start = range.start;
 3600                            selection.end = range.end;
 3601
 3602                            return selection;
 3603                        }
 3604                    }
 3605                }
 3606
 3607                let always_treat_brackets_as_autoclosed = buffer
 3608                    .language_settings_at(selection.start, cx)
 3609                    .always_treat_brackets_as_autoclosed;
 3610
 3611                if !always_treat_brackets_as_autoclosed {
 3612                    return selection;
 3613                }
 3614
 3615                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3616                    for (pair, enabled) in scope.brackets() {
 3617                        if !enabled || !pair.close {
 3618                            continue;
 3619                        }
 3620
 3621                        if buffer.contains_str_at(selection.start, &pair.end) {
 3622                            let pair_start_len = pair.start.len();
 3623                            if buffer.contains_str_at(
 3624                                selection.start.saturating_sub(pair_start_len),
 3625                                &pair.start,
 3626                            ) {
 3627                                selection.start -= pair_start_len;
 3628                                selection.end += pair.end.len();
 3629
 3630                                return selection;
 3631                            }
 3632                        }
 3633                    }
 3634                }
 3635
 3636                selection
 3637            })
 3638            .collect();
 3639
 3640        drop(buffer);
 3641        self.change_selections(None, window, cx, |selections| {
 3642            selections.select(new_selections)
 3643        });
 3644    }
 3645
 3646    /// Iterate the given selections, and for each one, find the smallest surrounding
 3647    /// autoclose region. This uses the ordering of the selections and the autoclose
 3648    /// regions to avoid repeated comparisons.
 3649    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3650        &'a self,
 3651        selections: impl IntoIterator<Item = Selection<D>>,
 3652        buffer: &'a MultiBufferSnapshot,
 3653    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3654        let mut i = 0;
 3655        let mut regions = self.autoclose_regions.as_slice();
 3656        selections.into_iter().map(move |selection| {
 3657            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3658
 3659            let mut enclosing = None;
 3660            while let Some(pair_state) = regions.get(i) {
 3661                if pair_state.range.end.to_offset(buffer) < range.start {
 3662                    regions = &regions[i + 1..];
 3663                    i = 0;
 3664                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3665                    break;
 3666                } else {
 3667                    if pair_state.selection_id == selection.id {
 3668                        enclosing = Some(pair_state);
 3669                    }
 3670                    i += 1;
 3671                }
 3672            }
 3673
 3674            (selection, enclosing)
 3675        })
 3676    }
 3677
 3678    /// Remove any autoclose regions that no longer contain their selection.
 3679    fn invalidate_autoclose_regions(
 3680        &mut self,
 3681        mut selections: &[Selection<Anchor>],
 3682        buffer: &MultiBufferSnapshot,
 3683    ) {
 3684        self.autoclose_regions.retain(|state| {
 3685            let mut i = 0;
 3686            while let Some(selection) = selections.get(i) {
 3687                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3688                    selections = &selections[1..];
 3689                    continue;
 3690                }
 3691                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3692                    break;
 3693                }
 3694                if selection.id == state.selection_id {
 3695                    return true;
 3696                } else {
 3697                    i += 1;
 3698                }
 3699            }
 3700            false
 3701        });
 3702    }
 3703
 3704    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3705        let offset = position.to_offset(buffer);
 3706        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3707        if offset > word_range.start && kind == Some(CharKind::Word) {
 3708            Some(
 3709                buffer
 3710                    .text_for_range(word_range.start..offset)
 3711                    .collect::<String>(),
 3712            )
 3713        } else {
 3714            None
 3715        }
 3716    }
 3717
 3718    pub fn toggle_inlay_hints(
 3719        &mut self,
 3720        _: &ToggleInlayHints,
 3721        _: &mut Window,
 3722        cx: &mut Context<Self>,
 3723    ) {
 3724        self.refresh_inlay_hints(
 3725            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 3726            cx,
 3727        );
 3728    }
 3729
 3730    pub fn inlay_hints_enabled(&self) -> bool {
 3731        self.inlay_hint_cache.enabled
 3732    }
 3733
 3734    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3735        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3736            return;
 3737        }
 3738
 3739        let reason_description = reason.description();
 3740        let ignore_debounce = matches!(
 3741            reason,
 3742            InlayHintRefreshReason::SettingsChange(_)
 3743                | InlayHintRefreshReason::Toggle(_)
 3744                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3745                | InlayHintRefreshReason::ModifiersChanged(_)
 3746        );
 3747        let (invalidate_cache, required_languages) = match reason {
 3748            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 3749                match self.inlay_hint_cache.modifiers_override(enabled) {
 3750                    Some(enabled) => {
 3751                        if enabled {
 3752                            (InvalidationStrategy::RefreshRequested, None)
 3753                        } else {
 3754                            self.splice_inlays(
 3755                                &self
 3756                                    .visible_inlay_hints(cx)
 3757                                    .iter()
 3758                                    .map(|inlay| inlay.id)
 3759                                    .collect::<Vec<InlayId>>(),
 3760                                Vec::new(),
 3761                                cx,
 3762                            );
 3763                            return;
 3764                        }
 3765                    }
 3766                    None => return,
 3767                }
 3768            }
 3769            InlayHintRefreshReason::Toggle(enabled) => {
 3770                if self.inlay_hint_cache.toggle(enabled) {
 3771                    if enabled {
 3772                        (InvalidationStrategy::RefreshRequested, None)
 3773                    } else {
 3774                        self.splice_inlays(
 3775                            &self
 3776                                .visible_inlay_hints(cx)
 3777                                .iter()
 3778                                .map(|inlay| inlay.id)
 3779                                .collect::<Vec<InlayId>>(),
 3780                            Vec::new(),
 3781                            cx,
 3782                        );
 3783                        return;
 3784                    }
 3785                } else {
 3786                    return;
 3787                }
 3788            }
 3789            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3790                match self.inlay_hint_cache.update_settings(
 3791                    &self.buffer,
 3792                    new_settings,
 3793                    self.visible_inlay_hints(cx),
 3794                    cx,
 3795                ) {
 3796                    ControlFlow::Break(Some(InlaySplice {
 3797                        to_remove,
 3798                        to_insert,
 3799                    })) => {
 3800                        self.splice_inlays(&to_remove, to_insert, cx);
 3801                        return;
 3802                    }
 3803                    ControlFlow::Break(None) => return,
 3804                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3805                }
 3806            }
 3807            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3808                if let Some(InlaySplice {
 3809                    to_remove,
 3810                    to_insert,
 3811                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3812                {
 3813                    self.splice_inlays(&to_remove, to_insert, cx);
 3814                }
 3815                return;
 3816            }
 3817            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3818            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3819                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3820            }
 3821            InlayHintRefreshReason::RefreshRequested => {
 3822                (InvalidationStrategy::RefreshRequested, None)
 3823            }
 3824        };
 3825
 3826        if let Some(InlaySplice {
 3827            to_remove,
 3828            to_insert,
 3829        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3830            reason_description,
 3831            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3832            invalidate_cache,
 3833            ignore_debounce,
 3834            cx,
 3835        ) {
 3836            self.splice_inlays(&to_remove, to_insert, cx);
 3837        }
 3838    }
 3839
 3840    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3841        self.display_map
 3842            .read(cx)
 3843            .current_inlays()
 3844            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3845            .cloned()
 3846            .collect()
 3847    }
 3848
 3849    pub fn excerpts_for_inlay_hints_query(
 3850        &self,
 3851        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3852        cx: &mut Context<Editor>,
 3853    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3854        let Some(project) = self.project.as_ref() else {
 3855            return HashMap::default();
 3856        };
 3857        let project = project.read(cx);
 3858        let multi_buffer = self.buffer().read(cx);
 3859        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3860        let multi_buffer_visible_start = self
 3861            .scroll_manager
 3862            .anchor()
 3863            .anchor
 3864            .to_point(&multi_buffer_snapshot);
 3865        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3866            multi_buffer_visible_start
 3867                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3868            Bias::Left,
 3869        );
 3870        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3871        multi_buffer_snapshot
 3872            .range_to_buffer_ranges(multi_buffer_visible_range)
 3873            .into_iter()
 3874            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3875            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3876                let buffer_file = project::File::from_dyn(buffer.file())?;
 3877                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3878                let worktree_entry = buffer_worktree
 3879                    .read(cx)
 3880                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3881                if worktree_entry.is_ignored {
 3882                    return None;
 3883                }
 3884
 3885                let language = buffer.language()?;
 3886                if let Some(restrict_to_languages) = restrict_to_languages {
 3887                    if !restrict_to_languages.contains(language) {
 3888                        return None;
 3889                    }
 3890                }
 3891                Some((
 3892                    excerpt_id,
 3893                    (
 3894                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3895                        buffer.version().clone(),
 3896                        excerpt_visible_range,
 3897                    ),
 3898                ))
 3899            })
 3900            .collect()
 3901    }
 3902
 3903    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3904        TextLayoutDetails {
 3905            text_system: window.text_system().clone(),
 3906            editor_style: self.style.clone().unwrap(),
 3907            rem_size: window.rem_size(),
 3908            scroll_anchor: self.scroll_manager.anchor(),
 3909            visible_rows: self.visible_line_count(),
 3910            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3911        }
 3912    }
 3913
 3914    pub fn splice_inlays(
 3915        &self,
 3916        to_remove: &[InlayId],
 3917        to_insert: Vec<Inlay>,
 3918        cx: &mut Context<Self>,
 3919    ) {
 3920        self.display_map.update(cx, |display_map, cx| {
 3921            display_map.splice_inlays(to_remove, to_insert, cx)
 3922        });
 3923        cx.notify();
 3924    }
 3925
 3926    fn trigger_on_type_formatting(
 3927        &self,
 3928        input: String,
 3929        window: &mut Window,
 3930        cx: &mut Context<Self>,
 3931    ) -> Option<Task<Result<()>>> {
 3932        if input.len() != 1 {
 3933            return None;
 3934        }
 3935
 3936        let project = self.project.as_ref()?;
 3937        let position = self.selections.newest_anchor().head();
 3938        let (buffer, buffer_position) = self
 3939            .buffer
 3940            .read(cx)
 3941            .text_anchor_for_position(position, cx)?;
 3942
 3943        let settings = language_settings::language_settings(
 3944            buffer
 3945                .read(cx)
 3946                .language_at(buffer_position)
 3947                .map(|l| l.name()),
 3948            buffer.read(cx).file(),
 3949            cx,
 3950        );
 3951        if !settings.use_on_type_format {
 3952            return None;
 3953        }
 3954
 3955        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3956        // hence we do LSP request & edit on host side only — add formats to host's history.
 3957        let push_to_lsp_host_history = true;
 3958        // If this is not the host, append its history with new edits.
 3959        let push_to_client_history = project.read(cx).is_via_collab();
 3960
 3961        let on_type_formatting = project.update(cx, |project, cx| {
 3962            project.on_type_format(
 3963                buffer.clone(),
 3964                buffer_position,
 3965                input,
 3966                push_to_lsp_host_history,
 3967                cx,
 3968            )
 3969        });
 3970        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3971            if let Some(transaction) = on_type_formatting.await? {
 3972                if push_to_client_history {
 3973                    buffer
 3974                        .update(&mut cx, |buffer, _| {
 3975                            buffer.push_transaction(transaction, Instant::now());
 3976                        })
 3977                        .ok();
 3978                }
 3979                editor.update(&mut cx, |editor, cx| {
 3980                    editor.refresh_document_highlights(cx);
 3981                })?;
 3982            }
 3983            Ok(())
 3984        }))
 3985    }
 3986
 3987    pub fn show_completions(
 3988        &mut self,
 3989        options: &ShowCompletions,
 3990        window: &mut Window,
 3991        cx: &mut Context<Self>,
 3992    ) {
 3993        if self.pending_rename.is_some() {
 3994            return;
 3995        }
 3996
 3997        let Some(provider) = self.completion_provider.as_ref() else {
 3998            return;
 3999        };
 4000
 4001        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4002            return;
 4003        }
 4004
 4005        let position = self.selections.newest_anchor().head();
 4006        if position.diff_base_anchor.is_some() {
 4007            return;
 4008        }
 4009        let (buffer, buffer_position) =
 4010            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4011                output
 4012            } else {
 4013                return;
 4014            };
 4015        let show_completion_documentation = buffer
 4016            .read(cx)
 4017            .snapshot()
 4018            .settings_at(buffer_position, cx)
 4019            .show_completion_documentation;
 4020
 4021        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4022
 4023        let trigger_kind = match &options.trigger {
 4024            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4025                CompletionTriggerKind::TRIGGER_CHARACTER
 4026            }
 4027            _ => CompletionTriggerKind::INVOKED,
 4028        };
 4029        let completion_context = CompletionContext {
 4030            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4031                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4032                    Some(String::from(trigger))
 4033                } else {
 4034                    None
 4035                }
 4036            }),
 4037            trigger_kind,
 4038        };
 4039        let completions =
 4040            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 4041        let sort_completions = provider.sort_completions();
 4042
 4043        let id = post_inc(&mut self.next_completion_id);
 4044        let task = cx.spawn_in(window, |editor, mut cx| {
 4045            async move {
 4046                editor.update(&mut cx, |this, _| {
 4047                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4048                })?;
 4049                let completions = completions.await.log_err();
 4050                let menu = if let Some(completions) = completions {
 4051                    let mut menu = CompletionsMenu::new(
 4052                        id,
 4053                        sort_completions,
 4054                        show_completion_documentation,
 4055                        position,
 4056                        buffer.clone(),
 4057                        completions.into(),
 4058                    );
 4059
 4060                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4061                        .await;
 4062
 4063                    menu.visible().then_some(menu)
 4064                } else {
 4065                    None
 4066                };
 4067
 4068                editor.update_in(&mut cx, |editor, window, cx| {
 4069                    match editor.context_menu.borrow().as_ref() {
 4070                        None => {}
 4071                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4072                            if prev_menu.id > id {
 4073                                return;
 4074                            }
 4075                        }
 4076                        _ => return,
 4077                    }
 4078
 4079                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4080                        let mut menu = menu.unwrap();
 4081                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4082
 4083                        *editor.context_menu.borrow_mut() =
 4084                            Some(CodeContextMenu::Completions(menu));
 4085
 4086                        if editor.show_edit_predictions_in_menu() {
 4087                            editor.update_visible_inline_completion(window, cx);
 4088                        } else {
 4089                            editor.discard_inline_completion(false, cx);
 4090                        }
 4091
 4092                        cx.notify();
 4093                    } else if editor.completion_tasks.len() <= 1 {
 4094                        // If there are no more completion tasks and the last menu was
 4095                        // empty, we should hide it.
 4096                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4097                        // If it was already hidden and we don't show inline
 4098                        // completions in the menu, we should also show the
 4099                        // inline-completion when available.
 4100                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4101                            editor.update_visible_inline_completion(window, cx);
 4102                        }
 4103                    }
 4104                })?;
 4105
 4106                Ok::<_, anyhow::Error>(())
 4107            }
 4108            .log_err()
 4109        });
 4110
 4111        self.completion_tasks.push((id, task));
 4112    }
 4113
 4114    pub fn confirm_completion(
 4115        &mut self,
 4116        action: &ConfirmCompletion,
 4117        window: &mut Window,
 4118        cx: &mut Context<Self>,
 4119    ) -> Option<Task<Result<()>>> {
 4120        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4121    }
 4122
 4123    pub fn compose_completion(
 4124        &mut self,
 4125        action: &ComposeCompletion,
 4126        window: &mut Window,
 4127        cx: &mut Context<Self>,
 4128    ) -> Option<Task<Result<()>>> {
 4129        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4130    }
 4131
 4132    fn do_completion(
 4133        &mut self,
 4134        item_ix: Option<usize>,
 4135        intent: CompletionIntent,
 4136        window: &mut Window,
 4137        cx: &mut Context<Editor>,
 4138    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4139        use language::ToOffset as _;
 4140
 4141        let completions_menu =
 4142            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4143                menu
 4144            } else {
 4145                return None;
 4146            };
 4147
 4148        let entries = completions_menu.entries.borrow();
 4149        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4150        if self.show_edit_predictions_in_menu() {
 4151            self.discard_inline_completion(true, cx);
 4152        }
 4153        let candidate_id = mat.candidate_id;
 4154        drop(entries);
 4155
 4156        let buffer_handle = completions_menu.buffer;
 4157        let completion = completions_menu
 4158            .completions
 4159            .borrow()
 4160            .get(candidate_id)?
 4161            .clone();
 4162        cx.stop_propagation();
 4163
 4164        let snippet;
 4165        let text;
 4166
 4167        if completion.is_snippet() {
 4168            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4169            text = snippet.as_ref().unwrap().text.clone();
 4170        } else {
 4171            snippet = None;
 4172            text = completion.new_text.clone();
 4173        };
 4174        let selections = self.selections.all::<usize>(cx);
 4175        let buffer = buffer_handle.read(cx);
 4176        let old_range = completion.old_range.to_offset(buffer);
 4177        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4178
 4179        let newest_selection = self.selections.newest_anchor();
 4180        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4181            return None;
 4182        }
 4183
 4184        let lookbehind = newest_selection
 4185            .start
 4186            .text_anchor
 4187            .to_offset(buffer)
 4188            .saturating_sub(old_range.start);
 4189        let lookahead = old_range
 4190            .end
 4191            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4192        let mut common_prefix_len = old_text
 4193            .bytes()
 4194            .zip(text.bytes())
 4195            .take_while(|(a, b)| a == b)
 4196            .count();
 4197
 4198        let snapshot = self.buffer.read(cx).snapshot(cx);
 4199        let mut range_to_replace: Option<Range<isize>> = None;
 4200        let mut ranges = Vec::new();
 4201        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4202        for selection in &selections {
 4203            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4204                let start = selection.start.saturating_sub(lookbehind);
 4205                let end = selection.end + lookahead;
 4206                if selection.id == newest_selection.id {
 4207                    range_to_replace = Some(
 4208                        ((start + common_prefix_len) as isize - selection.start as isize)
 4209                            ..(end as isize - selection.start as isize),
 4210                    );
 4211                }
 4212                ranges.push(start + common_prefix_len..end);
 4213            } else {
 4214                common_prefix_len = 0;
 4215                ranges.clear();
 4216                ranges.extend(selections.iter().map(|s| {
 4217                    if s.id == newest_selection.id {
 4218                        range_to_replace = Some(
 4219                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4220                                - selection.start as isize
 4221                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4222                                    - selection.start as isize,
 4223                        );
 4224                        old_range.clone()
 4225                    } else {
 4226                        s.start..s.end
 4227                    }
 4228                }));
 4229                break;
 4230            }
 4231            if !self.linked_edit_ranges.is_empty() {
 4232                let start_anchor = snapshot.anchor_before(selection.head());
 4233                let end_anchor = snapshot.anchor_after(selection.tail());
 4234                if let Some(ranges) = self
 4235                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4236                {
 4237                    for (buffer, edits) in ranges {
 4238                        linked_edits.entry(buffer.clone()).or_default().extend(
 4239                            edits
 4240                                .into_iter()
 4241                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4242                        );
 4243                    }
 4244                }
 4245            }
 4246        }
 4247        let text = &text[common_prefix_len..];
 4248
 4249        cx.emit(EditorEvent::InputHandled {
 4250            utf16_range_to_replace: range_to_replace,
 4251            text: text.into(),
 4252        });
 4253
 4254        self.transact(window, cx, |this, window, cx| {
 4255            if let Some(mut snippet) = snippet {
 4256                snippet.text = text.to_string();
 4257                for tabstop in snippet
 4258                    .tabstops
 4259                    .iter_mut()
 4260                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4261                {
 4262                    tabstop.start -= common_prefix_len as isize;
 4263                    tabstop.end -= common_prefix_len as isize;
 4264                }
 4265
 4266                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4267            } else {
 4268                this.buffer.update(cx, |buffer, cx| {
 4269                    buffer.edit(
 4270                        ranges.iter().map(|range| (range.clone(), text)),
 4271                        this.autoindent_mode.clone(),
 4272                        cx,
 4273                    );
 4274                });
 4275            }
 4276            for (buffer, edits) in linked_edits {
 4277                buffer.update(cx, |buffer, cx| {
 4278                    let snapshot = buffer.snapshot();
 4279                    let edits = edits
 4280                        .into_iter()
 4281                        .map(|(range, text)| {
 4282                            use text::ToPoint as TP;
 4283                            let end_point = TP::to_point(&range.end, &snapshot);
 4284                            let start_point = TP::to_point(&range.start, &snapshot);
 4285                            (start_point..end_point, text)
 4286                        })
 4287                        .sorted_by_key(|(range, _)| range.start)
 4288                        .collect::<Vec<_>>();
 4289                    buffer.edit(edits, None, cx);
 4290                })
 4291            }
 4292
 4293            this.refresh_inline_completion(true, false, window, cx);
 4294        });
 4295
 4296        let show_new_completions_on_confirm = completion
 4297            .confirm
 4298            .as_ref()
 4299            .map_or(false, |confirm| confirm(intent, window, cx));
 4300        if show_new_completions_on_confirm {
 4301            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4302        }
 4303
 4304        let provider = self.completion_provider.as_ref()?;
 4305        drop(completion);
 4306        let apply_edits = provider.apply_additional_edits_for_completion(
 4307            buffer_handle,
 4308            completions_menu.completions.clone(),
 4309            candidate_id,
 4310            true,
 4311            cx,
 4312        );
 4313
 4314        let editor_settings = EditorSettings::get_global(cx);
 4315        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4316            // After the code completion is finished, users often want to know what signatures are needed.
 4317            // so we should automatically call signature_help
 4318            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4319        }
 4320
 4321        Some(cx.foreground_executor().spawn(async move {
 4322            apply_edits.await?;
 4323            Ok(())
 4324        }))
 4325    }
 4326
 4327    pub fn toggle_code_actions(
 4328        &mut self,
 4329        action: &ToggleCodeActions,
 4330        window: &mut Window,
 4331        cx: &mut Context<Self>,
 4332    ) {
 4333        let mut context_menu = self.context_menu.borrow_mut();
 4334        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4335            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4336                // Toggle if we're selecting the same one
 4337                *context_menu = None;
 4338                cx.notify();
 4339                return;
 4340            } else {
 4341                // Otherwise, clear it and start a new one
 4342                *context_menu = None;
 4343                cx.notify();
 4344            }
 4345        }
 4346        drop(context_menu);
 4347        let snapshot = self.snapshot(window, cx);
 4348        let deployed_from_indicator = action.deployed_from_indicator;
 4349        let mut task = self.code_actions_task.take();
 4350        let action = action.clone();
 4351        cx.spawn_in(window, |editor, mut cx| async move {
 4352            while let Some(prev_task) = task {
 4353                prev_task.await.log_err();
 4354                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4355            }
 4356
 4357            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4358                if editor.focus_handle.is_focused(window) {
 4359                    let multibuffer_point = action
 4360                        .deployed_from_indicator
 4361                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4362                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4363                    let (buffer, buffer_row) = snapshot
 4364                        .buffer_snapshot
 4365                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4366                        .and_then(|(buffer_snapshot, range)| {
 4367                            editor
 4368                                .buffer
 4369                                .read(cx)
 4370                                .buffer(buffer_snapshot.remote_id())
 4371                                .map(|buffer| (buffer, range.start.row))
 4372                        })?;
 4373                    let (_, code_actions) = editor
 4374                        .available_code_actions
 4375                        .clone()
 4376                        .and_then(|(location, code_actions)| {
 4377                            let snapshot = location.buffer.read(cx).snapshot();
 4378                            let point_range = location.range.to_point(&snapshot);
 4379                            let point_range = point_range.start.row..=point_range.end.row;
 4380                            if point_range.contains(&buffer_row) {
 4381                                Some((location, code_actions))
 4382                            } else {
 4383                                None
 4384                            }
 4385                        })
 4386                        .unzip();
 4387                    let buffer_id = buffer.read(cx).remote_id();
 4388                    let tasks = editor
 4389                        .tasks
 4390                        .get(&(buffer_id, buffer_row))
 4391                        .map(|t| Arc::new(t.to_owned()));
 4392                    if tasks.is_none() && code_actions.is_none() {
 4393                        return None;
 4394                    }
 4395
 4396                    editor.completion_tasks.clear();
 4397                    editor.discard_inline_completion(false, cx);
 4398                    let task_context =
 4399                        tasks
 4400                            .as_ref()
 4401                            .zip(editor.project.clone())
 4402                            .map(|(tasks, project)| {
 4403                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4404                            });
 4405
 4406                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4407                        let task_context = match task_context {
 4408                            Some(task_context) => task_context.await,
 4409                            None => None,
 4410                        };
 4411                        let resolved_tasks =
 4412                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4413                                Rc::new(ResolvedTasks {
 4414                                    templates: tasks.resolve(&task_context).collect(),
 4415                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4416                                        multibuffer_point.row,
 4417                                        tasks.column,
 4418                                    )),
 4419                                })
 4420                            });
 4421                        let spawn_straight_away = resolved_tasks
 4422                            .as_ref()
 4423                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4424                            && code_actions
 4425                                .as_ref()
 4426                                .map_or(true, |actions| actions.is_empty());
 4427                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4428                            *editor.context_menu.borrow_mut() =
 4429                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4430                                    buffer,
 4431                                    actions: CodeActionContents {
 4432                                        tasks: resolved_tasks,
 4433                                        actions: code_actions,
 4434                                    },
 4435                                    selected_item: Default::default(),
 4436                                    scroll_handle: UniformListScrollHandle::default(),
 4437                                    deployed_from_indicator,
 4438                                }));
 4439                            if spawn_straight_away {
 4440                                if let Some(task) = editor.confirm_code_action(
 4441                                    &ConfirmCodeAction { item_ix: Some(0) },
 4442                                    window,
 4443                                    cx,
 4444                                ) {
 4445                                    cx.notify();
 4446                                    return task;
 4447                                }
 4448                            }
 4449                            cx.notify();
 4450                            Task::ready(Ok(()))
 4451                        }) {
 4452                            task.await
 4453                        } else {
 4454                            Ok(())
 4455                        }
 4456                    }))
 4457                } else {
 4458                    Some(Task::ready(Ok(())))
 4459                }
 4460            })?;
 4461            if let Some(task) = spawned_test_task {
 4462                task.await?;
 4463            }
 4464
 4465            Ok::<_, anyhow::Error>(())
 4466        })
 4467        .detach_and_log_err(cx);
 4468    }
 4469
 4470    pub fn confirm_code_action(
 4471        &mut self,
 4472        action: &ConfirmCodeAction,
 4473        window: &mut Window,
 4474        cx: &mut Context<Self>,
 4475    ) -> Option<Task<Result<()>>> {
 4476        let actions_menu =
 4477            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4478                menu
 4479            } else {
 4480                return None;
 4481            };
 4482        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4483        let action = actions_menu.actions.get(action_ix)?;
 4484        let title = action.label();
 4485        let buffer = actions_menu.buffer;
 4486        let workspace = self.workspace()?;
 4487
 4488        match action {
 4489            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4490                workspace.update(cx, |workspace, cx| {
 4491                    workspace::tasks::schedule_resolved_task(
 4492                        workspace,
 4493                        task_source_kind,
 4494                        resolved_task,
 4495                        false,
 4496                        cx,
 4497                    );
 4498
 4499                    Some(Task::ready(Ok(())))
 4500                })
 4501            }
 4502            CodeActionsItem::CodeAction {
 4503                excerpt_id,
 4504                action,
 4505                provider,
 4506            } => {
 4507                let apply_code_action =
 4508                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4509                let workspace = workspace.downgrade();
 4510                Some(cx.spawn_in(window, |editor, cx| async move {
 4511                    let project_transaction = apply_code_action.await?;
 4512                    Self::open_project_transaction(
 4513                        &editor,
 4514                        workspace,
 4515                        project_transaction,
 4516                        title,
 4517                        cx,
 4518                    )
 4519                    .await
 4520                }))
 4521            }
 4522        }
 4523    }
 4524
 4525    pub async fn open_project_transaction(
 4526        this: &WeakEntity<Editor>,
 4527        workspace: WeakEntity<Workspace>,
 4528        transaction: ProjectTransaction,
 4529        title: String,
 4530        mut cx: AsyncWindowContext,
 4531    ) -> Result<()> {
 4532        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4533        cx.update(|_, cx| {
 4534            entries.sort_unstable_by_key(|(buffer, _)| {
 4535                buffer.read(cx).file().map(|f| f.path().clone())
 4536            });
 4537        })?;
 4538
 4539        // If the project transaction's edits are all contained within this editor, then
 4540        // avoid opening a new editor to display them.
 4541
 4542        if let Some((buffer, transaction)) = entries.first() {
 4543            if entries.len() == 1 {
 4544                let excerpt = this.update(&mut cx, |editor, cx| {
 4545                    editor
 4546                        .buffer()
 4547                        .read(cx)
 4548                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4549                })?;
 4550                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4551                    if excerpted_buffer == *buffer {
 4552                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4553                            let excerpt_range = excerpt_range.to_offset(buffer);
 4554                            buffer
 4555                                .edited_ranges_for_transaction::<usize>(transaction)
 4556                                .all(|range| {
 4557                                    excerpt_range.start <= range.start
 4558                                        && excerpt_range.end >= range.end
 4559                                })
 4560                        })?;
 4561
 4562                        if all_edits_within_excerpt {
 4563                            return Ok(());
 4564                        }
 4565                    }
 4566                }
 4567            }
 4568        } else {
 4569            return Ok(());
 4570        }
 4571
 4572        let mut ranges_to_highlight = Vec::new();
 4573        let excerpt_buffer = cx.new(|cx| {
 4574            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4575            for (buffer_handle, transaction) in &entries {
 4576                let buffer = buffer_handle.read(cx);
 4577                ranges_to_highlight.extend(
 4578                    multibuffer.push_excerpts_with_context_lines(
 4579                        buffer_handle.clone(),
 4580                        buffer
 4581                            .edited_ranges_for_transaction::<usize>(transaction)
 4582                            .collect(),
 4583                        DEFAULT_MULTIBUFFER_CONTEXT,
 4584                        cx,
 4585                    ),
 4586                );
 4587            }
 4588            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4589            multibuffer
 4590        })?;
 4591
 4592        workspace.update_in(&mut cx, |workspace, window, cx| {
 4593            let project = workspace.project().clone();
 4594            let editor = cx
 4595                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4596            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4597            editor.update(cx, |editor, cx| {
 4598                editor.highlight_background::<Self>(
 4599                    &ranges_to_highlight,
 4600                    |theme| theme.editor_highlighted_line_background,
 4601                    cx,
 4602                );
 4603            });
 4604        })?;
 4605
 4606        Ok(())
 4607    }
 4608
 4609    pub fn clear_code_action_providers(&mut self) {
 4610        self.code_action_providers.clear();
 4611        self.available_code_actions.take();
 4612    }
 4613
 4614    pub fn add_code_action_provider(
 4615        &mut self,
 4616        provider: Rc<dyn CodeActionProvider>,
 4617        window: &mut Window,
 4618        cx: &mut Context<Self>,
 4619    ) {
 4620        if self
 4621            .code_action_providers
 4622            .iter()
 4623            .any(|existing_provider| existing_provider.id() == provider.id())
 4624        {
 4625            return;
 4626        }
 4627
 4628        self.code_action_providers.push(provider);
 4629        self.refresh_code_actions(window, cx);
 4630    }
 4631
 4632    pub fn remove_code_action_provider(
 4633        &mut self,
 4634        id: Arc<str>,
 4635        window: &mut Window,
 4636        cx: &mut Context<Self>,
 4637    ) {
 4638        self.code_action_providers
 4639            .retain(|provider| provider.id() != id);
 4640        self.refresh_code_actions(window, cx);
 4641    }
 4642
 4643    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4644        let buffer = self.buffer.read(cx);
 4645        let newest_selection = self.selections.newest_anchor().clone();
 4646        if newest_selection.head().diff_base_anchor.is_some() {
 4647            return None;
 4648        }
 4649        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4650        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4651        if start_buffer != end_buffer {
 4652            return None;
 4653        }
 4654
 4655        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4656            cx.background_executor()
 4657                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4658                .await;
 4659
 4660            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4661                let providers = this.code_action_providers.clone();
 4662                let tasks = this
 4663                    .code_action_providers
 4664                    .iter()
 4665                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4666                    .collect::<Vec<_>>();
 4667                (providers, tasks)
 4668            })?;
 4669
 4670            let mut actions = Vec::new();
 4671            for (provider, provider_actions) in
 4672                providers.into_iter().zip(future::join_all(tasks).await)
 4673            {
 4674                if let Some(provider_actions) = provider_actions.log_err() {
 4675                    actions.extend(provider_actions.into_iter().map(|action| {
 4676                        AvailableCodeAction {
 4677                            excerpt_id: newest_selection.start.excerpt_id,
 4678                            action,
 4679                            provider: provider.clone(),
 4680                        }
 4681                    }));
 4682                }
 4683            }
 4684
 4685            this.update(&mut cx, |this, cx| {
 4686                this.available_code_actions = if actions.is_empty() {
 4687                    None
 4688                } else {
 4689                    Some((
 4690                        Location {
 4691                            buffer: start_buffer,
 4692                            range: start..end,
 4693                        },
 4694                        actions.into(),
 4695                    ))
 4696                };
 4697                cx.notify();
 4698            })
 4699        }));
 4700        None
 4701    }
 4702
 4703    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4704        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4705            self.show_git_blame_inline = false;
 4706
 4707            self.show_git_blame_inline_delay_task =
 4708                Some(cx.spawn_in(window, |this, mut cx| async move {
 4709                    cx.background_executor().timer(delay).await;
 4710
 4711                    this.update(&mut cx, |this, cx| {
 4712                        this.show_git_blame_inline = true;
 4713                        cx.notify();
 4714                    })
 4715                    .log_err();
 4716                }));
 4717        }
 4718    }
 4719
 4720    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4721        if self.pending_rename.is_some() {
 4722            return None;
 4723        }
 4724
 4725        let provider = self.semantics_provider.clone()?;
 4726        let buffer = self.buffer.read(cx);
 4727        let newest_selection = self.selections.newest_anchor().clone();
 4728        let cursor_position = newest_selection.head();
 4729        let (cursor_buffer, cursor_buffer_position) =
 4730            buffer.text_anchor_for_position(cursor_position, cx)?;
 4731        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4732        if cursor_buffer != tail_buffer {
 4733            return None;
 4734        }
 4735        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4736        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4737            cx.background_executor()
 4738                .timer(Duration::from_millis(debounce))
 4739                .await;
 4740
 4741            let highlights = if let Some(highlights) = cx
 4742                .update(|cx| {
 4743                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4744                })
 4745                .ok()
 4746                .flatten()
 4747            {
 4748                highlights.await.log_err()
 4749            } else {
 4750                None
 4751            };
 4752
 4753            if let Some(highlights) = highlights {
 4754                this.update(&mut cx, |this, cx| {
 4755                    if this.pending_rename.is_some() {
 4756                        return;
 4757                    }
 4758
 4759                    let buffer_id = cursor_position.buffer_id;
 4760                    let buffer = this.buffer.read(cx);
 4761                    if !buffer
 4762                        .text_anchor_for_position(cursor_position, cx)
 4763                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4764                    {
 4765                        return;
 4766                    }
 4767
 4768                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4769                    let mut write_ranges = Vec::new();
 4770                    let mut read_ranges = Vec::new();
 4771                    for highlight in highlights {
 4772                        for (excerpt_id, excerpt_range) in
 4773                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4774                        {
 4775                            let start = highlight
 4776                                .range
 4777                                .start
 4778                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4779                            let end = highlight
 4780                                .range
 4781                                .end
 4782                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4783                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4784                                continue;
 4785                            }
 4786
 4787                            let range = Anchor {
 4788                                buffer_id,
 4789                                excerpt_id,
 4790                                text_anchor: start,
 4791                                diff_base_anchor: None,
 4792                            }..Anchor {
 4793                                buffer_id,
 4794                                excerpt_id,
 4795                                text_anchor: end,
 4796                                diff_base_anchor: None,
 4797                            };
 4798                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4799                                write_ranges.push(range);
 4800                            } else {
 4801                                read_ranges.push(range);
 4802                            }
 4803                        }
 4804                    }
 4805
 4806                    this.highlight_background::<DocumentHighlightRead>(
 4807                        &read_ranges,
 4808                        |theme| theme.editor_document_highlight_read_background,
 4809                        cx,
 4810                    );
 4811                    this.highlight_background::<DocumentHighlightWrite>(
 4812                        &write_ranges,
 4813                        |theme| theme.editor_document_highlight_write_background,
 4814                        cx,
 4815                    );
 4816                    cx.notify();
 4817                })
 4818                .log_err();
 4819            }
 4820        }));
 4821        None
 4822    }
 4823
 4824    pub fn refresh_selected_text_highlights(
 4825        &mut self,
 4826        window: &mut Window,
 4827        cx: &mut Context<Editor>,
 4828    ) {
 4829        self.selection_highlight_task.take();
 4830        if !EditorSettings::get_global(cx).selection_highlight {
 4831            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4832            return;
 4833        }
 4834        if self.selections.count() != 1 || self.selections.line_mode {
 4835            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4836            return;
 4837        }
 4838        let selection = self.selections.newest::<Point>(cx);
 4839        if selection.is_empty() || selection.start.row != selection.end.row {
 4840            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4841            return;
 4842        }
 4843        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4844        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4845            cx.background_executor()
 4846                .timer(Duration::from_millis(debounce))
 4847                .await;
 4848            let Some(Some(matches_task)) = editor
 4849                .update_in(&mut cx, |editor, _, cx| {
 4850                    if editor.selections.count() != 1 || editor.selections.line_mode {
 4851                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4852                        return None;
 4853                    }
 4854                    let selection = editor.selections.newest::<Point>(cx);
 4855                    if selection.is_empty() || selection.start.row != selection.end.row {
 4856                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4857                        return None;
 4858                    }
 4859                    let buffer = editor.buffer().read(cx).snapshot(cx);
 4860                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 4861                    if query.trim().is_empty() {
 4862                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4863                        return None;
 4864                    }
 4865                    Some(cx.background_spawn(async move {
 4866                        let mut ranges = Vec::new();
 4867                        let selection_anchors = selection.range().to_anchors(&buffer);
 4868                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 4869                            for (search_buffer, search_range, excerpt_id) in
 4870                                buffer.range_to_buffer_ranges(range)
 4871                            {
 4872                                ranges.extend(
 4873                                    project::search::SearchQuery::text(
 4874                                        query.clone(),
 4875                                        false,
 4876                                        false,
 4877                                        false,
 4878                                        Default::default(),
 4879                                        Default::default(),
 4880                                        None,
 4881                                    )
 4882                                    .unwrap()
 4883                                    .search(search_buffer, Some(search_range.clone()))
 4884                                    .await
 4885                                    .into_iter()
 4886                                    .filter_map(
 4887                                        |match_range| {
 4888                                            let start = search_buffer.anchor_after(
 4889                                                search_range.start + match_range.start,
 4890                                            );
 4891                                            let end = search_buffer.anchor_before(
 4892                                                search_range.start + match_range.end,
 4893                                            );
 4894                                            let range = Anchor::range_in_buffer(
 4895                                                excerpt_id,
 4896                                                search_buffer.remote_id(),
 4897                                                start..end,
 4898                                            );
 4899                                            (range != selection_anchors).then_some(range)
 4900                                        },
 4901                                    ),
 4902                                );
 4903                            }
 4904                        }
 4905                        ranges
 4906                    }))
 4907                })
 4908                .log_err()
 4909            else {
 4910                return;
 4911            };
 4912            let matches = matches_task.await;
 4913            editor
 4914                .update_in(&mut cx, |editor, _, cx| {
 4915                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4916                    if !matches.is_empty() {
 4917                        editor.highlight_background::<SelectedTextHighlight>(
 4918                            &matches,
 4919                            |theme| theme.editor_document_highlight_bracket_background,
 4920                            cx,
 4921                        )
 4922                    }
 4923                })
 4924                .log_err();
 4925        }));
 4926    }
 4927
 4928    pub fn refresh_inline_completion(
 4929        &mut self,
 4930        debounce: bool,
 4931        user_requested: bool,
 4932        window: &mut Window,
 4933        cx: &mut Context<Self>,
 4934    ) -> Option<()> {
 4935        let provider = self.edit_prediction_provider()?;
 4936        let cursor = self.selections.newest_anchor().head();
 4937        let (buffer, cursor_buffer_position) =
 4938            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4939
 4940        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4941            self.discard_inline_completion(false, cx);
 4942            return None;
 4943        }
 4944
 4945        if !user_requested
 4946            && (!self.should_show_edit_predictions()
 4947                || !self.is_focused(window)
 4948                || buffer.read(cx).is_empty())
 4949        {
 4950            self.discard_inline_completion(false, cx);
 4951            return None;
 4952        }
 4953
 4954        self.update_visible_inline_completion(window, cx);
 4955        provider.refresh(
 4956            self.project.clone(),
 4957            buffer,
 4958            cursor_buffer_position,
 4959            debounce,
 4960            cx,
 4961        );
 4962        Some(())
 4963    }
 4964
 4965    fn show_edit_predictions_in_menu(&self) -> bool {
 4966        match self.edit_prediction_settings {
 4967            EditPredictionSettings::Disabled => false,
 4968            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4969        }
 4970    }
 4971
 4972    pub fn edit_predictions_enabled(&self) -> bool {
 4973        match self.edit_prediction_settings {
 4974            EditPredictionSettings::Disabled => false,
 4975            EditPredictionSettings::Enabled { .. } => true,
 4976        }
 4977    }
 4978
 4979    fn edit_prediction_requires_modifier(&self) -> bool {
 4980        match self.edit_prediction_settings {
 4981            EditPredictionSettings::Disabled => false,
 4982            EditPredictionSettings::Enabled {
 4983                preview_requires_modifier,
 4984                ..
 4985            } => preview_requires_modifier,
 4986        }
 4987    }
 4988
 4989    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 4990        if self.edit_prediction_provider.is_none() {
 4991            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 4992        } else {
 4993            let selection = self.selections.newest_anchor();
 4994            let cursor = selection.head();
 4995
 4996            if let Some((buffer, cursor_buffer_position)) =
 4997                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4998            {
 4999                self.edit_prediction_settings =
 5000                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5001            }
 5002        }
 5003    }
 5004
 5005    fn edit_prediction_settings_at_position(
 5006        &self,
 5007        buffer: &Entity<Buffer>,
 5008        buffer_position: language::Anchor,
 5009        cx: &App,
 5010    ) -> EditPredictionSettings {
 5011        if self.mode != EditorMode::Full
 5012            || !self.show_inline_completions_override.unwrap_or(true)
 5013            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5014        {
 5015            return EditPredictionSettings::Disabled;
 5016        }
 5017
 5018        let buffer = buffer.read(cx);
 5019
 5020        let file = buffer.file();
 5021
 5022        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5023            return EditPredictionSettings::Disabled;
 5024        };
 5025
 5026        let by_provider = matches!(
 5027            self.menu_inline_completions_policy,
 5028            MenuInlineCompletionsPolicy::ByProvider
 5029        );
 5030
 5031        let show_in_menu = by_provider
 5032            && self
 5033                .edit_prediction_provider
 5034                .as_ref()
 5035                .map_or(false, |provider| {
 5036                    provider.provider.show_completions_in_menu()
 5037                });
 5038
 5039        let preview_requires_modifier =
 5040            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5041
 5042        EditPredictionSettings::Enabled {
 5043            show_in_menu,
 5044            preview_requires_modifier,
 5045        }
 5046    }
 5047
 5048    fn should_show_edit_predictions(&self) -> bool {
 5049        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5050    }
 5051
 5052    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5053        matches!(
 5054            self.edit_prediction_preview,
 5055            EditPredictionPreview::Active { .. }
 5056        )
 5057    }
 5058
 5059    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5060        let cursor = self.selections.newest_anchor().head();
 5061        if let Some((buffer, cursor_position)) =
 5062            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5063        {
 5064            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5065        } else {
 5066            false
 5067        }
 5068    }
 5069
 5070    fn edit_predictions_enabled_in_buffer(
 5071        &self,
 5072        buffer: &Entity<Buffer>,
 5073        buffer_position: language::Anchor,
 5074        cx: &App,
 5075    ) -> bool {
 5076        maybe!({
 5077            let provider = self.edit_prediction_provider()?;
 5078            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5079                return Some(false);
 5080            }
 5081            let buffer = buffer.read(cx);
 5082            let Some(file) = buffer.file() else {
 5083                return Some(true);
 5084            };
 5085            let settings = all_language_settings(Some(file), cx);
 5086            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5087        })
 5088        .unwrap_or(false)
 5089    }
 5090
 5091    fn cycle_inline_completion(
 5092        &mut self,
 5093        direction: Direction,
 5094        window: &mut Window,
 5095        cx: &mut Context<Self>,
 5096    ) -> Option<()> {
 5097        let provider = self.edit_prediction_provider()?;
 5098        let cursor = self.selections.newest_anchor().head();
 5099        let (buffer, cursor_buffer_position) =
 5100            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5101        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5102            return None;
 5103        }
 5104
 5105        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5106        self.update_visible_inline_completion(window, cx);
 5107
 5108        Some(())
 5109    }
 5110
 5111    pub fn show_inline_completion(
 5112        &mut self,
 5113        _: &ShowEditPrediction,
 5114        window: &mut Window,
 5115        cx: &mut Context<Self>,
 5116    ) {
 5117        if !self.has_active_inline_completion() {
 5118            self.refresh_inline_completion(false, true, window, cx);
 5119            return;
 5120        }
 5121
 5122        self.update_visible_inline_completion(window, cx);
 5123    }
 5124
 5125    pub fn display_cursor_names(
 5126        &mut self,
 5127        _: &DisplayCursorNames,
 5128        window: &mut Window,
 5129        cx: &mut Context<Self>,
 5130    ) {
 5131        self.show_cursor_names(window, cx);
 5132    }
 5133
 5134    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5135        self.show_cursor_names = true;
 5136        cx.notify();
 5137        cx.spawn_in(window, |this, mut cx| async move {
 5138            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5139            this.update(&mut cx, |this, cx| {
 5140                this.show_cursor_names = false;
 5141                cx.notify()
 5142            })
 5143            .ok()
 5144        })
 5145        .detach();
 5146    }
 5147
 5148    pub fn next_edit_prediction(
 5149        &mut self,
 5150        _: &NextEditPrediction,
 5151        window: &mut Window,
 5152        cx: &mut Context<Self>,
 5153    ) {
 5154        if self.has_active_inline_completion() {
 5155            self.cycle_inline_completion(Direction::Next, window, cx);
 5156        } else {
 5157            let is_copilot_disabled = self
 5158                .refresh_inline_completion(false, true, window, cx)
 5159                .is_none();
 5160            if is_copilot_disabled {
 5161                cx.propagate();
 5162            }
 5163        }
 5164    }
 5165
 5166    pub fn previous_edit_prediction(
 5167        &mut self,
 5168        _: &PreviousEditPrediction,
 5169        window: &mut Window,
 5170        cx: &mut Context<Self>,
 5171    ) {
 5172        if self.has_active_inline_completion() {
 5173            self.cycle_inline_completion(Direction::Prev, window, cx);
 5174        } else {
 5175            let is_copilot_disabled = self
 5176                .refresh_inline_completion(false, true, window, cx)
 5177                .is_none();
 5178            if is_copilot_disabled {
 5179                cx.propagate();
 5180            }
 5181        }
 5182    }
 5183
 5184    pub fn accept_edit_prediction(
 5185        &mut self,
 5186        _: &AcceptEditPrediction,
 5187        window: &mut Window,
 5188        cx: &mut Context<Self>,
 5189    ) {
 5190        if self.show_edit_predictions_in_menu() {
 5191            self.hide_context_menu(window, cx);
 5192        }
 5193
 5194        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5195            return;
 5196        };
 5197
 5198        self.report_inline_completion_event(
 5199            active_inline_completion.completion_id.clone(),
 5200            true,
 5201            cx,
 5202        );
 5203
 5204        match &active_inline_completion.completion {
 5205            InlineCompletion::Move { target, .. } => {
 5206                let target = *target;
 5207
 5208                if let Some(position_map) = &self.last_position_map {
 5209                    if position_map
 5210                        .visible_row_range
 5211                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5212                        || !self.edit_prediction_requires_modifier()
 5213                    {
 5214                        self.unfold_ranges(&[target..target], true, false, cx);
 5215                        // Note that this is also done in vim's handler of the Tab action.
 5216                        self.change_selections(
 5217                            Some(Autoscroll::newest()),
 5218                            window,
 5219                            cx,
 5220                            |selections| {
 5221                                selections.select_anchor_ranges([target..target]);
 5222                            },
 5223                        );
 5224                        self.clear_row_highlights::<EditPredictionPreview>();
 5225
 5226                        self.edit_prediction_preview
 5227                            .set_previous_scroll_position(None);
 5228                    } else {
 5229                        self.edit_prediction_preview
 5230                            .set_previous_scroll_position(Some(
 5231                                position_map.snapshot.scroll_anchor,
 5232                            ));
 5233
 5234                        self.highlight_rows::<EditPredictionPreview>(
 5235                            target..target,
 5236                            cx.theme().colors().editor_highlighted_line_background,
 5237                            true,
 5238                            cx,
 5239                        );
 5240                        self.request_autoscroll(Autoscroll::fit(), cx);
 5241                    }
 5242                }
 5243            }
 5244            InlineCompletion::Edit { edits, .. } => {
 5245                if let Some(provider) = self.edit_prediction_provider() {
 5246                    provider.accept(cx);
 5247                }
 5248
 5249                let snapshot = self.buffer.read(cx).snapshot(cx);
 5250                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5251
 5252                self.buffer.update(cx, |buffer, cx| {
 5253                    buffer.edit(edits.iter().cloned(), None, cx)
 5254                });
 5255
 5256                self.change_selections(None, window, cx, |s| {
 5257                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5258                });
 5259
 5260                self.update_visible_inline_completion(window, cx);
 5261                if self.active_inline_completion.is_none() {
 5262                    self.refresh_inline_completion(true, true, window, cx);
 5263                }
 5264
 5265                cx.notify();
 5266            }
 5267        }
 5268
 5269        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5270    }
 5271
 5272    pub fn accept_partial_inline_completion(
 5273        &mut self,
 5274        _: &AcceptPartialEditPrediction,
 5275        window: &mut Window,
 5276        cx: &mut Context<Self>,
 5277    ) {
 5278        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5279            return;
 5280        };
 5281        if self.selections.count() != 1 {
 5282            return;
 5283        }
 5284
 5285        self.report_inline_completion_event(
 5286            active_inline_completion.completion_id.clone(),
 5287            true,
 5288            cx,
 5289        );
 5290
 5291        match &active_inline_completion.completion {
 5292            InlineCompletion::Move { target, .. } => {
 5293                let target = *target;
 5294                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5295                    selections.select_anchor_ranges([target..target]);
 5296                });
 5297            }
 5298            InlineCompletion::Edit { edits, .. } => {
 5299                // Find an insertion that starts at the cursor position.
 5300                let snapshot = self.buffer.read(cx).snapshot(cx);
 5301                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5302                let insertion = edits.iter().find_map(|(range, text)| {
 5303                    let range = range.to_offset(&snapshot);
 5304                    if range.is_empty() && range.start == cursor_offset {
 5305                        Some(text)
 5306                    } else {
 5307                        None
 5308                    }
 5309                });
 5310
 5311                if let Some(text) = insertion {
 5312                    let mut partial_completion = text
 5313                        .chars()
 5314                        .by_ref()
 5315                        .take_while(|c| c.is_alphabetic())
 5316                        .collect::<String>();
 5317                    if partial_completion.is_empty() {
 5318                        partial_completion = text
 5319                            .chars()
 5320                            .by_ref()
 5321                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5322                            .collect::<String>();
 5323                    }
 5324
 5325                    cx.emit(EditorEvent::InputHandled {
 5326                        utf16_range_to_replace: None,
 5327                        text: partial_completion.clone().into(),
 5328                    });
 5329
 5330                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5331
 5332                    self.refresh_inline_completion(true, true, window, cx);
 5333                    cx.notify();
 5334                } else {
 5335                    self.accept_edit_prediction(&Default::default(), window, cx);
 5336                }
 5337            }
 5338        }
 5339    }
 5340
 5341    fn discard_inline_completion(
 5342        &mut self,
 5343        should_report_inline_completion_event: bool,
 5344        cx: &mut Context<Self>,
 5345    ) -> bool {
 5346        if should_report_inline_completion_event {
 5347            let completion_id = self
 5348                .active_inline_completion
 5349                .as_ref()
 5350                .and_then(|active_completion| active_completion.completion_id.clone());
 5351
 5352            self.report_inline_completion_event(completion_id, false, cx);
 5353        }
 5354
 5355        if let Some(provider) = self.edit_prediction_provider() {
 5356            provider.discard(cx);
 5357        }
 5358
 5359        self.take_active_inline_completion(cx)
 5360    }
 5361
 5362    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5363        let Some(provider) = self.edit_prediction_provider() else {
 5364            return;
 5365        };
 5366
 5367        let Some((_, buffer, _)) = self
 5368            .buffer
 5369            .read(cx)
 5370            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5371        else {
 5372            return;
 5373        };
 5374
 5375        let extension = buffer
 5376            .read(cx)
 5377            .file()
 5378            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5379
 5380        let event_type = match accepted {
 5381            true => "Edit Prediction Accepted",
 5382            false => "Edit Prediction Discarded",
 5383        };
 5384        telemetry::event!(
 5385            event_type,
 5386            provider = provider.name(),
 5387            prediction_id = id,
 5388            suggestion_accepted = accepted,
 5389            file_extension = extension,
 5390        );
 5391    }
 5392
 5393    pub fn has_active_inline_completion(&self) -> bool {
 5394        self.active_inline_completion.is_some()
 5395    }
 5396
 5397    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5398        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5399            return false;
 5400        };
 5401
 5402        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5403        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5404        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5405        true
 5406    }
 5407
 5408    /// Returns true when we're displaying the edit prediction popover below the cursor
 5409    /// like we are not previewing and the LSP autocomplete menu is visible
 5410    /// or we are in `when_holding_modifier` mode.
 5411    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5412        if self.edit_prediction_preview_is_active()
 5413            || !self.show_edit_predictions_in_menu()
 5414            || !self.edit_predictions_enabled()
 5415        {
 5416            return false;
 5417        }
 5418
 5419        if self.has_visible_completions_menu() {
 5420            return true;
 5421        }
 5422
 5423        has_completion && self.edit_prediction_requires_modifier()
 5424    }
 5425
 5426    fn handle_modifiers_changed(
 5427        &mut self,
 5428        modifiers: Modifiers,
 5429        position_map: &PositionMap,
 5430        window: &mut Window,
 5431        cx: &mut Context<Self>,
 5432    ) {
 5433        if self.show_edit_predictions_in_menu() {
 5434            self.update_edit_prediction_preview(&modifiers, window, cx);
 5435        }
 5436
 5437        self.update_selection_mode(&modifiers, position_map, window, cx);
 5438
 5439        let mouse_position = window.mouse_position();
 5440        if !position_map.text_hitbox.is_hovered(window) {
 5441            return;
 5442        }
 5443
 5444        self.update_hovered_link(
 5445            position_map.point_for_position(mouse_position),
 5446            &position_map.snapshot,
 5447            modifiers,
 5448            window,
 5449            cx,
 5450        )
 5451    }
 5452
 5453    fn update_selection_mode(
 5454        &mut self,
 5455        modifiers: &Modifiers,
 5456        position_map: &PositionMap,
 5457        window: &mut Window,
 5458        cx: &mut Context<Self>,
 5459    ) {
 5460        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5461            return;
 5462        }
 5463
 5464        let mouse_position = window.mouse_position();
 5465        let point_for_position = position_map.point_for_position(mouse_position);
 5466        let position = point_for_position.previous_valid;
 5467
 5468        self.select(
 5469            SelectPhase::BeginColumnar {
 5470                position,
 5471                reset: false,
 5472                goal_column: point_for_position.exact_unclipped.column(),
 5473            },
 5474            window,
 5475            cx,
 5476        );
 5477    }
 5478
 5479    fn update_edit_prediction_preview(
 5480        &mut self,
 5481        modifiers: &Modifiers,
 5482        window: &mut Window,
 5483        cx: &mut Context<Self>,
 5484    ) {
 5485        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5486        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5487            return;
 5488        };
 5489
 5490        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5491            if matches!(
 5492                self.edit_prediction_preview,
 5493                EditPredictionPreview::Inactive { .. }
 5494            ) {
 5495                self.edit_prediction_preview = EditPredictionPreview::Active {
 5496                    previous_scroll_position: None,
 5497                    since: Instant::now(),
 5498                };
 5499
 5500                self.update_visible_inline_completion(window, cx);
 5501                cx.notify();
 5502            }
 5503        } else if let EditPredictionPreview::Active {
 5504            previous_scroll_position,
 5505            since,
 5506        } = self.edit_prediction_preview
 5507        {
 5508            if let (Some(previous_scroll_position), Some(position_map)) =
 5509                (previous_scroll_position, self.last_position_map.as_ref())
 5510            {
 5511                self.set_scroll_position(
 5512                    previous_scroll_position
 5513                        .scroll_position(&position_map.snapshot.display_snapshot),
 5514                    window,
 5515                    cx,
 5516                );
 5517            }
 5518
 5519            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 5520                released_too_fast: since.elapsed() < Duration::from_millis(200),
 5521            };
 5522            self.clear_row_highlights::<EditPredictionPreview>();
 5523            self.update_visible_inline_completion(window, cx);
 5524            cx.notify();
 5525        }
 5526    }
 5527
 5528    fn update_visible_inline_completion(
 5529        &mut self,
 5530        _window: &mut Window,
 5531        cx: &mut Context<Self>,
 5532    ) -> Option<()> {
 5533        let selection = self.selections.newest_anchor();
 5534        let cursor = selection.head();
 5535        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5536        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5537        let excerpt_id = cursor.excerpt_id;
 5538
 5539        let show_in_menu = self.show_edit_predictions_in_menu();
 5540        let completions_menu_has_precedence = !show_in_menu
 5541            && (self.context_menu.borrow().is_some()
 5542                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5543
 5544        if completions_menu_has_precedence
 5545            || !offset_selection.is_empty()
 5546            || self
 5547                .active_inline_completion
 5548                .as_ref()
 5549                .map_or(false, |completion| {
 5550                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5551                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5552                    !invalidation_range.contains(&offset_selection.head())
 5553                })
 5554        {
 5555            self.discard_inline_completion(false, cx);
 5556            return None;
 5557        }
 5558
 5559        self.take_active_inline_completion(cx);
 5560        let Some(provider) = self.edit_prediction_provider() else {
 5561            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5562            return None;
 5563        };
 5564
 5565        let (buffer, cursor_buffer_position) =
 5566            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5567
 5568        self.edit_prediction_settings =
 5569            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5570
 5571        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 5572
 5573        if self.edit_prediction_indent_conflict {
 5574            let cursor_point = cursor.to_point(&multibuffer);
 5575
 5576            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 5577
 5578            if let Some((_, indent)) = indents.iter().next() {
 5579                if indent.len == cursor_point.column {
 5580                    self.edit_prediction_indent_conflict = false;
 5581                }
 5582            }
 5583        }
 5584
 5585        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5586        let edits = inline_completion
 5587            .edits
 5588            .into_iter()
 5589            .flat_map(|(range, new_text)| {
 5590                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5591                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5592                Some((start..end, new_text))
 5593            })
 5594            .collect::<Vec<_>>();
 5595        if edits.is_empty() {
 5596            return None;
 5597        }
 5598
 5599        let first_edit_start = edits.first().unwrap().0.start;
 5600        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5601        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5602
 5603        let last_edit_end = edits.last().unwrap().0.end;
 5604        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5605        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5606
 5607        let cursor_row = cursor.to_point(&multibuffer).row;
 5608
 5609        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5610
 5611        let mut inlay_ids = Vec::new();
 5612        let invalidation_row_range;
 5613        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5614            Some(cursor_row..edit_end_row)
 5615        } else if cursor_row > edit_end_row {
 5616            Some(edit_start_row..cursor_row)
 5617        } else {
 5618            None
 5619        };
 5620        let is_move =
 5621            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5622        let completion = if is_move {
 5623            invalidation_row_range =
 5624                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5625            let target = first_edit_start;
 5626            InlineCompletion::Move { target, snapshot }
 5627        } else {
 5628            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5629                && !self.inline_completions_hidden_for_vim_mode;
 5630
 5631            if show_completions_in_buffer {
 5632                if edits
 5633                    .iter()
 5634                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5635                {
 5636                    let mut inlays = Vec::new();
 5637                    for (range, new_text) in &edits {
 5638                        let inlay = Inlay::inline_completion(
 5639                            post_inc(&mut self.next_inlay_id),
 5640                            range.start,
 5641                            new_text.as_str(),
 5642                        );
 5643                        inlay_ids.push(inlay.id);
 5644                        inlays.push(inlay);
 5645                    }
 5646
 5647                    self.splice_inlays(&[], inlays, cx);
 5648                } else {
 5649                    let background_color = cx.theme().status().deleted_background;
 5650                    self.highlight_text::<InlineCompletionHighlight>(
 5651                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5652                        HighlightStyle {
 5653                            background_color: Some(background_color),
 5654                            ..Default::default()
 5655                        },
 5656                        cx,
 5657                    );
 5658                }
 5659            }
 5660
 5661            invalidation_row_range = edit_start_row..edit_end_row;
 5662
 5663            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5664                if provider.show_tab_accept_marker() {
 5665                    EditDisplayMode::TabAccept
 5666                } else {
 5667                    EditDisplayMode::Inline
 5668                }
 5669            } else {
 5670                EditDisplayMode::DiffPopover
 5671            };
 5672
 5673            InlineCompletion::Edit {
 5674                edits,
 5675                edit_preview: inline_completion.edit_preview,
 5676                display_mode,
 5677                snapshot,
 5678            }
 5679        };
 5680
 5681        let invalidation_range = multibuffer
 5682            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5683            ..multibuffer.anchor_after(Point::new(
 5684                invalidation_row_range.end,
 5685                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5686            ));
 5687
 5688        self.stale_inline_completion_in_menu = None;
 5689        self.active_inline_completion = Some(InlineCompletionState {
 5690            inlay_ids,
 5691            completion,
 5692            completion_id: inline_completion.id,
 5693            invalidation_range,
 5694        });
 5695
 5696        cx.notify();
 5697
 5698        Some(())
 5699    }
 5700
 5701    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5702        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5703    }
 5704
 5705    fn render_code_actions_indicator(
 5706        &self,
 5707        _style: &EditorStyle,
 5708        row: DisplayRow,
 5709        is_active: bool,
 5710        cx: &mut Context<Self>,
 5711    ) -> Option<IconButton> {
 5712        if self.available_code_actions.is_some() {
 5713            Some(
 5714                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5715                    .shape(ui::IconButtonShape::Square)
 5716                    .icon_size(IconSize::XSmall)
 5717                    .icon_color(Color::Muted)
 5718                    .toggle_state(is_active)
 5719                    .tooltip({
 5720                        let focus_handle = self.focus_handle.clone();
 5721                        move |window, cx| {
 5722                            Tooltip::for_action_in(
 5723                                "Toggle Code Actions",
 5724                                &ToggleCodeActions {
 5725                                    deployed_from_indicator: None,
 5726                                },
 5727                                &focus_handle,
 5728                                window,
 5729                                cx,
 5730                            )
 5731                        }
 5732                    })
 5733                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5734                        window.focus(&editor.focus_handle(cx));
 5735                        editor.toggle_code_actions(
 5736                            &ToggleCodeActions {
 5737                                deployed_from_indicator: Some(row),
 5738                            },
 5739                            window,
 5740                            cx,
 5741                        );
 5742                    })),
 5743            )
 5744        } else {
 5745            None
 5746        }
 5747    }
 5748
 5749    fn clear_tasks(&mut self) {
 5750        self.tasks.clear()
 5751    }
 5752
 5753    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5754        if self.tasks.insert(key, value).is_some() {
 5755            // This case should hopefully be rare, but just in case...
 5756            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5757        }
 5758    }
 5759
 5760    fn build_tasks_context(
 5761        project: &Entity<Project>,
 5762        buffer: &Entity<Buffer>,
 5763        buffer_row: u32,
 5764        tasks: &Arc<RunnableTasks>,
 5765        cx: &mut Context<Self>,
 5766    ) -> Task<Option<task::TaskContext>> {
 5767        let position = Point::new(buffer_row, tasks.column);
 5768        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5769        let location = Location {
 5770            buffer: buffer.clone(),
 5771            range: range_start..range_start,
 5772        };
 5773        // Fill in the environmental variables from the tree-sitter captures
 5774        let mut captured_task_variables = TaskVariables::default();
 5775        for (capture_name, value) in tasks.extra_variables.clone() {
 5776            captured_task_variables.insert(
 5777                task::VariableName::Custom(capture_name.into()),
 5778                value.clone(),
 5779            );
 5780        }
 5781        project.update(cx, |project, cx| {
 5782            project.task_store().update(cx, |task_store, cx| {
 5783                task_store.task_context_for_location(captured_task_variables, location, cx)
 5784            })
 5785        })
 5786    }
 5787
 5788    pub fn spawn_nearest_task(
 5789        &mut self,
 5790        action: &SpawnNearestTask,
 5791        window: &mut Window,
 5792        cx: &mut Context<Self>,
 5793    ) {
 5794        let Some((workspace, _)) = self.workspace.clone() else {
 5795            return;
 5796        };
 5797        let Some(project) = self.project.clone() else {
 5798            return;
 5799        };
 5800
 5801        // Try to find a closest, enclosing node using tree-sitter that has a
 5802        // task
 5803        let Some((buffer, buffer_row, tasks)) = self
 5804            .find_enclosing_node_task(cx)
 5805            // Or find the task that's closest in row-distance.
 5806            .or_else(|| self.find_closest_task(cx))
 5807        else {
 5808            return;
 5809        };
 5810
 5811        let reveal_strategy = action.reveal;
 5812        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5813        cx.spawn_in(window, |_, mut cx| async move {
 5814            let context = task_context.await?;
 5815            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5816
 5817            let resolved = resolved_task.resolved.as_mut()?;
 5818            resolved.reveal = reveal_strategy;
 5819
 5820            workspace
 5821                .update(&mut cx, |workspace, cx| {
 5822                    workspace::tasks::schedule_resolved_task(
 5823                        workspace,
 5824                        task_source_kind,
 5825                        resolved_task,
 5826                        false,
 5827                        cx,
 5828                    );
 5829                })
 5830                .ok()
 5831        })
 5832        .detach();
 5833    }
 5834
 5835    fn find_closest_task(
 5836        &mut self,
 5837        cx: &mut Context<Self>,
 5838    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5839        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5840
 5841        let ((buffer_id, row), tasks) = self
 5842            .tasks
 5843            .iter()
 5844            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5845
 5846        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5847        let tasks = Arc::new(tasks.to_owned());
 5848        Some((buffer, *row, tasks))
 5849    }
 5850
 5851    fn find_enclosing_node_task(
 5852        &mut self,
 5853        cx: &mut Context<Self>,
 5854    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5855        let snapshot = self.buffer.read(cx).snapshot(cx);
 5856        let offset = self.selections.newest::<usize>(cx).head();
 5857        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5858        let buffer_id = excerpt.buffer().remote_id();
 5859
 5860        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5861        let mut cursor = layer.node().walk();
 5862
 5863        while cursor.goto_first_child_for_byte(offset).is_some() {
 5864            if cursor.node().end_byte() == offset {
 5865                cursor.goto_next_sibling();
 5866            }
 5867        }
 5868
 5869        // Ascend to the smallest ancestor that contains the range and has a task.
 5870        loop {
 5871            let node = cursor.node();
 5872            let node_range = node.byte_range();
 5873            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5874
 5875            // Check if this node contains our offset
 5876            if node_range.start <= offset && node_range.end >= offset {
 5877                // If it contains offset, check for task
 5878                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5879                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5880                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5881                }
 5882            }
 5883
 5884            if !cursor.goto_parent() {
 5885                break;
 5886            }
 5887        }
 5888        None
 5889    }
 5890
 5891    fn render_run_indicator(
 5892        &self,
 5893        _style: &EditorStyle,
 5894        is_active: bool,
 5895        row: DisplayRow,
 5896        cx: &mut Context<Self>,
 5897    ) -> IconButton {
 5898        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5899            .shape(ui::IconButtonShape::Square)
 5900            .icon_size(IconSize::XSmall)
 5901            .icon_color(Color::Muted)
 5902            .toggle_state(is_active)
 5903            .on_click(cx.listener(move |editor, _e, window, cx| {
 5904                window.focus(&editor.focus_handle(cx));
 5905                editor.toggle_code_actions(
 5906                    &ToggleCodeActions {
 5907                        deployed_from_indicator: Some(row),
 5908                    },
 5909                    window,
 5910                    cx,
 5911                );
 5912            }))
 5913    }
 5914
 5915    pub fn context_menu_visible(&self) -> bool {
 5916        !self.edit_prediction_preview_is_active()
 5917            && self
 5918                .context_menu
 5919                .borrow()
 5920                .as_ref()
 5921                .map_or(false, |menu| menu.visible())
 5922    }
 5923
 5924    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5925        self.context_menu
 5926            .borrow()
 5927            .as_ref()
 5928            .map(|menu| menu.origin())
 5929    }
 5930
 5931    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 5932    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 5933
 5934    #[allow(clippy::too_many_arguments)]
 5935    fn render_edit_prediction_popover(
 5936        &mut self,
 5937        text_bounds: &Bounds<Pixels>,
 5938        content_origin: gpui::Point<Pixels>,
 5939        editor_snapshot: &EditorSnapshot,
 5940        visible_row_range: Range<DisplayRow>,
 5941        scroll_top: f32,
 5942        scroll_bottom: f32,
 5943        line_layouts: &[LineWithInvisibles],
 5944        line_height: Pixels,
 5945        scroll_pixel_position: gpui::Point<Pixels>,
 5946        newest_selection_head: Option<DisplayPoint>,
 5947        editor_width: Pixels,
 5948        style: &EditorStyle,
 5949        window: &mut Window,
 5950        cx: &mut App,
 5951    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5952        let active_inline_completion = self.active_inline_completion.as_ref()?;
 5953
 5954        if self.edit_prediction_visible_in_cursor_popover(true) {
 5955            return None;
 5956        }
 5957
 5958        match &active_inline_completion.completion {
 5959            InlineCompletion::Move { target, .. } => {
 5960                let target_display_point = target.to_display_point(editor_snapshot);
 5961
 5962                if self.edit_prediction_requires_modifier() {
 5963                    if !self.edit_prediction_preview_is_active() {
 5964                        return None;
 5965                    }
 5966
 5967                    self.render_edit_prediction_modifier_jump_popover(
 5968                        text_bounds,
 5969                        content_origin,
 5970                        visible_row_range,
 5971                        line_layouts,
 5972                        line_height,
 5973                        scroll_pixel_position,
 5974                        newest_selection_head,
 5975                        target_display_point,
 5976                        window,
 5977                        cx,
 5978                    )
 5979                } else {
 5980                    self.render_edit_prediction_eager_jump_popover(
 5981                        text_bounds,
 5982                        content_origin,
 5983                        editor_snapshot,
 5984                        visible_row_range,
 5985                        scroll_top,
 5986                        scroll_bottom,
 5987                        line_height,
 5988                        scroll_pixel_position,
 5989                        target_display_point,
 5990                        editor_width,
 5991                        window,
 5992                        cx,
 5993                    )
 5994                }
 5995            }
 5996            InlineCompletion::Edit {
 5997                display_mode: EditDisplayMode::Inline,
 5998                ..
 5999            } => None,
 6000            InlineCompletion::Edit {
 6001                display_mode: EditDisplayMode::TabAccept,
 6002                edits,
 6003                ..
 6004            } => {
 6005                let range = &edits.first()?.0;
 6006                let target_display_point = range.end.to_display_point(editor_snapshot);
 6007
 6008                self.render_edit_prediction_end_of_line_popover(
 6009                    "Accept",
 6010                    editor_snapshot,
 6011                    visible_row_range,
 6012                    target_display_point,
 6013                    line_height,
 6014                    scroll_pixel_position,
 6015                    content_origin,
 6016                    editor_width,
 6017                    window,
 6018                    cx,
 6019                )
 6020            }
 6021            InlineCompletion::Edit {
 6022                edits,
 6023                edit_preview,
 6024                display_mode: EditDisplayMode::DiffPopover,
 6025                snapshot,
 6026            } => self.render_edit_prediction_diff_popover(
 6027                text_bounds,
 6028                content_origin,
 6029                editor_snapshot,
 6030                visible_row_range,
 6031                line_layouts,
 6032                line_height,
 6033                scroll_pixel_position,
 6034                newest_selection_head,
 6035                editor_width,
 6036                style,
 6037                edits,
 6038                edit_preview,
 6039                snapshot,
 6040                window,
 6041                cx,
 6042            ),
 6043        }
 6044    }
 6045
 6046    #[allow(clippy::too_many_arguments)]
 6047    fn render_edit_prediction_modifier_jump_popover(
 6048        &mut self,
 6049        text_bounds: &Bounds<Pixels>,
 6050        content_origin: gpui::Point<Pixels>,
 6051        visible_row_range: Range<DisplayRow>,
 6052        line_layouts: &[LineWithInvisibles],
 6053        line_height: Pixels,
 6054        scroll_pixel_position: gpui::Point<Pixels>,
 6055        newest_selection_head: Option<DisplayPoint>,
 6056        target_display_point: DisplayPoint,
 6057        window: &mut Window,
 6058        cx: &mut App,
 6059    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6060        let scrolled_content_origin =
 6061            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 6062
 6063        const SCROLL_PADDING_Y: Pixels = px(12.);
 6064
 6065        if target_display_point.row() < visible_row_range.start {
 6066            return self.render_edit_prediction_scroll_popover(
 6067                |_| SCROLL_PADDING_Y,
 6068                IconName::ArrowUp,
 6069                visible_row_range,
 6070                line_layouts,
 6071                newest_selection_head,
 6072                scrolled_content_origin,
 6073                window,
 6074                cx,
 6075            );
 6076        } else if target_display_point.row() >= visible_row_range.end {
 6077            return self.render_edit_prediction_scroll_popover(
 6078                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 6079                IconName::ArrowDown,
 6080                visible_row_range,
 6081                line_layouts,
 6082                newest_selection_head,
 6083                scrolled_content_origin,
 6084                window,
 6085                cx,
 6086            );
 6087        }
 6088
 6089        const POLE_WIDTH: Pixels = px(2.);
 6090
 6091        let line_layout =
 6092            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 6093        let target_column = target_display_point.column() as usize;
 6094
 6095        let target_x = line_layout.x_for_index(target_column);
 6096        let target_y =
 6097            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 6098
 6099        let flag_on_right = target_x < text_bounds.size.width / 2.;
 6100
 6101        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 6102        border_color.l += 0.001;
 6103
 6104        let mut element = v_flex()
 6105            .items_end()
 6106            .when(flag_on_right, |el| el.items_start())
 6107            .child(if flag_on_right {
 6108                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6109                    .rounded_bl(px(0.))
 6110                    .rounded_tl(px(0.))
 6111                    .border_l_2()
 6112                    .border_color(border_color)
 6113            } else {
 6114                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6115                    .rounded_br(px(0.))
 6116                    .rounded_tr(px(0.))
 6117                    .border_r_2()
 6118                    .border_color(border_color)
 6119            })
 6120            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 6121            .into_any();
 6122
 6123        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6124
 6125        let mut origin = scrolled_content_origin + point(target_x, target_y)
 6126            - point(
 6127                if flag_on_right {
 6128                    POLE_WIDTH
 6129                } else {
 6130                    size.width - POLE_WIDTH
 6131                },
 6132                size.height - line_height,
 6133            );
 6134
 6135        origin.x = origin.x.max(content_origin.x);
 6136
 6137        element.prepaint_at(origin, window, cx);
 6138
 6139        Some((element, origin))
 6140    }
 6141
 6142    #[allow(clippy::too_many_arguments)]
 6143    fn render_edit_prediction_scroll_popover(
 6144        &mut self,
 6145        to_y: impl Fn(Size<Pixels>) -> Pixels,
 6146        scroll_icon: IconName,
 6147        visible_row_range: Range<DisplayRow>,
 6148        line_layouts: &[LineWithInvisibles],
 6149        newest_selection_head: Option<DisplayPoint>,
 6150        scrolled_content_origin: gpui::Point<Pixels>,
 6151        window: &mut Window,
 6152        cx: &mut App,
 6153    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6154        let mut element = self
 6155            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 6156            .into_any();
 6157
 6158        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6159
 6160        let cursor = newest_selection_head?;
 6161        let cursor_row_layout =
 6162            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6163        let cursor_column = cursor.column() as usize;
 6164
 6165        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6166
 6167        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6168
 6169        element.prepaint_at(origin, window, cx);
 6170        Some((element, origin))
 6171    }
 6172
 6173    #[allow(clippy::too_many_arguments)]
 6174    fn render_edit_prediction_eager_jump_popover(
 6175        &mut self,
 6176        text_bounds: &Bounds<Pixels>,
 6177        content_origin: gpui::Point<Pixels>,
 6178        editor_snapshot: &EditorSnapshot,
 6179        visible_row_range: Range<DisplayRow>,
 6180        scroll_top: f32,
 6181        scroll_bottom: f32,
 6182        line_height: Pixels,
 6183        scroll_pixel_position: gpui::Point<Pixels>,
 6184        target_display_point: DisplayPoint,
 6185        editor_width: Pixels,
 6186        window: &mut Window,
 6187        cx: &mut App,
 6188    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6189        if target_display_point.row().as_f32() < scroll_top {
 6190            let mut element = self
 6191                .render_edit_prediction_line_popover(
 6192                    "Jump to Edit",
 6193                    Some(IconName::ArrowUp),
 6194                    window,
 6195                    cx,
 6196                )?
 6197                .into_any();
 6198
 6199            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6200            let offset = point(
 6201                (text_bounds.size.width - size.width) / 2.,
 6202                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6203            );
 6204
 6205            let origin = text_bounds.origin + offset;
 6206            element.prepaint_at(origin, window, cx);
 6207            Some((element, origin))
 6208        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6209            let mut element = self
 6210                .render_edit_prediction_line_popover(
 6211                    "Jump to Edit",
 6212                    Some(IconName::ArrowDown),
 6213                    window,
 6214                    cx,
 6215                )?
 6216                .into_any();
 6217
 6218            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6219            let offset = point(
 6220                (text_bounds.size.width - size.width) / 2.,
 6221                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6222            );
 6223
 6224            let origin = text_bounds.origin + offset;
 6225            element.prepaint_at(origin, window, cx);
 6226            Some((element, origin))
 6227        } else {
 6228            self.render_edit_prediction_end_of_line_popover(
 6229                "Jump to Edit",
 6230                editor_snapshot,
 6231                visible_row_range,
 6232                target_display_point,
 6233                line_height,
 6234                scroll_pixel_position,
 6235                content_origin,
 6236                editor_width,
 6237                window,
 6238                cx,
 6239            )
 6240        }
 6241    }
 6242
 6243    #[allow(clippy::too_many_arguments)]
 6244    fn render_edit_prediction_end_of_line_popover(
 6245        self: &mut Editor,
 6246        label: &'static str,
 6247        editor_snapshot: &EditorSnapshot,
 6248        visible_row_range: Range<DisplayRow>,
 6249        target_display_point: DisplayPoint,
 6250        line_height: Pixels,
 6251        scroll_pixel_position: gpui::Point<Pixels>,
 6252        content_origin: gpui::Point<Pixels>,
 6253        editor_width: Pixels,
 6254        window: &mut Window,
 6255        cx: &mut App,
 6256    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6257        let target_line_end = DisplayPoint::new(
 6258            target_display_point.row(),
 6259            editor_snapshot.line_len(target_display_point.row()),
 6260        );
 6261
 6262        let mut element = self
 6263            .render_edit_prediction_line_popover(label, None, window, cx)?
 6264            .into_any();
 6265
 6266        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6267
 6268        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 6269
 6270        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 6271        let mut origin = start_point
 6272            + line_origin
 6273            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 6274        origin.x = origin.x.max(content_origin.x);
 6275
 6276        let max_x = content_origin.x + editor_width - size.width;
 6277
 6278        if origin.x > max_x {
 6279            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 6280
 6281            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 6282                origin.y += offset;
 6283                IconName::ArrowUp
 6284            } else {
 6285                origin.y -= offset;
 6286                IconName::ArrowDown
 6287            };
 6288
 6289            element = self
 6290                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 6291                .into_any();
 6292
 6293            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6294
 6295            origin.x = content_origin.x + editor_width - size.width - px(2.);
 6296        }
 6297
 6298        element.prepaint_at(origin, window, cx);
 6299        Some((element, origin))
 6300    }
 6301
 6302    #[allow(clippy::too_many_arguments)]
 6303    fn render_edit_prediction_diff_popover(
 6304        self: &Editor,
 6305        text_bounds: &Bounds<Pixels>,
 6306        content_origin: gpui::Point<Pixels>,
 6307        editor_snapshot: &EditorSnapshot,
 6308        visible_row_range: Range<DisplayRow>,
 6309        line_layouts: &[LineWithInvisibles],
 6310        line_height: Pixels,
 6311        scroll_pixel_position: gpui::Point<Pixels>,
 6312        newest_selection_head: Option<DisplayPoint>,
 6313        editor_width: Pixels,
 6314        style: &EditorStyle,
 6315        edits: &Vec<(Range<Anchor>, String)>,
 6316        edit_preview: &Option<language::EditPreview>,
 6317        snapshot: &language::BufferSnapshot,
 6318        window: &mut Window,
 6319        cx: &mut App,
 6320    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6321        let edit_start = edits
 6322            .first()
 6323            .unwrap()
 6324            .0
 6325            .start
 6326            .to_display_point(editor_snapshot);
 6327        let edit_end = edits
 6328            .last()
 6329            .unwrap()
 6330            .0
 6331            .end
 6332            .to_display_point(editor_snapshot);
 6333
 6334        let is_visible = visible_row_range.contains(&edit_start.row())
 6335            || visible_row_range.contains(&edit_end.row());
 6336        if !is_visible {
 6337            return None;
 6338        }
 6339
 6340        let highlighted_edits =
 6341            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 6342
 6343        let styled_text = highlighted_edits.to_styled_text(&style.text);
 6344        let line_count = highlighted_edits.text.lines().count();
 6345
 6346        const BORDER_WIDTH: Pixels = px(1.);
 6347
 6348        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 6349        let has_keybind = keybind.is_some();
 6350
 6351        let mut element = h_flex()
 6352            .items_start()
 6353            .child(
 6354                h_flex()
 6355                    .bg(cx.theme().colors().editor_background)
 6356                    .border(BORDER_WIDTH)
 6357                    .shadow_sm()
 6358                    .border_color(cx.theme().colors().border)
 6359                    .rounded_l_lg()
 6360                    .when(line_count > 1, |el| el.rounded_br_lg())
 6361                    .pr_1()
 6362                    .child(styled_text),
 6363            )
 6364            .child(
 6365                h_flex()
 6366                    .h(line_height + BORDER_WIDTH * px(2.))
 6367                    .px_1p5()
 6368                    .gap_1()
 6369                    // Workaround: For some reason, there's a gap if we don't do this
 6370                    .ml(-BORDER_WIDTH)
 6371                    .shadow(smallvec![gpui::BoxShadow {
 6372                        color: gpui::black().opacity(0.05),
 6373                        offset: point(px(1.), px(1.)),
 6374                        blur_radius: px(2.),
 6375                        spread_radius: px(0.),
 6376                    }])
 6377                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 6378                    .border(BORDER_WIDTH)
 6379                    .border_color(cx.theme().colors().border)
 6380                    .rounded_r_lg()
 6381                    .id("edit_prediction_diff_popover_keybind")
 6382                    .when(!has_keybind, |el| {
 6383                        let status_colors = cx.theme().status();
 6384
 6385                        el.bg(status_colors.error_background)
 6386                            .border_color(status_colors.error.opacity(0.6))
 6387                            .child(Icon::new(IconName::Info).color(Color::Error))
 6388                            .cursor_default()
 6389                            .hoverable_tooltip(move |_window, cx| {
 6390                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 6391                            })
 6392                    })
 6393                    .children(keybind),
 6394            )
 6395            .into_any();
 6396
 6397        let longest_row =
 6398            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 6399        let longest_line_width = if visible_row_range.contains(&longest_row) {
 6400            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 6401        } else {
 6402            layout_line(
 6403                longest_row,
 6404                editor_snapshot,
 6405                style,
 6406                editor_width,
 6407                |_| false,
 6408                window,
 6409                cx,
 6410            )
 6411            .width
 6412        };
 6413
 6414        let viewport_bounds =
 6415            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 6416                right: -EditorElement::SCROLLBAR_WIDTH,
 6417                ..Default::default()
 6418            });
 6419
 6420        let x_after_longest =
 6421            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 6422                - scroll_pixel_position.x;
 6423
 6424        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6425
 6426        // Fully visible if it can be displayed within the window (allow overlapping other
 6427        // panes). However, this is only allowed if the popover starts within text_bounds.
 6428        let can_position_to_the_right = x_after_longest < text_bounds.right()
 6429            && x_after_longest + element_bounds.width < viewport_bounds.right();
 6430
 6431        let mut origin = if can_position_to_the_right {
 6432            point(
 6433                x_after_longest,
 6434                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 6435                    - scroll_pixel_position.y,
 6436            )
 6437        } else {
 6438            let cursor_row = newest_selection_head.map(|head| head.row());
 6439            let above_edit = edit_start
 6440                .row()
 6441                .0
 6442                .checked_sub(line_count as u32)
 6443                .map(DisplayRow);
 6444            let below_edit = Some(edit_end.row() + 1);
 6445            let above_cursor =
 6446                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 6447            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 6448
 6449            // Place the edit popover adjacent to the edit if there is a location
 6450            // available that is onscreen and does not obscure the cursor. Otherwise,
 6451            // place it adjacent to the cursor.
 6452            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 6453                .into_iter()
 6454                .flatten()
 6455                .find(|&start_row| {
 6456                    let end_row = start_row + line_count as u32;
 6457                    visible_row_range.contains(&start_row)
 6458                        && visible_row_range.contains(&end_row)
 6459                        && cursor_row.map_or(true, |cursor_row| {
 6460                            !((start_row..end_row).contains(&cursor_row))
 6461                        })
 6462                })?;
 6463
 6464            content_origin
 6465                + point(
 6466                    -scroll_pixel_position.x,
 6467                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 6468                )
 6469        };
 6470
 6471        origin.x -= BORDER_WIDTH;
 6472
 6473        window.defer_draw(element, origin, 1);
 6474
 6475        // Do not return an element, since it will already be drawn due to defer_draw.
 6476        None
 6477    }
 6478
 6479    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 6480        px(30.)
 6481    }
 6482
 6483    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 6484        if self.read_only(cx) {
 6485            cx.theme().players().read_only()
 6486        } else {
 6487            self.style.as_ref().unwrap().local_player
 6488        }
 6489    }
 6490
 6491    fn render_edit_prediction_accept_keybind(
 6492        &self,
 6493        window: &mut Window,
 6494        cx: &App,
 6495    ) -> Option<AnyElement> {
 6496        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 6497        let accept_keystroke = accept_binding.keystroke()?;
 6498
 6499        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6500
 6501        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 6502            Color::Accent
 6503        } else {
 6504            Color::Muted
 6505        };
 6506
 6507        h_flex()
 6508            .px_0p5()
 6509            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 6510            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6511            .text_size(TextSize::XSmall.rems(cx))
 6512            .child(h_flex().children(ui::render_modifiers(
 6513                &accept_keystroke.modifiers,
 6514                PlatformStyle::platform(),
 6515                Some(modifiers_color),
 6516                Some(IconSize::XSmall.rems().into()),
 6517                true,
 6518            )))
 6519            .when(is_platform_style_mac, |parent| {
 6520                parent.child(accept_keystroke.key.clone())
 6521            })
 6522            .when(!is_platform_style_mac, |parent| {
 6523                parent.child(
 6524                    Key::new(
 6525                        util::capitalize(&accept_keystroke.key),
 6526                        Some(Color::Default),
 6527                    )
 6528                    .size(Some(IconSize::XSmall.rems().into())),
 6529                )
 6530            })
 6531            .into_any()
 6532            .into()
 6533    }
 6534
 6535    fn render_edit_prediction_line_popover(
 6536        &self,
 6537        label: impl Into<SharedString>,
 6538        icon: Option<IconName>,
 6539        window: &mut Window,
 6540        cx: &App,
 6541    ) -> Option<Stateful<Div>> {
 6542        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 6543
 6544        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 6545        let has_keybind = keybind.is_some();
 6546
 6547        let result = h_flex()
 6548            .id("ep-line-popover")
 6549            .py_0p5()
 6550            .pl_1()
 6551            .pr(padding_right)
 6552            .gap_1()
 6553            .rounded_md()
 6554            .border_1()
 6555            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6556            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 6557            .shadow_sm()
 6558            .when(!has_keybind, |el| {
 6559                let status_colors = cx.theme().status();
 6560
 6561                el.bg(status_colors.error_background)
 6562                    .border_color(status_colors.error.opacity(0.6))
 6563                    .pl_2()
 6564                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 6565                    .cursor_default()
 6566                    .hoverable_tooltip(move |_window, cx| {
 6567                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 6568                    })
 6569            })
 6570            .children(keybind)
 6571            .child(
 6572                Label::new(label)
 6573                    .size(LabelSize::Small)
 6574                    .when(!has_keybind, |el| {
 6575                        el.color(cx.theme().status().error.into()).strikethrough()
 6576                    }),
 6577            )
 6578            .when(!has_keybind, |el| {
 6579                el.child(
 6580                    h_flex().ml_1().child(
 6581                        Icon::new(IconName::Info)
 6582                            .size(IconSize::Small)
 6583                            .color(cx.theme().status().error.into()),
 6584                    ),
 6585                )
 6586            })
 6587            .when_some(icon, |element, icon| {
 6588                element.child(
 6589                    div()
 6590                        .mt(px(1.5))
 6591                        .child(Icon::new(icon).size(IconSize::Small)),
 6592                )
 6593            });
 6594
 6595        Some(result)
 6596    }
 6597
 6598    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 6599        let accent_color = cx.theme().colors().text_accent;
 6600        let editor_bg_color = cx.theme().colors().editor_background;
 6601        editor_bg_color.blend(accent_color.opacity(0.1))
 6602    }
 6603
 6604    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 6605        let accent_color = cx.theme().colors().text_accent;
 6606        let editor_bg_color = cx.theme().colors().editor_background;
 6607        editor_bg_color.blend(accent_color.opacity(0.6))
 6608    }
 6609
 6610    #[allow(clippy::too_many_arguments)]
 6611    fn render_edit_prediction_cursor_popover(
 6612        &self,
 6613        min_width: Pixels,
 6614        max_width: Pixels,
 6615        cursor_point: Point,
 6616        style: &EditorStyle,
 6617        accept_keystroke: Option<&gpui::Keystroke>,
 6618        _window: &Window,
 6619        cx: &mut Context<Editor>,
 6620    ) -> Option<AnyElement> {
 6621        let provider = self.edit_prediction_provider.as_ref()?;
 6622
 6623        if provider.provider.needs_terms_acceptance(cx) {
 6624            return Some(
 6625                h_flex()
 6626                    .min_w(min_width)
 6627                    .flex_1()
 6628                    .px_2()
 6629                    .py_1()
 6630                    .gap_3()
 6631                    .elevation_2(cx)
 6632                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 6633                    .id("accept-terms")
 6634                    .cursor_pointer()
 6635                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 6636                    .on_click(cx.listener(|this, _event, window, cx| {
 6637                        cx.stop_propagation();
 6638                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 6639                        window.dispatch_action(
 6640                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 6641                            cx,
 6642                        );
 6643                    }))
 6644                    .child(
 6645                        h_flex()
 6646                            .flex_1()
 6647                            .gap_2()
 6648                            .child(Icon::new(IconName::ZedPredict))
 6649                            .child(Label::new("Accept Terms of Service"))
 6650                            .child(div().w_full())
 6651                            .child(
 6652                                Icon::new(IconName::ArrowUpRight)
 6653                                    .color(Color::Muted)
 6654                                    .size(IconSize::Small),
 6655                            )
 6656                            .into_any_element(),
 6657                    )
 6658                    .into_any(),
 6659            );
 6660        }
 6661
 6662        let is_refreshing = provider.provider.is_refreshing(cx);
 6663
 6664        fn pending_completion_container() -> Div {
 6665            h_flex()
 6666                .h_full()
 6667                .flex_1()
 6668                .gap_2()
 6669                .child(Icon::new(IconName::ZedPredict))
 6670        }
 6671
 6672        let completion = match &self.active_inline_completion {
 6673            Some(prediction) => {
 6674                if !self.has_visible_completions_menu() {
 6675                    const RADIUS: Pixels = px(6.);
 6676                    const BORDER_WIDTH: Pixels = px(1.);
 6677
 6678                    return Some(
 6679                        h_flex()
 6680                            .elevation_2(cx)
 6681                            .border(BORDER_WIDTH)
 6682                            .border_color(cx.theme().colors().border)
 6683                            .when(accept_keystroke.is_none(), |el| {
 6684                                el.border_color(cx.theme().status().error)
 6685                            })
 6686                            .rounded(RADIUS)
 6687                            .rounded_tl(px(0.))
 6688                            .overflow_hidden()
 6689                            .child(div().px_1p5().child(match &prediction.completion {
 6690                                InlineCompletion::Move { target, snapshot } => {
 6691                                    use text::ToPoint as _;
 6692                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 6693                                    {
 6694                                        Icon::new(IconName::ZedPredictDown)
 6695                                    } else {
 6696                                        Icon::new(IconName::ZedPredictUp)
 6697                                    }
 6698                                }
 6699                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 6700                            }))
 6701                            .child(
 6702                                h_flex()
 6703                                    .gap_1()
 6704                                    .py_1()
 6705                                    .px_2()
 6706                                    .rounded_r(RADIUS - BORDER_WIDTH)
 6707                                    .border_l_1()
 6708                                    .border_color(cx.theme().colors().border)
 6709                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6710                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 6711                                        el.child(
 6712                                            Label::new("Hold")
 6713                                                .size(LabelSize::Small)
 6714                                                .when(accept_keystroke.is_none(), |el| {
 6715                                                    el.strikethrough()
 6716                                                })
 6717                                                .line_height_style(LineHeightStyle::UiLabel),
 6718                                        )
 6719                                    })
 6720                                    .id("edit_prediction_cursor_popover_keybind")
 6721                                    .when(accept_keystroke.is_none(), |el| {
 6722                                        let status_colors = cx.theme().status();
 6723
 6724                                        el.bg(status_colors.error_background)
 6725                                            .border_color(status_colors.error.opacity(0.6))
 6726                                            .child(Icon::new(IconName::Info).color(Color::Error))
 6727                                            .cursor_default()
 6728                                            .hoverable_tooltip(move |_window, cx| {
 6729                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 6730                                                    .into()
 6731                                            })
 6732                                    })
 6733                                    .when_some(
 6734                                        accept_keystroke.as_ref(),
 6735                                        |el, accept_keystroke| {
 6736                                            el.child(h_flex().children(ui::render_modifiers(
 6737                                                &accept_keystroke.modifiers,
 6738                                                PlatformStyle::platform(),
 6739                                                Some(Color::Default),
 6740                                                Some(IconSize::XSmall.rems().into()),
 6741                                                false,
 6742                                            )))
 6743                                        },
 6744                                    ),
 6745                            )
 6746                            .into_any(),
 6747                    );
 6748                }
 6749
 6750                self.render_edit_prediction_cursor_popover_preview(
 6751                    prediction,
 6752                    cursor_point,
 6753                    style,
 6754                    cx,
 6755                )?
 6756            }
 6757
 6758            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 6759                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 6760                    stale_completion,
 6761                    cursor_point,
 6762                    style,
 6763                    cx,
 6764                )?,
 6765
 6766                None => {
 6767                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6768                }
 6769            },
 6770
 6771            None => pending_completion_container().child(Label::new("No Prediction")),
 6772        };
 6773
 6774        let completion = if is_refreshing {
 6775            completion
 6776                .with_animation(
 6777                    "loading-completion",
 6778                    Animation::new(Duration::from_secs(2))
 6779                        .repeat()
 6780                        .with_easing(pulsating_between(0.4, 0.8)),
 6781                    |label, delta| label.opacity(delta),
 6782                )
 6783                .into_any_element()
 6784        } else {
 6785            completion.into_any_element()
 6786        };
 6787
 6788        let has_completion = self.active_inline_completion.is_some();
 6789
 6790        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6791        Some(
 6792            h_flex()
 6793                .min_w(min_width)
 6794                .max_w(max_width)
 6795                .flex_1()
 6796                .elevation_2(cx)
 6797                .border_color(cx.theme().colors().border)
 6798                .child(
 6799                    div()
 6800                        .flex_1()
 6801                        .py_1()
 6802                        .px_2()
 6803                        .overflow_hidden()
 6804                        .child(completion),
 6805                )
 6806                .when_some(accept_keystroke, |el, accept_keystroke| {
 6807                    if !accept_keystroke.modifiers.modified() {
 6808                        return el;
 6809                    }
 6810
 6811                    el.child(
 6812                        h_flex()
 6813                            .h_full()
 6814                            .border_l_1()
 6815                            .rounded_r_lg()
 6816                            .border_color(cx.theme().colors().border)
 6817                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6818                            .gap_1()
 6819                            .py_1()
 6820                            .px_2()
 6821                            .child(
 6822                                h_flex()
 6823                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6824                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6825                                    .child(h_flex().children(ui::render_modifiers(
 6826                                        &accept_keystroke.modifiers,
 6827                                        PlatformStyle::platform(),
 6828                                        Some(if !has_completion {
 6829                                            Color::Muted
 6830                                        } else {
 6831                                            Color::Default
 6832                                        }),
 6833                                        None,
 6834                                        false,
 6835                                    ))),
 6836                            )
 6837                            .child(Label::new("Preview").into_any_element())
 6838                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6839                    )
 6840                })
 6841                .into_any(),
 6842        )
 6843    }
 6844
 6845    fn render_edit_prediction_cursor_popover_preview(
 6846        &self,
 6847        completion: &InlineCompletionState,
 6848        cursor_point: Point,
 6849        style: &EditorStyle,
 6850        cx: &mut Context<Editor>,
 6851    ) -> Option<Div> {
 6852        use text::ToPoint as _;
 6853
 6854        fn render_relative_row_jump(
 6855            prefix: impl Into<String>,
 6856            current_row: u32,
 6857            target_row: u32,
 6858        ) -> Div {
 6859            let (row_diff, arrow) = if target_row < current_row {
 6860                (current_row - target_row, IconName::ArrowUp)
 6861            } else {
 6862                (target_row - current_row, IconName::ArrowDown)
 6863            };
 6864
 6865            h_flex()
 6866                .child(
 6867                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6868                        .color(Color::Muted)
 6869                        .size(LabelSize::Small),
 6870                )
 6871                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6872        }
 6873
 6874        match &completion.completion {
 6875            InlineCompletion::Move {
 6876                target, snapshot, ..
 6877            } => Some(
 6878                h_flex()
 6879                    .px_2()
 6880                    .gap_2()
 6881                    .flex_1()
 6882                    .child(
 6883                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6884                            Icon::new(IconName::ZedPredictDown)
 6885                        } else {
 6886                            Icon::new(IconName::ZedPredictUp)
 6887                        },
 6888                    )
 6889                    .child(Label::new("Jump to Edit")),
 6890            ),
 6891
 6892            InlineCompletion::Edit {
 6893                edits,
 6894                edit_preview,
 6895                snapshot,
 6896                display_mode: _,
 6897            } => {
 6898                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6899
 6900                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6901                    &snapshot,
 6902                    &edits,
 6903                    edit_preview.as_ref()?,
 6904                    true,
 6905                    cx,
 6906                )
 6907                .first_line_preview();
 6908
 6909                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6910                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 6911
 6912                let preview = h_flex()
 6913                    .gap_1()
 6914                    .min_w_16()
 6915                    .child(styled_text)
 6916                    .when(has_more_lines, |parent| parent.child(""));
 6917
 6918                let left = if first_edit_row != cursor_point.row {
 6919                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6920                        .into_any_element()
 6921                } else {
 6922                    Icon::new(IconName::ZedPredict).into_any_element()
 6923                };
 6924
 6925                Some(
 6926                    h_flex()
 6927                        .h_full()
 6928                        .flex_1()
 6929                        .gap_2()
 6930                        .pr_1()
 6931                        .overflow_x_hidden()
 6932                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6933                        .child(left)
 6934                        .child(preview),
 6935                )
 6936            }
 6937        }
 6938    }
 6939
 6940    fn render_context_menu(
 6941        &self,
 6942        style: &EditorStyle,
 6943        max_height_in_lines: u32,
 6944        y_flipped: bool,
 6945        window: &mut Window,
 6946        cx: &mut Context<Editor>,
 6947    ) -> Option<AnyElement> {
 6948        let menu = self.context_menu.borrow();
 6949        let menu = menu.as_ref()?;
 6950        if !menu.visible() {
 6951            return None;
 6952        };
 6953        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6954    }
 6955
 6956    fn render_context_menu_aside(
 6957        &mut self,
 6958        max_size: Size<Pixels>,
 6959        window: &mut Window,
 6960        cx: &mut Context<Editor>,
 6961    ) -> Option<AnyElement> {
 6962        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 6963            if menu.visible() {
 6964                menu.render_aside(self, max_size, window, cx)
 6965            } else {
 6966                None
 6967            }
 6968        })
 6969    }
 6970
 6971    fn hide_context_menu(
 6972        &mut self,
 6973        window: &mut Window,
 6974        cx: &mut Context<Self>,
 6975    ) -> Option<CodeContextMenu> {
 6976        cx.notify();
 6977        self.completion_tasks.clear();
 6978        let context_menu = self.context_menu.borrow_mut().take();
 6979        self.stale_inline_completion_in_menu.take();
 6980        self.update_visible_inline_completion(window, cx);
 6981        context_menu
 6982    }
 6983
 6984    fn show_snippet_choices(
 6985        &mut self,
 6986        choices: &Vec<String>,
 6987        selection: Range<Anchor>,
 6988        cx: &mut Context<Self>,
 6989    ) {
 6990        if selection.start.buffer_id.is_none() {
 6991            return;
 6992        }
 6993        let buffer_id = selection.start.buffer_id.unwrap();
 6994        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6995        let id = post_inc(&mut self.next_completion_id);
 6996
 6997        if let Some(buffer) = buffer {
 6998            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6999                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 7000            ));
 7001        }
 7002    }
 7003
 7004    pub fn insert_snippet(
 7005        &mut self,
 7006        insertion_ranges: &[Range<usize>],
 7007        snippet: Snippet,
 7008        window: &mut Window,
 7009        cx: &mut Context<Self>,
 7010    ) -> Result<()> {
 7011        struct Tabstop<T> {
 7012            is_end_tabstop: bool,
 7013            ranges: Vec<Range<T>>,
 7014            choices: Option<Vec<String>>,
 7015        }
 7016
 7017        let tabstops = self.buffer.update(cx, |buffer, cx| {
 7018            let snippet_text: Arc<str> = snippet.text.clone().into();
 7019            buffer.edit(
 7020                insertion_ranges
 7021                    .iter()
 7022                    .cloned()
 7023                    .map(|range| (range, snippet_text.clone())),
 7024                Some(AutoindentMode::EachLine),
 7025                cx,
 7026            );
 7027
 7028            let snapshot = &*buffer.read(cx);
 7029            let snippet = &snippet;
 7030            snippet
 7031                .tabstops
 7032                .iter()
 7033                .map(|tabstop| {
 7034                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 7035                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 7036                    });
 7037                    let mut tabstop_ranges = tabstop
 7038                        .ranges
 7039                        .iter()
 7040                        .flat_map(|tabstop_range| {
 7041                            let mut delta = 0_isize;
 7042                            insertion_ranges.iter().map(move |insertion_range| {
 7043                                let insertion_start = insertion_range.start as isize + delta;
 7044                                delta +=
 7045                                    snippet.text.len() as isize - insertion_range.len() as isize;
 7046
 7047                                let start = ((insertion_start + tabstop_range.start) as usize)
 7048                                    .min(snapshot.len());
 7049                                let end = ((insertion_start + tabstop_range.end) as usize)
 7050                                    .min(snapshot.len());
 7051                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 7052                            })
 7053                        })
 7054                        .collect::<Vec<_>>();
 7055                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 7056
 7057                    Tabstop {
 7058                        is_end_tabstop,
 7059                        ranges: tabstop_ranges,
 7060                        choices: tabstop.choices.clone(),
 7061                    }
 7062                })
 7063                .collect::<Vec<_>>()
 7064        });
 7065        if let Some(tabstop) = tabstops.first() {
 7066            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7067                s.select_ranges(tabstop.ranges.iter().cloned());
 7068            });
 7069
 7070            if let Some(choices) = &tabstop.choices {
 7071                if let Some(selection) = tabstop.ranges.first() {
 7072                    self.show_snippet_choices(choices, selection.clone(), cx)
 7073                }
 7074            }
 7075
 7076            // If we're already at the last tabstop and it's at the end of the snippet,
 7077            // we're done, we don't need to keep the state around.
 7078            if !tabstop.is_end_tabstop {
 7079                let choices = tabstops
 7080                    .iter()
 7081                    .map(|tabstop| tabstop.choices.clone())
 7082                    .collect();
 7083
 7084                let ranges = tabstops
 7085                    .into_iter()
 7086                    .map(|tabstop| tabstop.ranges)
 7087                    .collect::<Vec<_>>();
 7088
 7089                self.snippet_stack.push(SnippetState {
 7090                    active_index: 0,
 7091                    ranges,
 7092                    choices,
 7093                });
 7094            }
 7095
 7096            // Check whether the just-entered snippet ends with an auto-closable bracket.
 7097            if self.autoclose_regions.is_empty() {
 7098                let snapshot = self.buffer.read(cx).snapshot(cx);
 7099                for selection in &mut self.selections.all::<Point>(cx) {
 7100                    let selection_head = selection.head();
 7101                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 7102                        continue;
 7103                    };
 7104
 7105                    let mut bracket_pair = None;
 7106                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 7107                    let prev_chars = snapshot
 7108                        .reversed_chars_at(selection_head)
 7109                        .collect::<String>();
 7110                    for (pair, enabled) in scope.brackets() {
 7111                        if enabled
 7112                            && pair.close
 7113                            && prev_chars.starts_with(pair.start.as_str())
 7114                            && next_chars.starts_with(pair.end.as_str())
 7115                        {
 7116                            bracket_pair = Some(pair.clone());
 7117                            break;
 7118                        }
 7119                    }
 7120                    if let Some(pair) = bracket_pair {
 7121                        let start = snapshot.anchor_after(selection_head);
 7122                        let end = snapshot.anchor_after(selection_head);
 7123                        self.autoclose_regions.push(AutocloseRegion {
 7124                            selection_id: selection.id,
 7125                            range: start..end,
 7126                            pair,
 7127                        });
 7128                    }
 7129                }
 7130            }
 7131        }
 7132        Ok(())
 7133    }
 7134
 7135    pub fn move_to_next_snippet_tabstop(
 7136        &mut self,
 7137        window: &mut Window,
 7138        cx: &mut Context<Self>,
 7139    ) -> bool {
 7140        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 7141    }
 7142
 7143    pub fn move_to_prev_snippet_tabstop(
 7144        &mut self,
 7145        window: &mut Window,
 7146        cx: &mut Context<Self>,
 7147    ) -> bool {
 7148        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 7149    }
 7150
 7151    pub fn move_to_snippet_tabstop(
 7152        &mut self,
 7153        bias: Bias,
 7154        window: &mut Window,
 7155        cx: &mut Context<Self>,
 7156    ) -> bool {
 7157        if let Some(mut snippet) = self.snippet_stack.pop() {
 7158            match bias {
 7159                Bias::Left => {
 7160                    if snippet.active_index > 0 {
 7161                        snippet.active_index -= 1;
 7162                    } else {
 7163                        self.snippet_stack.push(snippet);
 7164                        return false;
 7165                    }
 7166                }
 7167                Bias::Right => {
 7168                    if snippet.active_index + 1 < snippet.ranges.len() {
 7169                        snippet.active_index += 1;
 7170                    } else {
 7171                        self.snippet_stack.push(snippet);
 7172                        return false;
 7173                    }
 7174                }
 7175            }
 7176            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 7177                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7178                    s.select_anchor_ranges(current_ranges.iter().cloned())
 7179                });
 7180
 7181                if let Some(choices) = &snippet.choices[snippet.active_index] {
 7182                    if let Some(selection) = current_ranges.first() {
 7183                        self.show_snippet_choices(&choices, selection.clone(), cx);
 7184                    }
 7185                }
 7186
 7187                // If snippet state is not at the last tabstop, push it back on the stack
 7188                if snippet.active_index + 1 < snippet.ranges.len() {
 7189                    self.snippet_stack.push(snippet);
 7190                }
 7191                return true;
 7192            }
 7193        }
 7194
 7195        false
 7196    }
 7197
 7198    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 7199        self.transact(window, cx, |this, window, cx| {
 7200            this.select_all(&SelectAll, window, cx);
 7201            this.insert("", window, cx);
 7202        });
 7203    }
 7204
 7205    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 7206        self.transact(window, cx, |this, window, cx| {
 7207            this.select_autoclose_pair(window, cx);
 7208            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 7209            if !this.linked_edit_ranges.is_empty() {
 7210                let selections = this.selections.all::<MultiBufferPoint>(cx);
 7211                let snapshot = this.buffer.read(cx).snapshot(cx);
 7212
 7213                for selection in selections.iter() {
 7214                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 7215                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 7216                    if selection_start.buffer_id != selection_end.buffer_id {
 7217                        continue;
 7218                    }
 7219                    if let Some(ranges) =
 7220                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 7221                    {
 7222                        for (buffer, entries) in ranges {
 7223                            linked_ranges.entry(buffer).or_default().extend(entries);
 7224                        }
 7225                    }
 7226                }
 7227            }
 7228
 7229            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7230            if !this.selections.line_mode {
 7231                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 7232                for selection in &mut selections {
 7233                    if selection.is_empty() {
 7234                        let old_head = selection.head();
 7235                        let mut new_head =
 7236                            movement::left(&display_map, old_head.to_display_point(&display_map))
 7237                                .to_point(&display_map);
 7238                        if let Some((buffer, line_buffer_range)) = display_map
 7239                            .buffer_snapshot
 7240                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 7241                        {
 7242                            let indent_size =
 7243                                buffer.indent_size_for_line(line_buffer_range.start.row);
 7244                            let indent_len = match indent_size.kind {
 7245                                IndentKind::Space => {
 7246                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 7247                                }
 7248                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 7249                            };
 7250                            if old_head.column <= indent_size.len && old_head.column > 0 {
 7251                                let indent_len = indent_len.get();
 7252                                new_head = cmp::min(
 7253                                    new_head,
 7254                                    MultiBufferPoint::new(
 7255                                        old_head.row,
 7256                                        ((old_head.column - 1) / indent_len) * indent_len,
 7257                                    ),
 7258                                );
 7259                            }
 7260                        }
 7261
 7262                        selection.set_head(new_head, SelectionGoal::None);
 7263                    }
 7264                }
 7265            }
 7266
 7267            this.signature_help_state.set_backspace_pressed(true);
 7268            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7269                s.select(selections)
 7270            });
 7271            this.insert("", window, cx);
 7272            let empty_str: Arc<str> = Arc::from("");
 7273            for (buffer, edits) in linked_ranges {
 7274                let snapshot = buffer.read(cx).snapshot();
 7275                use text::ToPoint as TP;
 7276
 7277                let edits = edits
 7278                    .into_iter()
 7279                    .map(|range| {
 7280                        let end_point = TP::to_point(&range.end, &snapshot);
 7281                        let mut start_point = TP::to_point(&range.start, &snapshot);
 7282
 7283                        if end_point == start_point {
 7284                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 7285                                .saturating_sub(1);
 7286                            start_point =
 7287                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 7288                        };
 7289
 7290                        (start_point..end_point, empty_str.clone())
 7291                    })
 7292                    .sorted_by_key(|(range, _)| range.start)
 7293                    .collect::<Vec<_>>();
 7294                buffer.update(cx, |this, cx| {
 7295                    this.edit(edits, None, cx);
 7296                })
 7297            }
 7298            this.refresh_inline_completion(true, false, window, cx);
 7299            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 7300        });
 7301    }
 7302
 7303    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 7304        self.transact(window, cx, |this, window, cx| {
 7305            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7306                let line_mode = s.line_mode;
 7307                s.move_with(|map, selection| {
 7308                    if selection.is_empty() && !line_mode {
 7309                        let cursor = movement::right(map, selection.head());
 7310                        selection.end = cursor;
 7311                        selection.reversed = true;
 7312                        selection.goal = SelectionGoal::None;
 7313                    }
 7314                })
 7315            });
 7316            this.insert("", window, cx);
 7317            this.refresh_inline_completion(true, false, window, cx);
 7318        });
 7319    }
 7320
 7321    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 7322        if self.move_to_prev_snippet_tabstop(window, cx) {
 7323            return;
 7324        }
 7325
 7326        self.outdent(&Outdent, window, cx);
 7327    }
 7328
 7329    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 7330        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 7331            return;
 7332        }
 7333
 7334        let mut selections = self.selections.all_adjusted(cx);
 7335        let buffer = self.buffer.read(cx);
 7336        let snapshot = buffer.snapshot(cx);
 7337        let rows_iter = selections.iter().map(|s| s.head().row);
 7338        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 7339
 7340        let mut edits = Vec::new();
 7341        let mut prev_edited_row = 0;
 7342        let mut row_delta = 0;
 7343        for selection in &mut selections {
 7344            if selection.start.row != prev_edited_row {
 7345                row_delta = 0;
 7346            }
 7347            prev_edited_row = selection.end.row;
 7348
 7349            // If the selection is non-empty, then increase the indentation of the selected lines.
 7350            if !selection.is_empty() {
 7351                row_delta =
 7352                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7353                continue;
 7354            }
 7355
 7356            // If the selection is empty and the cursor is in the leading whitespace before the
 7357            // suggested indentation, then auto-indent the line.
 7358            let cursor = selection.head();
 7359            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 7360            if let Some(suggested_indent) =
 7361                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 7362            {
 7363                if cursor.column < suggested_indent.len
 7364                    && cursor.column <= current_indent.len
 7365                    && current_indent.len <= suggested_indent.len
 7366                {
 7367                    selection.start = Point::new(cursor.row, suggested_indent.len);
 7368                    selection.end = selection.start;
 7369                    if row_delta == 0 {
 7370                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 7371                            cursor.row,
 7372                            current_indent,
 7373                            suggested_indent,
 7374                        ));
 7375                        row_delta = suggested_indent.len - current_indent.len;
 7376                    }
 7377                    continue;
 7378                }
 7379            }
 7380
 7381            // Otherwise, insert a hard or soft tab.
 7382            let settings = buffer.language_settings_at(cursor, cx);
 7383            let tab_size = if settings.hard_tabs {
 7384                IndentSize::tab()
 7385            } else {
 7386                let tab_size = settings.tab_size.get();
 7387                let char_column = snapshot
 7388                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 7389                    .flat_map(str::chars)
 7390                    .count()
 7391                    + row_delta as usize;
 7392                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 7393                IndentSize::spaces(chars_to_next_tab_stop)
 7394            };
 7395            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 7396            selection.end = selection.start;
 7397            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 7398            row_delta += tab_size.len;
 7399        }
 7400
 7401        self.transact(window, cx, |this, window, cx| {
 7402            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7403            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7404                s.select(selections)
 7405            });
 7406            this.refresh_inline_completion(true, false, window, cx);
 7407        });
 7408    }
 7409
 7410    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 7411        if self.read_only(cx) {
 7412            return;
 7413        }
 7414        let mut selections = self.selections.all::<Point>(cx);
 7415        let mut prev_edited_row = 0;
 7416        let mut row_delta = 0;
 7417        let mut edits = Vec::new();
 7418        let buffer = self.buffer.read(cx);
 7419        let snapshot = buffer.snapshot(cx);
 7420        for selection in &mut selections {
 7421            if selection.start.row != prev_edited_row {
 7422                row_delta = 0;
 7423            }
 7424            prev_edited_row = selection.end.row;
 7425
 7426            row_delta =
 7427                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7428        }
 7429
 7430        self.transact(window, cx, |this, window, cx| {
 7431            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7432            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7433                s.select(selections)
 7434            });
 7435        });
 7436    }
 7437
 7438    fn indent_selection(
 7439        buffer: &MultiBuffer,
 7440        snapshot: &MultiBufferSnapshot,
 7441        selection: &mut Selection<Point>,
 7442        edits: &mut Vec<(Range<Point>, String)>,
 7443        delta_for_start_row: u32,
 7444        cx: &App,
 7445    ) -> u32 {
 7446        let settings = buffer.language_settings_at(selection.start, cx);
 7447        let tab_size = settings.tab_size.get();
 7448        let indent_kind = if settings.hard_tabs {
 7449            IndentKind::Tab
 7450        } else {
 7451            IndentKind::Space
 7452        };
 7453        let mut start_row = selection.start.row;
 7454        let mut end_row = selection.end.row + 1;
 7455
 7456        // If a selection ends at the beginning of a line, don't indent
 7457        // that last line.
 7458        if selection.end.column == 0 && selection.end.row > selection.start.row {
 7459            end_row -= 1;
 7460        }
 7461
 7462        // Avoid re-indenting a row that has already been indented by a
 7463        // previous selection, but still update this selection's column
 7464        // to reflect that indentation.
 7465        if delta_for_start_row > 0 {
 7466            start_row += 1;
 7467            selection.start.column += delta_for_start_row;
 7468            if selection.end.row == selection.start.row {
 7469                selection.end.column += delta_for_start_row;
 7470            }
 7471        }
 7472
 7473        let mut delta_for_end_row = 0;
 7474        let has_multiple_rows = start_row + 1 != end_row;
 7475        for row in start_row..end_row {
 7476            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 7477            let indent_delta = match (current_indent.kind, indent_kind) {
 7478                (IndentKind::Space, IndentKind::Space) => {
 7479                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 7480                    IndentSize::spaces(columns_to_next_tab_stop)
 7481                }
 7482                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 7483                (_, IndentKind::Tab) => IndentSize::tab(),
 7484            };
 7485
 7486            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 7487                0
 7488            } else {
 7489                selection.start.column
 7490            };
 7491            let row_start = Point::new(row, start);
 7492            edits.push((
 7493                row_start..row_start,
 7494                indent_delta.chars().collect::<String>(),
 7495            ));
 7496
 7497            // Update this selection's endpoints to reflect the indentation.
 7498            if row == selection.start.row {
 7499                selection.start.column += indent_delta.len;
 7500            }
 7501            if row == selection.end.row {
 7502                selection.end.column += indent_delta.len;
 7503                delta_for_end_row = indent_delta.len;
 7504            }
 7505        }
 7506
 7507        if selection.start.row == selection.end.row {
 7508            delta_for_start_row + delta_for_end_row
 7509        } else {
 7510            delta_for_end_row
 7511        }
 7512    }
 7513
 7514    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 7515        if self.read_only(cx) {
 7516            return;
 7517        }
 7518        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7519        let selections = self.selections.all::<Point>(cx);
 7520        let mut deletion_ranges = Vec::new();
 7521        let mut last_outdent = None;
 7522        {
 7523            let buffer = self.buffer.read(cx);
 7524            let snapshot = buffer.snapshot(cx);
 7525            for selection in &selections {
 7526                let settings = buffer.language_settings_at(selection.start, cx);
 7527                let tab_size = settings.tab_size.get();
 7528                let mut rows = selection.spanned_rows(false, &display_map);
 7529
 7530                // Avoid re-outdenting a row that has already been outdented by a
 7531                // previous selection.
 7532                if let Some(last_row) = last_outdent {
 7533                    if last_row == rows.start {
 7534                        rows.start = rows.start.next_row();
 7535                    }
 7536                }
 7537                let has_multiple_rows = rows.len() > 1;
 7538                for row in rows.iter_rows() {
 7539                    let indent_size = snapshot.indent_size_for_line(row);
 7540                    if indent_size.len > 0 {
 7541                        let deletion_len = match indent_size.kind {
 7542                            IndentKind::Space => {
 7543                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 7544                                if columns_to_prev_tab_stop == 0 {
 7545                                    tab_size
 7546                                } else {
 7547                                    columns_to_prev_tab_stop
 7548                                }
 7549                            }
 7550                            IndentKind::Tab => 1,
 7551                        };
 7552                        let start = if has_multiple_rows
 7553                            || deletion_len > selection.start.column
 7554                            || indent_size.len < selection.start.column
 7555                        {
 7556                            0
 7557                        } else {
 7558                            selection.start.column - deletion_len
 7559                        };
 7560                        deletion_ranges.push(
 7561                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 7562                        );
 7563                        last_outdent = Some(row);
 7564                    }
 7565                }
 7566            }
 7567        }
 7568
 7569        self.transact(window, cx, |this, window, cx| {
 7570            this.buffer.update(cx, |buffer, cx| {
 7571                let empty_str: Arc<str> = Arc::default();
 7572                buffer.edit(
 7573                    deletion_ranges
 7574                        .into_iter()
 7575                        .map(|range| (range, empty_str.clone())),
 7576                    None,
 7577                    cx,
 7578                );
 7579            });
 7580            let selections = this.selections.all::<usize>(cx);
 7581            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7582                s.select(selections)
 7583            });
 7584        });
 7585    }
 7586
 7587    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 7588        if self.read_only(cx) {
 7589            return;
 7590        }
 7591        let selections = self
 7592            .selections
 7593            .all::<usize>(cx)
 7594            .into_iter()
 7595            .map(|s| s.range());
 7596
 7597        self.transact(window, cx, |this, window, cx| {
 7598            this.buffer.update(cx, |buffer, cx| {
 7599                buffer.autoindent_ranges(selections, cx);
 7600            });
 7601            let selections = this.selections.all::<usize>(cx);
 7602            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7603                s.select(selections)
 7604            });
 7605        });
 7606    }
 7607
 7608    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 7609        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7610        let selections = self.selections.all::<Point>(cx);
 7611
 7612        let mut new_cursors = Vec::new();
 7613        let mut edit_ranges = Vec::new();
 7614        let mut selections = selections.iter().peekable();
 7615        while let Some(selection) = selections.next() {
 7616            let mut rows = selection.spanned_rows(false, &display_map);
 7617            let goal_display_column = selection.head().to_display_point(&display_map).column();
 7618
 7619            // Accumulate contiguous regions of rows that we want to delete.
 7620            while let Some(next_selection) = selections.peek() {
 7621                let next_rows = next_selection.spanned_rows(false, &display_map);
 7622                if next_rows.start <= rows.end {
 7623                    rows.end = next_rows.end;
 7624                    selections.next().unwrap();
 7625                } else {
 7626                    break;
 7627                }
 7628            }
 7629
 7630            let buffer = &display_map.buffer_snapshot;
 7631            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 7632            let edit_end;
 7633            let cursor_buffer_row;
 7634            if buffer.max_point().row >= rows.end.0 {
 7635                // If there's a line after the range, delete the \n from the end of the row range
 7636                // and position the cursor on the next line.
 7637                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 7638                cursor_buffer_row = rows.end;
 7639            } else {
 7640                // If there isn't a line after the range, delete the \n from the line before the
 7641                // start of the row range and position the cursor there.
 7642                edit_start = edit_start.saturating_sub(1);
 7643                edit_end = buffer.len();
 7644                cursor_buffer_row = rows.start.previous_row();
 7645            }
 7646
 7647            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 7648            *cursor.column_mut() =
 7649                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 7650
 7651            new_cursors.push((
 7652                selection.id,
 7653                buffer.anchor_after(cursor.to_point(&display_map)),
 7654            ));
 7655            edit_ranges.push(edit_start..edit_end);
 7656        }
 7657
 7658        self.transact(window, cx, |this, window, cx| {
 7659            let buffer = this.buffer.update(cx, |buffer, cx| {
 7660                let empty_str: Arc<str> = Arc::default();
 7661                buffer.edit(
 7662                    edit_ranges
 7663                        .into_iter()
 7664                        .map(|range| (range, empty_str.clone())),
 7665                    None,
 7666                    cx,
 7667                );
 7668                buffer.snapshot(cx)
 7669            });
 7670            let new_selections = new_cursors
 7671                .into_iter()
 7672                .map(|(id, cursor)| {
 7673                    let cursor = cursor.to_point(&buffer);
 7674                    Selection {
 7675                        id,
 7676                        start: cursor,
 7677                        end: cursor,
 7678                        reversed: false,
 7679                        goal: SelectionGoal::None,
 7680                    }
 7681                })
 7682                .collect();
 7683
 7684            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7685                s.select(new_selections);
 7686            });
 7687        });
 7688    }
 7689
 7690    pub fn join_lines_impl(
 7691        &mut self,
 7692        insert_whitespace: bool,
 7693        window: &mut Window,
 7694        cx: &mut Context<Self>,
 7695    ) {
 7696        if self.read_only(cx) {
 7697            return;
 7698        }
 7699        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 7700        for selection in self.selections.all::<Point>(cx) {
 7701            let start = MultiBufferRow(selection.start.row);
 7702            // Treat single line selections as if they include the next line. Otherwise this action
 7703            // would do nothing for single line selections individual cursors.
 7704            let end = if selection.start.row == selection.end.row {
 7705                MultiBufferRow(selection.start.row + 1)
 7706            } else {
 7707                MultiBufferRow(selection.end.row)
 7708            };
 7709
 7710            if let Some(last_row_range) = row_ranges.last_mut() {
 7711                if start <= last_row_range.end {
 7712                    last_row_range.end = end;
 7713                    continue;
 7714                }
 7715            }
 7716            row_ranges.push(start..end);
 7717        }
 7718
 7719        let snapshot = self.buffer.read(cx).snapshot(cx);
 7720        let mut cursor_positions = Vec::new();
 7721        for row_range in &row_ranges {
 7722            let anchor = snapshot.anchor_before(Point::new(
 7723                row_range.end.previous_row().0,
 7724                snapshot.line_len(row_range.end.previous_row()),
 7725            ));
 7726            cursor_positions.push(anchor..anchor);
 7727        }
 7728
 7729        self.transact(window, cx, |this, window, cx| {
 7730            for row_range in row_ranges.into_iter().rev() {
 7731                for row in row_range.iter_rows().rev() {
 7732                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 7733                    let next_line_row = row.next_row();
 7734                    let indent = snapshot.indent_size_for_line(next_line_row);
 7735                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7736
 7737                    let replace =
 7738                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7739                            " "
 7740                        } else {
 7741                            ""
 7742                        };
 7743
 7744                    this.buffer.update(cx, |buffer, cx| {
 7745                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7746                    });
 7747                }
 7748            }
 7749
 7750            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7751                s.select_anchor_ranges(cursor_positions)
 7752            });
 7753        });
 7754    }
 7755
 7756    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7757        self.join_lines_impl(true, window, cx);
 7758    }
 7759
 7760    pub fn sort_lines_case_sensitive(
 7761        &mut self,
 7762        _: &SortLinesCaseSensitive,
 7763        window: &mut Window,
 7764        cx: &mut Context<Self>,
 7765    ) {
 7766        self.manipulate_lines(window, cx, |lines| lines.sort())
 7767    }
 7768
 7769    pub fn sort_lines_case_insensitive(
 7770        &mut self,
 7771        _: &SortLinesCaseInsensitive,
 7772        window: &mut Window,
 7773        cx: &mut Context<Self>,
 7774    ) {
 7775        self.manipulate_lines(window, cx, |lines| {
 7776            lines.sort_by_key(|line| line.to_lowercase())
 7777        })
 7778    }
 7779
 7780    pub fn unique_lines_case_insensitive(
 7781        &mut self,
 7782        _: &UniqueLinesCaseInsensitive,
 7783        window: &mut Window,
 7784        cx: &mut Context<Self>,
 7785    ) {
 7786        self.manipulate_lines(window, cx, |lines| {
 7787            let mut seen = HashSet::default();
 7788            lines.retain(|line| seen.insert(line.to_lowercase()));
 7789        })
 7790    }
 7791
 7792    pub fn unique_lines_case_sensitive(
 7793        &mut self,
 7794        _: &UniqueLinesCaseSensitive,
 7795        window: &mut Window,
 7796        cx: &mut Context<Self>,
 7797    ) {
 7798        self.manipulate_lines(window, cx, |lines| {
 7799            let mut seen = HashSet::default();
 7800            lines.retain(|line| seen.insert(*line));
 7801        })
 7802    }
 7803
 7804    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7805        let Some(project) = self.project.clone() else {
 7806            return;
 7807        };
 7808        self.reload(project, window, cx)
 7809            .detach_and_notify_err(window, cx);
 7810    }
 7811
 7812    pub fn restore_file(
 7813        &mut self,
 7814        _: &::git::RestoreFile,
 7815        window: &mut Window,
 7816        cx: &mut Context<Self>,
 7817    ) {
 7818        let mut buffer_ids = HashSet::default();
 7819        let snapshot = self.buffer().read(cx).snapshot(cx);
 7820        for selection in self.selections.all::<usize>(cx) {
 7821            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 7822        }
 7823
 7824        let buffer = self.buffer().read(cx);
 7825        let ranges = buffer_ids
 7826            .into_iter()
 7827            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 7828            .collect::<Vec<_>>();
 7829
 7830        self.restore_hunks_in_ranges(ranges, window, cx);
 7831    }
 7832
 7833    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 7834        let selections = self
 7835            .selections
 7836            .all(cx)
 7837            .into_iter()
 7838            .map(|s| s.range())
 7839            .collect();
 7840        self.restore_hunks_in_ranges(selections, window, cx);
 7841    }
 7842
 7843    fn restore_hunks_in_ranges(
 7844        &mut self,
 7845        ranges: Vec<Range<Point>>,
 7846        window: &mut Window,
 7847        cx: &mut Context<Editor>,
 7848    ) {
 7849        let mut revert_changes = HashMap::default();
 7850        let chunk_by = self
 7851            .snapshot(window, cx)
 7852            .hunks_for_ranges(ranges)
 7853            .into_iter()
 7854            .chunk_by(|hunk| hunk.buffer_id);
 7855        for (buffer_id, hunks) in &chunk_by {
 7856            let hunks = hunks.collect::<Vec<_>>();
 7857            for hunk in &hunks {
 7858                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 7859            }
 7860            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 7861        }
 7862        drop(chunk_by);
 7863        if !revert_changes.is_empty() {
 7864            self.transact(window, cx, |editor, window, cx| {
 7865                editor.restore(revert_changes, window, cx);
 7866            });
 7867        }
 7868    }
 7869
 7870    pub fn open_active_item_in_terminal(
 7871        &mut self,
 7872        _: &OpenInTerminal,
 7873        window: &mut Window,
 7874        cx: &mut Context<Self>,
 7875    ) {
 7876        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7877            let project_path = buffer.read(cx).project_path(cx)?;
 7878            let project = self.project.as_ref()?.read(cx);
 7879            let entry = project.entry_for_path(&project_path, cx)?;
 7880            let parent = match &entry.canonical_path {
 7881                Some(canonical_path) => canonical_path.to_path_buf(),
 7882                None => project.absolute_path(&project_path, cx)?,
 7883            }
 7884            .parent()?
 7885            .to_path_buf();
 7886            Some(parent)
 7887        }) {
 7888            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7889        }
 7890    }
 7891
 7892    pub fn prepare_restore_change(
 7893        &self,
 7894        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7895        hunk: &MultiBufferDiffHunk,
 7896        cx: &mut App,
 7897    ) -> Option<()> {
 7898        let buffer = self.buffer.read(cx);
 7899        let diff = buffer.diff_for(hunk.buffer_id)?;
 7900        let buffer = buffer.buffer(hunk.buffer_id)?;
 7901        let buffer = buffer.read(cx);
 7902        let original_text = diff
 7903            .read(cx)
 7904            .base_text()
 7905            .as_rope()
 7906            .slice(hunk.diff_base_byte_range.clone());
 7907        let buffer_snapshot = buffer.snapshot();
 7908        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7909        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7910            probe
 7911                .0
 7912                .start
 7913                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7914                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7915        }) {
 7916            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7917            Some(())
 7918        } else {
 7919            None
 7920        }
 7921    }
 7922
 7923    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7924        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7925    }
 7926
 7927    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7928        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7929    }
 7930
 7931    fn manipulate_lines<Fn>(
 7932        &mut self,
 7933        window: &mut Window,
 7934        cx: &mut Context<Self>,
 7935        mut callback: Fn,
 7936    ) where
 7937        Fn: FnMut(&mut Vec<&str>),
 7938    {
 7939        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7940        let buffer = self.buffer.read(cx).snapshot(cx);
 7941
 7942        let mut edits = Vec::new();
 7943
 7944        let selections = self.selections.all::<Point>(cx);
 7945        let mut selections = selections.iter().peekable();
 7946        let mut contiguous_row_selections = Vec::new();
 7947        let mut new_selections = Vec::new();
 7948        let mut added_lines = 0;
 7949        let mut removed_lines = 0;
 7950
 7951        while let Some(selection) = selections.next() {
 7952            let (start_row, end_row) = consume_contiguous_rows(
 7953                &mut contiguous_row_selections,
 7954                selection,
 7955                &display_map,
 7956                &mut selections,
 7957            );
 7958
 7959            let start_point = Point::new(start_row.0, 0);
 7960            let end_point = Point::new(
 7961                end_row.previous_row().0,
 7962                buffer.line_len(end_row.previous_row()),
 7963            );
 7964            let text = buffer
 7965                .text_for_range(start_point..end_point)
 7966                .collect::<String>();
 7967
 7968            let mut lines = text.split('\n').collect_vec();
 7969
 7970            let lines_before = lines.len();
 7971            callback(&mut lines);
 7972            let lines_after = lines.len();
 7973
 7974            edits.push((start_point..end_point, lines.join("\n")));
 7975
 7976            // Selections must change based on added and removed line count
 7977            let start_row =
 7978                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7979            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7980            new_selections.push(Selection {
 7981                id: selection.id,
 7982                start: start_row,
 7983                end: end_row,
 7984                goal: SelectionGoal::None,
 7985                reversed: selection.reversed,
 7986            });
 7987
 7988            if lines_after > lines_before {
 7989                added_lines += lines_after - lines_before;
 7990            } else if lines_before > lines_after {
 7991                removed_lines += lines_before - lines_after;
 7992            }
 7993        }
 7994
 7995        self.transact(window, cx, |this, window, cx| {
 7996            let buffer = this.buffer.update(cx, |buffer, cx| {
 7997                buffer.edit(edits, None, cx);
 7998                buffer.snapshot(cx)
 7999            });
 8000
 8001            // Recalculate offsets on newly edited buffer
 8002            let new_selections = new_selections
 8003                .iter()
 8004                .map(|s| {
 8005                    let start_point = Point::new(s.start.0, 0);
 8006                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 8007                    Selection {
 8008                        id: s.id,
 8009                        start: buffer.point_to_offset(start_point),
 8010                        end: buffer.point_to_offset(end_point),
 8011                        goal: s.goal,
 8012                        reversed: s.reversed,
 8013                    }
 8014                })
 8015                .collect();
 8016
 8017            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8018                s.select(new_selections);
 8019            });
 8020
 8021            this.request_autoscroll(Autoscroll::fit(), cx);
 8022        });
 8023    }
 8024
 8025    pub fn convert_to_upper_case(
 8026        &mut self,
 8027        _: &ConvertToUpperCase,
 8028        window: &mut Window,
 8029        cx: &mut Context<Self>,
 8030    ) {
 8031        self.manipulate_text(window, cx, |text| text.to_uppercase())
 8032    }
 8033
 8034    pub fn convert_to_lower_case(
 8035        &mut self,
 8036        _: &ConvertToLowerCase,
 8037        window: &mut Window,
 8038        cx: &mut Context<Self>,
 8039    ) {
 8040        self.manipulate_text(window, cx, |text| text.to_lowercase())
 8041    }
 8042
 8043    pub fn convert_to_title_case(
 8044        &mut self,
 8045        _: &ConvertToTitleCase,
 8046        window: &mut Window,
 8047        cx: &mut Context<Self>,
 8048    ) {
 8049        self.manipulate_text(window, cx, |text| {
 8050            text.split('\n')
 8051                .map(|line| line.to_case(Case::Title))
 8052                .join("\n")
 8053        })
 8054    }
 8055
 8056    pub fn convert_to_snake_case(
 8057        &mut self,
 8058        _: &ConvertToSnakeCase,
 8059        window: &mut Window,
 8060        cx: &mut Context<Self>,
 8061    ) {
 8062        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 8063    }
 8064
 8065    pub fn convert_to_kebab_case(
 8066        &mut self,
 8067        _: &ConvertToKebabCase,
 8068        window: &mut Window,
 8069        cx: &mut Context<Self>,
 8070    ) {
 8071        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 8072    }
 8073
 8074    pub fn convert_to_upper_camel_case(
 8075        &mut self,
 8076        _: &ConvertToUpperCamelCase,
 8077        window: &mut Window,
 8078        cx: &mut Context<Self>,
 8079    ) {
 8080        self.manipulate_text(window, cx, |text| {
 8081            text.split('\n')
 8082                .map(|line| line.to_case(Case::UpperCamel))
 8083                .join("\n")
 8084        })
 8085    }
 8086
 8087    pub fn convert_to_lower_camel_case(
 8088        &mut self,
 8089        _: &ConvertToLowerCamelCase,
 8090        window: &mut Window,
 8091        cx: &mut Context<Self>,
 8092    ) {
 8093        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 8094    }
 8095
 8096    pub fn convert_to_opposite_case(
 8097        &mut self,
 8098        _: &ConvertToOppositeCase,
 8099        window: &mut Window,
 8100        cx: &mut Context<Self>,
 8101    ) {
 8102        self.manipulate_text(window, cx, |text| {
 8103            text.chars()
 8104                .fold(String::with_capacity(text.len()), |mut t, c| {
 8105                    if c.is_uppercase() {
 8106                        t.extend(c.to_lowercase());
 8107                    } else {
 8108                        t.extend(c.to_uppercase());
 8109                    }
 8110                    t
 8111                })
 8112        })
 8113    }
 8114
 8115    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 8116    where
 8117        Fn: FnMut(&str) -> String,
 8118    {
 8119        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8120        let buffer = self.buffer.read(cx).snapshot(cx);
 8121
 8122        let mut new_selections = Vec::new();
 8123        let mut edits = Vec::new();
 8124        let mut selection_adjustment = 0i32;
 8125
 8126        for selection in self.selections.all::<usize>(cx) {
 8127            let selection_is_empty = selection.is_empty();
 8128
 8129            let (start, end) = if selection_is_empty {
 8130                let word_range = movement::surrounding_word(
 8131                    &display_map,
 8132                    selection.start.to_display_point(&display_map),
 8133                );
 8134                let start = word_range.start.to_offset(&display_map, Bias::Left);
 8135                let end = word_range.end.to_offset(&display_map, Bias::Left);
 8136                (start, end)
 8137            } else {
 8138                (selection.start, selection.end)
 8139            };
 8140
 8141            let text = buffer.text_for_range(start..end).collect::<String>();
 8142            let old_length = text.len() as i32;
 8143            let text = callback(&text);
 8144
 8145            new_selections.push(Selection {
 8146                start: (start as i32 - selection_adjustment) as usize,
 8147                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 8148                goal: SelectionGoal::None,
 8149                ..selection
 8150            });
 8151
 8152            selection_adjustment += old_length - text.len() as i32;
 8153
 8154            edits.push((start..end, text));
 8155        }
 8156
 8157        self.transact(window, cx, |this, window, cx| {
 8158            this.buffer.update(cx, |buffer, cx| {
 8159                buffer.edit(edits, None, cx);
 8160            });
 8161
 8162            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8163                s.select(new_selections);
 8164            });
 8165
 8166            this.request_autoscroll(Autoscroll::fit(), cx);
 8167        });
 8168    }
 8169
 8170    pub fn duplicate(
 8171        &mut self,
 8172        upwards: bool,
 8173        whole_lines: bool,
 8174        window: &mut Window,
 8175        cx: &mut Context<Self>,
 8176    ) {
 8177        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8178        let buffer = &display_map.buffer_snapshot;
 8179        let selections = self.selections.all::<Point>(cx);
 8180
 8181        let mut edits = Vec::new();
 8182        let mut selections_iter = selections.iter().peekable();
 8183        while let Some(selection) = selections_iter.next() {
 8184            let mut rows = selection.spanned_rows(false, &display_map);
 8185            // duplicate line-wise
 8186            if whole_lines || selection.start == selection.end {
 8187                // Avoid duplicating the same lines twice.
 8188                while let Some(next_selection) = selections_iter.peek() {
 8189                    let next_rows = next_selection.spanned_rows(false, &display_map);
 8190                    if next_rows.start < rows.end {
 8191                        rows.end = next_rows.end;
 8192                        selections_iter.next().unwrap();
 8193                    } else {
 8194                        break;
 8195                    }
 8196                }
 8197
 8198                // Copy the text from the selected row region and splice it either at the start
 8199                // or end of the region.
 8200                let start = Point::new(rows.start.0, 0);
 8201                let end = Point::new(
 8202                    rows.end.previous_row().0,
 8203                    buffer.line_len(rows.end.previous_row()),
 8204                );
 8205                let text = buffer
 8206                    .text_for_range(start..end)
 8207                    .chain(Some("\n"))
 8208                    .collect::<String>();
 8209                let insert_location = if upwards {
 8210                    Point::new(rows.end.0, 0)
 8211                } else {
 8212                    start
 8213                };
 8214                edits.push((insert_location..insert_location, text));
 8215            } else {
 8216                // duplicate character-wise
 8217                let start = selection.start;
 8218                let end = selection.end;
 8219                let text = buffer.text_for_range(start..end).collect::<String>();
 8220                edits.push((selection.end..selection.end, text));
 8221            }
 8222        }
 8223
 8224        self.transact(window, cx, |this, _, cx| {
 8225            this.buffer.update(cx, |buffer, cx| {
 8226                buffer.edit(edits, None, cx);
 8227            });
 8228
 8229            this.request_autoscroll(Autoscroll::fit(), cx);
 8230        });
 8231    }
 8232
 8233    pub fn duplicate_line_up(
 8234        &mut self,
 8235        _: &DuplicateLineUp,
 8236        window: &mut Window,
 8237        cx: &mut Context<Self>,
 8238    ) {
 8239        self.duplicate(true, true, window, cx);
 8240    }
 8241
 8242    pub fn duplicate_line_down(
 8243        &mut self,
 8244        _: &DuplicateLineDown,
 8245        window: &mut Window,
 8246        cx: &mut Context<Self>,
 8247    ) {
 8248        self.duplicate(false, true, window, cx);
 8249    }
 8250
 8251    pub fn duplicate_selection(
 8252        &mut self,
 8253        _: &DuplicateSelection,
 8254        window: &mut Window,
 8255        cx: &mut Context<Self>,
 8256    ) {
 8257        self.duplicate(false, false, window, cx);
 8258    }
 8259
 8260    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 8261        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8262        let buffer = self.buffer.read(cx).snapshot(cx);
 8263
 8264        let mut edits = Vec::new();
 8265        let mut unfold_ranges = Vec::new();
 8266        let mut refold_creases = Vec::new();
 8267
 8268        let selections = self.selections.all::<Point>(cx);
 8269        let mut selections = selections.iter().peekable();
 8270        let mut contiguous_row_selections = Vec::new();
 8271        let mut new_selections = Vec::new();
 8272
 8273        while let Some(selection) = selections.next() {
 8274            // Find all the selections that span a contiguous row range
 8275            let (start_row, end_row) = consume_contiguous_rows(
 8276                &mut contiguous_row_selections,
 8277                selection,
 8278                &display_map,
 8279                &mut selections,
 8280            );
 8281
 8282            // Move the text spanned by the row range to be before the line preceding the row range
 8283            if start_row.0 > 0 {
 8284                let range_to_move = Point::new(
 8285                    start_row.previous_row().0,
 8286                    buffer.line_len(start_row.previous_row()),
 8287                )
 8288                    ..Point::new(
 8289                        end_row.previous_row().0,
 8290                        buffer.line_len(end_row.previous_row()),
 8291                    );
 8292                let insertion_point = display_map
 8293                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 8294                    .0;
 8295
 8296                // Don't move lines across excerpts
 8297                if buffer
 8298                    .excerpt_containing(insertion_point..range_to_move.end)
 8299                    .is_some()
 8300                {
 8301                    let text = buffer
 8302                        .text_for_range(range_to_move.clone())
 8303                        .flat_map(|s| s.chars())
 8304                        .skip(1)
 8305                        .chain(['\n'])
 8306                        .collect::<String>();
 8307
 8308                    edits.push((
 8309                        buffer.anchor_after(range_to_move.start)
 8310                            ..buffer.anchor_before(range_to_move.end),
 8311                        String::new(),
 8312                    ));
 8313                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8314                    edits.push((insertion_anchor..insertion_anchor, text));
 8315
 8316                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 8317
 8318                    // Move selections up
 8319                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8320                        |mut selection| {
 8321                            selection.start.row -= row_delta;
 8322                            selection.end.row -= row_delta;
 8323                            selection
 8324                        },
 8325                    ));
 8326
 8327                    // Move folds up
 8328                    unfold_ranges.push(range_to_move.clone());
 8329                    for fold in display_map.folds_in_range(
 8330                        buffer.anchor_before(range_to_move.start)
 8331                            ..buffer.anchor_after(range_to_move.end),
 8332                    ) {
 8333                        let mut start = fold.range.start.to_point(&buffer);
 8334                        let mut end = fold.range.end.to_point(&buffer);
 8335                        start.row -= row_delta;
 8336                        end.row -= row_delta;
 8337                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8338                    }
 8339                }
 8340            }
 8341
 8342            // If we didn't move line(s), preserve the existing selections
 8343            new_selections.append(&mut contiguous_row_selections);
 8344        }
 8345
 8346        self.transact(window, cx, |this, window, cx| {
 8347            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8348            this.buffer.update(cx, |buffer, cx| {
 8349                for (range, text) in edits {
 8350                    buffer.edit([(range, text)], None, cx);
 8351                }
 8352            });
 8353            this.fold_creases(refold_creases, true, window, cx);
 8354            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8355                s.select(new_selections);
 8356            })
 8357        });
 8358    }
 8359
 8360    pub fn move_line_down(
 8361        &mut self,
 8362        _: &MoveLineDown,
 8363        window: &mut Window,
 8364        cx: &mut Context<Self>,
 8365    ) {
 8366        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8367        let buffer = self.buffer.read(cx).snapshot(cx);
 8368
 8369        let mut edits = Vec::new();
 8370        let mut unfold_ranges = Vec::new();
 8371        let mut refold_creases = Vec::new();
 8372
 8373        let selections = self.selections.all::<Point>(cx);
 8374        let mut selections = selections.iter().peekable();
 8375        let mut contiguous_row_selections = Vec::new();
 8376        let mut new_selections = Vec::new();
 8377
 8378        while let Some(selection) = selections.next() {
 8379            // Find all the selections that span a contiguous row range
 8380            let (start_row, end_row) = consume_contiguous_rows(
 8381                &mut contiguous_row_selections,
 8382                selection,
 8383                &display_map,
 8384                &mut selections,
 8385            );
 8386
 8387            // Move the text spanned by the row range to be after the last line of the row range
 8388            if end_row.0 <= buffer.max_point().row {
 8389                let range_to_move =
 8390                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 8391                let insertion_point = display_map
 8392                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 8393                    .0;
 8394
 8395                // Don't move lines across excerpt boundaries
 8396                if buffer
 8397                    .excerpt_containing(range_to_move.start..insertion_point)
 8398                    .is_some()
 8399                {
 8400                    let mut text = String::from("\n");
 8401                    text.extend(buffer.text_for_range(range_to_move.clone()));
 8402                    text.pop(); // Drop trailing newline
 8403                    edits.push((
 8404                        buffer.anchor_after(range_to_move.start)
 8405                            ..buffer.anchor_before(range_to_move.end),
 8406                        String::new(),
 8407                    ));
 8408                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8409                    edits.push((insertion_anchor..insertion_anchor, text));
 8410
 8411                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 8412
 8413                    // Move selections down
 8414                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8415                        |mut selection| {
 8416                            selection.start.row += row_delta;
 8417                            selection.end.row += row_delta;
 8418                            selection
 8419                        },
 8420                    ));
 8421
 8422                    // Move folds down
 8423                    unfold_ranges.push(range_to_move.clone());
 8424                    for fold in display_map.folds_in_range(
 8425                        buffer.anchor_before(range_to_move.start)
 8426                            ..buffer.anchor_after(range_to_move.end),
 8427                    ) {
 8428                        let mut start = fold.range.start.to_point(&buffer);
 8429                        let mut end = fold.range.end.to_point(&buffer);
 8430                        start.row += row_delta;
 8431                        end.row += row_delta;
 8432                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8433                    }
 8434                }
 8435            }
 8436
 8437            // If we didn't move line(s), preserve the existing selections
 8438            new_selections.append(&mut contiguous_row_selections);
 8439        }
 8440
 8441        self.transact(window, cx, |this, window, cx| {
 8442            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8443            this.buffer.update(cx, |buffer, cx| {
 8444                for (range, text) in edits {
 8445                    buffer.edit([(range, text)], None, cx);
 8446                }
 8447            });
 8448            this.fold_creases(refold_creases, true, window, cx);
 8449            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8450                s.select(new_selections)
 8451            });
 8452        });
 8453    }
 8454
 8455    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 8456        let text_layout_details = &self.text_layout_details(window);
 8457        self.transact(window, cx, |this, window, cx| {
 8458            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8459                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 8460                let line_mode = s.line_mode;
 8461                s.move_with(|display_map, selection| {
 8462                    if !selection.is_empty() || line_mode {
 8463                        return;
 8464                    }
 8465
 8466                    let mut head = selection.head();
 8467                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 8468                    if head.column() == display_map.line_len(head.row()) {
 8469                        transpose_offset = display_map
 8470                            .buffer_snapshot
 8471                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8472                    }
 8473
 8474                    if transpose_offset == 0 {
 8475                        return;
 8476                    }
 8477
 8478                    *head.column_mut() += 1;
 8479                    head = display_map.clip_point(head, Bias::Right);
 8480                    let goal = SelectionGoal::HorizontalPosition(
 8481                        display_map
 8482                            .x_for_display_point(head, text_layout_details)
 8483                            .into(),
 8484                    );
 8485                    selection.collapse_to(head, goal);
 8486
 8487                    let transpose_start = display_map
 8488                        .buffer_snapshot
 8489                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8490                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 8491                        let transpose_end = display_map
 8492                            .buffer_snapshot
 8493                            .clip_offset(transpose_offset + 1, Bias::Right);
 8494                        if let Some(ch) =
 8495                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 8496                        {
 8497                            edits.push((transpose_start..transpose_offset, String::new()));
 8498                            edits.push((transpose_end..transpose_end, ch.to_string()));
 8499                        }
 8500                    }
 8501                });
 8502                edits
 8503            });
 8504            this.buffer
 8505                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8506            let selections = this.selections.all::<usize>(cx);
 8507            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8508                s.select(selections);
 8509            });
 8510        });
 8511    }
 8512
 8513    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 8514        self.rewrap_impl(IsVimMode::No, cx)
 8515    }
 8516
 8517    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 8518        let buffer = self.buffer.read(cx).snapshot(cx);
 8519        let selections = self.selections.all::<Point>(cx);
 8520        let mut selections = selections.iter().peekable();
 8521
 8522        let mut edits = Vec::new();
 8523        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 8524
 8525        while let Some(selection) = selections.next() {
 8526            let mut start_row = selection.start.row;
 8527            let mut end_row = selection.end.row;
 8528
 8529            // Skip selections that overlap with a range that has already been rewrapped.
 8530            let selection_range = start_row..end_row;
 8531            if rewrapped_row_ranges
 8532                .iter()
 8533                .any(|range| range.overlaps(&selection_range))
 8534            {
 8535                continue;
 8536            }
 8537
 8538            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 8539
 8540            // Since not all lines in the selection may be at the same indent
 8541            // level, choose the indent size that is the most common between all
 8542            // of the lines.
 8543            //
 8544            // If there is a tie, we use the deepest indent.
 8545            let (indent_size, indent_end) = {
 8546                let mut indent_size_occurrences = HashMap::default();
 8547                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 8548
 8549                for row in start_row..=end_row {
 8550                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 8551                    rows_by_indent_size.entry(indent).or_default().push(row);
 8552                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 8553                }
 8554
 8555                let indent_size = indent_size_occurrences
 8556                    .into_iter()
 8557                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 8558                    .map(|(indent, _)| indent)
 8559                    .unwrap_or_default();
 8560                let row = rows_by_indent_size[&indent_size][0];
 8561                let indent_end = Point::new(row, indent_size.len);
 8562
 8563                (indent_size, indent_end)
 8564            };
 8565
 8566            let mut line_prefix = indent_size.chars().collect::<String>();
 8567
 8568            let mut inside_comment = false;
 8569            if let Some(comment_prefix) =
 8570                buffer
 8571                    .language_scope_at(selection.head())
 8572                    .and_then(|language| {
 8573                        language
 8574                            .line_comment_prefixes()
 8575                            .iter()
 8576                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 8577                            .cloned()
 8578                    })
 8579            {
 8580                line_prefix.push_str(&comment_prefix);
 8581                inside_comment = true;
 8582            }
 8583
 8584            let language_settings = buffer.language_settings_at(selection.head(), cx);
 8585            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 8586                RewrapBehavior::InComments => inside_comment,
 8587                RewrapBehavior::InSelections => !selection.is_empty(),
 8588                RewrapBehavior::Anywhere => true,
 8589            };
 8590
 8591            let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
 8592            if !should_rewrap {
 8593                continue;
 8594            }
 8595
 8596            if selection.is_empty() {
 8597                'expand_upwards: while start_row > 0 {
 8598                    let prev_row = start_row - 1;
 8599                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 8600                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 8601                    {
 8602                        start_row = prev_row;
 8603                    } else {
 8604                        break 'expand_upwards;
 8605                    }
 8606                }
 8607
 8608                'expand_downwards: while end_row < buffer.max_point().row {
 8609                    let next_row = end_row + 1;
 8610                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 8611                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 8612                    {
 8613                        end_row = next_row;
 8614                    } else {
 8615                        break 'expand_downwards;
 8616                    }
 8617                }
 8618            }
 8619
 8620            let start = Point::new(start_row, 0);
 8621            let start_offset = start.to_offset(&buffer);
 8622            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 8623            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 8624            let Some(lines_without_prefixes) = selection_text
 8625                .lines()
 8626                .map(|line| {
 8627                    line.strip_prefix(&line_prefix)
 8628                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 8629                        .ok_or_else(|| {
 8630                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 8631                        })
 8632                })
 8633                .collect::<Result<Vec<_>, _>>()
 8634                .log_err()
 8635            else {
 8636                continue;
 8637            };
 8638
 8639            let wrap_column = buffer
 8640                .language_settings_at(Point::new(start_row, 0), cx)
 8641                .preferred_line_length as usize;
 8642            let wrapped_text = wrap_with_prefix(
 8643                line_prefix,
 8644                lines_without_prefixes.join(" "),
 8645                wrap_column,
 8646                tab_size,
 8647            );
 8648
 8649            // TODO: should always use char-based diff while still supporting cursor behavior that
 8650            // matches vim.
 8651            let mut diff_options = DiffOptions::default();
 8652            if is_vim_mode == IsVimMode::Yes {
 8653                diff_options.max_word_diff_len = 0;
 8654                diff_options.max_word_diff_line_count = 0;
 8655            } else {
 8656                diff_options.max_word_diff_len = usize::MAX;
 8657                diff_options.max_word_diff_line_count = usize::MAX;
 8658            }
 8659
 8660            for (old_range, new_text) in
 8661                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 8662            {
 8663                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 8664                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 8665                edits.push((edit_start..edit_end, new_text));
 8666            }
 8667
 8668            rewrapped_row_ranges.push(start_row..=end_row);
 8669        }
 8670
 8671        self.buffer
 8672            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8673    }
 8674
 8675    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 8676        let mut text = String::new();
 8677        let buffer = self.buffer.read(cx).snapshot(cx);
 8678        let mut selections = self.selections.all::<Point>(cx);
 8679        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8680        {
 8681            let max_point = buffer.max_point();
 8682            let mut is_first = true;
 8683            for selection in &mut selections {
 8684                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8685                if is_entire_line {
 8686                    selection.start = Point::new(selection.start.row, 0);
 8687                    if !selection.is_empty() && selection.end.column == 0 {
 8688                        selection.end = cmp::min(max_point, selection.end);
 8689                    } else {
 8690                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 8691                    }
 8692                    selection.goal = SelectionGoal::None;
 8693                }
 8694                if is_first {
 8695                    is_first = false;
 8696                } else {
 8697                    text += "\n";
 8698                }
 8699                let mut len = 0;
 8700                for chunk in buffer.text_for_range(selection.start..selection.end) {
 8701                    text.push_str(chunk);
 8702                    len += chunk.len();
 8703                }
 8704                clipboard_selections.push(ClipboardSelection {
 8705                    len,
 8706                    is_entire_line,
 8707                    first_line_indent: buffer
 8708                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 8709                        .len,
 8710                });
 8711            }
 8712        }
 8713
 8714        self.transact(window, cx, |this, window, cx| {
 8715            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8716                s.select(selections);
 8717            });
 8718            this.insert("", window, cx);
 8719        });
 8720        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 8721    }
 8722
 8723    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8724        let item = self.cut_common(window, cx);
 8725        cx.write_to_clipboard(item);
 8726    }
 8727
 8728    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8729        self.change_selections(None, window, cx, |s| {
 8730            s.move_with(|snapshot, sel| {
 8731                if sel.is_empty() {
 8732                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8733                }
 8734            });
 8735        });
 8736        let item = self.cut_common(window, cx);
 8737        cx.set_global(KillRing(item))
 8738    }
 8739
 8740    pub fn kill_ring_yank(
 8741        &mut self,
 8742        _: &KillRingYank,
 8743        window: &mut Window,
 8744        cx: &mut Context<Self>,
 8745    ) {
 8746        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8747            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8748                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8749            } else {
 8750                return;
 8751            }
 8752        } else {
 8753            return;
 8754        };
 8755        self.do_paste(&text, metadata, false, window, cx);
 8756    }
 8757
 8758    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8759        let selections = self.selections.all::<Point>(cx);
 8760        let buffer = self.buffer.read(cx).read(cx);
 8761        let mut text = String::new();
 8762
 8763        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8764        {
 8765            let max_point = buffer.max_point();
 8766            let mut is_first = true;
 8767            for selection in selections.iter() {
 8768                let mut start = selection.start;
 8769                let mut end = selection.end;
 8770                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8771                if is_entire_line {
 8772                    start = Point::new(start.row, 0);
 8773                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8774                }
 8775                if is_first {
 8776                    is_first = false;
 8777                } else {
 8778                    text += "\n";
 8779                }
 8780                let mut len = 0;
 8781                for chunk in buffer.text_for_range(start..end) {
 8782                    text.push_str(chunk);
 8783                    len += chunk.len();
 8784                }
 8785                clipboard_selections.push(ClipboardSelection {
 8786                    len,
 8787                    is_entire_line,
 8788                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 8789                });
 8790            }
 8791        }
 8792
 8793        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8794            text,
 8795            clipboard_selections,
 8796        ));
 8797    }
 8798
 8799    pub fn do_paste(
 8800        &mut self,
 8801        text: &String,
 8802        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8803        handle_entire_lines: bool,
 8804        window: &mut Window,
 8805        cx: &mut Context<Self>,
 8806    ) {
 8807        if self.read_only(cx) {
 8808            return;
 8809        }
 8810
 8811        let clipboard_text = Cow::Borrowed(text);
 8812
 8813        self.transact(window, cx, |this, window, cx| {
 8814            if let Some(mut clipboard_selections) = clipboard_selections {
 8815                let old_selections = this.selections.all::<usize>(cx);
 8816                let all_selections_were_entire_line =
 8817                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8818                let first_selection_indent_column =
 8819                    clipboard_selections.first().map(|s| s.first_line_indent);
 8820                if clipboard_selections.len() != old_selections.len() {
 8821                    clipboard_selections.drain(..);
 8822                }
 8823                let cursor_offset = this.selections.last::<usize>(cx).head();
 8824                let mut auto_indent_on_paste = true;
 8825
 8826                this.buffer.update(cx, |buffer, cx| {
 8827                    let snapshot = buffer.read(cx);
 8828                    auto_indent_on_paste = snapshot
 8829                        .language_settings_at(cursor_offset, cx)
 8830                        .auto_indent_on_paste;
 8831
 8832                    let mut start_offset = 0;
 8833                    let mut edits = Vec::new();
 8834                    let mut original_indent_columns = Vec::new();
 8835                    for (ix, selection) in old_selections.iter().enumerate() {
 8836                        let to_insert;
 8837                        let entire_line;
 8838                        let original_indent_column;
 8839                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8840                            let end_offset = start_offset + clipboard_selection.len;
 8841                            to_insert = &clipboard_text[start_offset..end_offset];
 8842                            entire_line = clipboard_selection.is_entire_line;
 8843                            start_offset = end_offset + 1;
 8844                            original_indent_column = Some(clipboard_selection.first_line_indent);
 8845                        } else {
 8846                            to_insert = clipboard_text.as_str();
 8847                            entire_line = all_selections_were_entire_line;
 8848                            original_indent_column = first_selection_indent_column
 8849                        }
 8850
 8851                        // If the corresponding selection was empty when this slice of the
 8852                        // clipboard text was written, then the entire line containing the
 8853                        // selection was copied. If this selection is also currently empty,
 8854                        // then paste the line before the current line of the buffer.
 8855                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8856                            let column = selection.start.to_point(&snapshot).column as usize;
 8857                            let line_start = selection.start - column;
 8858                            line_start..line_start
 8859                        } else {
 8860                            selection.range()
 8861                        };
 8862
 8863                        edits.push((range, to_insert));
 8864                        original_indent_columns.push(original_indent_column);
 8865                    }
 8866                    drop(snapshot);
 8867
 8868                    buffer.edit(
 8869                        edits,
 8870                        if auto_indent_on_paste {
 8871                            Some(AutoindentMode::Block {
 8872                                original_indent_columns,
 8873                            })
 8874                        } else {
 8875                            None
 8876                        },
 8877                        cx,
 8878                    );
 8879                });
 8880
 8881                let selections = this.selections.all::<usize>(cx);
 8882                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8883                    s.select(selections)
 8884                });
 8885            } else {
 8886                this.insert(&clipboard_text, window, cx);
 8887            }
 8888        });
 8889    }
 8890
 8891    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8892        if let Some(item) = cx.read_from_clipboard() {
 8893            let entries = item.entries();
 8894
 8895            match entries.first() {
 8896                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8897                // of all the pasted entries.
 8898                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8899                    .do_paste(
 8900                        clipboard_string.text(),
 8901                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8902                        true,
 8903                        window,
 8904                        cx,
 8905                    ),
 8906                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8907            }
 8908        }
 8909    }
 8910
 8911    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8912        if self.read_only(cx) {
 8913            return;
 8914        }
 8915
 8916        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8917            if let Some((selections, _)) =
 8918                self.selection_history.transaction(transaction_id).cloned()
 8919            {
 8920                self.change_selections(None, window, cx, |s| {
 8921                    s.select_anchors(selections.to_vec());
 8922                });
 8923            } else {
 8924                log::error!(
 8925                    "No entry in selection_history found for undo. \
 8926                     This may correspond to a bug where undo does not update the selection. \
 8927                     If this is occurring, please add details to \
 8928                     https://github.com/zed-industries/zed/issues/22692"
 8929                );
 8930            }
 8931            self.request_autoscroll(Autoscroll::fit(), cx);
 8932            self.unmark_text(window, cx);
 8933            self.refresh_inline_completion(true, false, window, cx);
 8934            cx.emit(EditorEvent::Edited { transaction_id });
 8935            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8936        }
 8937    }
 8938
 8939    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8940        if self.read_only(cx) {
 8941            return;
 8942        }
 8943
 8944        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8945            if let Some((_, Some(selections))) =
 8946                self.selection_history.transaction(transaction_id).cloned()
 8947            {
 8948                self.change_selections(None, window, cx, |s| {
 8949                    s.select_anchors(selections.to_vec());
 8950                });
 8951            } else {
 8952                log::error!(
 8953                    "No entry in selection_history found for redo. \
 8954                     This may correspond to a bug where undo does not update the selection. \
 8955                     If this is occurring, please add details to \
 8956                     https://github.com/zed-industries/zed/issues/22692"
 8957                );
 8958            }
 8959            self.request_autoscroll(Autoscroll::fit(), cx);
 8960            self.unmark_text(window, cx);
 8961            self.refresh_inline_completion(true, false, window, cx);
 8962            cx.emit(EditorEvent::Edited { transaction_id });
 8963        }
 8964    }
 8965
 8966    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8967        self.buffer
 8968            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8969    }
 8970
 8971    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8972        self.buffer
 8973            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8974    }
 8975
 8976    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8977        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8978            let line_mode = s.line_mode;
 8979            s.move_with(|map, selection| {
 8980                let cursor = if selection.is_empty() && !line_mode {
 8981                    movement::left(map, selection.start)
 8982                } else {
 8983                    selection.start
 8984                };
 8985                selection.collapse_to(cursor, SelectionGoal::None);
 8986            });
 8987        })
 8988    }
 8989
 8990    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8991        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8992            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8993        })
 8994    }
 8995
 8996    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8997        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8998            let line_mode = s.line_mode;
 8999            s.move_with(|map, selection| {
 9000                let cursor = if selection.is_empty() && !line_mode {
 9001                    movement::right(map, selection.end)
 9002                } else {
 9003                    selection.end
 9004                };
 9005                selection.collapse_to(cursor, SelectionGoal::None)
 9006            });
 9007        })
 9008    }
 9009
 9010    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 9011        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9012            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 9013        })
 9014    }
 9015
 9016    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 9017        if self.take_rename(true, window, cx).is_some() {
 9018            return;
 9019        }
 9020
 9021        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9022            cx.propagate();
 9023            return;
 9024        }
 9025
 9026        let text_layout_details = &self.text_layout_details(window);
 9027        let selection_count = self.selections.count();
 9028        let first_selection = self.selections.first_anchor();
 9029
 9030        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9031            let line_mode = s.line_mode;
 9032            s.move_with(|map, selection| {
 9033                if !selection.is_empty() && !line_mode {
 9034                    selection.goal = SelectionGoal::None;
 9035                }
 9036                let (cursor, goal) = movement::up(
 9037                    map,
 9038                    selection.start,
 9039                    selection.goal,
 9040                    false,
 9041                    text_layout_details,
 9042                );
 9043                selection.collapse_to(cursor, goal);
 9044            });
 9045        });
 9046
 9047        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9048        {
 9049            cx.propagate();
 9050        }
 9051    }
 9052
 9053    pub fn move_up_by_lines(
 9054        &mut self,
 9055        action: &MoveUpByLines,
 9056        window: &mut Window,
 9057        cx: &mut Context<Self>,
 9058    ) {
 9059        if self.take_rename(true, window, cx).is_some() {
 9060            return;
 9061        }
 9062
 9063        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9064            cx.propagate();
 9065            return;
 9066        }
 9067
 9068        let text_layout_details = &self.text_layout_details(window);
 9069
 9070        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9071            let line_mode = s.line_mode;
 9072            s.move_with(|map, selection| {
 9073                if !selection.is_empty() && !line_mode {
 9074                    selection.goal = SelectionGoal::None;
 9075                }
 9076                let (cursor, goal) = movement::up_by_rows(
 9077                    map,
 9078                    selection.start,
 9079                    action.lines,
 9080                    selection.goal,
 9081                    false,
 9082                    text_layout_details,
 9083                );
 9084                selection.collapse_to(cursor, goal);
 9085            });
 9086        })
 9087    }
 9088
 9089    pub fn move_down_by_lines(
 9090        &mut self,
 9091        action: &MoveDownByLines,
 9092        window: &mut Window,
 9093        cx: &mut Context<Self>,
 9094    ) {
 9095        if self.take_rename(true, window, cx).is_some() {
 9096            return;
 9097        }
 9098
 9099        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9100            cx.propagate();
 9101            return;
 9102        }
 9103
 9104        let text_layout_details = &self.text_layout_details(window);
 9105
 9106        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9107            let line_mode = s.line_mode;
 9108            s.move_with(|map, selection| {
 9109                if !selection.is_empty() && !line_mode {
 9110                    selection.goal = SelectionGoal::None;
 9111                }
 9112                let (cursor, goal) = movement::down_by_rows(
 9113                    map,
 9114                    selection.start,
 9115                    action.lines,
 9116                    selection.goal,
 9117                    false,
 9118                    text_layout_details,
 9119                );
 9120                selection.collapse_to(cursor, goal);
 9121            });
 9122        })
 9123    }
 9124
 9125    pub fn select_down_by_lines(
 9126        &mut self,
 9127        action: &SelectDownByLines,
 9128        window: &mut Window,
 9129        cx: &mut Context<Self>,
 9130    ) {
 9131        let text_layout_details = &self.text_layout_details(window);
 9132        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9133            s.move_heads_with(|map, head, goal| {
 9134                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9135            })
 9136        })
 9137    }
 9138
 9139    pub fn select_up_by_lines(
 9140        &mut self,
 9141        action: &SelectUpByLines,
 9142        window: &mut Window,
 9143        cx: &mut Context<Self>,
 9144    ) {
 9145        let text_layout_details = &self.text_layout_details(window);
 9146        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9147            s.move_heads_with(|map, head, goal| {
 9148                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9149            })
 9150        })
 9151    }
 9152
 9153    pub fn select_page_up(
 9154        &mut self,
 9155        _: &SelectPageUp,
 9156        window: &mut Window,
 9157        cx: &mut Context<Self>,
 9158    ) {
 9159        let Some(row_count) = self.visible_row_count() else {
 9160            return;
 9161        };
 9162
 9163        let text_layout_details = &self.text_layout_details(window);
 9164
 9165        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9166            s.move_heads_with(|map, head, goal| {
 9167                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 9168            })
 9169        })
 9170    }
 9171
 9172    pub fn move_page_up(
 9173        &mut self,
 9174        action: &MovePageUp,
 9175        window: &mut Window,
 9176        cx: &mut Context<Self>,
 9177    ) {
 9178        if self.take_rename(true, window, cx).is_some() {
 9179            return;
 9180        }
 9181
 9182        if self
 9183            .context_menu
 9184            .borrow_mut()
 9185            .as_mut()
 9186            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 9187            .unwrap_or(false)
 9188        {
 9189            return;
 9190        }
 9191
 9192        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9193            cx.propagate();
 9194            return;
 9195        }
 9196
 9197        let Some(row_count) = self.visible_row_count() else {
 9198            return;
 9199        };
 9200
 9201        let autoscroll = if action.center_cursor {
 9202            Autoscroll::center()
 9203        } else {
 9204            Autoscroll::fit()
 9205        };
 9206
 9207        let text_layout_details = &self.text_layout_details(window);
 9208
 9209        self.change_selections(Some(autoscroll), window, cx, |s| {
 9210            let line_mode = s.line_mode;
 9211            s.move_with(|map, selection| {
 9212                if !selection.is_empty() && !line_mode {
 9213                    selection.goal = SelectionGoal::None;
 9214                }
 9215                let (cursor, goal) = movement::up_by_rows(
 9216                    map,
 9217                    selection.end,
 9218                    row_count,
 9219                    selection.goal,
 9220                    false,
 9221                    text_layout_details,
 9222                );
 9223                selection.collapse_to(cursor, goal);
 9224            });
 9225        });
 9226    }
 9227
 9228    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 9229        let text_layout_details = &self.text_layout_details(window);
 9230        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9231            s.move_heads_with(|map, head, goal| {
 9232                movement::up(map, head, goal, false, text_layout_details)
 9233            })
 9234        })
 9235    }
 9236
 9237    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 9238        self.take_rename(true, window, cx);
 9239
 9240        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9241            cx.propagate();
 9242            return;
 9243        }
 9244
 9245        let text_layout_details = &self.text_layout_details(window);
 9246        let selection_count = self.selections.count();
 9247        let first_selection = self.selections.first_anchor();
 9248
 9249        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9250            let line_mode = s.line_mode;
 9251            s.move_with(|map, selection| {
 9252                if !selection.is_empty() && !line_mode {
 9253                    selection.goal = SelectionGoal::None;
 9254                }
 9255                let (cursor, goal) = movement::down(
 9256                    map,
 9257                    selection.end,
 9258                    selection.goal,
 9259                    false,
 9260                    text_layout_details,
 9261                );
 9262                selection.collapse_to(cursor, goal);
 9263            });
 9264        });
 9265
 9266        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9267        {
 9268            cx.propagate();
 9269        }
 9270    }
 9271
 9272    pub fn select_page_down(
 9273        &mut self,
 9274        _: &SelectPageDown,
 9275        window: &mut Window,
 9276        cx: &mut Context<Self>,
 9277    ) {
 9278        let Some(row_count) = self.visible_row_count() else {
 9279            return;
 9280        };
 9281
 9282        let text_layout_details = &self.text_layout_details(window);
 9283
 9284        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9285            s.move_heads_with(|map, head, goal| {
 9286                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 9287            })
 9288        })
 9289    }
 9290
 9291    pub fn move_page_down(
 9292        &mut self,
 9293        action: &MovePageDown,
 9294        window: &mut Window,
 9295        cx: &mut Context<Self>,
 9296    ) {
 9297        if self.take_rename(true, window, cx).is_some() {
 9298            return;
 9299        }
 9300
 9301        if self
 9302            .context_menu
 9303            .borrow_mut()
 9304            .as_mut()
 9305            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 9306            .unwrap_or(false)
 9307        {
 9308            return;
 9309        }
 9310
 9311        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9312            cx.propagate();
 9313            return;
 9314        }
 9315
 9316        let Some(row_count) = self.visible_row_count() else {
 9317            return;
 9318        };
 9319
 9320        let autoscroll = if action.center_cursor {
 9321            Autoscroll::center()
 9322        } else {
 9323            Autoscroll::fit()
 9324        };
 9325
 9326        let text_layout_details = &self.text_layout_details(window);
 9327        self.change_selections(Some(autoscroll), window, cx, |s| {
 9328            let line_mode = s.line_mode;
 9329            s.move_with(|map, selection| {
 9330                if !selection.is_empty() && !line_mode {
 9331                    selection.goal = SelectionGoal::None;
 9332                }
 9333                let (cursor, goal) = movement::down_by_rows(
 9334                    map,
 9335                    selection.end,
 9336                    row_count,
 9337                    selection.goal,
 9338                    false,
 9339                    text_layout_details,
 9340                );
 9341                selection.collapse_to(cursor, goal);
 9342            });
 9343        });
 9344    }
 9345
 9346    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 9347        let text_layout_details = &self.text_layout_details(window);
 9348        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9349            s.move_heads_with(|map, head, goal| {
 9350                movement::down(map, head, goal, false, text_layout_details)
 9351            })
 9352        });
 9353    }
 9354
 9355    pub fn context_menu_first(
 9356        &mut self,
 9357        _: &ContextMenuFirst,
 9358        _window: &mut Window,
 9359        cx: &mut Context<Self>,
 9360    ) {
 9361        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9362            context_menu.select_first(self.completion_provider.as_deref(), cx);
 9363        }
 9364    }
 9365
 9366    pub fn context_menu_prev(
 9367        &mut self,
 9368        _: &ContextMenuPrevious,
 9369        _window: &mut Window,
 9370        cx: &mut Context<Self>,
 9371    ) {
 9372        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9373            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 9374        }
 9375    }
 9376
 9377    pub fn context_menu_next(
 9378        &mut self,
 9379        _: &ContextMenuNext,
 9380        _window: &mut Window,
 9381        cx: &mut Context<Self>,
 9382    ) {
 9383        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9384            context_menu.select_next(self.completion_provider.as_deref(), cx);
 9385        }
 9386    }
 9387
 9388    pub fn context_menu_last(
 9389        &mut self,
 9390        _: &ContextMenuLast,
 9391        _window: &mut Window,
 9392        cx: &mut Context<Self>,
 9393    ) {
 9394        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9395            context_menu.select_last(self.completion_provider.as_deref(), cx);
 9396        }
 9397    }
 9398
 9399    pub fn move_to_previous_word_start(
 9400        &mut self,
 9401        _: &MoveToPreviousWordStart,
 9402        window: &mut Window,
 9403        cx: &mut Context<Self>,
 9404    ) {
 9405        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9406            s.move_cursors_with(|map, head, _| {
 9407                (
 9408                    movement::previous_word_start(map, head),
 9409                    SelectionGoal::None,
 9410                )
 9411            });
 9412        })
 9413    }
 9414
 9415    pub fn move_to_previous_subword_start(
 9416        &mut self,
 9417        _: &MoveToPreviousSubwordStart,
 9418        window: &mut Window,
 9419        cx: &mut Context<Self>,
 9420    ) {
 9421        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9422            s.move_cursors_with(|map, head, _| {
 9423                (
 9424                    movement::previous_subword_start(map, head),
 9425                    SelectionGoal::None,
 9426                )
 9427            });
 9428        })
 9429    }
 9430
 9431    pub fn select_to_previous_word_start(
 9432        &mut self,
 9433        _: &SelectToPreviousWordStart,
 9434        window: &mut Window,
 9435        cx: &mut Context<Self>,
 9436    ) {
 9437        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9438            s.move_heads_with(|map, head, _| {
 9439                (
 9440                    movement::previous_word_start(map, head),
 9441                    SelectionGoal::None,
 9442                )
 9443            });
 9444        })
 9445    }
 9446
 9447    pub fn select_to_previous_subword_start(
 9448        &mut self,
 9449        _: &SelectToPreviousSubwordStart,
 9450        window: &mut Window,
 9451        cx: &mut Context<Self>,
 9452    ) {
 9453        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9454            s.move_heads_with(|map, head, _| {
 9455                (
 9456                    movement::previous_subword_start(map, head),
 9457                    SelectionGoal::None,
 9458                )
 9459            });
 9460        })
 9461    }
 9462
 9463    pub fn delete_to_previous_word_start(
 9464        &mut self,
 9465        action: &DeleteToPreviousWordStart,
 9466        window: &mut Window,
 9467        cx: &mut Context<Self>,
 9468    ) {
 9469        self.transact(window, cx, |this, window, cx| {
 9470            this.select_autoclose_pair(window, cx);
 9471            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9472                let line_mode = s.line_mode;
 9473                s.move_with(|map, selection| {
 9474                    if selection.is_empty() && !line_mode {
 9475                        let cursor = if action.ignore_newlines {
 9476                            movement::previous_word_start(map, selection.head())
 9477                        } else {
 9478                            movement::previous_word_start_or_newline(map, selection.head())
 9479                        };
 9480                        selection.set_head(cursor, SelectionGoal::None);
 9481                    }
 9482                });
 9483            });
 9484            this.insert("", window, cx);
 9485        });
 9486    }
 9487
 9488    pub fn delete_to_previous_subword_start(
 9489        &mut self,
 9490        _: &DeleteToPreviousSubwordStart,
 9491        window: &mut Window,
 9492        cx: &mut Context<Self>,
 9493    ) {
 9494        self.transact(window, cx, |this, window, cx| {
 9495            this.select_autoclose_pair(window, cx);
 9496            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9497                let line_mode = s.line_mode;
 9498                s.move_with(|map, selection| {
 9499                    if selection.is_empty() && !line_mode {
 9500                        let cursor = movement::previous_subword_start(map, selection.head());
 9501                        selection.set_head(cursor, SelectionGoal::None);
 9502                    }
 9503                });
 9504            });
 9505            this.insert("", window, cx);
 9506        });
 9507    }
 9508
 9509    pub fn move_to_next_word_end(
 9510        &mut self,
 9511        _: &MoveToNextWordEnd,
 9512        window: &mut Window,
 9513        cx: &mut Context<Self>,
 9514    ) {
 9515        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9516            s.move_cursors_with(|map, head, _| {
 9517                (movement::next_word_end(map, head), SelectionGoal::None)
 9518            });
 9519        })
 9520    }
 9521
 9522    pub fn move_to_next_subword_end(
 9523        &mut self,
 9524        _: &MoveToNextSubwordEnd,
 9525        window: &mut Window,
 9526        cx: &mut Context<Self>,
 9527    ) {
 9528        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9529            s.move_cursors_with(|map, head, _| {
 9530                (movement::next_subword_end(map, head), SelectionGoal::None)
 9531            });
 9532        })
 9533    }
 9534
 9535    pub fn select_to_next_word_end(
 9536        &mut self,
 9537        _: &SelectToNextWordEnd,
 9538        window: &mut Window,
 9539        cx: &mut Context<Self>,
 9540    ) {
 9541        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9542            s.move_heads_with(|map, head, _| {
 9543                (movement::next_word_end(map, head), SelectionGoal::None)
 9544            });
 9545        })
 9546    }
 9547
 9548    pub fn select_to_next_subword_end(
 9549        &mut self,
 9550        _: &SelectToNextSubwordEnd,
 9551        window: &mut Window,
 9552        cx: &mut Context<Self>,
 9553    ) {
 9554        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9555            s.move_heads_with(|map, head, _| {
 9556                (movement::next_subword_end(map, head), SelectionGoal::None)
 9557            });
 9558        })
 9559    }
 9560
 9561    pub fn delete_to_next_word_end(
 9562        &mut self,
 9563        action: &DeleteToNextWordEnd,
 9564        window: &mut Window,
 9565        cx: &mut Context<Self>,
 9566    ) {
 9567        self.transact(window, cx, |this, window, cx| {
 9568            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9569                let line_mode = s.line_mode;
 9570                s.move_with(|map, selection| {
 9571                    if selection.is_empty() && !line_mode {
 9572                        let cursor = if action.ignore_newlines {
 9573                            movement::next_word_end(map, selection.head())
 9574                        } else {
 9575                            movement::next_word_end_or_newline(map, selection.head())
 9576                        };
 9577                        selection.set_head(cursor, SelectionGoal::None);
 9578                    }
 9579                });
 9580            });
 9581            this.insert("", window, cx);
 9582        });
 9583    }
 9584
 9585    pub fn delete_to_next_subword_end(
 9586        &mut self,
 9587        _: &DeleteToNextSubwordEnd,
 9588        window: &mut Window,
 9589        cx: &mut Context<Self>,
 9590    ) {
 9591        self.transact(window, cx, |this, window, cx| {
 9592            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9593                s.move_with(|map, selection| {
 9594                    if selection.is_empty() {
 9595                        let cursor = movement::next_subword_end(map, selection.head());
 9596                        selection.set_head(cursor, SelectionGoal::None);
 9597                    }
 9598                });
 9599            });
 9600            this.insert("", window, cx);
 9601        });
 9602    }
 9603
 9604    pub fn move_to_beginning_of_line(
 9605        &mut self,
 9606        action: &MoveToBeginningOfLine,
 9607        window: &mut Window,
 9608        cx: &mut Context<Self>,
 9609    ) {
 9610        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9611            s.move_cursors_with(|map, head, _| {
 9612                (
 9613                    movement::indented_line_beginning(
 9614                        map,
 9615                        head,
 9616                        action.stop_at_soft_wraps,
 9617                        action.stop_at_indent,
 9618                    ),
 9619                    SelectionGoal::None,
 9620                )
 9621            });
 9622        })
 9623    }
 9624
 9625    pub fn select_to_beginning_of_line(
 9626        &mut self,
 9627        action: &SelectToBeginningOfLine,
 9628        window: &mut Window,
 9629        cx: &mut Context<Self>,
 9630    ) {
 9631        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9632            s.move_heads_with(|map, head, _| {
 9633                (
 9634                    movement::indented_line_beginning(
 9635                        map,
 9636                        head,
 9637                        action.stop_at_soft_wraps,
 9638                        action.stop_at_indent,
 9639                    ),
 9640                    SelectionGoal::None,
 9641                )
 9642            });
 9643        });
 9644    }
 9645
 9646    pub fn delete_to_beginning_of_line(
 9647        &mut self,
 9648        action: &DeleteToBeginningOfLine,
 9649        window: &mut Window,
 9650        cx: &mut Context<Self>,
 9651    ) {
 9652        self.transact(window, cx, |this, window, cx| {
 9653            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9654                s.move_with(|_, selection| {
 9655                    selection.reversed = true;
 9656                });
 9657            });
 9658
 9659            this.select_to_beginning_of_line(
 9660                &SelectToBeginningOfLine {
 9661                    stop_at_soft_wraps: false,
 9662                    stop_at_indent: action.stop_at_indent,
 9663                },
 9664                window,
 9665                cx,
 9666            );
 9667            this.backspace(&Backspace, window, cx);
 9668        });
 9669    }
 9670
 9671    pub fn move_to_end_of_line(
 9672        &mut self,
 9673        action: &MoveToEndOfLine,
 9674        window: &mut Window,
 9675        cx: &mut Context<Self>,
 9676    ) {
 9677        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9678            s.move_cursors_with(|map, head, _| {
 9679                (
 9680                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9681                    SelectionGoal::None,
 9682                )
 9683            });
 9684        })
 9685    }
 9686
 9687    pub fn select_to_end_of_line(
 9688        &mut self,
 9689        action: &SelectToEndOfLine,
 9690        window: &mut Window,
 9691        cx: &mut Context<Self>,
 9692    ) {
 9693        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9694            s.move_heads_with(|map, head, _| {
 9695                (
 9696                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9697                    SelectionGoal::None,
 9698                )
 9699            });
 9700        })
 9701    }
 9702
 9703    pub fn delete_to_end_of_line(
 9704        &mut self,
 9705        _: &DeleteToEndOfLine,
 9706        window: &mut Window,
 9707        cx: &mut Context<Self>,
 9708    ) {
 9709        self.transact(window, cx, |this, window, cx| {
 9710            this.select_to_end_of_line(
 9711                &SelectToEndOfLine {
 9712                    stop_at_soft_wraps: false,
 9713                },
 9714                window,
 9715                cx,
 9716            );
 9717            this.delete(&Delete, window, cx);
 9718        });
 9719    }
 9720
 9721    pub fn cut_to_end_of_line(
 9722        &mut self,
 9723        _: &CutToEndOfLine,
 9724        window: &mut Window,
 9725        cx: &mut Context<Self>,
 9726    ) {
 9727        self.transact(window, cx, |this, window, cx| {
 9728            this.select_to_end_of_line(
 9729                &SelectToEndOfLine {
 9730                    stop_at_soft_wraps: false,
 9731                },
 9732                window,
 9733                cx,
 9734            );
 9735            this.cut(&Cut, window, cx);
 9736        });
 9737    }
 9738
 9739    pub fn move_to_start_of_paragraph(
 9740        &mut self,
 9741        _: &MoveToStartOfParagraph,
 9742        window: &mut Window,
 9743        cx: &mut Context<Self>,
 9744    ) {
 9745        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9746            cx.propagate();
 9747            return;
 9748        }
 9749
 9750        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9751            s.move_with(|map, selection| {
 9752                selection.collapse_to(
 9753                    movement::start_of_paragraph(map, selection.head(), 1),
 9754                    SelectionGoal::None,
 9755                )
 9756            });
 9757        })
 9758    }
 9759
 9760    pub fn move_to_end_of_paragraph(
 9761        &mut self,
 9762        _: &MoveToEndOfParagraph,
 9763        window: &mut Window,
 9764        cx: &mut Context<Self>,
 9765    ) {
 9766        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9767            cx.propagate();
 9768            return;
 9769        }
 9770
 9771        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9772            s.move_with(|map, selection| {
 9773                selection.collapse_to(
 9774                    movement::end_of_paragraph(map, selection.head(), 1),
 9775                    SelectionGoal::None,
 9776                )
 9777            });
 9778        })
 9779    }
 9780
 9781    pub fn select_to_start_of_paragraph(
 9782        &mut self,
 9783        _: &SelectToStartOfParagraph,
 9784        window: &mut Window,
 9785        cx: &mut Context<Self>,
 9786    ) {
 9787        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9788            cx.propagate();
 9789            return;
 9790        }
 9791
 9792        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9793            s.move_heads_with(|map, head, _| {
 9794                (
 9795                    movement::start_of_paragraph(map, head, 1),
 9796                    SelectionGoal::None,
 9797                )
 9798            });
 9799        })
 9800    }
 9801
 9802    pub fn select_to_end_of_paragraph(
 9803        &mut self,
 9804        _: &SelectToEndOfParagraph,
 9805        window: &mut Window,
 9806        cx: &mut Context<Self>,
 9807    ) {
 9808        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9809            cx.propagate();
 9810            return;
 9811        }
 9812
 9813        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9814            s.move_heads_with(|map, head, _| {
 9815                (
 9816                    movement::end_of_paragraph(map, head, 1),
 9817                    SelectionGoal::None,
 9818                )
 9819            });
 9820        })
 9821    }
 9822
 9823    pub fn move_to_start_of_excerpt(
 9824        &mut self,
 9825        _: &MoveToStartOfExcerpt,
 9826        window: &mut Window,
 9827        cx: &mut Context<Self>,
 9828    ) {
 9829        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9830            cx.propagate();
 9831            return;
 9832        }
 9833
 9834        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9835            s.move_with(|map, selection| {
 9836                selection.collapse_to(
 9837                    movement::start_of_excerpt(
 9838                        map,
 9839                        selection.head(),
 9840                        workspace::searchable::Direction::Prev,
 9841                    ),
 9842                    SelectionGoal::None,
 9843                )
 9844            });
 9845        })
 9846    }
 9847
 9848    pub fn move_to_end_of_excerpt(
 9849        &mut self,
 9850        _: &MoveToEndOfExcerpt,
 9851        window: &mut Window,
 9852        cx: &mut Context<Self>,
 9853    ) {
 9854        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9855            cx.propagate();
 9856            return;
 9857        }
 9858
 9859        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9860            s.move_with(|map, selection| {
 9861                selection.collapse_to(
 9862                    movement::end_of_excerpt(
 9863                        map,
 9864                        selection.head(),
 9865                        workspace::searchable::Direction::Next,
 9866                    ),
 9867                    SelectionGoal::None,
 9868                )
 9869            });
 9870        })
 9871    }
 9872
 9873    pub fn select_to_start_of_excerpt(
 9874        &mut self,
 9875        _: &SelectToStartOfExcerpt,
 9876        window: &mut Window,
 9877        cx: &mut Context<Self>,
 9878    ) {
 9879        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9880            cx.propagate();
 9881            return;
 9882        }
 9883
 9884        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9885            s.move_heads_with(|map, head, _| {
 9886                (
 9887                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
 9888                    SelectionGoal::None,
 9889                )
 9890            });
 9891        })
 9892    }
 9893
 9894    pub fn select_to_end_of_excerpt(
 9895        &mut self,
 9896        _: &SelectToEndOfExcerpt,
 9897        window: &mut Window,
 9898        cx: &mut Context<Self>,
 9899    ) {
 9900        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9901            cx.propagate();
 9902            return;
 9903        }
 9904
 9905        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9906            s.move_heads_with(|map, head, _| {
 9907                (
 9908                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
 9909                    SelectionGoal::None,
 9910                )
 9911            });
 9912        })
 9913    }
 9914
 9915    pub fn move_to_beginning(
 9916        &mut self,
 9917        _: &MoveToBeginning,
 9918        window: &mut Window,
 9919        cx: &mut Context<Self>,
 9920    ) {
 9921        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9922            cx.propagate();
 9923            return;
 9924        }
 9925
 9926        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9927            s.select_ranges(vec![0..0]);
 9928        });
 9929    }
 9930
 9931    pub fn select_to_beginning(
 9932        &mut self,
 9933        _: &SelectToBeginning,
 9934        window: &mut Window,
 9935        cx: &mut Context<Self>,
 9936    ) {
 9937        let mut selection = self.selections.last::<Point>(cx);
 9938        selection.set_head(Point::zero(), SelectionGoal::None);
 9939
 9940        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9941            s.select(vec![selection]);
 9942        });
 9943    }
 9944
 9945    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9946        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9947            cx.propagate();
 9948            return;
 9949        }
 9950
 9951        let cursor = self.buffer.read(cx).read(cx).len();
 9952        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9953            s.select_ranges(vec![cursor..cursor])
 9954        });
 9955    }
 9956
 9957    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9958        self.nav_history = nav_history;
 9959    }
 9960
 9961    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9962        self.nav_history.as_ref()
 9963    }
 9964
 9965    fn push_to_nav_history(
 9966        &mut self,
 9967        cursor_anchor: Anchor,
 9968        new_position: Option<Point>,
 9969        cx: &mut Context<Self>,
 9970    ) {
 9971        if let Some(nav_history) = self.nav_history.as_mut() {
 9972            let buffer = self.buffer.read(cx).read(cx);
 9973            let cursor_position = cursor_anchor.to_point(&buffer);
 9974            let scroll_state = self.scroll_manager.anchor();
 9975            let scroll_top_row = scroll_state.top_row(&buffer);
 9976            drop(buffer);
 9977
 9978            if let Some(new_position) = new_position {
 9979                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9980                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9981                    return;
 9982                }
 9983            }
 9984
 9985            nav_history.push(
 9986                Some(NavigationData {
 9987                    cursor_anchor,
 9988                    cursor_position,
 9989                    scroll_anchor: scroll_state,
 9990                    scroll_top_row,
 9991                }),
 9992                cx,
 9993            );
 9994        }
 9995    }
 9996
 9997    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9998        let buffer = self.buffer.read(cx).snapshot(cx);
 9999        let mut selection = self.selections.first::<usize>(cx);
10000        selection.set_head(buffer.len(), SelectionGoal::None);
10001        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10002            s.select(vec![selection]);
10003        });
10004    }
10005
10006    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
10007        let end = self.buffer.read(cx).read(cx).len();
10008        self.change_selections(None, window, cx, |s| {
10009            s.select_ranges(vec![0..end]);
10010        });
10011    }
10012
10013    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
10014        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10015        let mut selections = self.selections.all::<Point>(cx);
10016        let max_point = display_map.buffer_snapshot.max_point();
10017        for selection in &mut selections {
10018            let rows = selection.spanned_rows(true, &display_map);
10019            selection.start = Point::new(rows.start.0, 0);
10020            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
10021            selection.reversed = false;
10022        }
10023        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10024            s.select(selections);
10025        });
10026    }
10027
10028    pub fn split_selection_into_lines(
10029        &mut self,
10030        _: &SplitSelectionIntoLines,
10031        window: &mut Window,
10032        cx: &mut Context<Self>,
10033    ) {
10034        let selections = self
10035            .selections
10036            .all::<Point>(cx)
10037            .into_iter()
10038            .map(|selection| selection.start..selection.end)
10039            .collect::<Vec<_>>();
10040        self.unfold_ranges(&selections, true, true, cx);
10041
10042        let mut new_selection_ranges = Vec::new();
10043        {
10044            let buffer = self.buffer.read(cx).read(cx);
10045            for selection in selections {
10046                for row in selection.start.row..selection.end.row {
10047                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
10048                    new_selection_ranges.push(cursor..cursor);
10049                }
10050
10051                let is_multiline_selection = selection.start.row != selection.end.row;
10052                // Don't insert last one if it's a multi-line selection ending at the start of a line,
10053                // so this action feels more ergonomic when paired with other selection operations
10054                let should_skip_last = is_multiline_selection && selection.end.column == 0;
10055                if !should_skip_last {
10056                    new_selection_ranges.push(selection.end..selection.end);
10057                }
10058            }
10059        }
10060        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10061            s.select_ranges(new_selection_ranges);
10062        });
10063    }
10064
10065    pub fn add_selection_above(
10066        &mut self,
10067        _: &AddSelectionAbove,
10068        window: &mut Window,
10069        cx: &mut Context<Self>,
10070    ) {
10071        self.add_selection(true, window, cx);
10072    }
10073
10074    pub fn add_selection_below(
10075        &mut self,
10076        _: &AddSelectionBelow,
10077        window: &mut Window,
10078        cx: &mut Context<Self>,
10079    ) {
10080        self.add_selection(false, window, cx);
10081    }
10082
10083    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
10084        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10085        let mut selections = self.selections.all::<Point>(cx);
10086        let text_layout_details = self.text_layout_details(window);
10087        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10088            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10089            let range = oldest_selection.display_range(&display_map).sorted();
10090
10091            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10092            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10093            let positions = start_x.min(end_x)..start_x.max(end_x);
10094
10095            selections.clear();
10096            let mut stack = Vec::new();
10097            for row in range.start.row().0..=range.end.row().0 {
10098                if let Some(selection) = self.selections.build_columnar_selection(
10099                    &display_map,
10100                    DisplayRow(row),
10101                    &positions,
10102                    oldest_selection.reversed,
10103                    &text_layout_details,
10104                ) {
10105                    stack.push(selection.id);
10106                    selections.push(selection);
10107                }
10108            }
10109
10110            if above {
10111                stack.reverse();
10112            }
10113
10114            AddSelectionsState { above, stack }
10115        });
10116
10117        let last_added_selection = *state.stack.last().unwrap();
10118        let mut new_selections = Vec::new();
10119        if above == state.above {
10120            let end_row = if above {
10121                DisplayRow(0)
10122            } else {
10123                display_map.max_point().row()
10124            };
10125
10126            'outer: for selection in selections {
10127                if selection.id == last_added_selection {
10128                    let range = selection.display_range(&display_map).sorted();
10129                    debug_assert_eq!(range.start.row(), range.end.row());
10130                    let mut row = range.start.row();
10131                    let positions =
10132                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10133                            px(start)..px(end)
10134                        } else {
10135                            let start_x =
10136                                display_map.x_for_display_point(range.start, &text_layout_details);
10137                            let end_x =
10138                                display_map.x_for_display_point(range.end, &text_layout_details);
10139                            start_x.min(end_x)..start_x.max(end_x)
10140                        };
10141
10142                    while row != end_row {
10143                        if above {
10144                            row.0 -= 1;
10145                        } else {
10146                            row.0 += 1;
10147                        }
10148
10149                        if let Some(new_selection) = self.selections.build_columnar_selection(
10150                            &display_map,
10151                            row,
10152                            &positions,
10153                            selection.reversed,
10154                            &text_layout_details,
10155                        ) {
10156                            state.stack.push(new_selection.id);
10157                            if above {
10158                                new_selections.push(new_selection);
10159                                new_selections.push(selection);
10160                            } else {
10161                                new_selections.push(selection);
10162                                new_selections.push(new_selection);
10163                            }
10164
10165                            continue 'outer;
10166                        }
10167                    }
10168                }
10169
10170                new_selections.push(selection);
10171            }
10172        } else {
10173            new_selections = selections;
10174            new_selections.retain(|s| s.id != last_added_selection);
10175            state.stack.pop();
10176        }
10177
10178        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10179            s.select(new_selections);
10180        });
10181        if state.stack.len() > 1 {
10182            self.add_selections_state = Some(state);
10183        }
10184    }
10185
10186    pub fn select_next_match_internal(
10187        &mut self,
10188        display_map: &DisplaySnapshot,
10189        replace_newest: bool,
10190        autoscroll: Option<Autoscroll>,
10191        window: &mut Window,
10192        cx: &mut Context<Self>,
10193    ) -> Result<()> {
10194        fn select_next_match_ranges(
10195            this: &mut Editor,
10196            range: Range<usize>,
10197            replace_newest: bool,
10198            auto_scroll: Option<Autoscroll>,
10199            window: &mut Window,
10200            cx: &mut Context<Editor>,
10201        ) {
10202            this.unfold_ranges(&[range.clone()], false, true, cx);
10203            this.change_selections(auto_scroll, window, cx, |s| {
10204                if replace_newest {
10205                    s.delete(s.newest_anchor().id);
10206                }
10207                s.insert_range(range.clone());
10208            });
10209        }
10210
10211        let buffer = &display_map.buffer_snapshot;
10212        let mut selections = self.selections.all::<usize>(cx);
10213        if let Some(mut select_next_state) = self.select_next_state.take() {
10214            let query = &select_next_state.query;
10215            if !select_next_state.done {
10216                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10217                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10218                let mut next_selected_range = None;
10219
10220                let bytes_after_last_selection =
10221                    buffer.bytes_in_range(last_selection.end..buffer.len());
10222                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10223                let query_matches = query
10224                    .stream_find_iter(bytes_after_last_selection)
10225                    .map(|result| (last_selection.end, result))
10226                    .chain(
10227                        query
10228                            .stream_find_iter(bytes_before_first_selection)
10229                            .map(|result| (0, result)),
10230                    );
10231
10232                for (start_offset, query_match) in query_matches {
10233                    let query_match = query_match.unwrap(); // can only fail due to I/O
10234                    let offset_range =
10235                        start_offset + query_match.start()..start_offset + query_match.end();
10236                    let display_range = offset_range.start.to_display_point(display_map)
10237                        ..offset_range.end.to_display_point(display_map);
10238
10239                    if !select_next_state.wordwise
10240                        || (!movement::is_inside_word(display_map, display_range.start)
10241                            && !movement::is_inside_word(display_map, display_range.end))
10242                    {
10243                        // TODO: This is n^2, because we might check all the selections
10244                        if !selections
10245                            .iter()
10246                            .any(|selection| selection.range().overlaps(&offset_range))
10247                        {
10248                            next_selected_range = Some(offset_range);
10249                            break;
10250                        }
10251                    }
10252                }
10253
10254                if let Some(next_selected_range) = next_selected_range {
10255                    select_next_match_ranges(
10256                        self,
10257                        next_selected_range,
10258                        replace_newest,
10259                        autoscroll,
10260                        window,
10261                        cx,
10262                    );
10263                } else {
10264                    select_next_state.done = true;
10265                }
10266            }
10267
10268            self.select_next_state = Some(select_next_state);
10269        } else {
10270            let mut only_carets = true;
10271            let mut same_text_selected = true;
10272            let mut selected_text = None;
10273
10274            let mut selections_iter = selections.iter().peekable();
10275            while let Some(selection) = selections_iter.next() {
10276                if selection.start != selection.end {
10277                    only_carets = false;
10278                }
10279
10280                if same_text_selected {
10281                    if selected_text.is_none() {
10282                        selected_text =
10283                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10284                    }
10285
10286                    if let Some(next_selection) = selections_iter.peek() {
10287                        if next_selection.range().len() == selection.range().len() {
10288                            let next_selected_text = buffer
10289                                .text_for_range(next_selection.range())
10290                                .collect::<String>();
10291                            if Some(next_selected_text) != selected_text {
10292                                same_text_selected = false;
10293                                selected_text = None;
10294                            }
10295                        } else {
10296                            same_text_selected = false;
10297                            selected_text = None;
10298                        }
10299                    }
10300                }
10301            }
10302
10303            if only_carets {
10304                for selection in &mut selections {
10305                    let word_range = movement::surrounding_word(
10306                        display_map,
10307                        selection.start.to_display_point(display_map),
10308                    );
10309                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
10310                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
10311                    selection.goal = SelectionGoal::None;
10312                    selection.reversed = false;
10313                    select_next_match_ranges(
10314                        self,
10315                        selection.start..selection.end,
10316                        replace_newest,
10317                        autoscroll,
10318                        window,
10319                        cx,
10320                    );
10321                }
10322
10323                if selections.len() == 1 {
10324                    let selection = selections
10325                        .last()
10326                        .expect("ensured that there's only one selection");
10327                    let query = buffer
10328                        .text_for_range(selection.start..selection.end)
10329                        .collect::<String>();
10330                    let is_empty = query.is_empty();
10331                    let select_state = SelectNextState {
10332                        query: AhoCorasick::new(&[query])?,
10333                        wordwise: true,
10334                        done: is_empty,
10335                    };
10336                    self.select_next_state = Some(select_state);
10337                } else {
10338                    self.select_next_state = None;
10339                }
10340            } else if let Some(selected_text) = selected_text {
10341                self.select_next_state = Some(SelectNextState {
10342                    query: AhoCorasick::new(&[selected_text])?,
10343                    wordwise: false,
10344                    done: false,
10345                });
10346                self.select_next_match_internal(
10347                    display_map,
10348                    replace_newest,
10349                    autoscroll,
10350                    window,
10351                    cx,
10352                )?;
10353            }
10354        }
10355        Ok(())
10356    }
10357
10358    pub fn select_all_matches(
10359        &mut self,
10360        _action: &SelectAllMatches,
10361        window: &mut Window,
10362        cx: &mut Context<Self>,
10363    ) -> Result<()> {
10364        self.push_to_selection_history();
10365        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10366
10367        self.select_next_match_internal(&display_map, false, None, window, cx)?;
10368        let Some(select_next_state) = self.select_next_state.as_mut() else {
10369            return Ok(());
10370        };
10371        if select_next_state.done {
10372            return Ok(());
10373        }
10374
10375        let mut new_selections = self.selections.all::<usize>(cx);
10376
10377        let buffer = &display_map.buffer_snapshot;
10378        let query_matches = select_next_state
10379            .query
10380            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10381
10382        for query_match in query_matches {
10383            let query_match = query_match.unwrap(); // can only fail due to I/O
10384            let offset_range = query_match.start()..query_match.end();
10385            let display_range = offset_range.start.to_display_point(&display_map)
10386                ..offset_range.end.to_display_point(&display_map);
10387
10388            if !select_next_state.wordwise
10389                || (!movement::is_inside_word(&display_map, display_range.start)
10390                    && !movement::is_inside_word(&display_map, display_range.end))
10391            {
10392                self.selections.change_with(cx, |selections| {
10393                    new_selections.push(Selection {
10394                        id: selections.new_selection_id(),
10395                        start: offset_range.start,
10396                        end: offset_range.end,
10397                        reversed: false,
10398                        goal: SelectionGoal::None,
10399                    });
10400                });
10401            }
10402        }
10403
10404        new_selections.sort_by_key(|selection| selection.start);
10405        let mut ix = 0;
10406        while ix + 1 < new_selections.len() {
10407            let current_selection = &new_selections[ix];
10408            let next_selection = &new_selections[ix + 1];
10409            if current_selection.range().overlaps(&next_selection.range()) {
10410                if current_selection.id < next_selection.id {
10411                    new_selections.remove(ix + 1);
10412                } else {
10413                    new_selections.remove(ix);
10414                }
10415            } else {
10416                ix += 1;
10417            }
10418        }
10419
10420        let reversed = self.selections.oldest::<usize>(cx).reversed;
10421
10422        for selection in new_selections.iter_mut() {
10423            selection.reversed = reversed;
10424        }
10425
10426        select_next_state.done = true;
10427        self.unfold_ranges(
10428            &new_selections
10429                .iter()
10430                .map(|selection| selection.range())
10431                .collect::<Vec<_>>(),
10432            false,
10433            false,
10434            cx,
10435        );
10436        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10437            selections.select(new_selections)
10438        });
10439
10440        Ok(())
10441    }
10442
10443    pub fn select_next(
10444        &mut self,
10445        action: &SelectNext,
10446        window: &mut Window,
10447        cx: &mut Context<Self>,
10448    ) -> Result<()> {
10449        self.push_to_selection_history();
10450        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10451        self.select_next_match_internal(
10452            &display_map,
10453            action.replace_newest,
10454            Some(Autoscroll::newest()),
10455            window,
10456            cx,
10457        )?;
10458        Ok(())
10459    }
10460
10461    pub fn select_previous(
10462        &mut self,
10463        action: &SelectPrevious,
10464        window: &mut Window,
10465        cx: &mut Context<Self>,
10466    ) -> Result<()> {
10467        self.push_to_selection_history();
10468        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10469        let buffer = &display_map.buffer_snapshot;
10470        let mut selections = self.selections.all::<usize>(cx);
10471        if let Some(mut select_prev_state) = self.select_prev_state.take() {
10472            let query = &select_prev_state.query;
10473            if !select_prev_state.done {
10474                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10475                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10476                let mut next_selected_range = None;
10477                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10478                let bytes_before_last_selection =
10479                    buffer.reversed_bytes_in_range(0..last_selection.start);
10480                let bytes_after_first_selection =
10481                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10482                let query_matches = query
10483                    .stream_find_iter(bytes_before_last_selection)
10484                    .map(|result| (last_selection.start, result))
10485                    .chain(
10486                        query
10487                            .stream_find_iter(bytes_after_first_selection)
10488                            .map(|result| (buffer.len(), result)),
10489                    );
10490                for (end_offset, query_match) in query_matches {
10491                    let query_match = query_match.unwrap(); // can only fail due to I/O
10492                    let offset_range =
10493                        end_offset - query_match.end()..end_offset - query_match.start();
10494                    let display_range = offset_range.start.to_display_point(&display_map)
10495                        ..offset_range.end.to_display_point(&display_map);
10496
10497                    if !select_prev_state.wordwise
10498                        || (!movement::is_inside_word(&display_map, display_range.start)
10499                            && !movement::is_inside_word(&display_map, display_range.end))
10500                    {
10501                        next_selected_range = Some(offset_range);
10502                        break;
10503                    }
10504                }
10505
10506                if let Some(next_selected_range) = next_selected_range {
10507                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10508                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10509                        if action.replace_newest {
10510                            s.delete(s.newest_anchor().id);
10511                        }
10512                        s.insert_range(next_selected_range);
10513                    });
10514                } else {
10515                    select_prev_state.done = true;
10516                }
10517            }
10518
10519            self.select_prev_state = Some(select_prev_state);
10520        } else {
10521            let mut only_carets = true;
10522            let mut same_text_selected = true;
10523            let mut selected_text = None;
10524
10525            let mut selections_iter = selections.iter().peekable();
10526            while let Some(selection) = selections_iter.next() {
10527                if selection.start != selection.end {
10528                    only_carets = false;
10529                }
10530
10531                if same_text_selected {
10532                    if selected_text.is_none() {
10533                        selected_text =
10534                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10535                    }
10536
10537                    if let Some(next_selection) = selections_iter.peek() {
10538                        if next_selection.range().len() == selection.range().len() {
10539                            let next_selected_text = buffer
10540                                .text_for_range(next_selection.range())
10541                                .collect::<String>();
10542                            if Some(next_selected_text) != selected_text {
10543                                same_text_selected = false;
10544                                selected_text = None;
10545                            }
10546                        } else {
10547                            same_text_selected = false;
10548                            selected_text = None;
10549                        }
10550                    }
10551                }
10552            }
10553
10554            if only_carets {
10555                for selection in &mut selections {
10556                    let word_range = movement::surrounding_word(
10557                        &display_map,
10558                        selection.start.to_display_point(&display_map),
10559                    );
10560                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10561                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10562                    selection.goal = SelectionGoal::None;
10563                    selection.reversed = false;
10564                }
10565                if selections.len() == 1 {
10566                    let selection = selections
10567                        .last()
10568                        .expect("ensured that there's only one selection");
10569                    let query = buffer
10570                        .text_for_range(selection.start..selection.end)
10571                        .collect::<String>();
10572                    let is_empty = query.is_empty();
10573                    let select_state = SelectNextState {
10574                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10575                        wordwise: true,
10576                        done: is_empty,
10577                    };
10578                    self.select_prev_state = Some(select_state);
10579                } else {
10580                    self.select_prev_state = None;
10581                }
10582
10583                self.unfold_ranges(
10584                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10585                    false,
10586                    true,
10587                    cx,
10588                );
10589                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10590                    s.select(selections);
10591                });
10592            } else if let Some(selected_text) = selected_text {
10593                self.select_prev_state = Some(SelectNextState {
10594                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10595                    wordwise: false,
10596                    done: false,
10597                });
10598                self.select_previous(action, window, cx)?;
10599            }
10600        }
10601        Ok(())
10602    }
10603
10604    pub fn toggle_comments(
10605        &mut self,
10606        action: &ToggleComments,
10607        window: &mut Window,
10608        cx: &mut Context<Self>,
10609    ) {
10610        if self.read_only(cx) {
10611            return;
10612        }
10613        let text_layout_details = &self.text_layout_details(window);
10614        self.transact(window, cx, |this, window, cx| {
10615            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10616            let mut edits = Vec::new();
10617            let mut selection_edit_ranges = Vec::new();
10618            let mut last_toggled_row = None;
10619            let snapshot = this.buffer.read(cx).read(cx);
10620            let empty_str: Arc<str> = Arc::default();
10621            let mut suffixes_inserted = Vec::new();
10622            let ignore_indent = action.ignore_indent;
10623
10624            fn comment_prefix_range(
10625                snapshot: &MultiBufferSnapshot,
10626                row: MultiBufferRow,
10627                comment_prefix: &str,
10628                comment_prefix_whitespace: &str,
10629                ignore_indent: bool,
10630            ) -> Range<Point> {
10631                let indent_size = if ignore_indent {
10632                    0
10633                } else {
10634                    snapshot.indent_size_for_line(row).len
10635                };
10636
10637                let start = Point::new(row.0, indent_size);
10638
10639                let mut line_bytes = snapshot
10640                    .bytes_in_range(start..snapshot.max_point())
10641                    .flatten()
10642                    .copied();
10643
10644                // If this line currently begins with the line comment prefix, then record
10645                // the range containing the prefix.
10646                if line_bytes
10647                    .by_ref()
10648                    .take(comment_prefix.len())
10649                    .eq(comment_prefix.bytes())
10650                {
10651                    // Include any whitespace that matches the comment prefix.
10652                    let matching_whitespace_len = line_bytes
10653                        .zip(comment_prefix_whitespace.bytes())
10654                        .take_while(|(a, b)| a == b)
10655                        .count() as u32;
10656                    let end = Point::new(
10657                        start.row,
10658                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10659                    );
10660                    start..end
10661                } else {
10662                    start..start
10663                }
10664            }
10665
10666            fn comment_suffix_range(
10667                snapshot: &MultiBufferSnapshot,
10668                row: MultiBufferRow,
10669                comment_suffix: &str,
10670                comment_suffix_has_leading_space: bool,
10671            ) -> Range<Point> {
10672                let end = Point::new(row.0, snapshot.line_len(row));
10673                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10674
10675                let mut line_end_bytes = snapshot
10676                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10677                    .flatten()
10678                    .copied();
10679
10680                let leading_space_len = if suffix_start_column > 0
10681                    && line_end_bytes.next() == Some(b' ')
10682                    && comment_suffix_has_leading_space
10683                {
10684                    1
10685                } else {
10686                    0
10687                };
10688
10689                // If this line currently begins with the line comment prefix, then record
10690                // the range containing the prefix.
10691                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10692                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
10693                    start..end
10694                } else {
10695                    end..end
10696                }
10697            }
10698
10699            // TODO: Handle selections that cross excerpts
10700            for selection in &mut selections {
10701                let start_column = snapshot
10702                    .indent_size_for_line(MultiBufferRow(selection.start.row))
10703                    .len;
10704                let language = if let Some(language) =
10705                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10706                {
10707                    language
10708                } else {
10709                    continue;
10710                };
10711
10712                selection_edit_ranges.clear();
10713
10714                // If multiple selections contain a given row, avoid processing that
10715                // row more than once.
10716                let mut start_row = MultiBufferRow(selection.start.row);
10717                if last_toggled_row == Some(start_row) {
10718                    start_row = start_row.next_row();
10719                }
10720                let end_row =
10721                    if selection.end.row > selection.start.row && selection.end.column == 0 {
10722                        MultiBufferRow(selection.end.row - 1)
10723                    } else {
10724                        MultiBufferRow(selection.end.row)
10725                    };
10726                last_toggled_row = Some(end_row);
10727
10728                if start_row > end_row {
10729                    continue;
10730                }
10731
10732                // If the language has line comments, toggle those.
10733                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10734
10735                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10736                if ignore_indent {
10737                    full_comment_prefixes = full_comment_prefixes
10738                        .into_iter()
10739                        .map(|s| Arc::from(s.trim_end()))
10740                        .collect();
10741                }
10742
10743                if !full_comment_prefixes.is_empty() {
10744                    let first_prefix = full_comment_prefixes
10745                        .first()
10746                        .expect("prefixes is non-empty");
10747                    let prefix_trimmed_lengths = full_comment_prefixes
10748                        .iter()
10749                        .map(|p| p.trim_end_matches(' ').len())
10750                        .collect::<SmallVec<[usize; 4]>>();
10751
10752                    let mut all_selection_lines_are_comments = true;
10753
10754                    for row in start_row.0..=end_row.0 {
10755                        let row = MultiBufferRow(row);
10756                        if start_row < end_row && snapshot.is_line_blank(row) {
10757                            continue;
10758                        }
10759
10760                        let prefix_range = full_comment_prefixes
10761                            .iter()
10762                            .zip(prefix_trimmed_lengths.iter().copied())
10763                            .map(|(prefix, trimmed_prefix_len)| {
10764                                comment_prefix_range(
10765                                    snapshot.deref(),
10766                                    row,
10767                                    &prefix[..trimmed_prefix_len],
10768                                    &prefix[trimmed_prefix_len..],
10769                                    ignore_indent,
10770                                )
10771                            })
10772                            .max_by_key(|range| range.end.column - range.start.column)
10773                            .expect("prefixes is non-empty");
10774
10775                        if prefix_range.is_empty() {
10776                            all_selection_lines_are_comments = false;
10777                        }
10778
10779                        selection_edit_ranges.push(prefix_range);
10780                    }
10781
10782                    if all_selection_lines_are_comments {
10783                        edits.extend(
10784                            selection_edit_ranges
10785                                .iter()
10786                                .cloned()
10787                                .map(|range| (range, empty_str.clone())),
10788                        );
10789                    } else {
10790                        let min_column = selection_edit_ranges
10791                            .iter()
10792                            .map(|range| range.start.column)
10793                            .min()
10794                            .unwrap_or(0);
10795                        edits.extend(selection_edit_ranges.iter().map(|range| {
10796                            let position = Point::new(range.start.row, min_column);
10797                            (position..position, first_prefix.clone())
10798                        }));
10799                    }
10800                } else if let Some((full_comment_prefix, comment_suffix)) =
10801                    language.block_comment_delimiters()
10802                {
10803                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10804                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10805                    let prefix_range = comment_prefix_range(
10806                        snapshot.deref(),
10807                        start_row,
10808                        comment_prefix,
10809                        comment_prefix_whitespace,
10810                        ignore_indent,
10811                    );
10812                    let suffix_range = comment_suffix_range(
10813                        snapshot.deref(),
10814                        end_row,
10815                        comment_suffix.trim_start_matches(' '),
10816                        comment_suffix.starts_with(' '),
10817                    );
10818
10819                    if prefix_range.is_empty() || suffix_range.is_empty() {
10820                        edits.push((
10821                            prefix_range.start..prefix_range.start,
10822                            full_comment_prefix.clone(),
10823                        ));
10824                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10825                        suffixes_inserted.push((end_row, comment_suffix.len()));
10826                    } else {
10827                        edits.push((prefix_range, empty_str.clone()));
10828                        edits.push((suffix_range, empty_str.clone()));
10829                    }
10830                } else {
10831                    continue;
10832                }
10833            }
10834
10835            drop(snapshot);
10836            this.buffer.update(cx, |buffer, cx| {
10837                buffer.edit(edits, None, cx);
10838            });
10839
10840            // Adjust selections so that they end before any comment suffixes that
10841            // were inserted.
10842            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10843            let mut selections = this.selections.all::<Point>(cx);
10844            let snapshot = this.buffer.read(cx).read(cx);
10845            for selection in &mut selections {
10846                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10847                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10848                        Ordering::Less => {
10849                            suffixes_inserted.next();
10850                            continue;
10851                        }
10852                        Ordering::Greater => break,
10853                        Ordering::Equal => {
10854                            if selection.end.column == snapshot.line_len(row) {
10855                                if selection.is_empty() {
10856                                    selection.start.column -= suffix_len as u32;
10857                                }
10858                                selection.end.column -= suffix_len as u32;
10859                            }
10860                            break;
10861                        }
10862                    }
10863                }
10864            }
10865
10866            drop(snapshot);
10867            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10868                s.select(selections)
10869            });
10870
10871            let selections = this.selections.all::<Point>(cx);
10872            let selections_on_single_row = selections.windows(2).all(|selections| {
10873                selections[0].start.row == selections[1].start.row
10874                    && selections[0].end.row == selections[1].end.row
10875                    && selections[0].start.row == selections[0].end.row
10876            });
10877            let selections_selecting = selections
10878                .iter()
10879                .any(|selection| selection.start != selection.end);
10880            let advance_downwards = action.advance_downwards
10881                && selections_on_single_row
10882                && !selections_selecting
10883                && !matches!(this.mode, EditorMode::SingleLine { .. });
10884
10885            if advance_downwards {
10886                let snapshot = this.buffer.read(cx).snapshot(cx);
10887
10888                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10889                    s.move_cursors_with(|display_snapshot, display_point, _| {
10890                        let mut point = display_point.to_point(display_snapshot);
10891                        point.row += 1;
10892                        point = snapshot.clip_point(point, Bias::Left);
10893                        let display_point = point.to_display_point(display_snapshot);
10894                        let goal = SelectionGoal::HorizontalPosition(
10895                            display_snapshot
10896                                .x_for_display_point(display_point, text_layout_details)
10897                                .into(),
10898                        );
10899                        (display_point, goal)
10900                    })
10901                });
10902            }
10903        });
10904    }
10905
10906    pub fn select_enclosing_symbol(
10907        &mut self,
10908        _: &SelectEnclosingSymbol,
10909        window: &mut Window,
10910        cx: &mut Context<Self>,
10911    ) {
10912        let buffer = self.buffer.read(cx).snapshot(cx);
10913        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10914
10915        fn update_selection(
10916            selection: &Selection<usize>,
10917            buffer_snap: &MultiBufferSnapshot,
10918        ) -> Option<Selection<usize>> {
10919            let cursor = selection.head();
10920            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10921            for symbol in symbols.iter().rev() {
10922                let start = symbol.range.start.to_offset(buffer_snap);
10923                let end = symbol.range.end.to_offset(buffer_snap);
10924                let new_range = start..end;
10925                if start < selection.start || end > selection.end {
10926                    return Some(Selection {
10927                        id: selection.id,
10928                        start: new_range.start,
10929                        end: new_range.end,
10930                        goal: SelectionGoal::None,
10931                        reversed: selection.reversed,
10932                    });
10933                }
10934            }
10935            None
10936        }
10937
10938        let mut selected_larger_symbol = false;
10939        let new_selections = old_selections
10940            .iter()
10941            .map(|selection| match update_selection(selection, &buffer) {
10942                Some(new_selection) => {
10943                    if new_selection.range() != selection.range() {
10944                        selected_larger_symbol = true;
10945                    }
10946                    new_selection
10947                }
10948                None => selection.clone(),
10949            })
10950            .collect::<Vec<_>>();
10951
10952        if selected_larger_symbol {
10953            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10954                s.select(new_selections);
10955            });
10956        }
10957    }
10958
10959    pub fn select_larger_syntax_node(
10960        &mut self,
10961        _: &SelectLargerSyntaxNode,
10962        window: &mut Window,
10963        cx: &mut Context<Self>,
10964    ) {
10965        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10966        let buffer = self.buffer.read(cx).snapshot(cx);
10967        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10968
10969        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10970        let mut selected_larger_node = false;
10971        let new_selections = old_selections
10972            .iter()
10973            .map(|selection| {
10974                let old_range = selection.start..selection.end;
10975                let mut new_range = old_range.clone();
10976                let mut new_node = None;
10977                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10978                {
10979                    new_node = Some(node);
10980                    new_range = match containing_range {
10981                        MultiOrSingleBufferOffsetRange::Single(_) => break,
10982                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
10983                    };
10984                    if !display_map.intersects_fold(new_range.start)
10985                        && !display_map.intersects_fold(new_range.end)
10986                    {
10987                        break;
10988                    }
10989                }
10990
10991                if let Some(node) = new_node {
10992                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10993                    // nodes. Parent and grandparent are also logged because this operation will not
10994                    // visit nodes that have the same range as their parent.
10995                    log::info!("Node: {node:?}");
10996                    let parent = node.parent();
10997                    log::info!("Parent: {parent:?}");
10998                    let grandparent = parent.and_then(|x| x.parent());
10999                    log::info!("Grandparent: {grandparent:?}");
11000                }
11001
11002                selected_larger_node |= new_range != old_range;
11003                Selection {
11004                    id: selection.id,
11005                    start: new_range.start,
11006                    end: new_range.end,
11007                    goal: SelectionGoal::None,
11008                    reversed: selection.reversed,
11009                }
11010            })
11011            .collect::<Vec<_>>();
11012
11013        if selected_larger_node {
11014            stack.push(old_selections);
11015            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11016                s.select(new_selections);
11017            });
11018        }
11019        self.select_larger_syntax_node_stack = stack;
11020    }
11021
11022    pub fn select_smaller_syntax_node(
11023        &mut self,
11024        _: &SelectSmallerSyntaxNode,
11025        window: &mut Window,
11026        cx: &mut Context<Self>,
11027    ) {
11028        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11029        if let Some(selections) = stack.pop() {
11030            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11031                s.select(selections.to_vec());
11032            });
11033        }
11034        self.select_larger_syntax_node_stack = stack;
11035    }
11036
11037    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
11038        if !EditorSettings::get_global(cx).gutter.runnables {
11039            self.clear_tasks();
11040            return Task::ready(());
11041        }
11042        let project = self.project.as_ref().map(Entity::downgrade);
11043        cx.spawn_in(window, |this, mut cx| async move {
11044            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
11045            let Some(project) = project.and_then(|p| p.upgrade()) else {
11046                return;
11047            };
11048            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
11049                this.display_map.update(cx, |map, cx| map.snapshot(cx))
11050            }) else {
11051                return;
11052            };
11053
11054            let hide_runnables = project
11055                .update(&mut cx, |project, cx| {
11056                    // Do not display any test indicators in non-dev server remote projects.
11057                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
11058                })
11059                .unwrap_or(true);
11060            if hide_runnables {
11061                return;
11062            }
11063            let new_rows =
11064                cx.background_spawn({
11065                    let snapshot = display_snapshot.clone();
11066                    async move {
11067                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
11068                    }
11069                })
11070                    .await;
11071
11072            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
11073            this.update(&mut cx, |this, _| {
11074                this.clear_tasks();
11075                for (key, value) in rows {
11076                    this.insert_tasks(key, value);
11077                }
11078            })
11079            .ok();
11080        })
11081    }
11082    fn fetch_runnable_ranges(
11083        snapshot: &DisplaySnapshot,
11084        range: Range<Anchor>,
11085    ) -> Vec<language::RunnableRange> {
11086        snapshot.buffer_snapshot.runnable_ranges(range).collect()
11087    }
11088
11089    fn runnable_rows(
11090        project: Entity<Project>,
11091        snapshot: DisplaySnapshot,
11092        runnable_ranges: Vec<RunnableRange>,
11093        mut cx: AsyncWindowContext,
11094    ) -> Vec<((BufferId, u32), RunnableTasks)> {
11095        runnable_ranges
11096            .into_iter()
11097            .filter_map(|mut runnable| {
11098                let tasks = cx
11099                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11100                    .ok()?;
11101                if tasks.is_empty() {
11102                    return None;
11103                }
11104
11105                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11106
11107                let row = snapshot
11108                    .buffer_snapshot
11109                    .buffer_line_for_row(MultiBufferRow(point.row))?
11110                    .1
11111                    .start
11112                    .row;
11113
11114                let context_range =
11115                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11116                Some((
11117                    (runnable.buffer_id, row),
11118                    RunnableTasks {
11119                        templates: tasks,
11120                        offset: snapshot
11121                            .buffer_snapshot
11122                            .anchor_before(runnable.run_range.start),
11123                        context_range,
11124                        column: point.column,
11125                        extra_variables: runnable.extra_captures,
11126                    },
11127                ))
11128            })
11129            .collect()
11130    }
11131
11132    fn templates_with_tags(
11133        project: &Entity<Project>,
11134        runnable: &mut Runnable,
11135        cx: &mut App,
11136    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11137        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11138            let (worktree_id, file) = project
11139                .buffer_for_id(runnable.buffer, cx)
11140                .and_then(|buffer| buffer.read(cx).file())
11141                .map(|file| (file.worktree_id(cx), file.clone()))
11142                .unzip();
11143
11144            (
11145                project.task_store().read(cx).task_inventory().cloned(),
11146                worktree_id,
11147                file,
11148            )
11149        });
11150
11151        let tags = mem::take(&mut runnable.tags);
11152        let mut tags: Vec<_> = tags
11153            .into_iter()
11154            .flat_map(|tag| {
11155                let tag = tag.0.clone();
11156                inventory
11157                    .as_ref()
11158                    .into_iter()
11159                    .flat_map(|inventory| {
11160                        inventory.read(cx).list_tasks(
11161                            file.clone(),
11162                            Some(runnable.language.clone()),
11163                            worktree_id,
11164                            cx,
11165                        )
11166                    })
11167                    .filter(move |(_, template)| {
11168                        template.tags.iter().any(|source_tag| source_tag == &tag)
11169                    })
11170            })
11171            .sorted_by_key(|(kind, _)| kind.to_owned())
11172            .collect();
11173        if let Some((leading_tag_source, _)) = tags.first() {
11174            // Strongest source wins; if we have worktree tag binding, prefer that to
11175            // global and language bindings;
11176            // if we have a global binding, prefer that to language binding.
11177            let first_mismatch = tags
11178                .iter()
11179                .position(|(tag_source, _)| tag_source != leading_tag_source);
11180            if let Some(index) = first_mismatch {
11181                tags.truncate(index);
11182            }
11183        }
11184
11185        tags
11186    }
11187
11188    pub fn move_to_enclosing_bracket(
11189        &mut self,
11190        _: &MoveToEnclosingBracket,
11191        window: &mut Window,
11192        cx: &mut Context<Self>,
11193    ) {
11194        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11195            s.move_offsets_with(|snapshot, selection| {
11196                let Some(enclosing_bracket_ranges) =
11197                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11198                else {
11199                    return;
11200                };
11201
11202                let mut best_length = usize::MAX;
11203                let mut best_inside = false;
11204                let mut best_in_bracket_range = false;
11205                let mut best_destination = None;
11206                for (open, close) in enclosing_bracket_ranges {
11207                    let close = close.to_inclusive();
11208                    let length = close.end() - open.start;
11209                    let inside = selection.start >= open.end && selection.end <= *close.start();
11210                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
11211                        || close.contains(&selection.head());
11212
11213                    // If best is next to a bracket and current isn't, skip
11214                    if !in_bracket_range && best_in_bracket_range {
11215                        continue;
11216                    }
11217
11218                    // Prefer smaller lengths unless best is inside and current isn't
11219                    if length > best_length && (best_inside || !inside) {
11220                        continue;
11221                    }
11222
11223                    best_length = length;
11224                    best_inside = inside;
11225                    best_in_bracket_range = in_bracket_range;
11226                    best_destination = Some(
11227                        if close.contains(&selection.start) && close.contains(&selection.end) {
11228                            if inside {
11229                                open.end
11230                            } else {
11231                                open.start
11232                            }
11233                        } else if inside {
11234                            *close.start()
11235                        } else {
11236                            *close.end()
11237                        },
11238                    );
11239                }
11240
11241                if let Some(destination) = best_destination {
11242                    selection.collapse_to(destination, SelectionGoal::None);
11243                }
11244            })
11245        });
11246    }
11247
11248    pub fn undo_selection(
11249        &mut self,
11250        _: &UndoSelection,
11251        window: &mut Window,
11252        cx: &mut Context<Self>,
11253    ) {
11254        self.end_selection(window, cx);
11255        self.selection_history.mode = SelectionHistoryMode::Undoing;
11256        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11257            self.change_selections(None, window, cx, |s| {
11258                s.select_anchors(entry.selections.to_vec())
11259            });
11260            self.select_next_state = entry.select_next_state;
11261            self.select_prev_state = entry.select_prev_state;
11262            self.add_selections_state = entry.add_selections_state;
11263            self.request_autoscroll(Autoscroll::newest(), cx);
11264        }
11265        self.selection_history.mode = SelectionHistoryMode::Normal;
11266    }
11267
11268    pub fn redo_selection(
11269        &mut self,
11270        _: &RedoSelection,
11271        window: &mut Window,
11272        cx: &mut Context<Self>,
11273    ) {
11274        self.end_selection(window, cx);
11275        self.selection_history.mode = SelectionHistoryMode::Redoing;
11276        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11277            self.change_selections(None, window, cx, |s| {
11278                s.select_anchors(entry.selections.to_vec())
11279            });
11280            self.select_next_state = entry.select_next_state;
11281            self.select_prev_state = entry.select_prev_state;
11282            self.add_selections_state = entry.add_selections_state;
11283            self.request_autoscroll(Autoscroll::newest(), cx);
11284        }
11285        self.selection_history.mode = SelectionHistoryMode::Normal;
11286    }
11287
11288    pub fn expand_excerpts(
11289        &mut self,
11290        action: &ExpandExcerpts,
11291        _: &mut Window,
11292        cx: &mut Context<Self>,
11293    ) {
11294        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11295    }
11296
11297    pub fn expand_excerpts_down(
11298        &mut self,
11299        action: &ExpandExcerptsDown,
11300        _: &mut Window,
11301        cx: &mut Context<Self>,
11302    ) {
11303        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11304    }
11305
11306    pub fn expand_excerpts_up(
11307        &mut self,
11308        action: &ExpandExcerptsUp,
11309        _: &mut Window,
11310        cx: &mut Context<Self>,
11311    ) {
11312        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11313    }
11314
11315    pub fn expand_excerpts_for_direction(
11316        &mut self,
11317        lines: u32,
11318        direction: ExpandExcerptDirection,
11319
11320        cx: &mut Context<Self>,
11321    ) {
11322        let selections = self.selections.disjoint_anchors();
11323
11324        let lines = if lines == 0 {
11325            EditorSettings::get_global(cx).expand_excerpt_lines
11326        } else {
11327            lines
11328        };
11329
11330        self.buffer.update(cx, |buffer, cx| {
11331            let snapshot = buffer.snapshot(cx);
11332            let mut excerpt_ids = selections
11333                .iter()
11334                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11335                .collect::<Vec<_>>();
11336            excerpt_ids.sort();
11337            excerpt_ids.dedup();
11338            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11339        })
11340    }
11341
11342    pub fn expand_excerpt(
11343        &mut self,
11344        excerpt: ExcerptId,
11345        direction: ExpandExcerptDirection,
11346        cx: &mut Context<Self>,
11347    ) {
11348        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11349        self.buffer.update(cx, |buffer, cx| {
11350            buffer.expand_excerpts([excerpt], lines, direction, cx)
11351        })
11352    }
11353
11354    pub fn go_to_singleton_buffer_point(
11355        &mut self,
11356        point: Point,
11357        window: &mut Window,
11358        cx: &mut Context<Self>,
11359    ) {
11360        self.go_to_singleton_buffer_range(point..point, window, cx);
11361    }
11362
11363    pub fn go_to_singleton_buffer_range(
11364        &mut self,
11365        range: Range<Point>,
11366        window: &mut Window,
11367        cx: &mut Context<Self>,
11368    ) {
11369        let multibuffer = self.buffer().read(cx);
11370        let Some(buffer) = multibuffer.as_singleton() else {
11371            return;
11372        };
11373        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11374            return;
11375        };
11376        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11377            return;
11378        };
11379        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11380            s.select_anchor_ranges([start..end])
11381        });
11382    }
11383
11384    fn go_to_diagnostic(
11385        &mut self,
11386        _: &GoToDiagnostic,
11387        window: &mut Window,
11388        cx: &mut Context<Self>,
11389    ) {
11390        self.go_to_diagnostic_impl(Direction::Next, window, cx)
11391    }
11392
11393    fn go_to_prev_diagnostic(
11394        &mut self,
11395        _: &GoToPreviousDiagnostic,
11396        window: &mut Window,
11397        cx: &mut Context<Self>,
11398    ) {
11399        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11400    }
11401
11402    pub fn go_to_diagnostic_impl(
11403        &mut self,
11404        direction: Direction,
11405        window: &mut Window,
11406        cx: &mut Context<Self>,
11407    ) {
11408        let buffer = self.buffer.read(cx).snapshot(cx);
11409        let selection = self.selections.newest::<usize>(cx);
11410
11411        // If there is an active Diagnostic Popover jump to its diagnostic instead.
11412        if direction == Direction::Next {
11413            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11414                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11415                    return;
11416                };
11417                self.activate_diagnostics(
11418                    buffer_id,
11419                    popover.local_diagnostic.diagnostic.group_id,
11420                    window,
11421                    cx,
11422                );
11423                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11424                    let primary_range_start = active_diagnostics.primary_range.start;
11425                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11426                        let mut new_selection = s.newest_anchor().clone();
11427                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11428                        s.select_anchors(vec![new_selection.clone()]);
11429                    });
11430                    self.refresh_inline_completion(false, true, window, cx);
11431                }
11432                return;
11433            }
11434        }
11435
11436        let active_group_id = self
11437            .active_diagnostics
11438            .as_ref()
11439            .map(|active_group| active_group.group_id);
11440        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11441            active_diagnostics
11442                .primary_range
11443                .to_offset(&buffer)
11444                .to_inclusive()
11445        });
11446        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11447            if active_primary_range.contains(&selection.head()) {
11448                *active_primary_range.start()
11449            } else {
11450                selection.head()
11451            }
11452        } else {
11453            selection.head()
11454        };
11455
11456        let snapshot = self.snapshot(window, cx);
11457        let primary_diagnostics_before = buffer
11458            .diagnostics_in_range::<usize>(0..search_start)
11459            .filter(|entry| entry.diagnostic.is_primary)
11460            .filter(|entry| entry.range.start != entry.range.end)
11461            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11462            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11463            .collect::<Vec<_>>();
11464        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11465            primary_diagnostics_before
11466                .iter()
11467                .position(|entry| entry.diagnostic.group_id == active_group_id)
11468        });
11469
11470        let primary_diagnostics_after = buffer
11471            .diagnostics_in_range::<usize>(search_start..buffer.len())
11472            .filter(|entry| entry.diagnostic.is_primary)
11473            .filter(|entry| entry.range.start != entry.range.end)
11474            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11475            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11476            .collect::<Vec<_>>();
11477        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11478            primary_diagnostics_after
11479                .iter()
11480                .enumerate()
11481                .rev()
11482                .find_map(|(i, entry)| {
11483                    if entry.diagnostic.group_id == active_group_id {
11484                        Some(i)
11485                    } else {
11486                        None
11487                    }
11488                })
11489        });
11490
11491        let next_primary_diagnostic = match direction {
11492            Direction::Prev => primary_diagnostics_before
11493                .iter()
11494                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11495                .rev()
11496                .next(),
11497            Direction::Next => primary_diagnostics_after
11498                .iter()
11499                .skip(
11500                    last_same_group_diagnostic_after
11501                        .map(|index| index + 1)
11502                        .unwrap_or(0),
11503                )
11504                .next(),
11505        };
11506
11507        // Cycle around to the start of the buffer, potentially moving back to the start of
11508        // the currently active diagnostic.
11509        let cycle_around = || match direction {
11510            Direction::Prev => primary_diagnostics_after
11511                .iter()
11512                .rev()
11513                .chain(primary_diagnostics_before.iter().rev())
11514                .next(),
11515            Direction::Next => primary_diagnostics_before
11516                .iter()
11517                .chain(primary_diagnostics_after.iter())
11518                .next(),
11519        };
11520
11521        if let Some((primary_range, group_id)) = next_primary_diagnostic
11522            .or_else(cycle_around)
11523            .map(|entry| (&entry.range, entry.diagnostic.group_id))
11524        {
11525            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11526                return;
11527            };
11528            self.activate_diagnostics(buffer_id, group_id, window, cx);
11529            if self.active_diagnostics.is_some() {
11530                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11531                    s.select(vec![Selection {
11532                        id: selection.id,
11533                        start: primary_range.start,
11534                        end: primary_range.start,
11535                        reversed: false,
11536                        goal: SelectionGoal::None,
11537                    }]);
11538                });
11539                self.refresh_inline_completion(false, true, window, cx);
11540            }
11541        }
11542    }
11543
11544    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11545        let snapshot = self.snapshot(window, cx);
11546        let selection = self.selections.newest::<Point>(cx);
11547        self.go_to_hunk_after_or_before_position(
11548            &snapshot,
11549            selection.head(),
11550            Direction::Next,
11551            window,
11552            cx,
11553        );
11554    }
11555
11556    fn go_to_hunk_after_or_before_position(
11557        &mut self,
11558        snapshot: &EditorSnapshot,
11559        position: Point,
11560        direction: Direction,
11561        window: &mut Window,
11562        cx: &mut Context<Editor>,
11563    ) {
11564        let row = if direction == Direction::Next {
11565            self.hunk_after_position(snapshot, position)
11566                .map(|hunk| hunk.row_range.start)
11567        } else {
11568            self.hunk_before_position(snapshot, position)
11569        };
11570
11571        if let Some(row) = row {
11572            let destination = Point::new(row.0, 0);
11573            let autoscroll = Autoscroll::center();
11574
11575            self.unfold_ranges(&[destination..destination], false, false, cx);
11576            self.change_selections(Some(autoscroll), window, cx, |s| {
11577                s.select_ranges([destination..destination]);
11578            });
11579        }
11580    }
11581
11582    fn hunk_after_position(
11583        &mut self,
11584        snapshot: &EditorSnapshot,
11585        position: Point,
11586    ) -> Option<MultiBufferDiffHunk> {
11587        snapshot
11588            .buffer_snapshot
11589            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11590            .find(|hunk| hunk.row_range.start.0 > position.row)
11591            .or_else(|| {
11592                snapshot
11593                    .buffer_snapshot
11594                    .diff_hunks_in_range(Point::zero()..position)
11595                    .find(|hunk| hunk.row_range.end.0 < position.row)
11596            })
11597    }
11598
11599    fn go_to_prev_hunk(
11600        &mut self,
11601        _: &GoToPreviousHunk,
11602        window: &mut Window,
11603        cx: &mut Context<Self>,
11604    ) {
11605        let snapshot = self.snapshot(window, cx);
11606        let selection = self.selections.newest::<Point>(cx);
11607        self.go_to_hunk_after_or_before_position(
11608            &snapshot,
11609            selection.head(),
11610            Direction::Prev,
11611            window,
11612            cx,
11613        );
11614    }
11615
11616    fn hunk_before_position(
11617        &mut self,
11618        snapshot: &EditorSnapshot,
11619        position: Point,
11620    ) -> Option<MultiBufferRow> {
11621        snapshot
11622            .buffer_snapshot
11623            .diff_hunk_before(position)
11624            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11625    }
11626
11627    pub fn go_to_definition(
11628        &mut self,
11629        _: &GoToDefinition,
11630        window: &mut Window,
11631        cx: &mut Context<Self>,
11632    ) -> Task<Result<Navigated>> {
11633        let definition =
11634            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11635        cx.spawn_in(window, |editor, mut cx| async move {
11636            if definition.await? == Navigated::Yes {
11637                return Ok(Navigated::Yes);
11638            }
11639            match editor.update_in(&mut cx, |editor, window, cx| {
11640                editor.find_all_references(&FindAllReferences, window, cx)
11641            })? {
11642                Some(references) => references.await,
11643                None => Ok(Navigated::No),
11644            }
11645        })
11646    }
11647
11648    pub fn go_to_declaration(
11649        &mut self,
11650        _: &GoToDeclaration,
11651        window: &mut Window,
11652        cx: &mut Context<Self>,
11653    ) -> Task<Result<Navigated>> {
11654        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11655    }
11656
11657    pub fn go_to_declaration_split(
11658        &mut self,
11659        _: &GoToDeclaration,
11660        window: &mut Window,
11661        cx: &mut Context<Self>,
11662    ) -> Task<Result<Navigated>> {
11663        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11664    }
11665
11666    pub fn go_to_implementation(
11667        &mut self,
11668        _: &GoToImplementation,
11669        window: &mut Window,
11670        cx: &mut Context<Self>,
11671    ) -> Task<Result<Navigated>> {
11672        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11673    }
11674
11675    pub fn go_to_implementation_split(
11676        &mut self,
11677        _: &GoToImplementationSplit,
11678        window: &mut Window,
11679        cx: &mut Context<Self>,
11680    ) -> Task<Result<Navigated>> {
11681        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11682    }
11683
11684    pub fn go_to_type_definition(
11685        &mut self,
11686        _: &GoToTypeDefinition,
11687        window: &mut Window,
11688        cx: &mut Context<Self>,
11689    ) -> Task<Result<Navigated>> {
11690        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11691    }
11692
11693    pub fn go_to_definition_split(
11694        &mut self,
11695        _: &GoToDefinitionSplit,
11696        window: &mut Window,
11697        cx: &mut Context<Self>,
11698    ) -> Task<Result<Navigated>> {
11699        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11700    }
11701
11702    pub fn go_to_type_definition_split(
11703        &mut self,
11704        _: &GoToTypeDefinitionSplit,
11705        window: &mut Window,
11706        cx: &mut Context<Self>,
11707    ) -> Task<Result<Navigated>> {
11708        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11709    }
11710
11711    fn go_to_definition_of_kind(
11712        &mut self,
11713        kind: GotoDefinitionKind,
11714        split: bool,
11715        window: &mut Window,
11716        cx: &mut Context<Self>,
11717    ) -> Task<Result<Navigated>> {
11718        let Some(provider) = self.semantics_provider.clone() else {
11719            return Task::ready(Ok(Navigated::No));
11720        };
11721        let head = self.selections.newest::<usize>(cx).head();
11722        let buffer = self.buffer.read(cx);
11723        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11724            text_anchor
11725        } else {
11726            return Task::ready(Ok(Navigated::No));
11727        };
11728
11729        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11730            return Task::ready(Ok(Navigated::No));
11731        };
11732
11733        cx.spawn_in(window, |editor, mut cx| async move {
11734            let definitions = definitions.await?;
11735            let navigated = editor
11736                .update_in(&mut cx, |editor, window, cx| {
11737                    editor.navigate_to_hover_links(
11738                        Some(kind),
11739                        definitions
11740                            .into_iter()
11741                            .filter(|location| {
11742                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11743                            })
11744                            .map(HoverLink::Text)
11745                            .collect::<Vec<_>>(),
11746                        split,
11747                        window,
11748                        cx,
11749                    )
11750                })?
11751                .await?;
11752            anyhow::Ok(navigated)
11753        })
11754    }
11755
11756    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11757        let selection = self.selections.newest_anchor();
11758        let head = selection.head();
11759        let tail = selection.tail();
11760
11761        let Some((buffer, start_position)) =
11762            self.buffer.read(cx).text_anchor_for_position(head, cx)
11763        else {
11764            return;
11765        };
11766
11767        let end_position = if head != tail {
11768            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11769                return;
11770            };
11771            Some(pos)
11772        } else {
11773            None
11774        };
11775
11776        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11777            let url = if let Some(end_pos) = end_position {
11778                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11779            } else {
11780                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11781            };
11782
11783            if let Some(url) = url {
11784                editor.update(&mut cx, |_, cx| {
11785                    cx.open_url(&url);
11786                })
11787            } else {
11788                Ok(())
11789            }
11790        });
11791
11792        url_finder.detach();
11793    }
11794
11795    pub fn open_selected_filename(
11796        &mut self,
11797        _: &OpenSelectedFilename,
11798        window: &mut Window,
11799        cx: &mut Context<Self>,
11800    ) {
11801        let Some(workspace) = self.workspace() else {
11802            return;
11803        };
11804
11805        let position = self.selections.newest_anchor().head();
11806
11807        let Some((buffer, buffer_position)) =
11808            self.buffer.read(cx).text_anchor_for_position(position, cx)
11809        else {
11810            return;
11811        };
11812
11813        let project = self.project.clone();
11814
11815        cx.spawn_in(window, |_, mut cx| async move {
11816            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11817
11818            if let Some((_, path)) = result {
11819                workspace
11820                    .update_in(&mut cx, |workspace, window, cx| {
11821                        workspace.open_resolved_path(path, window, cx)
11822                    })?
11823                    .await?;
11824            }
11825            anyhow::Ok(())
11826        })
11827        .detach();
11828    }
11829
11830    pub(crate) fn navigate_to_hover_links(
11831        &mut self,
11832        kind: Option<GotoDefinitionKind>,
11833        mut definitions: Vec<HoverLink>,
11834        split: bool,
11835        window: &mut Window,
11836        cx: &mut Context<Editor>,
11837    ) -> Task<Result<Navigated>> {
11838        // If there is one definition, just open it directly
11839        if definitions.len() == 1 {
11840            let definition = definitions.pop().unwrap();
11841
11842            enum TargetTaskResult {
11843                Location(Option<Location>),
11844                AlreadyNavigated,
11845            }
11846
11847            let target_task = match definition {
11848                HoverLink::Text(link) => {
11849                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11850                }
11851                HoverLink::InlayHint(lsp_location, server_id) => {
11852                    let computation =
11853                        self.compute_target_location(lsp_location, server_id, window, cx);
11854                    cx.background_spawn(async move {
11855                        let location = computation.await?;
11856                        Ok(TargetTaskResult::Location(location))
11857                    })
11858                }
11859                HoverLink::Url(url) => {
11860                    cx.open_url(&url);
11861                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11862                }
11863                HoverLink::File(path) => {
11864                    if let Some(workspace) = self.workspace() {
11865                        cx.spawn_in(window, |_, mut cx| async move {
11866                            workspace
11867                                .update_in(&mut cx, |workspace, window, cx| {
11868                                    workspace.open_resolved_path(path, window, cx)
11869                                })?
11870                                .await
11871                                .map(|_| TargetTaskResult::AlreadyNavigated)
11872                        })
11873                    } else {
11874                        Task::ready(Ok(TargetTaskResult::Location(None)))
11875                    }
11876                }
11877            };
11878            cx.spawn_in(window, |editor, mut cx| async move {
11879                let target = match target_task.await.context("target resolution task")? {
11880                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11881                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11882                    TargetTaskResult::Location(Some(target)) => target,
11883                };
11884
11885                editor.update_in(&mut cx, |editor, window, cx| {
11886                    let Some(workspace) = editor.workspace() else {
11887                        return Navigated::No;
11888                    };
11889                    let pane = workspace.read(cx).active_pane().clone();
11890
11891                    let range = target.range.to_point(target.buffer.read(cx));
11892                    let range = editor.range_for_match(&range);
11893                    let range = collapse_multiline_range(range);
11894
11895                    if !split
11896                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11897                    {
11898                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11899                    } else {
11900                        window.defer(cx, move |window, cx| {
11901                            let target_editor: Entity<Self> =
11902                                workspace.update(cx, |workspace, cx| {
11903                                    let pane = if split {
11904                                        workspace.adjacent_pane(window, cx)
11905                                    } else {
11906                                        workspace.active_pane().clone()
11907                                    };
11908
11909                                    workspace.open_project_item(
11910                                        pane,
11911                                        target.buffer.clone(),
11912                                        true,
11913                                        true,
11914                                        window,
11915                                        cx,
11916                                    )
11917                                });
11918                            target_editor.update(cx, |target_editor, cx| {
11919                                // When selecting a definition in a different buffer, disable the nav history
11920                                // to avoid creating a history entry at the previous cursor location.
11921                                pane.update(cx, |pane, _| pane.disable_history());
11922                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11923                                pane.update(cx, |pane, _| pane.enable_history());
11924                            });
11925                        });
11926                    }
11927                    Navigated::Yes
11928                })
11929            })
11930        } else if !definitions.is_empty() {
11931            cx.spawn_in(window, |editor, mut cx| async move {
11932                let (title, location_tasks, workspace) = editor
11933                    .update_in(&mut cx, |editor, window, cx| {
11934                        let tab_kind = match kind {
11935                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11936                            _ => "Definitions",
11937                        };
11938                        let title = definitions
11939                            .iter()
11940                            .find_map(|definition| match definition {
11941                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11942                                    let buffer = origin.buffer.read(cx);
11943                                    format!(
11944                                        "{} for {}",
11945                                        tab_kind,
11946                                        buffer
11947                                            .text_for_range(origin.range.clone())
11948                                            .collect::<String>()
11949                                    )
11950                                }),
11951                                HoverLink::InlayHint(_, _) => None,
11952                                HoverLink::Url(_) => None,
11953                                HoverLink::File(_) => None,
11954                            })
11955                            .unwrap_or(tab_kind.to_string());
11956                        let location_tasks = definitions
11957                            .into_iter()
11958                            .map(|definition| match definition {
11959                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11960                                HoverLink::InlayHint(lsp_location, server_id) => editor
11961                                    .compute_target_location(lsp_location, server_id, window, cx),
11962                                HoverLink::Url(_) => Task::ready(Ok(None)),
11963                                HoverLink::File(_) => Task::ready(Ok(None)),
11964                            })
11965                            .collect::<Vec<_>>();
11966                        (title, location_tasks, editor.workspace().clone())
11967                    })
11968                    .context("location tasks preparation")?;
11969
11970                let locations = future::join_all(location_tasks)
11971                    .await
11972                    .into_iter()
11973                    .filter_map(|location| location.transpose())
11974                    .collect::<Result<_>>()
11975                    .context("location tasks")?;
11976
11977                let Some(workspace) = workspace else {
11978                    return Ok(Navigated::No);
11979                };
11980                let opened = workspace
11981                    .update_in(&mut cx, |workspace, window, cx| {
11982                        Self::open_locations_in_multibuffer(
11983                            workspace,
11984                            locations,
11985                            title,
11986                            split,
11987                            MultibufferSelectionMode::First,
11988                            window,
11989                            cx,
11990                        )
11991                    })
11992                    .ok();
11993
11994                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11995            })
11996        } else {
11997            Task::ready(Ok(Navigated::No))
11998        }
11999    }
12000
12001    fn compute_target_location(
12002        &self,
12003        lsp_location: lsp::Location,
12004        server_id: LanguageServerId,
12005        window: &mut Window,
12006        cx: &mut Context<Self>,
12007    ) -> Task<anyhow::Result<Option<Location>>> {
12008        let Some(project) = self.project.clone() else {
12009            return Task::ready(Ok(None));
12010        };
12011
12012        cx.spawn_in(window, move |editor, mut cx| async move {
12013            let location_task = editor.update(&mut cx, |_, cx| {
12014                project.update(cx, |project, cx| {
12015                    let language_server_name = project
12016                        .language_server_statuses(cx)
12017                        .find(|(id, _)| server_id == *id)
12018                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
12019                    language_server_name.map(|language_server_name| {
12020                        project.open_local_buffer_via_lsp(
12021                            lsp_location.uri.clone(),
12022                            server_id,
12023                            language_server_name,
12024                            cx,
12025                        )
12026                    })
12027                })
12028            })?;
12029            let location = match location_task {
12030                Some(task) => Some({
12031                    let target_buffer_handle = task.await.context("open local buffer")?;
12032                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
12033                        let target_start = target_buffer
12034                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
12035                        let target_end = target_buffer
12036                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
12037                        target_buffer.anchor_after(target_start)
12038                            ..target_buffer.anchor_before(target_end)
12039                    })?;
12040                    Location {
12041                        buffer: target_buffer_handle,
12042                        range,
12043                    }
12044                }),
12045                None => None,
12046            };
12047            Ok(location)
12048        })
12049    }
12050
12051    pub fn find_all_references(
12052        &mut self,
12053        _: &FindAllReferences,
12054        window: &mut Window,
12055        cx: &mut Context<Self>,
12056    ) -> Option<Task<Result<Navigated>>> {
12057        let selection = self.selections.newest::<usize>(cx);
12058        let multi_buffer = self.buffer.read(cx);
12059        let head = selection.head();
12060
12061        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12062        let head_anchor = multi_buffer_snapshot.anchor_at(
12063            head,
12064            if head < selection.tail() {
12065                Bias::Right
12066            } else {
12067                Bias::Left
12068            },
12069        );
12070
12071        match self
12072            .find_all_references_task_sources
12073            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12074        {
12075            Ok(_) => {
12076                log::info!(
12077                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
12078                );
12079                return None;
12080            }
12081            Err(i) => {
12082                self.find_all_references_task_sources.insert(i, head_anchor);
12083            }
12084        }
12085
12086        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12087        let workspace = self.workspace()?;
12088        let project = workspace.read(cx).project().clone();
12089        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12090        Some(cx.spawn_in(window, |editor, mut cx| async move {
12091            let _cleanup = defer({
12092                let mut cx = cx.clone();
12093                move || {
12094                    let _ = editor.update(&mut cx, |editor, _| {
12095                        if let Ok(i) =
12096                            editor
12097                                .find_all_references_task_sources
12098                                .binary_search_by(|anchor| {
12099                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
12100                                })
12101                        {
12102                            editor.find_all_references_task_sources.remove(i);
12103                        }
12104                    });
12105                }
12106            });
12107
12108            let locations = references.await?;
12109            if locations.is_empty() {
12110                return anyhow::Ok(Navigated::No);
12111            }
12112
12113            workspace.update_in(&mut cx, |workspace, window, cx| {
12114                let title = locations
12115                    .first()
12116                    .as_ref()
12117                    .map(|location| {
12118                        let buffer = location.buffer.read(cx);
12119                        format!(
12120                            "References to `{}`",
12121                            buffer
12122                                .text_for_range(location.range.clone())
12123                                .collect::<String>()
12124                        )
12125                    })
12126                    .unwrap();
12127                Self::open_locations_in_multibuffer(
12128                    workspace,
12129                    locations,
12130                    title,
12131                    false,
12132                    MultibufferSelectionMode::First,
12133                    window,
12134                    cx,
12135                );
12136                Navigated::Yes
12137            })
12138        }))
12139    }
12140
12141    /// Opens a multibuffer with the given project locations in it
12142    pub fn open_locations_in_multibuffer(
12143        workspace: &mut Workspace,
12144        mut locations: Vec<Location>,
12145        title: String,
12146        split: bool,
12147        multibuffer_selection_mode: MultibufferSelectionMode,
12148        window: &mut Window,
12149        cx: &mut Context<Workspace>,
12150    ) {
12151        // If there are multiple definitions, open them in a multibuffer
12152        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12153        let mut locations = locations.into_iter().peekable();
12154        let mut ranges = Vec::new();
12155        let capability = workspace.project().read(cx).capability();
12156
12157        let excerpt_buffer = cx.new(|cx| {
12158            let mut multibuffer = MultiBuffer::new(capability);
12159            while let Some(location) = locations.next() {
12160                let buffer = location.buffer.read(cx);
12161                let mut ranges_for_buffer = Vec::new();
12162                let range = location.range.to_offset(buffer);
12163                ranges_for_buffer.push(range.clone());
12164
12165                while let Some(next_location) = locations.peek() {
12166                    if next_location.buffer == location.buffer {
12167                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
12168                        locations.next();
12169                    } else {
12170                        break;
12171                    }
12172                }
12173
12174                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12175                ranges.extend(multibuffer.push_excerpts_with_context_lines(
12176                    location.buffer.clone(),
12177                    ranges_for_buffer,
12178                    DEFAULT_MULTIBUFFER_CONTEXT,
12179                    cx,
12180                ))
12181            }
12182
12183            multibuffer.with_title(title)
12184        });
12185
12186        let editor = cx.new(|cx| {
12187            Editor::for_multibuffer(
12188                excerpt_buffer,
12189                Some(workspace.project().clone()),
12190                true,
12191                window,
12192                cx,
12193            )
12194        });
12195        editor.update(cx, |editor, cx| {
12196            match multibuffer_selection_mode {
12197                MultibufferSelectionMode::First => {
12198                    if let Some(first_range) = ranges.first() {
12199                        editor.change_selections(None, window, cx, |selections| {
12200                            selections.clear_disjoint();
12201                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12202                        });
12203                    }
12204                    editor.highlight_background::<Self>(
12205                        &ranges,
12206                        |theme| theme.editor_highlighted_line_background,
12207                        cx,
12208                    );
12209                }
12210                MultibufferSelectionMode::All => {
12211                    editor.change_selections(None, window, cx, |selections| {
12212                        selections.clear_disjoint();
12213                        selections.select_anchor_ranges(ranges);
12214                    });
12215                }
12216            }
12217            editor.register_buffers_with_language_servers(cx);
12218        });
12219
12220        let item = Box::new(editor);
12221        let item_id = item.item_id();
12222
12223        if split {
12224            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12225        } else {
12226            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12227                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12228                    pane.close_current_preview_item(window, cx)
12229                } else {
12230                    None
12231                }
12232            });
12233            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12234        }
12235        workspace.active_pane().update(cx, |pane, cx| {
12236            pane.set_preview_item_id(Some(item_id), cx);
12237        });
12238    }
12239
12240    pub fn rename(
12241        &mut self,
12242        _: &Rename,
12243        window: &mut Window,
12244        cx: &mut Context<Self>,
12245    ) -> Option<Task<Result<()>>> {
12246        use language::ToOffset as _;
12247
12248        let provider = self.semantics_provider.clone()?;
12249        let selection = self.selections.newest_anchor().clone();
12250        let (cursor_buffer, cursor_buffer_position) = self
12251            .buffer
12252            .read(cx)
12253            .text_anchor_for_position(selection.head(), cx)?;
12254        let (tail_buffer, cursor_buffer_position_end) = self
12255            .buffer
12256            .read(cx)
12257            .text_anchor_for_position(selection.tail(), cx)?;
12258        if tail_buffer != cursor_buffer {
12259            return None;
12260        }
12261
12262        let snapshot = cursor_buffer.read(cx).snapshot();
12263        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12264        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12265        let prepare_rename = provider
12266            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12267            .unwrap_or_else(|| Task::ready(Ok(None)));
12268        drop(snapshot);
12269
12270        Some(cx.spawn_in(window, |this, mut cx| async move {
12271            let rename_range = if let Some(range) = prepare_rename.await? {
12272                Some(range)
12273            } else {
12274                this.update(&mut cx, |this, cx| {
12275                    let buffer = this.buffer.read(cx).snapshot(cx);
12276                    let mut buffer_highlights = this
12277                        .document_highlights_for_position(selection.head(), &buffer)
12278                        .filter(|highlight| {
12279                            highlight.start.excerpt_id == selection.head().excerpt_id
12280                                && highlight.end.excerpt_id == selection.head().excerpt_id
12281                        });
12282                    buffer_highlights
12283                        .next()
12284                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12285                })?
12286            };
12287            if let Some(rename_range) = rename_range {
12288                this.update_in(&mut cx, |this, window, cx| {
12289                    let snapshot = cursor_buffer.read(cx).snapshot();
12290                    let rename_buffer_range = rename_range.to_offset(&snapshot);
12291                    let cursor_offset_in_rename_range =
12292                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12293                    let cursor_offset_in_rename_range_end =
12294                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12295
12296                    this.take_rename(false, window, cx);
12297                    let buffer = this.buffer.read(cx).read(cx);
12298                    let cursor_offset = selection.head().to_offset(&buffer);
12299                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12300                    let rename_end = rename_start + rename_buffer_range.len();
12301                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12302                    let mut old_highlight_id = None;
12303                    let old_name: Arc<str> = buffer
12304                        .chunks(rename_start..rename_end, true)
12305                        .map(|chunk| {
12306                            if old_highlight_id.is_none() {
12307                                old_highlight_id = chunk.syntax_highlight_id;
12308                            }
12309                            chunk.text
12310                        })
12311                        .collect::<String>()
12312                        .into();
12313
12314                    drop(buffer);
12315
12316                    // Position the selection in the rename editor so that it matches the current selection.
12317                    this.show_local_selections = false;
12318                    let rename_editor = cx.new(|cx| {
12319                        let mut editor = Editor::single_line(window, cx);
12320                        editor.buffer.update(cx, |buffer, cx| {
12321                            buffer.edit([(0..0, old_name.clone())], None, cx)
12322                        });
12323                        let rename_selection_range = match cursor_offset_in_rename_range
12324                            .cmp(&cursor_offset_in_rename_range_end)
12325                        {
12326                            Ordering::Equal => {
12327                                editor.select_all(&SelectAll, window, cx);
12328                                return editor;
12329                            }
12330                            Ordering::Less => {
12331                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12332                            }
12333                            Ordering::Greater => {
12334                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12335                            }
12336                        };
12337                        if rename_selection_range.end > old_name.len() {
12338                            editor.select_all(&SelectAll, window, cx);
12339                        } else {
12340                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12341                                s.select_ranges([rename_selection_range]);
12342                            });
12343                        }
12344                        editor
12345                    });
12346                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12347                        if e == &EditorEvent::Focused {
12348                            cx.emit(EditorEvent::FocusedIn)
12349                        }
12350                    })
12351                    .detach();
12352
12353                    let write_highlights =
12354                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12355                    let read_highlights =
12356                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
12357                    let ranges = write_highlights
12358                        .iter()
12359                        .flat_map(|(_, ranges)| ranges.iter())
12360                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12361                        .cloned()
12362                        .collect();
12363
12364                    this.highlight_text::<Rename>(
12365                        ranges,
12366                        HighlightStyle {
12367                            fade_out: Some(0.6),
12368                            ..Default::default()
12369                        },
12370                        cx,
12371                    );
12372                    let rename_focus_handle = rename_editor.focus_handle(cx);
12373                    window.focus(&rename_focus_handle);
12374                    let block_id = this.insert_blocks(
12375                        [BlockProperties {
12376                            style: BlockStyle::Flex,
12377                            placement: BlockPlacement::Below(range.start),
12378                            height: 1,
12379                            render: Arc::new({
12380                                let rename_editor = rename_editor.clone();
12381                                move |cx: &mut BlockContext| {
12382                                    let mut text_style = cx.editor_style.text.clone();
12383                                    if let Some(highlight_style) = old_highlight_id
12384                                        .and_then(|h| h.style(&cx.editor_style.syntax))
12385                                    {
12386                                        text_style = text_style.highlight(highlight_style);
12387                                    }
12388                                    div()
12389                                        .block_mouse_down()
12390                                        .pl(cx.anchor_x)
12391                                        .child(EditorElement::new(
12392                                            &rename_editor,
12393                                            EditorStyle {
12394                                                background: cx.theme().system().transparent,
12395                                                local_player: cx.editor_style.local_player,
12396                                                text: text_style,
12397                                                scrollbar_width: cx.editor_style.scrollbar_width,
12398                                                syntax: cx.editor_style.syntax.clone(),
12399                                                status: cx.editor_style.status.clone(),
12400                                                inlay_hints_style: HighlightStyle {
12401                                                    font_weight: Some(FontWeight::BOLD),
12402                                                    ..make_inlay_hints_style(cx.app)
12403                                                },
12404                                                inline_completion_styles: make_suggestion_styles(
12405                                                    cx.app,
12406                                                ),
12407                                                ..EditorStyle::default()
12408                                            },
12409                                        ))
12410                                        .into_any_element()
12411                                }
12412                            }),
12413                            priority: 0,
12414                        }],
12415                        Some(Autoscroll::fit()),
12416                        cx,
12417                    )[0];
12418                    this.pending_rename = Some(RenameState {
12419                        range,
12420                        old_name,
12421                        editor: rename_editor,
12422                        block_id,
12423                    });
12424                })?;
12425            }
12426
12427            Ok(())
12428        }))
12429    }
12430
12431    pub fn confirm_rename(
12432        &mut self,
12433        _: &ConfirmRename,
12434        window: &mut Window,
12435        cx: &mut Context<Self>,
12436    ) -> Option<Task<Result<()>>> {
12437        let rename = self.take_rename(false, window, cx)?;
12438        let workspace = self.workspace()?.downgrade();
12439        let (buffer, start) = self
12440            .buffer
12441            .read(cx)
12442            .text_anchor_for_position(rename.range.start, cx)?;
12443        let (end_buffer, _) = self
12444            .buffer
12445            .read(cx)
12446            .text_anchor_for_position(rename.range.end, cx)?;
12447        if buffer != end_buffer {
12448            return None;
12449        }
12450
12451        let old_name = rename.old_name;
12452        let new_name = rename.editor.read(cx).text(cx);
12453
12454        let rename = self.semantics_provider.as_ref()?.perform_rename(
12455            &buffer,
12456            start,
12457            new_name.clone(),
12458            cx,
12459        )?;
12460
12461        Some(cx.spawn_in(window, |editor, mut cx| async move {
12462            let project_transaction = rename.await?;
12463            Self::open_project_transaction(
12464                &editor,
12465                workspace,
12466                project_transaction,
12467                format!("Rename: {}{}", old_name, new_name),
12468                cx.clone(),
12469            )
12470            .await?;
12471
12472            editor.update(&mut cx, |editor, cx| {
12473                editor.refresh_document_highlights(cx);
12474            })?;
12475            Ok(())
12476        }))
12477    }
12478
12479    fn take_rename(
12480        &mut self,
12481        moving_cursor: bool,
12482        window: &mut Window,
12483        cx: &mut Context<Self>,
12484    ) -> Option<RenameState> {
12485        let rename = self.pending_rename.take()?;
12486        if rename.editor.focus_handle(cx).is_focused(window) {
12487            window.focus(&self.focus_handle);
12488        }
12489
12490        self.remove_blocks(
12491            [rename.block_id].into_iter().collect(),
12492            Some(Autoscroll::fit()),
12493            cx,
12494        );
12495        self.clear_highlights::<Rename>(cx);
12496        self.show_local_selections = true;
12497
12498        if moving_cursor {
12499            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12500                editor.selections.newest::<usize>(cx).head()
12501            });
12502
12503            // Update the selection to match the position of the selection inside
12504            // the rename editor.
12505            let snapshot = self.buffer.read(cx).read(cx);
12506            let rename_range = rename.range.to_offset(&snapshot);
12507            let cursor_in_editor = snapshot
12508                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12509                .min(rename_range.end);
12510            drop(snapshot);
12511
12512            self.change_selections(None, window, cx, |s| {
12513                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12514            });
12515        } else {
12516            self.refresh_document_highlights(cx);
12517        }
12518
12519        Some(rename)
12520    }
12521
12522    pub fn pending_rename(&self) -> Option<&RenameState> {
12523        self.pending_rename.as_ref()
12524    }
12525
12526    fn format(
12527        &mut self,
12528        _: &Format,
12529        window: &mut Window,
12530        cx: &mut Context<Self>,
12531    ) -> Option<Task<Result<()>>> {
12532        let project = match &self.project {
12533            Some(project) => project.clone(),
12534            None => return None,
12535        };
12536
12537        Some(self.perform_format(
12538            project,
12539            FormatTrigger::Manual,
12540            FormatTarget::Buffers,
12541            window,
12542            cx,
12543        ))
12544    }
12545
12546    fn format_selections(
12547        &mut self,
12548        _: &FormatSelections,
12549        window: &mut Window,
12550        cx: &mut Context<Self>,
12551    ) -> Option<Task<Result<()>>> {
12552        let project = match &self.project {
12553            Some(project) => project.clone(),
12554            None => return None,
12555        };
12556
12557        let ranges = self
12558            .selections
12559            .all_adjusted(cx)
12560            .into_iter()
12561            .map(|selection| selection.range())
12562            .collect_vec();
12563
12564        Some(self.perform_format(
12565            project,
12566            FormatTrigger::Manual,
12567            FormatTarget::Ranges(ranges),
12568            window,
12569            cx,
12570        ))
12571    }
12572
12573    fn perform_format(
12574        &mut self,
12575        project: Entity<Project>,
12576        trigger: FormatTrigger,
12577        target: FormatTarget,
12578        window: &mut Window,
12579        cx: &mut Context<Self>,
12580    ) -> Task<Result<()>> {
12581        let buffer = self.buffer.clone();
12582        let (buffers, target) = match target {
12583            FormatTarget::Buffers => {
12584                let mut buffers = buffer.read(cx).all_buffers();
12585                if trigger == FormatTrigger::Save {
12586                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
12587                }
12588                (buffers, LspFormatTarget::Buffers)
12589            }
12590            FormatTarget::Ranges(selection_ranges) => {
12591                let multi_buffer = buffer.read(cx);
12592                let snapshot = multi_buffer.read(cx);
12593                let mut buffers = HashSet::default();
12594                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12595                    BTreeMap::new();
12596                for selection_range in selection_ranges {
12597                    for (buffer, buffer_range, _) in
12598                        snapshot.range_to_buffer_ranges(selection_range)
12599                    {
12600                        let buffer_id = buffer.remote_id();
12601                        let start = buffer.anchor_before(buffer_range.start);
12602                        let end = buffer.anchor_after(buffer_range.end);
12603                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12604                        buffer_id_to_ranges
12605                            .entry(buffer_id)
12606                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12607                            .or_insert_with(|| vec![start..end]);
12608                    }
12609                }
12610                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12611            }
12612        };
12613
12614        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12615        let format = project.update(cx, |project, cx| {
12616            project.format(buffers, target, true, trigger, cx)
12617        });
12618
12619        cx.spawn_in(window, |_, mut cx| async move {
12620            let transaction = futures::select_biased! {
12621                () = timeout => {
12622                    log::warn!("timed out waiting for formatting");
12623                    None
12624                }
12625                transaction = format.log_err().fuse() => transaction,
12626            };
12627
12628            buffer
12629                .update(&mut cx, |buffer, cx| {
12630                    if let Some(transaction) = transaction {
12631                        if !buffer.is_singleton() {
12632                            buffer.push_transaction(&transaction.0, cx);
12633                        }
12634                    }
12635                    cx.notify();
12636                })
12637                .ok();
12638
12639            Ok(())
12640        })
12641    }
12642
12643    fn organize_imports(
12644        &mut self,
12645        _: &OrganizeImports,
12646        window: &mut Window,
12647        cx: &mut Context<Self>,
12648    ) -> Option<Task<Result<()>>> {
12649        let project = match &self.project {
12650            Some(project) => project.clone(),
12651            None => return None,
12652        };
12653        Some(self.perform_code_action_kind(
12654            project,
12655            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12656            window,
12657            cx,
12658        ))
12659    }
12660
12661    fn perform_code_action_kind(
12662        &mut self,
12663        project: Entity<Project>,
12664        kind: CodeActionKind,
12665        window: &mut Window,
12666        cx: &mut Context<Self>,
12667    ) -> Task<Result<()>> {
12668        let buffer = self.buffer.clone();
12669        let buffers = buffer.read(cx).all_buffers();
12670        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12671        let apply_action = project.update(cx, |project, cx| {
12672            project.apply_code_action_kind(buffers, kind, true, cx)
12673        });
12674        cx.spawn_in(window, |_, mut cx| async move {
12675            let transaction = futures::select_biased! {
12676                () = timeout => {
12677                    log::warn!("timed out waiting for executing code action");
12678                    None
12679                }
12680                transaction = apply_action.log_err().fuse() => transaction,
12681            };
12682            buffer
12683                .update(&mut cx, |buffer, cx| {
12684                    // check if we need this
12685                    if let Some(transaction) = transaction {
12686                        if !buffer.is_singleton() {
12687                            buffer.push_transaction(&transaction.0, cx);
12688                        }
12689                    }
12690                    cx.notify();
12691                })
12692                .ok();
12693            Ok(())
12694        })
12695    }
12696
12697    fn restart_language_server(
12698        &mut self,
12699        _: &RestartLanguageServer,
12700        _: &mut Window,
12701        cx: &mut Context<Self>,
12702    ) {
12703        if let Some(project) = self.project.clone() {
12704            self.buffer.update(cx, |multi_buffer, cx| {
12705                project.update(cx, |project, cx| {
12706                    project.restart_language_servers_for_buffers(
12707                        multi_buffer.all_buffers().into_iter().collect(),
12708                        cx,
12709                    );
12710                });
12711            })
12712        }
12713    }
12714
12715    fn cancel_language_server_work(
12716        workspace: &mut Workspace,
12717        _: &actions::CancelLanguageServerWork,
12718        _: &mut Window,
12719        cx: &mut Context<Workspace>,
12720    ) {
12721        let project = workspace.project();
12722        let buffers = workspace
12723            .active_item(cx)
12724            .and_then(|item| item.act_as::<Editor>(cx))
12725            .map_or(HashSet::default(), |editor| {
12726                editor.read(cx).buffer.read(cx).all_buffers()
12727            });
12728        project.update(cx, |project, cx| {
12729            project.cancel_language_server_work_for_buffers(buffers, cx);
12730        });
12731    }
12732
12733    fn show_character_palette(
12734        &mut self,
12735        _: &ShowCharacterPalette,
12736        window: &mut Window,
12737        _: &mut Context<Self>,
12738    ) {
12739        window.show_character_palette();
12740    }
12741
12742    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12743        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12744            let buffer = self.buffer.read(cx).snapshot(cx);
12745            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12746            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12747            let is_valid = buffer
12748                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12749                .any(|entry| {
12750                    entry.diagnostic.is_primary
12751                        && !entry.range.is_empty()
12752                        && entry.range.start == primary_range_start
12753                        && entry.diagnostic.message == active_diagnostics.primary_message
12754                });
12755
12756            if is_valid != active_diagnostics.is_valid {
12757                active_diagnostics.is_valid = is_valid;
12758                if is_valid {
12759                    let mut new_styles = HashMap::default();
12760                    for (block_id, diagnostic) in &active_diagnostics.blocks {
12761                        new_styles.insert(
12762                            *block_id,
12763                            diagnostic_block_renderer(diagnostic.clone(), None, true),
12764                        );
12765                    }
12766                    self.display_map.update(cx, |display_map, _cx| {
12767                        display_map.replace_blocks(new_styles);
12768                    });
12769                } else {
12770                    self.dismiss_diagnostics(cx);
12771                }
12772            }
12773        }
12774    }
12775
12776    fn activate_diagnostics(
12777        &mut self,
12778        buffer_id: BufferId,
12779        group_id: usize,
12780        window: &mut Window,
12781        cx: &mut Context<Self>,
12782    ) {
12783        self.dismiss_diagnostics(cx);
12784        let snapshot = self.snapshot(window, cx);
12785        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12786            let buffer = self.buffer.read(cx).snapshot(cx);
12787
12788            let mut primary_range = None;
12789            let mut primary_message = None;
12790            let diagnostic_group = buffer
12791                .diagnostic_group(buffer_id, group_id)
12792                .filter_map(|entry| {
12793                    let start = entry.range.start;
12794                    let end = entry.range.end;
12795                    if snapshot.is_line_folded(MultiBufferRow(start.row))
12796                        && (start.row == end.row
12797                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
12798                    {
12799                        return None;
12800                    }
12801                    if entry.diagnostic.is_primary {
12802                        primary_range = Some(entry.range.clone());
12803                        primary_message = Some(entry.diagnostic.message.clone());
12804                    }
12805                    Some(entry)
12806                })
12807                .collect::<Vec<_>>();
12808            let primary_range = primary_range?;
12809            let primary_message = primary_message?;
12810
12811            let blocks = display_map
12812                .insert_blocks(
12813                    diagnostic_group.iter().map(|entry| {
12814                        let diagnostic = entry.diagnostic.clone();
12815                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12816                        BlockProperties {
12817                            style: BlockStyle::Fixed,
12818                            placement: BlockPlacement::Below(
12819                                buffer.anchor_after(entry.range.start),
12820                            ),
12821                            height: message_height,
12822                            render: diagnostic_block_renderer(diagnostic, None, true),
12823                            priority: 0,
12824                        }
12825                    }),
12826                    cx,
12827                )
12828                .into_iter()
12829                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12830                .collect();
12831
12832            Some(ActiveDiagnosticGroup {
12833                primary_range: buffer.anchor_before(primary_range.start)
12834                    ..buffer.anchor_after(primary_range.end),
12835                primary_message,
12836                group_id,
12837                blocks,
12838                is_valid: true,
12839            })
12840        });
12841    }
12842
12843    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12844        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12845            self.display_map.update(cx, |display_map, cx| {
12846                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12847            });
12848            cx.notify();
12849        }
12850    }
12851
12852    /// Disable inline diagnostics rendering for this editor.
12853    pub fn disable_inline_diagnostics(&mut self) {
12854        self.inline_diagnostics_enabled = false;
12855        self.inline_diagnostics_update = Task::ready(());
12856        self.inline_diagnostics.clear();
12857    }
12858
12859    pub fn inline_diagnostics_enabled(&self) -> bool {
12860        self.inline_diagnostics_enabled
12861    }
12862
12863    pub fn show_inline_diagnostics(&self) -> bool {
12864        self.show_inline_diagnostics
12865    }
12866
12867    pub fn toggle_inline_diagnostics(
12868        &mut self,
12869        _: &ToggleInlineDiagnostics,
12870        window: &mut Window,
12871        cx: &mut Context<'_, Editor>,
12872    ) {
12873        self.show_inline_diagnostics = !self.show_inline_diagnostics;
12874        self.refresh_inline_diagnostics(false, window, cx);
12875    }
12876
12877    fn refresh_inline_diagnostics(
12878        &mut self,
12879        debounce: bool,
12880        window: &mut Window,
12881        cx: &mut Context<Self>,
12882    ) {
12883        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12884            self.inline_diagnostics_update = Task::ready(());
12885            self.inline_diagnostics.clear();
12886            return;
12887        }
12888
12889        let debounce_ms = ProjectSettings::get_global(cx)
12890            .diagnostics
12891            .inline
12892            .update_debounce_ms;
12893        let debounce = if debounce && debounce_ms > 0 {
12894            Some(Duration::from_millis(debounce_ms))
12895        } else {
12896            None
12897        };
12898        self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12899            if let Some(debounce) = debounce {
12900                cx.background_executor().timer(debounce).await;
12901            }
12902            let Some(snapshot) = editor
12903                .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12904                .ok()
12905            else {
12906                return;
12907            };
12908
12909            let new_inline_diagnostics = cx
12910                .background_spawn(async move {
12911                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12912                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12913                        let message = diagnostic_entry
12914                            .diagnostic
12915                            .message
12916                            .split_once('\n')
12917                            .map(|(line, _)| line)
12918                            .map(SharedString::new)
12919                            .unwrap_or_else(|| {
12920                                SharedString::from(diagnostic_entry.diagnostic.message)
12921                            });
12922                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12923                        let (Ok(i) | Err(i)) = inline_diagnostics
12924                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12925                        inline_diagnostics.insert(
12926                            i,
12927                            (
12928                                start_anchor,
12929                                InlineDiagnostic {
12930                                    message,
12931                                    group_id: diagnostic_entry.diagnostic.group_id,
12932                                    start: diagnostic_entry.range.start.to_point(&snapshot),
12933                                    is_primary: diagnostic_entry.diagnostic.is_primary,
12934                                    severity: diagnostic_entry.diagnostic.severity,
12935                                },
12936                            ),
12937                        );
12938                    }
12939                    inline_diagnostics
12940                })
12941                .await;
12942
12943            editor
12944                .update(&mut cx, |editor, cx| {
12945                    editor.inline_diagnostics = new_inline_diagnostics;
12946                    cx.notify();
12947                })
12948                .ok();
12949        });
12950    }
12951
12952    pub fn set_selections_from_remote(
12953        &mut self,
12954        selections: Vec<Selection<Anchor>>,
12955        pending_selection: Option<Selection<Anchor>>,
12956        window: &mut Window,
12957        cx: &mut Context<Self>,
12958    ) {
12959        let old_cursor_position = self.selections.newest_anchor().head();
12960        self.selections.change_with(cx, |s| {
12961            s.select_anchors(selections);
12962            if let Some(pending_selection) = pending_selection {
12963                s.set_pending(pending_selection, SelectMode::Character);
12964            } else {
12965                s.clear_pending();
12966            }
12967        });
12968        self.selections_did_change(false, &old_cursor_position, true, window, cx);
12969    }
12970
12971    fn push_to_selection_history(&mut self) {
12972        self.selection_history.push(SelectionHistoryEntry {
12973            selections: self.selections.disjoint_anchors(),
12974            select_next_state: self.select_next_state.clone(),
12975            select_prev_state: self.select_prev_state.clone(),
12976            add_selections_state: self.add_selections_state.clone(),
12977        });
12978    }
12979
12980    pub fn transact(
12981        &mut self,
12982        window: &mut Window,
12983        cx: &mut Context<Self>,
12984        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12985    ) -> Option<TransactionId> {
12986        self.start_transaction_at(Instant::now(), window, cx);
12987        update(self, window, cx);
12988        self.end_transaction_at(Instant::now(), cx)
12989    }
12990
12991    pub fn start_transaction_at(
12992        &mut self,
12993        now: Instant,
12994        window: &mut Window,
12995        cx: &mut Context<Self>,
12996    ) {
12997        self.end_selection(window, cx);
12998        if let Some(tx_id) = self
12999            .buffer
13000            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
13001        {
13002            self.selection_history
13003                .insert_transaction(tx_id, self.selections.disjoint_anchors());
13004            cx.emit(EditorEvent::TransactionBegun {
13005                transaction_id: tx_id,
13006            })
13007        }
13008    }
13009
13010    pub fn end_transaction_at(
13011        &mut self,
13012        now: Instant,
13013        cx: &mut Context<Self>,
13014    ) -> Option<TransactionId> {
13015        if let Some(transaction_id) = self
13016            .buffer
13017            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
13018        {
13019            if let Some((_, end_selections)) =
13020                self.selection_history.transaction_mut(transaction_id)
13021            {
13022                *end_selections = Some(self.selections.disjoint_anchors());
13023            } else {
13024                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
13025            }
13026
13027            cx.emit(EditorEvent::Edited { transaction_id });
13028            Some(transaction_id)
13029        } else {
13030            None
13031        }
13032    }
13033
13034    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
13035        if self.selection_mark_mode {
13036            self.change_selections(None, window, cx, |s| {
13037                s.move_with(|_, sel| {
13038                    sel.collapse_to(sel.head(), SelectionGoal::None);
13039                });
13040            })
13041        }
13042        self.selection_mark_mode = true;
13043        cx.notify();
13044    }
13045
13046    pub fn swap_selection_ends(
13047        &mut self,
13048        _: &actions::SwapSelectionEnds,
13049        window: &mut Window,
13050        cx: &mut Context<Self>,
13051    ) {
13052        self.change_selections(None, window, cx, |s| {
13053            s.move_with(|_, sel| {
13054                if sel.start != sel.end {
13055                    sel.reversed = !sel.reversed
13056                }
13057            });
13058        });
13059        self.request_autoscroll(Autoscroll::newest(), cx);
13060        cx.notify();
13061    }
13062
13063    pub fn toggle_fold(
13064        &mut self,
13065        _: &actions::ToggleFold,
13066        window: &mut Window,
13067        cx: &mut Context<Self>,
13068    ) {
13069        if self.is_singleton(cx) {
13070            let selection = self.selections.newest::<Point>(cx);
13071
13072            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13073            let range = if selection.is_empty() {
13074                let point = selection.head().to_display_point(&display_map);
13075                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13076                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13077                    .to_point(&display_map);
13078                start..end
13079            } else {
13080                selection.range()
13081            };
13082            if display_map.folds_in_range(range).next().is_some() {
13083                self.unfold_lines(&Default::default(), window, cx)
13084            } else {
13085                self.fold(&Default::default(), window, cx)
13086            }
13087        } else {
13088            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13089            let buffer_ids: HashSet<_> = self
13090                .selections
13091                .disjoint_anchor_ranges()
13092                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13093                .collect();
13094
13095            let should_unfold = buffer_ids
13096                .iter()
13097                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13098
13099            for buffer_id in buffer_ids {
13100                if should_unfold {
13101                    self.unfold_buffer(buffer_id, cx);
13102                } else {
13103                    self.fold_buffer(buffer_id, cx);
13104                }
13105            }
13106        }
13107    }
13108
13109    pub fn toggle_fold_recursive(
13110        &mut self,
13111        _: &actions::ToggleFoldRecursive,
13112        window: &mut Window,
13113        cx: &mut Context<Self>,
13114    ) {
13115        let selection = self.selections.newest::<Point>(cx);
13116
13117        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13118        let range = if selection.is_empty() {
13119            let point = selection.head().to_display_point(&display_map);
13120            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13121            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13122                .to_point(&display_map);
13123            start..end
13124        } else {
13125            selection.range()
13126        };
13127        if display_map.folds_in_range(range).next().is_some() {
13128            self.unfold_recursive(&Default::default(), window, cx)
13129        } else {
13130            self.fold_recursive(&Default::default(), window, cx)
13131        }
13132    }
13133
13134    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13135        if self.is_singleton(cx) {
13136            let mut to_fold = Vec::new();
13137            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13138            let selections = self.selections.all_adjusted(cx);
13139
13140            for selection in selections {
13141                let range = selection.range().sorted();
13142                let buffer_start_row = range.start.row;
13143
13144                if range.start.row != range.end.row {
13145                    let mut found = false;
13146                    let mut row = range.start.row;
13147                    while row <= range.end.row {
13148                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13149                        {
13150                            found = true;
13151                            row = crease.range().end.row + 1;
13152                            to_fold.push(crease);
13153                        } else {
13154                            row += 1
13155                        }
13156                    }
13157                    if found {
13158                        continue;
13159                    }
13160                }
13161
13162                for row in (0..=range.start.row).rev() {
13163                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13164                        if crease.range().end.row >= buffer_start_row {
13165                            to_fold.push(crease);
13166                            if row <= range.start.row {
13167                                break;
13168                            }
13169                        }
13170                    }
13171                }
13172            }
13173
13174            self.fold_creases(to_fold, true, window, cx);
13175        } else {
13176            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13177            let buffer_ids = self
13178                .selections
13179                .disjoint_anchor_ranges()
13180                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13181                .collect::<HashSet<_>>();
13182            for buffer_id in buffer_ids {
13183                self.fold_buffer(buffer_id, cx);
13184            }
13185        }
13186    }
13187
13188    fn fold_at_level(
13189        &mut self,
13190        fold_at: &FoldAtLevel,
13191        window: &mut Window,
13192        cx: &mut Context<Self>,
13193    ) {
13194        if !self.buffer.read(cx).is_singleton() {
13195            return;
13196        }
13197
13198        let fold_at_level = fold_at.0;
13199        let snapshot = self.buffer.read(cx).snapshot(cx);
13200        let mut to_fold = Vec::new();
13201        let mut stack = vec![(0, snapshot.max_row().0, 1)];
13202
13203        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13204            while start_row < end_row {
13205                match self
13206                    .snapshot(window, cx)
13207                    .crease_for_buffer_row(MultiBufferRow(start_row))
13208                {
13209                    Some(crease) => {
13210                        let nested_start_row = crease.range().start.row + 1;
13211                        let nested_end_row = crease.range().end.row;
13212
13213                        if current_level < fold_at_level {
13214                            stack.push((nested_start_row, nested_end_row, current_level + 1));
13215                        } else if current_level == fold_at_level {
13216                            to_fold.push(crease);
13217                        }
13218
13219                        start_row = nested_end_row + 1;
13220                    }
13221                    None => start_row += 1,
13222                }
13223            }
13224        }
13225
13226        self.fold_creases(to_fold, true, window, cx);
13227    }
13228
13229    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13230        if self.buffer.read(cx).is_singleton() {
13231            let mut fold_ranges = Vec::new();
13232            let snapshot = self.buffer.read(cx).snapshot(cx);
13233
13234            for row in 0..snapshot.max_row().0 {
13235                if let Some(foldable_range) = self
13236                    .snapshot(window, cx)
13237                    .crease_for_buffer_row(MultiBufferRow(row))
13238                {
13239                    fold_ranges.push(foldable_range);
13240                }
13241            }
13242
13243            self.fold_creases(fold_ranges, true, window, cx);
13244        } else {
13245            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13246                editor
13247                    .update_in(&mut cx, |editor, _, cx| {
13248                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13249                            editor.fold_buffer(buffer_id, cx);
13250                        }
13251                    })
13252                    .ok();
13253            });
13254        }
13255    }
13256
13257    pub fn fold_function_bodies(
13258        &mut self,
13259        _: &actions::FoldFunctionBodies,
13260        window: &mut Window,
13261        cx: &mut Context<Self>,
13262    ) {
13263        let snapshot = self.buffer.read(cx).snapshot(cx);
13264
13265        let ranges = snapshot
13266            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13267            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13268            .collect::<Vec<_>>();
13269
13270        let creases = ranges
13271            .into_iter()
13272            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13273            .collect();
13274
13275        self.fold_creases(creases, true, window, cx);
13276    }
13277
13278    pub fn fold_recursive(
13279        &mut self,
13280        _: &actions::FoldRecursive,
13281        window: &mut Window,
13282        cx: &mut Context<Self>,
13283    ) {
13284        let mut to_fold = Vec::new();
13285        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13286        let selections = self.selections.all_adjusted(cx);
13287
13288        for selection in selections {
13289            let range = selection.range().sorted();
13290            let buffer_start_row = range.start.row;
13291
13292            if range.start.row != range.end.row {
13293                let mut found = false;
13294                for row in range.start.row..=range.end.row {
13295                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13296                        found = true;
13297                        to_fold.push(crease);
13298                    }
13299                }
13300                if found {
13301                    continue;
13302                }
13303            }
13304
13305            for row in (0..=range.start.row).rev() {
13306                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13307                    if crease.range().end.row >= buffer_start_row {
13308                        to_fold.push(crease);
13309                    } else {
13310                        break;
13311                    }
13312                }
13313            }
13314        }
13315
13316        self.fold_creases(to_fold, true, window, cx);
13317    }
13318
13319    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13320        let buffer_row = fold_at.buffer_row;
13321        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13322
13323        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13324            let autoscroll = self
13325                .selections
13326                .all::<Point>(cx)
13327                .iter()
13328                .any(|selection| crease.range().overlaps(&selection.range()));
13329
13330            self.fold_creases(vec![crease], autoscroll, window, cx);
13331        }
13332    }
13333
13334    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13335        if self.is_singleton(cx) {
13336            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13337            let buffer = &display_map.buffer_snapshot;
13338            let selections = self.selections.all::<Point>(cx);
13339            let ranges = selections
13340                .iter()
13341                .map(|s| {
13342                    let range = s.display_range(&display_map).sorted();
13343                    let mut start = range.start.to_point(&display_map);
13344                    let mut end = range.end.to_point(&display_map);
13345                    start.column = 0;
13346                    end.column = buffer.line_len(MultiBufferRow(end.row));
13347                    start..end
13348                })
13349                .collect::<Vec<_>>();
13350
13351            self.unfold_ranges(&ranges, true, true, cx);
13352        } else {
13353            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13354            let buffer_ids = self
13355                .selections
13356                .disjoint_anchor_ranges()
13357                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13358                .collect::<HashSet<_>>();
13359            for buffer_id in buffer_ids {
13360                self.unfold_buffer(buffer_id, cx);
13361            }
13362        }
13363    }
13364
13365    pub fn unfold_recursive(
13366        &mut self,
13367        _: &UnfoldRecursive,
13368        _window: &mut Window,
13369        cx: &mut Context<Self>,
13370    ) {
13371        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13372        let selections = self.selections.all::<Point>(cx);
13373        let ranges = selections
13374            .iter()
13375            .map(|s| {
13376                let mut range = s.display_range(&display_map).sorted();
13377                *range.start.column_mut() = 0;
13378                *range.end.column_mut() = display_map.line_len(range.end.row());
13379                let start = range.start.to_point(&display_map);
13380                let end = range.end.to_point(&display_map);
13381                start..end
13382            })
13383            .collect::<Vec<_>>();
13384
13385        self.unfold_ranges(&ranges, true, true, cx);
13386    }
13387
13388    pub fn unfold_at(
13389        &mut self,
13390        unfold_at: &UnfoldAt,
13391        _window: &mut Window,
13392        cx: &mut Context<Self>,
13393    ) {
13394        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13395
13396        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13397            ..Point::new(
13398                unfold_at.buffer_row.0,
13399                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13400            );
13401
13402        let autoscroll = self
13403            .selections
13404            .all::<Point>(cx)
13405            .iter()
13406            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13407
13408        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13409    }
13410
13411    pub fn unfold_all(
13412        &mut self,
13413        _: &actions::UnfoldAll,
13414        _window: &mut Window,
13415        cx: &mut Context<Self>,
13416    ) {
13417        if self.buffer.read(cx).is_singleton() {
13418            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13419            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13420        } else {
13421            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13422                editor
13423                    .update(&mut cx, |editor, cx| {
13424                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13425                            editor.unfold_buffer(buffer_id, cx);
13426                        }
13427                    })
13428                    .ok();
13429            });
13430        }
13431    }
13432
13433    pub fn fold_selected_ranges(
13434        &mut self,
13435        _: &FoldSelectedRanges,
13436        window: &mut Window,
13437        cx: &mut Context<Self>,
13438    ) {
13439        let selections = self.selections.all::<Point>(cx);
13440        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13441        let line_mode = self.selections.line_mode;
13442        let ranges = selections
13443            .into_iter()
13444            .map(|s| {
13445                if line_mode {
13446                    let start = Point::new(s.start.row, 0);
13447                    let end = Point::new(
13448                        s.end.row,
13449                        display_map
13450                            .buffer_snapshot
13451                            .line_len(MultiBufferRow(s.end.row)),
13452                    );
13453                    Crease::simple(start..end, display_map.fold_placeholder.clone())
13454                } else {
13455                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13456                }
13457            })
13458            .collect::<Vec<_>>();
13459        self.fold_creases(ranges, true, window, cx);
13460    }
13461
13462    pub fn fold_ranges<T: ToOffset + Clone>(
13463        &mut self,
13464        ranges: Vec<Range<T>>,
13465        auto_scroll: bool,
13466        window: &mut Window,
13467        cx: &mut Context<Self>,
13468    ) {
13469        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13470        let ranges = ranges
13471            .into_iter()
13472            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13473            .collect::<Vec<_>>();
13474        self.fold_creases(ranges, auto_scroll, window, cx);
13475    }
13476
13477    pub fn fold_creases<T: ToOffset + Clone>(
13478        &mut self,
13479        creases: Vec<Crease<T>>,
13480        auto_scroll: bool,
13481        window: &mut Window,
13482        cx: &mut Context<Self>,
13483    ) {
13484        if creases.is_empty() {
13485            return;
13486        }
13487
13488        let mut buffers_affected = HashSet::default();
13489        let multi_buffer = self.buffer().read(cx);
13490        for crease in &creases {
13491            if let Some((_, buffer, _)) =
13492                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13493            {
13494                buffers_affected.insert(buffer.read(cx).remote_id());
13495            };
13496        }
13497
13498        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13499
13500        if auto_scroll {
13501            self.request_autoscroll(Autoscroll::fit(), cx);
13502        }
13503
13504        cx.notify();
13505
13506        if let Some(active_diagnostics) = self.active_diagnostics.take() {
13507            // Clear diagnostics block when folding a range that contains it.
13508            let snapshot = self.snapshot(window, cx);
13509            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13510                drop(snapshot);
13511                self.active_diagnostics = Some(active_diagnostics);
13512                self.dismiss_diagnostics(cx);
13513            } else {
13514                self.active_diagnostics = Some(active_diagnostics);
13515            }
13516        }
13517
13518        self.scrollbar_marker_state.dirty = true;
13519    }
13520
13521    /// Removes any folds whose ranges intersect any of the given ranges.
13522    pub fn unfold_ranges<T: ToOffset + Clone>(
13523        &mut self,
13524        ranges: &[Range<T>],
13525        inclusive: bool,
13526        auto_scroll: bool,
13527        cx: &mut Context<Self>,
13528    ) {
13529        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13530            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13531        });
13532    }
13533
13534    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13535        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13536            return;
13537        }
13538        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13539        self.display_map.update(cx, |display_map, cx| {
13540            display_map.fold_buffers([buffer_id], cx)
13541        });
13542        cx.emit(EditorEvent::BufferFoldToggled {
13543            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13544            folded: true,
13545        });
13546        cx.notify();
13547    }
13548
13549    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13550        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13551            return;
13552        }
13553        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13554        self.display_map.update(cx, |display_map, cx| {
13555            display_map.unfold_buffers([buffer_id], cx);
13556        });
13557        cx.emit(EditorEvent::BufferFoldToggled {
13558            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13559            folded: false,
13560        });
13561        cx.notify();
13562    }
13563
13564    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13565        self.display_map.read(cx).is_buffer_folded(buffer)
13566    }
13567
13568    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13569        self.display_map.read(cx).folded_buffers()
13570    }
13571
13572    /// Removes any folds with the given ranges.
13573    pub fn remove_folds_with_type<T: ToOffset + Clone>(
13574        &mut self,
13575        ranges: &[Range<T>],
13576        type_id: TypeId,
13577        auto_scroll: bool,
13578        cx: &mut Context<Self>,
13579    ) {
13580        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13581            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13582        });
13583    }
13584
13585    fn remove_folds_with<T: ToOffset + Clone>(
13586        &mut self,
13587        ranges: &[Range<T>],
13588        auto_scroll: bool,
13589        cx: &mut Context<Self>,
13590        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13591    ) {
13592        if ranges.is_empty() {
13593            return;
13594        }
13595
13596        let mut buffers_affected = HashSet::default();
13597        let multi_buffer = self.buffer().read(cx);
13598        for range in ranges {
13599            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13600                buffers_affected.insert(buffer.read(cx).remote_id());
13601            };
13602        }
13603
13604        self.display_map.update(cx, update);
13605
13606        if auto_scroll {
13607            self.request_autoscroll(Autoscroll::fit(), cx);
13608        }
13609
13610        cx.notify();
13611        self.scrollbar_marker_state.dirty = true;
13612        self.active_indent_guides_state.dirty = true;
13613    }
13614
13615    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13616        self.display_map.read(cx).fold_placeholder.clone()
13617    }
13618
13619    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13620        self.buffer.update(cx, |buffer, cx| {
13621            buffer.set_all_diff_hunks_expanded(cx);
13622        });
13623    }
13624
13625    pub fn expand_all_diff_hunks(
13626        &mut self,
13627        _: &ExpandAllDiffHunks,
13628        _window: &mut Window,
13629        cx: &mut Context<Self>,
13630    ) {
13631        self.buffer.update(cx, |buffer, cx| {
13632            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13633        });
13634    }
13635
13636    pub fn toggle_selected_diff_hunks(
13637        &mut self,
13638        _: &ToggleSelectedDiffHunks,
13639        _window: &mut Window,
13640        cx: &mut Context<Self>,
13641    ) {
13642        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13643        self.toggle_diff_hunks_in_ranges(ranges, cx);
13644    }
13645
13646    pub fn diff_hunks_in_ranges<'a>(
13647        &'a self,
13648        ranges: &'a [Range<Anchor>],
13649        buffer: &'a MultiBufferSnapshot,
13650    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13651        ranges.iter().flat_map(move |range| {
13652            let end_excerpt_id = range.end.excerpt_id;
13653            let range = range.to_point(buffer);
13654            let mut peek_end = range.end;
13655            if range.end.row < buffer.max_row().0 {
13656                peek_end = Point::new(range.end.row + 1, 0);
13657            }
13658            buffer
13659                .diff_hunks_in_range(range.start..peek_end)
13660                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13661        })
13662    }
13663
13664    pub fn has_stageable_diff_hunks_in_ranges(
13665        &self,
13666        ranges: &[Range<Anchor>],
13667        snapshot: &MultiBufferSnapshot,
13668    ) -> bool {
13669        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13670        hunks.any(|hunk| hunk.status().has_secondary_hunk())
13671    }
13672
13673    pub fn toggle_staged_selected_diff_hunks(
13674        &mut self,
13675        _: &::git::ToggleStaged,
13676        _: &mut Window,
13677        cx: &mut Context<Self>,
13678    ) {
13679        let snapshot = self.buffer.read(cx).snapshot(cx);
13680        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13681        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13682        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13683    }
13684
13685    pub fn stage_and_next(
13686        &mut self,
13687        _: &::git::StageAndNext,
13688        window: &mut Window,
13689        cx: &mut Context<Self>,
13690    ) {
13691        self.do_stage_or_unstage_and_next(true, window, cx);
13692    }
13693
13694    pub fn unstage_and_next(
13695        &mut self,
13696        _: &::git::UnstageAndNext,
13697        window: &mut Window,
13698        cx: &mut Context<Self>,
13699    ) {
13700        self.do_stage_or_unstage_and_next(false, window, cx);
13701    }
13702
13703    pub fn stage_or_unstage_diff_hunks(
13704        &mut self,
13705        stage: bool,
13706        ranges: Vec<Range<Anchor>>,
13707        cx: &mut Context<Self>,
13708    ) {
13709        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
13710        cx.spawn(|this, mut cx| async move {
13711            task.await?;
13712            this.update(&mut cx, |this, cx| {
13713                let snapshot = this.buffer.read(cx).snapshot(cx);
13714                let chunk_by = this
13715                    .diff_hunks_in_ranges(&ranges, &snapshot)
13716                    .chunk_by(|hunk| hunk.buffer_id);
13717                for (buffer_id, hunks) in &chunk_by {
13718                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
13719                }
13720            })
13721        })
13722        .detach_and_log_err(cx);
13723    }
13724
13725    fn save_buffers_for_ranges_if_needed(
13726        &mut self,
13727        ranges: &[Range<Anchor>],
13728        cx: &mut Context<'_, Editor>,
13729    ) -> Task<Result<()>> {
13730        let multibuffer = self.buffer.read(cx);
13731        let snapshot = multibuffer.read(cx);
13732        let buffer_ids: HashSet<_> = ranges
13733            .iter()
13734            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
13735            .collect();
13736        drop(snapshot);
13737
13738        let mut buffers = HashSet::default();
13739        for buffer_id in buffer_ids {
13740            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
13741                let buffer = buffer_entity.read(cx);
13742                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
13743                {
13744                    buffers.insert(buffer_entity);
13745                }
13746            }
13747        }
13748
13749        if let Some(project) = &self.project {
13750            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
13751        } else {
13752            Task::ready(Ok(()))
13753        }
13754    }
13755
13756    fn do_stage_or_unstage_and_next(
13757        &mut self,
13758        stage: bool,
13759        window: &mut Window,
13760        cx: &mut Context<Self>,
13761    ) {
13762        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13763
13764        if ranges.iter().any(|range| range.start != range.end) {
13765            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13766            return;
13767        }
13768
13769        let snapshot = self.snapshot(window, cx);
13770        let newest_range = self.selections.newest::<Point>(cx).range();
13771
13772        let run_twice = snapshot
13773            .hunks_for_ranges([newest_range])
13774            .first()
13775            .is_some_and(|hunk| {
13776                let next_line = Point::new(hunk.row_range.end.0 + 1, 0);
13777                self.hunk_after_position(&snapshot, next_line)
13778                    .is_some_and(|other| other.row_range == hunk.row_range)
13779            });
13780
13781        if run_twice {
13782            self.go_to_next_hunk(&GoToHunk, window, cx);
13783        }
13784        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13785        self.go_to_next_hunk(&GoToHunk, window, cx);
13786    }
13787
13788    fn do_stage_or_unstage(
13789        &self,
13790        stage: bool,
13791        buffer_id: BufferId,
13792        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13793        cx: &mut App,
13794    ) -> Option<()> {
13795        let project = self.project.as_ref()?;
13796        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
13797        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
13798        let buffer_snapshot = buffer.read(cx).snapshot();
13799        let file_exists = buffer_snapshot
13800            .file()
13801            .is_some_and(|file| file.disk_state().exists());
13802        diff.update(cx, |diff, cx| {
13803            diff.stage_or_unstage_hunks(
13804                stage,
13805                &hunks
13806                    .map(|hunk| buffer_diff::DiffHunk {
13807                        buffer_range: hunk.buffer_range,
13808                        diff_base_byte_range: hunk.diff_base_byte_range,
13809                        secondary_status: hunk.secondary_status,
13810                        range: Point::zero()..Point::zero(), // unused
13811                    })
13812                    .collect::<Vec<_>>(),
13813                &buffer_snapshot,
13814                file_exists,
13815                cx,
13816            )
13817        });
13818        None
13819    }
13820
13821    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13822        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13823        self.buffer
13824            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13825    }
13826
13827    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13828        self.buffer.update(cx, |buffer, cx| {
13829            let ranges = vec![Anchor::min()..Anchor::max()];
13830            if !buffer.all_diff_hunks_expanded()
13831                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13832            {
13833                buffer.collapse_diff_hunks(ranges, cx);
13834                true
13835            } else {
13836                false
13837            }
13838        })
13839    }
13840
13841    fn toggle_diff_hunks_in_ranges(
13842        &mut self,
13843        ranges: Vec<Range<Anchor>>,
13844        cx: &mut Context<'_, Editor>,
13845    ) {
13846        self.buffer.update(cx, |buffer, cx| {
13847            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13848            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13849        })
13850    }
13851
13852    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13853        self.buffer.update(cx, |buffer, cx| {
13854            let snapshot = buffer.snapshot(cx);
13855            let excerpt_id = range.end.excerpt_id;
13856            let point_range = range.to_point(&snapshot);
13857            let expand = !buffer.single_hunk_is_expanded(range, cx);
13858            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13859        })
13860    }
13861
13862    pub(crate) fn apply_all_diff_hunks(
13863        &mut self,
13864        _: &ApplyAllDiffHunks,
13865        window: &mut Window,
13866        cx: &mut Context<Self>,
13867    ) {
13868        let buffers = self.buffer.read(cx).all_buffers();
13869        for branch_buffer in buffers {
13870            branch_buffer.update(cx, |branch_buffer, cx| {
13871                branch_buffer.merge_into_base(Vec::new(), cx);
13872            });
13873        }
13874
13875        if let Some(project) = self.project.clone() {
13876            self.save(true, project, window, cx).detach_and_log_err(cx);
13877        }
13878    }
13879
13880    pub(crate) fn apply_selected_diff_hunks(
13881        &mut self,
13882        _: &ApplyDiffHunk,
13883        window: &mut Window,
13884        cx: &mut Context<Self>,
13885    ) {
13886        let snapshot = self.snapshot(window, cx);
13887        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
13888        let mut ranges_by_buffer = HashMap::default();
13889        self.transact(window, cx, |editor, _window, cx| {
13890            for hunk in hunks {
13891                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13892                    ranges_by_buffer
13893                        .entry(buffer.clone())
13894                        .or_insert_with(Vec::new)
13895                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13896                }
13897            }
13898
13899            for (buffer, ranges) in ranges_by_buffer {
13900                buffer.update(cx, |buffer, cx| {
13901                    buffer.merge_into_base(ranges, cx);
13902                });
13903            }
13904        });
13905
13906        if let Some(project) = self.project.clone() {
13907            self.save(true, project, window, cx).detach_and_log_err(cx);
13908        }
13909    }
13910
13911    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13912        if hovered != self.gutter_hovered {
13913            self.gutter_hovered = hovered;
13914            cx.notify();
13915        }
13916    }
13917
13918    pub fn insert_blocks(
13919        &mut self,
13920        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13921        autoscroll: Option<Autoscroll>,
13922        cx: &mut Context<Self>,
13923    ) -> Vec<CustomBlockId> {
13924        let blocks = self
13925            .display_map
13926            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13927        if let Some(autoscroll) = autoscroll {
13928            self.request_autoscroll(autoscroll, cx);
13929        }
13930        cx.notify();
13931        blocks
13932    }
13933
13934    pub fn resize_blocks(
13935        &mut self,
13936        heights: HashMap<CustomBlockId, u32>,
13937        autoscroll: Option<Autoscroll>,
13938        cx: &mut Context<Self>,
13939    ) {
13940        self.display_map
13941            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13942        if let Some(autoscroll) = autoscroll {
13943            self.request_autoscroll(autoscroll, cx);
13944        }
13945        cx.notify();
13946    }
13947
13948    pub fn replace_blocks(
13949        &mut self,
13950        renderers: HashMap<CustomBlockId, RenderBlock>,
13951        autoscroll: Option<Autoscroll>,
13952        cx: &mut Context<Self>,
13953    ) {
13954        self.display_map
13955            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13956        if let Some(autoscroll) = autoscroll {
13957            self.request_autoscroll(autoscroll, cx);
13958        }
13959        cx.notify();
13960    }
13961
13962    pub fn remove_blocks(
13963        &mut self,
13964        block_ids: HashSet<CustomBlockId>,
13965        autoscroll: Option<Autoscroll>,
13966        cx: &mut Context<Self>,
13967    ) {
13968        self.display_map.update(cx, |display_map, cx| {
13969            display_map.remove_blocks(block_ids, cx)
13970        });
13971        if let Some(autoscroll) = autoscroll {
13972            self.request_autoscroll(autoscroll, cx);
13973        }
13974        cx.notify();
13975    }
13976
13977    pub fn row_for_block(
13978        &self,
13979        block_id: CustomBlockId,
13980        cx: &mut Context<Self>,
13981    ) -> Option<DisplayRow> {
13982        self.display_map
13983            .update(cx, |map, cx| map.row_for_block(block_id, cx))
13984    }
13985
13986    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13987        self.focused_block = Some(focused_block);
13988    }
13989
13990    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13991        self.focused_block.take()
13992    }
13993
13994    pub fn insert_creases(
13995        &mut self,
13996        creases: impl IntoIterator<Item = Crease<Anchor>>,
13997        cx: &mut Context<Self>,
13998    ) -> Vec<CreaseId> {
13999        self.display_map
14000            .update(cx, |map, cx| map.insert_creases(creases, cx))
14001    }
14002
14003    pub fn remove_creases(
14004        &mut self,
14005        ids: impl IntoIterator<Item = CreaseId>,
14006        cx: &mut Context<Self>,
14007    ) {
14008        self.display_map
14009            .update(cx, |map, cx| map.remove_creases(ids, cx));
14010    }
14011
14012    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
14013        self.display_map
14014            .update(cx, |map, cx| map.snapshot(cx))
14015            .longest_row()
14016    }
14017
14018    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
14019        self.display_map
14020            .update(cx, |map, cx| map.snapshot(cx))
14021            .max_point()
14022    }
14023
14024    pub fn text(&self, cx: &App) -> String {
14025        self.buffer.read(cx).read(cx).text()
14026    }
14027
14028    pub fn is_empty(&self, cx: &App) -> bool {
14029        self.buffer.read(cx).read(cx).is_empty()
14030    }
14031
14032    pub fn text_option(&self, cx: &App) -> Option<String> {
14033        let text = self.text(cx);
14034        let text = text.trim();
14035
14036        if text.is_empty() {
14037            return None;
14038        }
14039
14040        Some(text.to_string())
14041    }
14042
14043    pub fn set_text(
14044        &mut self,
14045        text: impl Into<Arc<str>>,
14046        window: &mut Window,
14047        cx: &mut Context<Self>,
14048    ) {
14049        self.transact(window, cx, |this, _, cx| {
14050            this.buffer
14051                .read(cx)
14052                .as_singleton()
14053                .expect("you can only call set_text on editors for singleton buffers")
14054                .update(cx, |buffer, cx| buffer.set_text(text, cx));
14055        });
14056    }
14057
14058    pub fn display_text(&self, cx: &mut App) -> String {
14059        self.display_map
14060            .update(cx, |map, cx| map.snapshot(cx))
14061            .text()
14062    }
14063
14064    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
14065        let mut wrap_guides = smallvec::smallvec![];
14066
14067        if self.show_wrap_guides == Some(false) {
14068            return wrap_guides;
14069        }
14070
14071        let settings = self.buffer.read(cx).language_settings(cx);
14072        if settings.show_wrap_guides {
14073            match self.soft_wrap_mode(cx) {
14074                SoftWrap::Column(soft_wrap) => {
14075                    wrap_guides.push((soft_wrap as usize, true));
14076                }
14077                SoftWrap::Bounded(soft_wrap) => {
14078                    wrap_guides.push((soft_wrap as usize, true));
14079                }
14080                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
14081            }
14082            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14083        }
14084
14085        wrap_guides
14086    }
14087
14088    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14089        let settings = self.buffer.read(cx).language_settings(cx);
14090        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14091        match mode {
14092            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14093                SoftWrap::None
14094            }
14095            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14096            language_settings::SoftWrap::PreferredLineLength => {
14097                SoftWrap::Column(settings.preferred_line_length)
14098            }
14099            language_settings::SoftWrap::Bounded => {
14100                SoftWrap::Bounded(settings.preferred_line_length)
14101            }
14102        }
14103    }
14104
14105    pub fn set_soft_wrap_mode(
14106        &mut self,
14107        mode: language_settings::SoftWrap,
14108
14109        cx: &mut Context<Self>,
14110    ) {
14111        self.soft_wrap_mode_override = Some(mode);
14112        cx.notify();
14113    }
14114
14115    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14116        self.text_style_refinement = Some(style);
14117    }
14118
14119    /// called by the Element so we know what style we were most recently rendered with.
14120    pub(crate) fn set_style(
14121        &mut self,
14122        style: EditorStyle,
14123        window: &mut Window,
14124        cx: &mut Context<Self>,
14125    ) {
14126        let rem_size = window.rem_size();
14127        self.display_map.update(cx, |map, cx| {
14128            map.set_font(
14129                style.text.font(),
14130                style.text.font_size.to_pixels(rem_size),
14131                cx,
14132            )
14133        });
14134        self.style = Some(style);
14135    }
14136
14137    pub fn style(&self) -> Option<&EditorStyle> {
14138        self.style.as_ref()
14139    }
14140
14141    // Called by the element. This method is not designed to be called outside of the editor
14142    // element's layout code because it does not notify when rewrapping is computed synchronously.
14143    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14144        self.display_map
14145            .update(cx, |map, cx| map.set_wrap_width(width, cx))
14146    }
14147
14148    pub fn set_soft_wrap(&mut self) {
14149        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14150    }
14151
14152    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14153        if self.soft_wrap_mode_override.is_some() {
14154            self.soft_wrap_mode_override.take();
14155        } else {
14156            let soft_wrap = match self.soft_wrap_mode(cx) {
14157                SoftWrap::GitDiff => return,
14158                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14159                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14160                    language_settings::SoftWrap::None
14161                }
14162            };
14163            self.soft_wrap_mode_override = Some(soft_wrap);
14164        }
14165        cx.notify();
14166    }
14167
14168    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14169        let Some(workspace) = self.workspace() else {
14170            return;
14171        };
14172        let fs = workspace.read(cx).app_state().fs.clone();
14173        let current_show = TabBarSettings::get_global(cx).show;
14174        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14175            setting.show = Some(!current_show);
14176        });
14177    }
14178
14179    pub fn toggle_indent_guides(
14180        &mut self,
14181        _: &ToggleIndentGuides,
14182        _: &mut Window,
14183        cx: &mut Context<Self>,
14184    ) {
14185        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14186            self.buffer
14187                .read(cx)
14188                .language_settings(cx)
14189                .indent_guides
14190                .enabled
14191        });
14192        self.show_indent_guides = Some(!currently_enabled);
14193        cx.notify();
14194    }
14195
14196    fn should_show_indent_guides(&self) -> Option<bool> {
14197        self.show_indent_guides
14198    }
14199
14200    pub fn toggle_line_numbers(
14201        &mut self,
14202        _: &ToggleLineNumbers,
14203        _: &mut Window,
14204        cx: &mut Context<Self>,
14205    ) {
14206        let mut editor_settings = EditorSettings::get_global(cx).clone();
14207        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14208        EditorSettings::override_global(editor_settings, cx);
14209    }
14210
14211    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14212        self.use_relative_line_numbers
14213            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14214    }
14215
14216    pub fn toggle_relative_line_numbers(
14217        &mut self,
14218        _: &ToggleRelativeLineNumbers,
14219        _: &mut Window,
14220        cx: &mut Context<Self>,
14221    ) {
14222        let is_relative = self.should_use_relative_line_numbers(cx);
14223        self.set_relative_line_number(Some(!is_relative), cx)
14224    }
14225
14226    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14227        self.use_relative_line_numbers = is_relative;
14228        cx.notify();
14229    }
14230
14231    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14232        self.show_gutter = show_gutter;
14233        cx.notify();
14234    }
14235
14236    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14237        self.show_scrollbars = show_scrollbars;
14238        cx.notify();
14239    }
14240
14241    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14242        self.show_line_numbers = Some(show_line_numbers);
14243        cx.notify();
14244    }
14245
14246    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14247        self.show_git_diff_gutter = Some(show_git_diff_gutter);
14248        cx.notify();
14249    }
14250
14251    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14252        self.show_code_actions = Some(show_code_actions);
14253        cx.notify();
14254    }
14255
14256    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14257        self.show_runnables = Some(show_runnables);
14258        cx.notify();
14259    }
14260
14261    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14262        if self.display_map.read(cx).masked != masked {
14263            self.display_map.update(cx, |map, _| map.masked = masked);
14264        }
14265        cx.notify()
14266    }
14267
14268    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14269        self.show_wrap_guides = Some(show_wrap_guides);
14270        cx.notify();
14271    }
14272
14273    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14274        self.show_indent_guides = Some(show_indent_guides);
14275        cx.notify();
14276    }
14277
14278    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14279        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14280            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14281                if let Some(dir) = file.abs_path(cx).parent() {
14282                    return Some(dir.to_owned());
14283                }
14284            }
14285
14286            if let Some(project_path) = buffer.read(cx).project_path(cx) {
14287                return Some(project_path.path.to_path_buf());
14288            }
14289        }
14290
14291        None
14292    }
14293
14294    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14295        self.active_excerpt(cx)?
14296            .1
14297            .read(cx)
14298            .file()
14299            .and_then(|f| f.as_local())
14300    }
14301
14302    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14303        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14304            let buffer = buffer.read(cx);
14305            if let Some(project_path) = buffer.project_path(cx) {
14306                let project = self.project.as_ref()?.read(cx);
14307                project.absolute_path(&project_path, cx)
14308            } else {
14309                buffer
14310                    .file()
14311                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14312            }
14313        })
14314    }
14315
14316    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14317        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14318            let project_path = buffer.read(cx).project_path(cx)?;
14319            let project = self.project.as_ref()?.read(cx);
14320            let entry = project.entry_for_path(&project_path, cx)?;
14321            let path = entry.path.to_path_buf();
14322            Some(path)
14323        })
14324    }
14325
14326    pub fn reveal_in_finder(
14327        &mut self,
14328        _: &RevealInFileManager,
14329        _window: &mut Window,
14330        cx: &mut Context<Self>,
14331    ) {
14332        if let Some(target) = self.target_file(cx) {
14333            cx.reveal_path(&target.abs_path(cx));
14334        }
14335    }
14336
14337    pub fn copy_path(
14338        &mut self,
14339        _: &zed_actions::workspace::CopyPath,
14340        _window: &mut Window,
14341        cx: &mut Context<Self>,
14342    ) {
14343        if let Some(path) = self.target_file_abs_path(cx) {
14344            if let Some(path) = path.to_str() {
14345                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14346            }
14347        }
14348    }
14349
14350    pub fn copy_relative_path(
14351        &mut self,
14352        _: &zed_actions::workspace::CopyRelativePath,
14353        _window: &mut Window,
14354        cx: &mut Context<Self>,
14355    ) {
14356        if let Some(path) = self.target_file_path(cx) {
14357            if let Some(path) = path.to_str() {
14358                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14359            }
14360        }
14361    }
14362
14363    pub fn copy_file_name_without_extension(
14364        &mut self,
14365        _: &CopyFileNameWithoutExtension,
14366        _: &mut Window,
14367        cx: &mut Context<Self>,
14368    ) {
14369        if let Some(file) = self.target_file(cx) {
14370            if let Some(file_stem) = file.path().file_stem() {
14371                if let Some(name) = file_stem.to_str() {
14372                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14373                }
14374            }
14375        }
14376    }
14377
14378    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14379        if let Some(file) = self.target_file(cx) {
14380            if let Some(file_name) = file.path().file_name() {
14381                if let Some(name) = file_name.to_str() {
14382                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14383                }
14384            }
14385        }
14386    }
14387
14388    pub fn toggle_git_blame(
14389        &mut self,
14390        _: &ToggleGitBlame,
14391        window: &mut Window,
14392        cx: &mut Context<Self>,
14393    ) {
14394        self.show_git_blame_gutter = !self.show_git_blame_gutter;
14395
14396        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14397            self.start_git_blame(true, window, cx);
14398        }
14399
14400        cx.notify();
14401    }
14402
14403    pub fn toggle_git_blame_inline(
14404        &mut self,
14405        _: &ToggleGitBlameInline,
14406        window: &mut Window,
14407        cx: &mut Context<Self>,
14408    ) {
14409        self.toggle_git_blame_inline_internal(true, window, cx);
14410        cx.notify();
14411    }
14412
14413    pub fn git_blame_inline_enabled(&self) -> bool {
14414        self.git_blame_inline_enabled
14415    }
14416
14417    pub fn toggle_selection_menu(
14418        &mut self,
14419        _: &ToggleSelectionMenu,
14420        _: &mut Window,
14421        cx: &mut Context<Self>,
14422    ) {
14423        self.show_selection_menu = self
14424            .show_selection_menu
14425            .map(|show_selections_menu| !show_selections_menu)
14426            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14427
14428        cx.notify();
14429    }
14430
14431    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14432        self.show_selection_menu
14433            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14434    }
14435
14436    fn start_git_blame(
14437        &mut self,
14438        user_triggered: bool,
14439        window: &mut Window,
14440        cx: &mut Context<Self>,
14441    ) {
14442        if let Some(project) = self.project.as_ref() {
14443            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14444                return;
14445            };
14446
14447            if buffer.read(cx).file().is_none() {
14448                return;
14449            }
14450
14451            let focused = self.focus_handle(cx).contains_focused(window, cx);
14452
14453            let project = project.clone();
14454            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14455            self.blame_subscription =
14456                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14457            self.blame = Some(blame);
14458        }
14459    }
14460
14461    fn toggle_git_blame_inline_internal(
14462        &mut self,
14463        user_triggered: bool,
14464        window: &mut Window,
14465        cx: &mut Context<Self>,
14466    ) {
14467        if self.git_blame_inline_enabled {
14468            self.git_blame_inline_enabled = false;
14469            self.show_git_blame_inline = false;
14470            self.show_git_blame_inline_delay_task.take();
14471        } else {
14472            self.git_blame_inline_enabled = true;
14473            self.start_git_blame_inline(user_triggered, window, cx);
14474        }
14475
14476        cx.notify();
14477    }
14478
14479    fn start_git_blame_inline(
14480        &mut self,
14481        user_triggered: bool,
14482        window: &mut Window,
14483        cx: &mut Context<Self>,
14484    ) {
14485        self.start_git_blame(user_triggered, window, cx);
14486
14487        if ProjectSettings::get_global(cx)
14488            .git
14489            .inline_blame_delay()
14490            .is_some()
14491        {
14492            self.start_inline_blame_timer(window, cx);
14493        } else {
14494            self.show_git_blame_inline = true
14495        }
14496    }
14497
14498    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14499        self.blame.as_ref()
14500    }
14501
14502    pub fn show_git_blame_gutter(&self) -> bool {
14503        self.show_git_blame_gutter
14504    }
14505
14506    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14507        self.show_git_blame_gutter && self.has_blame_entries(cx)
14508    }
14509
14510    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14511        self.show_git_blame_inline
14512            && (self.focus_handle.is_focused(window)
14513                || self
14514                    .git_blame_inline_tooltip
14515                    .as_ref()
14516                    .and_then(|t| t.upgrade())
14517                    .is_some())
14518            && !self.newest_selection_head_on_empty_line(cx)
14519            && self.has_blame_entries(cx)
14520    }
14521
14522    fn has_blame_entries(&self, cx: &App) -> bool {
14523        self.blame()
14524            .map_or(false, |blame| blame.read(cx).has_generated_entries())
14525    }
14526
14527    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14528        let cursor_anchor = self.selections.newest_anchor().head();
14529
14530        let snapshot = self.buffer.read(cx).snapshot(cx);
14531        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14532
14533        snapshot.line_len(buffer_row) == 0
14534    }
14535
14536    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14537        let buffer_and_selection = maybe!({
14538            let selection = self.selections.newest::<Point>(cx);
14539            let selection_range = selection.range();
14540
14541            let multi_buffer = self.buffer().read(cx);
14542            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14543            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14544
14545            let (buffer, range, _) = if selection.reversed {
14546                buffer_ranges.first()
14547            } else {
14548                buffer_ranges.last()
14549            }?;
14550
14551            let selection = text::ToPoint::to_point(&range.start, &buffer).row
14552                ..text::ToPoint::to_point(&range.end, &buffer).row;
14553            Some((
14554                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14555                selection,
14556            ))
14557        });
14558
14559        let Some((buffer, selection)) = buffer_and_selection else {
14560            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14561        };
14562
14563        let Some(project) = self.project.as_ref() else {
14564            return Task::ready(Err(anyhow!("editor does not have project")));
14565        };
14566
14567        project.update(cx, |project, cx| {
14568            project.get_permalink_to_line(&buffer, selection, cx)
14569        })
14570    }
14571
14572    pub fn copy_permalink_to_line(
14573        &mut self,
14574        _: &CopyPermalinkToLine,
14575        window: &mut Window,
14576        cx: &mut Context<Self>,
14577    ) {
14578        let permalink_task = self.get_permalink_to_line(cx);
14579        let workspace = self.workspace();
14580
14581        cx.spawn_in(window, |_, mut cx| async move {
14582            match permalink_task.await {
14583                Ok(permalink) => {
14584                    cx.update(|_, cx| {
14585                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14586                    })
14587                    .ok();
14588                }
14589                Err(err) => {
14590                    let message = format!("Failed to copy permalink: {err}");
14591
14592                    Err::<(), anyhow::Error>(err).log_err();
14593
14594                    if let Some(workspace) = workspace {
14595                        workspace
14596                            .update_in(&mut cx, |workspace, _, cx| {
14597                                struct CopyPermalinkToLine;
14598
14599                                workspace.show_toast(
14600                                    Toast::new(
14601                                        NotificationId::unique::<CopyPermalinkToLine>(),
14602                                        message,
14603                                    ),
14604                                    cx,
14605                                )
14606                            })
14607                            .ok();
14608                    }
14609                }
14610            }
14611        })
14612        .detach();
14613    }
14614
14615    pub fn copy_file_location(
14616        &mut self,
14617        _: &CopyFileLocation,
14618        _: &mut Window,
14619        cx: &mut Context<Self>,
14620    ) {
14621        let selection = self.selections.newest::<Point>(cx).start.row + 1;
14622        if let Some(file) = self.target_file(cx) {
14623            if let Some(path) = file.path().to_str() {
14624                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14625            }
14626        }
14627    }
14628
14629    pub fn open_permalink_to_line(
14630        &mut self,
14631        _: &OpenPermalinkToLine,
14632        window: &mut Window,
14633        cx: &mut Context<Self>,
14634    ) {
14635        let permalink_task = self.get_permalink_to_line(cx);
14636        let workspace = self.workspace();
14637
14638        cx.spawn_in(window, |_, mut cx| async move {
14639            match permalink_task.await {
14640                Ok(permalink) => {
14641                    cx.update(|_, cx| {
14642                        cx.open_url(permalink.as_ref());
14643                    })
14644                    .ok();
14645                }
14646                Err(err) => {
14647                    let message = format!("Failed to open permalink: {err}");
14648
14649                    Err::<(), anyhow::Error>(err).log_err();
14650
14651                    if let Some(workspace) = workspace {
14652                        workspace
14653                            .update(&mut cx, |workspace, cx| {
14654                                struct OpenPermalinkToLine;
14655
14656                                workspace.show_toast(
14657                                    Toast::new(
14658                                        NotificationId::unique::<OpenPermalinkToLine>(),
14659                                        message,
14660                                    ),
14661                                    cx,
14662                                )
14663                            })
14664                            .ok();
14665                    }
14666                }
14667            }
14668        })
14669        .detach();
14670    }
14671
14672    pub fn insert_uuid_v4(
14673        &mut self,
14674        _: &InsertUuidV4,
14675        window: &mut Window,
14676        cx: &mut Context<Self>,
14677    ) {
14678        self.insert_uuid(UuidVersion::V4, window, cx);
14679    }
14680
14681    pub fn insert_uuid_v7(
14682        &mut self,
14683        _: &InsertUuidV7,
14684        window: &mut Window,
14685        cx: &mut Context<Self>,
14686    ) {
14687        self.insert_uuid(UuidVersion::V7, window, cx);
14688    }
14689
14690    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14691        self.transact(window, cx, |this, window, cx| {
14692            let edits = this
14693                .selections
14694                .all::<Point>(cx)
14695                .into_iter()
14696                .map(|selection| {
14697                    let uuid = match version {
14698                        UuidVersion::V4 => uuid::Uuid::new_v4(),
14699                        UuidVersion::V7 => uuid::Uuid::now_v7(),
14700                    };
14701
14702                    (selection.range(), uuid.to_string())
14703                });
14704            this.edit(edits, cx);
14705            this.refresh_inline_completion(true, false, window, cx);
14706        });
14707    }
14708
14709    pub fn open_selections_in_multibuffer(
14710        &mut self,
14711        _: &OpenSelectionsInMultibuffer,
14712        window: &mut Window,
14713        cx: &mut Context<Self>,
14714    ) {
14715        let multibuffer = self.buffer.read(cx);
14716
14717        let Some(buffer) = multibuffer.as_singleton() else {
14718            return;
14719        };
14720
14721        let Some(workspace) = self.workspace() else {
14722            return;
14723        };
14724
14725        let locations = self
14726            .selections
14727            .disjoint_anchors()
14728            .iter()
14729            .map(|range| Location {
14730                buffer: buffer.clone(),
14731                range: range.start.text_anchor..range.end.text_anchor,
14732            })
14733            .collect::<Vec<_>>();
14734
14735        let title = multibuffer.title(cx).to_string();
14736
14737        cx.spawn_in(window, |_, mut cx| async move {
14738            workspace.update_in(&mut cx, |workspace, window, cx| {
14739                Self::open_locations_in_multibuffer(
14740                    workspace,
14741                    locations,
14742                    format!("Selections for '{title}'"),
14743                    false,
14744                    MultibufferSelectionMode::All,
14745                    window,
14746                    cx,
14747                );
14748            })
14749        })
14750        .detach();
14751    }
14752
14753    /// Adds a row highlight for the given range. If a row has multiple highlights, the
14754    /// last highlight added will be used.
14755    ///
14756    /// If the range ends at the beginning of a line, then that line will not be highlighted.
14757    pub fn highlight_rows<T: 'static>(
14758        &mut self,
14759        range: Range<Anchor>,
14760        color: Hsla,
14761        should_autoscroll: bool,
14762        cx: &mut Context<Self>,
14763    ) {
14764        let snapshot = self.buffer().read(cx).snapshot(cx);
14765        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14766        let ix = row_highlights.binary_search_by(|highlight| {
14767            Ordering::Equal
14768                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14769                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14770        });
14771
14772        if let Err(mut ix) = ix {
14773            let index = post_inc(&mut self.highlight_order);
14774
14775            // If this range intersects with the preceding highlight, then merge it with
14776            // the preceding highlight. Otherwise insert a new highlight.
14777            let mut merged = false;
14778            if ix > 0 {
14779                let prev_highlight = &mut row_highlights[ix - 1];
14780                if prev_highlight
14781                    .range
14782                    .end
14783                    .cmp(&range.start, &snapshot)
14784                    .is_ge()
14785                {
14786                    ix -= 1;
14787                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14788                        prev_highlight.range.end = range.end;
14789                    }
14790                    merged = true;
14791                    prev_highlight.index = index;
14792                    prev_highlight.color = color;
14793                    prev_highlight.should_autoscroll = should_autoscroll;
14794                }
14795            }
14796
14797            if !merged {
14798                row_highlights.insert(
14799                    ix,
14800                    RowHighlight {
14801                        range: range.clone(),
14802                        index,
14803                        color,
14804                        should_autoscroll,
14805                    },
14806                );
14807            }
14808
14809            // If any of the following highlights intersect with this one, merge them.
14810            while let Some(next_highlight) = row_highlights.get(ix + 1) {
14811                let highlight = &row_highlights[ix];
14812                if next_highlight
14813                    .range
14814                    .start
14815                    .cmp(&highlight.range.end, &snapshot)
14816                    .is_le()
14817                {
14818                    if next_highlight
14819                        .range
14820                        .end
14821                        .cmp(&highlight.range.end, &snapshot)
14822                        .is_gt()
14823                    {
14824                        row_highlights[ix].range.end = next_highlight.range.end;
14825                    }
14826                    row_highlights.remove(ix + 1);
14827                } else {
14828                    break;
14829                }
14830            }
14831        }
14832    }
14833
14834    /// Remove any highlighted row ranges of the given type that intersect the
14835    /// given ranges.
14836    pub fn remove_highlighted_rows<T: 'static>(
14837        &mut self,
14838        ranges_to_remove: Vec<Range<Anchor>>,
14839        cx: &mut Context<Self>,
14840    ) {
14841        let snapshot = self.buffer().read(cx).snapshot(cx);
14842        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14843        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14844        row_highlights.retain(|highlight| {
14845            while let Some(range_to_remove) = ranges_to_remove.peek() {
14846                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14847                    Ordering::Less | Ordering::Equal => {
14848                        ranges_to_remove.next();
14849                    }
14850                    Ordering::Greater => {
14851                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14852                            Ordering::Less | Ordering::Equal => {
14853                                return false;
14854                            }
14855                            Ordering::Greater => break,
14856                        }
14857                    }
14858                }
14859            }
14860
14861            true
14862        })
14863    }
14864
14865    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14866    pub fn clear_row_highlights<T: 'static>(&mut self) {
14867        self.highlighted_rows.remove(&TypeId::of::<T>());
14868    }
14869
14870    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14871    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14872        self.highlighted_rows
14873            .get(&TypeId::of::<T>())
14874            .map_or(&[] as &[_], |vec| vec.as_slice())
14875            .iter()
14876            .map(|highlight| (highlight.range.clone(), highlight.color))
14877    }
14878
14879    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14880    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14881    /// Allows to ignore certain kinds of highlights.
14882    pub fn highlighted_display_rows(
14883        &self,
14884        window: &mut Window,
14885        cx: &mut App,
14886    ) -> BTreeMap<DisplayRow, Background> {
14887        let snapshot = self.snapshot(window, cx);
14888        let mut used_highlight_orders = HashMap::default();
14889        self.highlighted_rows
14890            .iter()
14891            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14892            .fold(
14893                BTreeMap::<DisplayRow, Background>::new(),
14894                |mut unique_rows, highlight| {
14895                    let start = highlight.range.start.to_display_point(&snapshot);
14896                    let end = highlight.range.end.to_display_point(&snapshot);
14897                    let start_row = start.row().0;
14898                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14899                        && end.column() == 0
14900                    {
14901                        end.row().0.saturating_sub(1)
14902                    } else {
14903                        end.row().0
14904                    };
14905                    for row in start_row..=end_row {
14906                        let used_index =
14907                            used_highlight_orders.entry(row).or_insert(highlight.index);
14908                        if highlight.index >= *used_index {
14909                            *used_index = highlight.index;
14910                            unique_rows.insert(DisplayRow(row), highlight.color.into());
14911                        }
14912                    }
14913                    unique_rows
14914                },
14915            )
14916    }
14917
14918    pub fn highlighted_display_row_for_autoscroll(
14919        &self,
14920        snapshot: &DisplaySnapshot,
14921    ) -> Option<DisplayRow> {
14922        self.highlighted_rows
14923            .values()
14924            .flat_map(|highlighted_rows| highlighted_rows.iter())
14925            .filter_map(|highlight| {
14926                if highlight.should_autoscroll {
14927                    Some(highlight.range.start.to_display_point(snapshot).row())
14928                } else {
14929                    None
14930                }
14931            })
14932            .min()
14933    }
14934
14935    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14936        self.highlight_background::<SearchWithinRange>(
14937            ranges,
14938            |colors| colors.editor_document_highlight_read_background,
14939            cx,
14940        )
14941    }
14942
14943    pub fn set_breadcrumb_header(&mut self, new_header: String) {
14944        self.breadcrumb_header = Some(new_header);
14945    }
14946
14947    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14948        self.clear_background_highlights::<SearchWithinRange>(cx);
14949    }
14950
14951    pub fn highlight_background<T: 'static>(
14952        &mut self,
14953        ranges: &[Range<Anchor>],
14954        color_fetcher: fn(&ThemeColors) -> Hsla,
14955        cx: &mut Context<Self>,
14956    ) {
14957        self.background_highlights
14958            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14959        self.scrollbar_marker_state.dirty = true;
14960        cx.notify();
14961    }
14962
14963    pub fn clear_background_highlights<T: 'static>(
14964        &mut self,
14965        cx: &mut Context<Self>,
14966    ) -> Option<BackgroundHighlight> {
14967        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14968        if !text_highlights.1.is_empty() {
14969            self.scrollbar_marker_state.dirty = true;
14970            cx.notify();
14971        }
14972        Some(text_highlights)
14973    }
14974
14975    pub fn highlight_gutter<T: 'static>(
14976        &mut self,
14977        ranges: &[Range<Anchor>],
14978        color_fetcher: fn(&App) -> Hsla,
14979        cx: &mut Context<Self>,
14980    ) {
14981        self.gutter_highlights
14982            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14983        cx.notify();
14984    }
14985
14986    pub fn clear_gutter_highlights<T: 'static>(
14987        &mut self,
14988        cx: &mut Context<Self>,
14989    ) -> Option<GutterHighlight> {
14990        cx.notify();
14991        self.gutter_highlights.remove(&TypeId::of::<T>())
14992    }
14993
14994    #[cfg(feature = "test-support")]
14995    pub fn all_text_background_highlights(
14996        &self,
14997        window: &mut Window,
14998        cx: &mut Context<Self>,
14999    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15000        let snapshot = self.snapshot(window, cx);
15001        let buffer = &snapshot.buffer_snapshot;
15002        let start = buffer.anchor_before(0);
15003        let end = buffer.anchor_after(buffer.len());
15004        let theme = cx.theme().colors();
15005        self.background_highlights_in_range(start..end, &snapshot, theme)
15006    }
15007
15008    #[cfg(feature = "test-support")]
15009    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
15010        let snapshot = self.buffer().read(cx).snapshot(cx);
15011
15012        let highlights = self
15013            .background_highlights
15014            .get(&TypeId::of::<items::BufferSearchHighlights>());
15015
15016        if let Some((_color, ranges)) = highlights {
15017            ranges
15018                .iter()
15019                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
15020                .collect_vec()
15021        } else {
15022            vec![]
15023        }
15024    }
15025
15026    fn document_highlights_for_position<'a>(
15027        &'a self,
15028        position: Anchor,
15029        buffer: &'a MultiBufferSnapshot,
15030    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
15031        let read_highlights = self
15032            .background_highlights
15033            .get(&TypeId::of::<DocumentHighlightRead>())
15034            .map(|h| &h.1);
15035        let write_highlights = self
15036            .background_highlights
15037            .get(&TypeId::of::<DocumentHighlightWrite>())
15038            .map(|h| &h.1);
15039        let left_position = position.bias_left(buffer);
15040        let right_position = position.bias_right(buffer);
15041        read_highlights
15042            .into_iter()
15043            .chain(write_highlights)
15044            .flat_map(move |ranges| {
15045                let start_ix = match ranges.binary_search_by(|probe| {
15046                    let cmp = probe.end.cmp(&left_position, buffer);
15047                    if cmp.is_ge() {
15048                        Ordering::Greater
15049                    } else {
15050                        Ordering::Less
15051                    }
15052                }) {
15053                    Ok(i) | Err(i) => i,
15054                };
15055
15056                ranges[start_ix..]
15057                    .iter()
15058                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
15059            })
15060    }
15061
15062    pub fn has_background_highlights<T: 'static>(&self) -> bool {
15063        self.background_highlights
15064            .get(&TypeId::of::<T>())
15065            .map_or(false, |(_, highlights)| !highlights.is_empty())
15066    }
15067
15068    pub fn background_highlights_in_range(
15069        &self,
15070        search_range: Range<Anchor>,
15071        display_snapshot: &DisplaySnapshot,
15072        theme: &ThemeColors,
15073    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15074        let mut results = Vec::new();
15075        for (color_fetcher, ranges) in self.background_highlights.values() {
15076            let color = color_fetcher(theme);
15077            let start_ix = match ranges.binary_search_by(|probe| {
15078                let cmp = probe
15079                    .end
15080                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15081                if cmp.is_gt() {
15082                    Ordering::Greater
15083                } else {
15084                    Ordering::Less
15085                }
15086            }) {
15087                Ok(i) | Err(i) => i,
15088            };
15089            for range in &ranges[start_ix..] {
15090                if range
15091                    .start
15092                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15093                    .is_ge()
15094                {
15095                    break;
15096                }
15097
15098                let start = range.start.to_display_point(display_snapshot);
15099                let end = range.end.to_display_point(display_snapshot);
15100                results.push((start..end, color))
15101            }
15102        }
15103        results
15104    }
15105
15106    pub fn background_highlight_row_ranges<T: 'static>(
15107        &self,
15108        search_range: Range<Anchor>,
15109        display_snapshot: &DisplaySnapshot,
15110        count: usize,
15111    ) -> Vec<RangeInclusive<DisplayPoint>> {
15112        let mut results = Vec::new();
15113        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15114            return vec![];
15115        };
15116
15117        let start_ix = match ranges.binary_search_by(|probe| {
15118            let cmp = probe
15119                .end
15120                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15121            if cmp.is_gt() {
15122                Ordering::Greater
15123            } else {
15124                Ordering::Less
15125            }
15126        }) {
15127            Ok(i) | Err(i) => i,
15128        };
15129        let mut push_region = |start: Option<Point>, end: Option<Point>| {
15130            if let (Some(start_display), Some(end_display)) = (start, end) {
15131                results.push(
15132                    start_display.to_display_point(display_snapshot)
15133                        ..=end_display.to_display_point(display_snapshot),
15134                );
15135            }
15136        };
15137        let mut start_row: Option<Point> = None;
15138        let mut end_row: Option<Point> = None;
15139        if ranges.len() > count {
15140            return Vec::new();
15141        }
15142        for range in &ranges[start_ix..] {
15143            if range
15144                .start
15145                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15146                .is_ge()
15147            {
15148                break;
15149            }
15150            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15151            if let Some(current_row) = &end_row {
15152                if end.row == current_row.row {
15153                    continue;
15154                }
15155            }
15156            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15157            if start_row.is_none() {
15158                assert_eq!(end_row, None);
15159                start_row = Some(start);
15160                end_row = Some(end);
15161                continue;
15162            }
15163            if let Some(current_end) = end_row.as_mut() {
15164                if start.row > current_end.row + 1 {
15165                    push_region(start_row, end_row);
15166                    start_row = Some(start);
15167                    end_row = Some(end);
15168                } else {
15169                    // Merge two hunks.
15170                    *current_end = end;
15171                }
15172            } else {
15173                unreachable!();
15174            }
15175        }
15176        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15177        push_region(start_row, end_row);
15178        results
15179    }
15180
15181    pub fn gutter_highlights_in_range(
15182        &self,
15183        search_range: Range<Anchor>,
15184        display_snapshot: &DisplaySnapshot,
15185        cx: &App,
15186    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15187        let mut results = Vec::new();
15188        for (color_fetcher, ranges) in self.gutter_highlights.values() {
15189            let color = color_fetcher(cx);
15190            let start_ix = match ranges.binary_search_by(|probe| {
15191                let cmp = probe
15192                    .end
15193                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15194                if cmp.is_gt() {
15195                    Ordering::Greater
15196                } else {
15197                    Ordering::Less
15198                }
15199            }) {
15200                Ok(i) | Err(i) => i,
15201            };
15202            for range in &ranges[start_ix..] {
15203                if range
15204                    .start
15205                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15206                    .is_ge()
15207                {
15208                    break;
15209                }
15210
15211                let start = range.start.to_display_point(display_snapshot);
15212                let end = range.end.to_display_point(display_snapshot);
15213                results.push((start..end, color))
15214            }
15215        }
15216        results
15217    }
15218
15219    /// Get the text ranges corresponding to the redaction query
15220    pub fn redacted_ranges(
15221        &self,
15222        search_range: Range<Anchor>,
15223        display_snapshot: &DisplaySnapshot,
15224        cx: &App,
15225    ) -> Vec<Range<DisplayPoint>> {
15226        display_snapshot
15227            .buffer_snapshot
15228            .redacted_ranges(search_range, |file| {
15229                if let Some(file) = file {
15230                    file.is_private()
15231                        && EditorSettings::get(
15232                            Some(SettingsLocation {
15233                                worktree_id: file.worktree_id(cx),
15234                                path: file.path().as_ref(),
15235                            }),
15236                            cx,
15237                        )
15238                        .redact_private_values
15239                } else {
15240                    false
15241                }
15242            })
15243            .map(|range| {
15244                range.start.to_display_point(display_snapshot)
15245                    ..range.end.to_display_point(display_snapshot)
15246            })
15247            .collect()
15248    }
15249
15250    pub fn highlight_text<T: 'static>(
15251        &mut self,
15252        ranges: Vec<Range<Anchor>>,
15253        style: HighlightStyle,
15254        cx: &mut Context<Self>,
15255    ) {
15256        self.display_map.update(cx, |map, _| {
15257            map.highlight_text(TypeId::of::<T>(), ranges, style)
15258        });
15259        cx.notify();
15260    }
15261
15262    pub(crate) fn highlight_inlays<T: 'static>(
15263        &mut self,
15264        highlights: Vec<InlayHighlight>,
15265        style: HighlightStyle,
15266        cx: &mut Context<Self>,
15267    ) {
15268        self.display_map.update(cx, |map, _| {
15269            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15270        });
15271        cx.notify();
15272    }
15273
15274    pub fn text_highlights<'a, T: 'static>(
15275        &'a self,
15276        cx: &'a App,
15277    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15278        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15279    }
15280
15281    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15282        let cleared = self
15283            .display_map
15284            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15285        if cleared {
15286            cx.notify();
15287        }
15288    }
15289
15290    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15291        (self.read_only(cx) || self.blink_manager.read(cx).visible())
15292            && self.focus_handle.is_focused(window)
15293    }
15294
15295    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15296        self.show_cursor_when_unfocused = is_enabled;
15297        cx.notify();
15298    }
15299
15300    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15301        cx.notify();
15302    }
15303
15304    fn on_buffer_event(
15305        &mut self,
15306        multibuffer: &Entity<MultiBuffer>,
15307        event: &multi_buffer::Event,
15308        window: &mut Window,
15309        cx: &mut Context<Self>,
15310    ) {
15311        match event {
15312            multi_buffer::Event::Edited {
15313                singleton_buffer_edited,
15314                edited_buffer: buffer_edited,
15315            } => {
15316                self.scrollbar_marker_state.dirty = true;
15317                self.active_indent_guides_state.dirty = true;
15318                self.refresh_active_diagnostics(cx);
15319                self.refresh_code_actions(window, cx);
15320                if self.has_active_inline_completion() {
15321                    self.update_visible_inline_completion(window, cx);
15322                }
15323                if let Some(buffer) = buffer_edited {
15324                    let buffer_id = buffer.read(cx).remote_id();
15325                    if !self.registered_buffers.contains_key(&buffer_id) {
15326                        if let Some(project) = self.project.as_ref() {
15327                            project.update(cx, |project, cx| {
15328                                self.registered_buffers.insert(
15329                                    buffer_id,
15330                                    project.register_buffer_with_language_servers(&buffer, cx),
15331                                );
15332                            })
15333                        }
15334                    }
15335                }
15336                cx.emit(EditorEvent::BufferEdited);
15337                cx.emit(SearchEvent::MatchesInvalidated);
15338                if *singleton_buffer_edited {
15339                    if let Some(project) = &self.project {
15340                        #[allow(clippy::mutable_key_type)]
15341                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15342                            multibuffer
15343                                .all_buffers()
15344                                .into_iter()
15345                                .filter_map(|buffer| {
15346                                    buffer.update(cx, |buffer, cx| {
15347                                        let language = buffer.language()?;
15348                                        let should_discard = project.update(cx, |project, cx| {
15349                                            project.is_local()
15350                                                && !project.has_language_servers_for(buffer, cx)
15351                                        });
15352                                        should_discard.not().then_some(language.clone())
15353                                    })
15354                                })
15355                                .collect::<HashSet<_>>()
15356                        });
15357                        if !languages_affected.is_empty() {
15358                            self.refresh_inlay_hints(
15359                                InlayHintRefreshReason::BufferEdited(languages_affected),
15360                                cx,
15361                            );
15362                        }
15363                    }
15364                }
15365
15366                let Some(project) = &self.project else { return };
15367                let (telemetry, is_via_ssh) = {
15368                    let project = project.read(cx);
15369                    let telemetry = project.client().telemetry().clone();
15370                    let is_via_ssh = project.is_via_ssh();
15371                    (telemetry, is_via_ssh)
15372                };
15373                refresh_linked_ranges(self, window, cx);
15374                telemetry.log_edit_event("editor", is_via_ssh);
15375            }
15376            multi_buffer::Event::ExcerptsAdded {
15377                buffer,
15378                predecessor,
15379                excerpts,
15380            } => {
15381                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15382                let buffer_id = buffer.read(cx).remote_id();
15383                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15384                    if let Some(project) = &self.project {
15385                        get_uncommitted_diff_for_buffer(
15386                            project,
15387                            [buffer.clone()],
15388                            self.buffer.clone(),
15389                            cx,
15390                        )
15391                        .detach();
15392                    }
15393                }
15394                cx.emit(EditorEvent::ExcerptsAdded {
15395                    buffer: buffer.clone(),
15396                    predecessor: *predecessor,
15397                    excerpts: excerpts.clone(),
15398                });
15399                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15400            }
15401            multi_buffer::Event::ExcerptsRemoved { ids } => {
15402                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15403                let buffer = self.buffer.read(cx);
15404                self.registered_buffers
15405                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15406                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15407                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15408            }
15409            multi_buffer::Event::ExcerptsEdited {
15410                excerpt_ids,
15411                buffer_ids,
15412            } => {
15413                self.display_map.update(cx, |map, cx| {
15414                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
15415                });
15416                cx.emit(EditorEvent::ExcerptsEdited {
15417                    ids: excerpt_ids.clone(),
15418                })
15419            }
15420            multi_buffer::Event::ExcerptsExpanded { ids } => {
15421                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15422                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15423            }
15424            multi_buffer::Event::Reparsed(buffer_id) => {
15425                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15426                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15427
15428                cx.emit(EditorEvent::Reparsed(*buffer_id));
15429            }
15430            multi_buffer::Event::DiffHunksToggled => {
15431                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15432            }
15433            multi_buffer::Event::LanguageChanged(buffer_id) => {
15434                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15435                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15436                cx.emit(EditorEvent::Reparsed(*buffer_id));
15437                cx.notify();
15438            }
15439            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15440            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15441            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15442                cx.emit(EditorEvent::TitleChanged)
15443            }
15444            // multi_buffer::Event::DiffBaseChanged => {
15445            //     self.scrollbar_marker_state.dirty = true;
15446            //     cx.emit(EditorEvent::DiffBaseChanged);
15447            //     cx.notify();
15448            // }
15449            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15450            multi_buffer::Event::DiagnosticsUpdated => {
15451                self.refresh_active_diagnostics(cx);
15452                self.refresh_inline_diagnostics(true, window, cx);
15453                self.scrollbar_marker_state.dirty = true;
15454                cx.notify();
15455            }
15456            _ => {}
15457        };
15458    }
15459
15460    fn on_display_map_changed(
15461        &mut self,
15462        _: Entity<DisplayMap>,
15463        _: &mut Window,
15464        cx: &mut Context<Self>,
15465    ) {
15466        cx.notify();
15467    }
15468
15469    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15470        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15471        self.update_edit_prediction_settings(cx);
15472        self.refresh_inline_completion(true, false, window, cx);
15473        self.refresh_inlay_hints(
15474            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15475                self.selections.newest_anchor().head(),
15476                &self.buffer.read(cx).snapshot(cx),
15477                cx,
15478            )),
15479            cx,
15480        );
15481
15482        let old_cursor_shape = self.cursor_shape;
15483
15484        {
15485            let editor_settings = EditorSettings::get_global(cx);
15486            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15487            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15488            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15489        }
15490
15491        if old_cursor_shape != self.cursor_shape {
15492            cx.emit(EditorEvent::CursorShapeChanged);
15493        }
15494
15495        let project_settings = ProjectSettings::get_global(cx);
15496        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15497
15498        if self.mode == EditorMode::Full {
15499            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15500            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15501            if self.show_inline_diagnostics != show_inline_diagnostics {
15502                self.show_inline_diagnostics = show_inline_diagnostics;
15503                self.refresh_inline_diagnostics(false, window, cx);
15504            }
15505
15506            if self.git_blame_inline_enabled != inline_blame_enabled {
15507                self.toggle_git_blame_inline_internal(false, window, cx);
15508            }
15509        }
15510
15511        cx.notify();
15512    }
15513
15514    pub fn set_searchable(&mut self, searchable: bool) {
15515        self.searchable = searchable;
15516    }
15517
15518    pub fn searchable(&self) -> bool {
15519        self.searchable
15520    }
15521
15522    fn open_proposed_changes_editor(
15523        &mut self,
15524        _: &OpenProposedChangesEditor,
15525        window: &mut Window,
15526        cx: &mut Context<Self>,
15527    ) {
15528        let Some(workspace) = self.workspace() else {
15529            cx.propagate();
15530            return;
15531        };
15532
15533        let selections = self.selections.all::<usize>(cx);
15534        let multi_buffer = self.buffer.read(cx);
15535        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15536        let mut new_selections_by_buffer = HashMap::default();
15537        for selection in selections {
15538            for (buffer, range, _) in
15539                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15540            {
15541                let mut range = range.to_point(buffer);
15542                range.start.column = 0;
15543                range.end.column = buffer.line_len(range.end.row);
15544                new_selections_by_buffer
15545                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15546                    .or_insert(Vec::new())
15547                    .push(range)
15548            }
15549        }
15550
15551        let proposed_changes_buffers = new_selections_by_buffer
15552            .into_iter()
15553            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15554            .collect::<Vec<_>>();
15555        let proposed_changes_editor = cx.new(|cx| {
15556            ProposedChangesEditor::new(
15557                "Proposed changes",
15558                proposed_changes_buffers,
15559                self.project.clone(),
15560                window,
15561                cx,
15562            )
15563        });
15564
15565        window.defer(cx, move |window, cx| {
15566            workspace.update(cx, |workspace, cx| {
15567                workspace.active_pane().update(cx, |pane, cx| {
15568                    pane.add_item(
15569                        Box::new(proposed_changes_editor),
15570                        true,
15571                        true,
15572                        None,
15573                        window,
15574                        cx,
15575                    );
15576                });
15577            });
15578        });
15579    }
15580
15581    pub fn open_excerpts_in_split(
15582        &mut self,
15583        _: &OpenExcerptsSplit,
15584        window: &mut Window,
15585        cx: &mut Context<Self>,
15586    ) {
15587        self.open_excerpts_common(None, true, window, cx)
15588    }
15589
15590    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15591        self.open_excerpts_common(None, false, window, cx)
15592    }
15593
15594    fn open_excerpts_common(
15595        &mut self,
15596        jump_data: Option<JumpData>,
15597        split: bool,
15598        window: &mut Window,
15599        cx: &mut Context<Self>,
15600    ) {
15601        let Some(workspace) = self.workspace() else {
15602            cx.propagate();
15603            return;
15604        };
15605
15606        if self.buffer.read(cx).is_singleton() {
15607            cx.propagate();
15608            return;
15609        }
15610
15611        let mut new_selections_by_buffer = HashMap::default();
15612        match &jump_data {
15613            Some(JumpData::MultiBufferPoint {
15614                excerpt_id,
15615                position,
15616                anchor,
15617                line_offset_from_top,
15618            }) => {
15619                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15620                if let Some(buffer) = multi_buffer_snapshot
15621                    .buffer_id_for_excerpt(*excerpt_id)
15622                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15623                {
15624                    let buffer_snapshot = buffer.read(cx).snapshot();
15625                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15626                        language::ToPoint::to_point(anchor, &buffer_snapshot)
15627                    } else {
15628                        buffer_snapshot.clip_point(*position, Bias::Left)
15629                    };
15630                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15631                    new_selections_by_buffer.insert(
15632                        buffer,
15633                        (
15634                            vec![jump_to_offset..jump_to_offset],
15635                            Some(*line_offset_from_top),
15636                        ),
15637                    );
15638                }
15639            }
15640            Some(JumpData::MultiBufferRow {
15641                row,
15642                line_offset_from_top,
15643            }) => {
15644                let point = MultiBufferPoint::new(row.0, 0);
15645                if let Some((buffer, buffer_point, _)) =
15646                    self.buffer.read(cx).point_to_buffer_point(point, cx)
15647                {
15648                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15649                    new_selections_by_buffer
15650                        .entry(buffer)
15651                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
15652                        .0
15653                        .push(buffer_offset..buffer_offset)
15654                }
15655            }
15656            None => {
15657                let selections = self.selections.all::<usize>(cx);
15658                let multi_buffer = self.buffer.read(cx);
15659                for selection in selections {
15660                    for (snapshot, range, _, anchor) in multi_buffer
15661                        .snapshot(cx)
15662                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15663                    {
15664                        if let Some(anchor) = anchor {
15665                            // selection is in a deleted hunk
15666                            let Some(buffer_id) = anchor.buffer_id else {
15667                                continue;
15668                            };
15669                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15670                                continue;
15671                            };
15672                            let offset = text::ToOffset::to_offset(
15673                                &anchor.text_anchor,
15674                                &buffer_handle.read(cx).snapshot(),
15675                            );
15676                            let range = offset..offset;
15677                            new_selections_by_buffer
15678                                .entry(buffer_handle)
15679                                .or_insert((Vec::new(), None))
15680                                .0
15681                                .push(range)
15682                        } else {
15683                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15684                            else {
15685                                continue;
15686                            };
15687                            new_selections_by_buffer
15688                                .entry(buffer_handle)
15689                                .or_insert((Vec::new(), None))
15690                                .0
15691                                .push(range)
15692                        }
15693                    }
15694                }
15695            }
15696        }
15697
15698        if new_selections_by_buffer.is_empty() {
15699            return;
15700        }
15701
15702        // We defer the pane interaction because we ourselves are a workspace item
15703        // and activating a new item causes the pane to call a method on us reentrantly,
15704        // which panics if we're on the stack.
15705        window.defer(cx, move |window, cx| {
15706            workspace.update(cx, |workspace, cx| {
15707                let pane = if split {
15708                    workspace.adjacent_pane(window, cx)
15709                } else {
15710                    workspace.active_pane().clone()
15711                };
15712
15713                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15714                    let editor = buffer
15715                        .read(cx)
15716                        .file()
15717                        .is_none()
15718                        .then(|| {
15719                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15720                            // so `workspace.open_project_item` will never find them, always opening a new editor.
15721                            // Instead, we try to activate the existing editor in the pane first.
15722                            let (editor, pane_item_index) =
15723                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
15724                                    let editor = item.downcast::<Editor>()?;
15725                                    let singleton_buffer =
15726                                        editor.read(cx).buffer().read(cx).as_singleton()?;
15727                                    if singleton_buffer == buffer {
15728                                        Some((editor, i))
15729                                    } else {
15730                                        None
15731                                    }
15732                                })?;
15733                            pane.update(cx, |pane, cx| {
15734                                pane.activate_item(pane_item_index, true, true, window, cx)
15735                            });
15736                            Some(editor)
15737                        })
15738                        .flatten()
15739                        .unwrap_or_else(|| {
15740                            workspace.open_project_item::<Self>(
15741                                pane.clone(),
15742                                buffer,
15743                                true,
15744                                true,
15745                                window,
15746                                cx,
15747                            )
15748                        });
15749
15750                    editor.update(cx, |editor, cx| {
15751                        let autoscroll = match scroll_offset {
15752                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15753                            None => Autoscroll::newest(),
15754                        };
15755                        let nav_history = editor.nav_history.take();
15756                        editor.change_selections(Some(autoscroll), window, cx, |s| {
15757                            s.select_ranges(ranges);
15758                        });
15759                        editor.nav_history = nav_history;
15760                    });
15761                }
15762            })
15763        });
15764    }
15765
15766    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15767        let snapshot = self.buffer.read(cx).read(cx);
15768        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15769        Some(
15770            ranges
15771                .iter()
15772                .map(move |range| {
15773                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15774                })
15775                .collect(),
15776        )
15777    }
15778
15779    fn selection_replacement_ranges(
15780        &self,
15781        range: Range<OffsetUtf16>,
15782        cx: &mut App,
15783    ) -> Vec<Range<OffsetUtf16>> {
15784        let selections = self.selections.all::<OffsetUtf16>(cx);
15785        let newest_selection = selections
15786            .iter()
15787            .max_by_key(|selection| selection.id)
15788            .unwrap();
15789        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15790        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15791        let snapshot = self.buffer.read(cx).read(cx);
15792        selections
15793            .into_iter()
15794            .map(|mut selection| {
15795                selection.start.0 =
15796                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
15797                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15798                snapshot.clip_offset_utf16(selection.start, Bias::Left)
15799                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15800            })
15801            .collect()
15802    }
15803
15804    fn report_editor_event(
15805        &self,
15806        event_type: &'static str,
15807        file_extension: Option<String>,
15808        cx: &App,
15809    ) {
15810        if cfg!(any(test, feature = "test-support")) {
15811            return;
15812        }
15813
15814        let Some(project) = &self.project else { return };
15815
15816        // If None, we are in a file without an extension
15817        let file = self
15818            .buffer
15819            .read(cx)
15820            .as_singleton()
15821            .and_then(|b| b.read(cx).file());
15822        let file_extension = file_extension.or(file
15823            .as_ref()
15824            .and_then(|file| Path::new(file.file_name(cx)).extension())
15825            .and_then(|e| e.to_str())
15826            .map(|a| a.to_string()));
15827
15828        let vim_mode = cx
15829            .global::<SettingsStore>()
15830            .raw_user_settings()
15831            .get("vim_mode")
15832            == Some(&serde_json::Value::Bool(true));
15833
15834        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15835        let copilot_enabled = edit_predictions_provider
15836            == language::language_settings::EditPredictionProvider::Copilot;
15837        let copilot_enabled_for_language = self
15838            .buffer
15839            .read(cx)
15840            .language_settings(cx)
15841            .show_edit_predictions;
15842
15843        let project = project.read(cx);
15844        telemetry::event!(
15845            event_type,
15846            file_extension,
15847            vim_mode,
15848            copilot_enabled,
15849            copilot_enabled_for_language,
15850            edit_predictions_provider,
15851            is_via_ssh = project.is_via_ssh(),
15852        );
15853    }
15854
15855    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15856    /// with each line being an array of {text, highlight} objects.
15857    fn copy_highlight_json(
15858        &mut self,
15859        _: &CopyHighlightJson,
15860        window: &mut Window,
15861        cx: &mut Context<Self>,
15862    ) {
15863        #[derive(Serialize)]
15864        struct Chunk<'a> {
15865            text: String,
15866            highlight: Option<&'a str>,
15867        }
15868
15869        let snapshot = self.buffer.read(cx).snapshot(cx);
15870        let range = self
15871            .selected_text_range(false, window, cx)
15872            .and_then(|selection| {
15873                if selection.range.is_empty() {
15874                    None
15875                } else {
15876                    Some(selection.range)
15877                }
15878            })
15879            .unwrap_or_else(|| 0..snapshot.len());
15880
15881        let chunks = snapshot.chunks(range, true);
15882        let mut lines = Vec::new();
15883        let mut line: VecDeque<Chunk> = VecDeque::new();
15884
15885        let Some(style) = self.style.as_ref() else {
15886            return;
15887        };
15888
15889        for chunk in chunks {
15890            let highlight = chunk
15891                .syntax_highlight_id
15892                .and_then(|id| id.name(&style.syntax));
15893            let mut chunk_lines = chunk.text.split('\n').peekable();
15894            while let Some(text) = chunk_lines.next() {
15895                let mut merged_with_last_token = false;
15896                if let Some(last_token) = line.back_mut() {
15897                    if last_token.highlight == highlight {
15898                        last_token.text.push_str(text);
15899                        merged_with_last_token = true;
15900                    }
15901                }
15902
15903                if !merged_with_last_token {
15904                    line.push_back(Chunk {
15905                        text: text.into(),
15906                        highlight,
15907                    });
15908                }
15909
15910                if chunk_lines.peek().is_some() {
15911                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
15912                        line.pop_front();
15913                    }
15914                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
15915                        line.pop_back();
15916                    }
15917
15918                    lines.push(mem::take(&mut line));
15919                }
15920            }
15921        }
15922
15923        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15924            return;
15925        };
15926        cx.write_to_clipboard(ClipboardItem::new_string(lines));
15927    }
15928
15929    pub fn open_context_menu(
15930        &mut self,
15931        _: &OpenContextMenu,
15932        window: &mut Window,
15933        cx: &mut Context<Self>,
15934    ) {
15935        self.request_autoscroll(Autoscroll::newest(), cx);
15936        let position = self.selections.newest_display(cx).start;
15937        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15938    }
15939
15940    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15941        &self.inlay_hint_cache
15942    }
15943
15944    pub fn replay_insert_event(
15945        &mut self,
15946        text: &str,
15947        relative_utf16_range: Option<Range<isize>>,
15948        window: &mut Window,
15949        cx: &mut Context<Self>,
15950    ) {
15951        if !self.input_enabled {
15952            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15953            return;
15954        }
15955        if let Some(relative_utf16_range) = relative_utf16_range {
15956            let selections = self.selections.all::<OffsetUtf16>(cx);
15957            self.change_selections(None, window, cx, |s| {
15958                let new_ranges = selections.into_iter().map(|range| {
15959                    let start = OffsetUtf16(
15960                        range
15961                            .head()
15962                            .0
15963                            .saturating_add_signed(relative_utf16_range.start),
15964                    );
15965                    let end = OffsetUtf16(
15966                        range
15967                            .head()
15968                            .0
15969                            .saturating_add_signed(relative_utf16_range.end),
15970                    );
15971                    start..end
15972                });
15973                s.select_ranges(new_ranges);
15974            });
15975        }
15976
15977        self.handle_input(text, window, cx);
15978    }
15979
15980    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15981        let Some(provider) = self.semantics_provider.as_ref() else {
15982            return false;
15983        };
15984
15985        let mut supports = false;
15986        self.buffer().update(cx, |this, cx| {
15987            this.for_each_buffer(|buffer| {
15988                supports |= provider.supports_inlay_hints(buffer, cx);
15989            });
15990        });
15991
15992        supports
15993    }
15994
15995    pub fn is_focused(&self, window: &Window) -> bool {
15996        self.focus_handle.is_focused(window)
15997    }
15998
15999    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16000        cx.emit(EditorEvent::Focused);
16001
16002        if let Some(descendant) = self
16003            .last_focused_descendant
16004            .take()
16005            .and_then(|descendant| descendant.upgrade())
16006        {
16007            window.focus(&descendant);
16008        } else {
16009            if let Some(blame) = self.blame.as_ref() {
16010                blame.update(cx, GitBlame::focus)
16011            }
16012
16013            self.blink_manager.update(cx, BlinkManager::enable);
16014            self.show_cursor_names(window, cx);
16015            self.buffer.update(cx, |buffer, cx| {
16016                buffer.finalize_last_transaction(cx);
16017                if self.leader_peer_id.is_none() {
16018                    buffer.set_active_selections(
16019                        &self.selections.disjoint_anchors(),
16020                        self.selections.line_mode,
16021                        self.cursor_shape,
16022                        cx,
16023                    );
16024                }
16025            });
16026        }
16027    }
16028
16029    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16030        cx.emit(EditorEvent::FocusedIn)
16031    }
16032
16033    fn handle_focus_out(
16034        &mut self,
16035        event: FocusOutEvent,
16036        _window: &mut Window,
16037        cx: &mut Context<Self>,
16038    ) {
16039        if event.blurred != self.focus_handle {
16040            self.last_focused_descendant = Some(event.blurred);
16041        }
16042        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
16043    }
16044
16045    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16046        self.blink_manager.update(cx, BlinkManager::disable);
16047        self.buffer
16048            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
16049
16050        if let Some(blame) = self.blame.as_ref() {
16051            blame.update(cx, GitBlame::blur)
16052        }
16053        if !self.hover_state.focused(window, cx) {
16054            hide_hover(self, cx);
16055        }
16056        if !self
16057            .context_menu
16058            .borrow()
16059            .as_ref()
16060            .is_some_and(|context_menu| context_menu.focused(window, cx))
16061        {
16062            self.hide_context_menu(window, cx);
16063        }
16064        self.discard_inline_completion(false, cx);
16065        cx.emit(EditorEvent::Blurred);
16066        cx.notify();
16067    }
16068
16069    pub fn register_action<A: Action>(
16070        &mut self,
16071        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
16072    ) -> Subscription {
16073        let id = self.next_editor_action_id.post_inc();
16074        let listener = Arc::new(listener);
16075        self.editor_actions.borrow_mut().insert(
16076            id,
16077            Box::new(move |window, _| {
16078                let listener = listener.clone();
16079                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
16080                    let action = action.downcast_ref().unwrap();
16081                    if phase == DispatchPhase::Bubble {
16082                        listener(action, window, cx)
16083                    }
16084                })
16085            }),
16086        );
16087
16088        let editor_actions = self.editor_actions.clone();
16089        Subscription::new(move || {
16090            editor_actions.borrow_mut().remove(&id);
16091        })
16092    }
16093
16094    pub fn file_header_size(&self) -> u32 {
16095        FILE_HEADER_HEIGHT
16096    }
16097
16098    pub fn restore(
16099        &mut self,
16100        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16101        window: &mut Window,
16102        cx: &mut Context<Self>,
16103    ) {
16104        let workspace = self.workspace();
16105        let project = self.project.as_ref();
16106        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16107            let mut tasks = Vec::new();
16108            for (buffer_id, changes) in revert_changes {
16109                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16110                    buffer.update(cx, |buffer, cx| {
16111                        buffer.edit(
16112                            changes
16113                                .into_iter()
16114                                .map(|(range, text)| (range, text.to_string())),
16115                            None,
16116                            cx,
16117                        );
16118                    });
16119
16120                    if let Some(project) =
16121                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16122                    {
16123                        project.update(cx, |project, cx| {
16124                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16125                        })
16126                    }
16127                }
16128            }
16129            tasks
16130        });
16131        cx.spawn_in(window, |_, mut cx| async move {
16132            for (buffer, task) in save_tasks {
16133                let result = task.await;
16134                if result.is_err() {
16135                    let Some(path) = buffer
16136                        .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16137                        .ok()
16138                    else {
16139                        continue;
16140                    };
16141                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16142                        let Some(task) = cx
16143                            .update_window_entity(&workspace, |workspace, window, cx| {
16144                                workspace
16145                                    .open_path_preview(path, None, false, false, false, window, cx)
16146                            })
16147                            .ok()
16148                        else {
16149                            continue;
16150                        };
16151                        task.await.log_err();
16152                    }
16153                }
16154            }
16155        })
16156        .detach();
16157        self.change_selections(None, window, cx, |selections| selections.refresh());
16158    }
16159
16160    pub fn to_pixel_point(
16161        &self,
16162        source: multi_buffer::Anchor,
16163        editor_snapshot: &EditorSnapshot,
16164        window: &mut Window,
16165    ) -> Option<gpui::Point<Pixels>> {
16166        let source_point = source.to_display_point(editor_snapshot);
16167        self.display_to_pixel_point(source_point, editor_snapshot, window)
16168    }
16169
16170    pub fn display_to_pixel_point(
16171        &self,
16172        source: DisplayPoint,
16173        editor_snapshot: &EditorSnapshot,
16174        window: &mut Window,
16175    ) -> Option<gpui::Point<Pixels>> {
16176        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16177        let text_layout_details = self.text_layout_details(window);
16178        let scroll_top = text_layout_details
16179            .scroll_anchor
16180            .scroll_position(editor_snapshot)
16181            .y;
16182
16183        if source.row().as_f32() < scroll_top.floor() {
16184            return None;
16185        }
16186        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16187        let source_y = line_height * (source.row().as_f32() - scroll_top);
16188        Some(gpui::Point::new(source_x, source_y))
16189    }
16190
16191    pub fn has_visible_completions_menu(&self) -> bool {
16192        !self.edit_prediction_preview_is_active()
16193            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16194                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16195            })
16196    }
16197
16198    pub fn register_addon<T: Addon>(&mut self, instance: T) {
16199        self.addons
16200            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16201    }
16202
16203    pub fn unregister_addon<T: Addon>(&mut self) {
16204        self.addons.remove(&std::any::TypeId::of::<T>());
16205    }
16206
16207    pub fn addon<T: Addon>(&self) -> Option<&T> {
16208        let type_id = std::any::TypeId::of::<T>();
16209        self.addons
16210            .get(&type_id)
16211            .and_then(|item| item.to_any().downcast_ref::<T>())
16212    }
16213
16214    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16215        let text_layout_details = self.text_layout_details(window);
16216        let style = &text_layout_details.editor_style;
16217        let font_id = window.text_system().resolve_font(&style.text.font());
16218        let font_size = style.text.font_size.to_pixels(window.rem_size());
16219        let line_height = style.text.line_height_in_pixels(window.rem_size());
16220        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16221
16222        gpui::Size::new(em_width, line_height)
16223    }
16224
16225    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16226        self.load_diff_task.clone()
16227    }
16228
16229    fn read_selections_from_db(
16230        &mut self,
16231        item_id: u64,
16232        workspace_id: WorkspaceId,
16233        window: &mut Window,
16234        cx: &mut Context<Editor>,
16235    ) {
16236        if !self.is_singleton(cx)
16237            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16238        {
16239            return;
16240        }
16241        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16242            return;
16243        };
16244        if selections.is_empty() {
16245            return;
16246        }
16247
16248        let snapshot = self.buffer.read(cx).snapshot(cx);
16249        self.change_selections(None, window, cx, |s| {
16250            s.select_ranges(selections.into_iter().map(|(start, end)| {
16251                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16252            }));
16253        });
16254    }
16255}
16256
16257fn insert_extra_newline_brackets(
16258    buffer: &MultiBufferSnapshot,
16259    range: Range<usize>,
16260    language: &language::LanguageScope,
16261) -> bool {
16262    let leading_whitespace_len = buffer
16263        .reversed_chars_at(range.start)
16264        .take_while(|c| c.is_whitespace() && *c != '\n')
16265        .map(|c| c.len_utf8())
16266        .sum::<usize>();
16267    let trailing_whitespace_len = buffer
16268        .chars_at(range.end)
16269        .take_while(|c| c.is_whitespace() && *c != '\n')
16270        .map(|c| c.len_utf8())
16271        .sum::<usize>();
16272    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16273
16274    language.brackets().any(|(pair, enabled)| {
16275        let pair_start = pair.start.trim_end();
16276        let pair_end = pair.end.trim_start();
16277
16278        enabled
16279            && pair.newline
16280            && buffer.contains_str_at(range.end, pair_end)
16281            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16282    })
16283}
16284
16285fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16286    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16287        [(buffer, range, _)] => (*buffer, range.clone()),
16288        _ => return false,
16289    };
16290    let pair = {
16291        let mut result: Option<BracketMatch> = None;
16292
16293        for pair in buffer
16294            .all_bracket_ranges(range.clone())
16295            .filter(move |pair| {
16296                pair.open_range.start <= range.start && pair.close_range.end >= range.end
16297            })
16298        {
16299            let len = pair.close_range.end - pair.open_range.start;
16300
16301            if let Some(existing) = &result {
16302                let existing_len = existing.close_range.end - existing.open_range.start;
16303                if len > existing_len {
16304                    continue;
16305                }
16306            }
16307
16308            result = Some(pair);
16309        }
16310
16311        result
16312    };
16313    let Some(pair) = pair else {
16314        return false;
16315    };
16316    pair.newline_only
16317        && buffer
16318            .chars_for_range(pair.open_range.end..range.start)
16319            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16320            .all(|c| c.is_whitespace() && c != '\n')
16321}
16322
16323fn get_uncommitted_diff_for_buffer(
16324    project: &Entity<Project>,
16325    buffers: impl IntoIterator<Item = Entity<Buffer>>,
16326    buffer: Entity<MultiBuffer>,
16327    cx: &mut App,
16328) -> Task<()> {
16329    let mut tasks = Vec::new();
16330    project.update(cx, |project, cx| {
16331        for buffer in buffers {
16332            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16333        }
16334    });
16335    cx.spawn(|mut cx| async move {
16336        let diffs = future::join_all(tasks).await;
16337        buffer
16338            .update(&mut cx, |buffer, cx| {
16339                for diff in diffs.into_iter().flatten() {
16340                    buffer.add_diff(diff, cx);
16341                }
16342            })
16343            .ok();
16344    })
16345}
16346
16347fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16348    let tab_size = tab_size.get() as usize;
16349    let mut width = offset;
16350
16351    for ch in text.chars() {
16352        width += if ch == '\t' {
16353            tab_size - (width % tab_size)
16354        } else {
16355            1
16356        };
16357    }
16358
16359    width - offset
16360}
16361
16362#[cfg(test)]
16363mod tests {
16364    use super::*;
16365
16366    #[test]
16367    fn test_string_size_with_expanded_tabs() {
16368        let nz = |val| NonZeroU32::new(val).unwrap();
16369        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16370        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16371        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16372        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16373        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16374        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16375        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16376        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16377    }
16378}
16379
16380/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16381struct WordBreakingTokenizer<'a> {
16382    input: &'a str,
16383}
16384
16385impl<'a> WordBreakingTokenizer<'a> {
16386    fn new(input: &'a str) -> Self {
16387        Self { input }
16388    }
16389}
16390
16391fn is_char_ideographic(ch: char) -> bool {
16392    use unicode_script::Script::*;
16393    use unicode_script::UnicodeScript;
16394    matches!(ch.script(), Han | Tangut | Yi)
16395}
16396
16397fn is_grapheme_ideographic(text: &str) -> bool {
16398    text.chars().any(is_char_ideographic)
16399}
16400
16401fn is_grapheme_whitespace(text: &str) -> bool {
16402    text.chars().any(|x| x.is_whitespace())
16403}
16404
16405fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16406    text.chars().next().map_or(false, |ch| {
16407        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16408    })
16409}
16410
16411#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16412struct WordBreakToken<'a> {
16413    token: &'a str,
16414    grapheme_len: usize,
16415    is_whitespace: bool,
16416}
16417
16418impl<'a> Iterator for WordBreakingTokenizer<'a> {
16419    /// Yields a span, the count of graphemes in the token, and whether it was
16420    /// whitespace. Note that it also breaks at word boundaries.
16421    type Item = WordBreakToken<'a>;
16422
16423    fn next(&mut self) -> Option<Self::Item> {
16424        use unicode_segmentation::UnicodeSegmentation;
16425        if self.input.is_empty() {
16426            return None;
16427        }
16428
16429        let mut iter = self.input.graphemes(true).peekable();
16430        let mut offset = 0;
16431        let mut graphemes = 0;
16432        if let Some(first_grapheme) = iter.next() {
16433            let is_whitespace = is_grapheme_whitespace(first_grapheme);
16434            offset += first_grapheme.len();
16435            graphemes += 1;
16436            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16437                if let Some(grapheme) = iter.peek().copied() {
16438                    if should_stay_with_preceding_ideograph(grapheme) {
16439                        offset += grapheme.len();
16440                        graphemes += 1;
16441                    }
16442                }
16443            } else {
16444                let mut words = self.input[offset..].split_word_bound_indices().peekable();
16445                let mut next_word_bound = words.peek().copied();
16446                if next_word_bound.map_or(false, |(i, _)| i == 0) {
16447                    next_word_bound = words.next();
16448                }
16449                while let Some(grapheme) = iter.peek().copied() {
16450                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
16451                        break;
16452                    };
16453                    if is_grapheme_whitespace(grapheme) != is_whitespace {
16454                        break;
16455                    };
16456                    offset += grapheme.len();
16457                    graphemes += 1;
16458                    iter.next();
16459                }
16460            }
16461            let token = &self.input[..offset];
16462            self.input = &self.input[offset..];
16463            if is_whitespace {
16464                Some(WordBreakToken {
16465                    token: " ",
16466                    grapheme_len: 1,
16467                    is_whitespace: true,
16468                })
16469            } else {
16470                Some(WordBreakToken {
16471                    token,
16472                    grapheme_len: graphemes,
16473                    is_whitespace: false,
16474                })
16475            }
16476        } else {
16477            None
16478        }
16479    }
16480}
16481
16482#[test]
16483fn test_word_breaking_tokenizer() {
16484    let tests: &[(&str, &[(&str, usize, bool)])] = &[
16485        ("", &[]),
16486        ("  ", &[(" ", 1, true)]),
16487        ("Ʒ", &[("Ʒ", 1, false)]),
16488        ("Ǽ", &[("Ǽ", 1, false)]),
16489        ("", &[("", 1, false)]),
16490        ("⋑⋑", &[("⋑⋑", 2, false)]),
16491        (
16492            "原理,进而",
16493            &[
16494                ("", 1, false),
16495                ("理,", 2, false),
16496                ("", 1, false),
16497                ("", 1, false),
16498            ],
16499        ),
16500        (
16501            "hello world",
16502            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16503        ),
16504        (
16505            "hello, world",
16506            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16507        ),
16508        (
16509            "  hello world",
16510            &[
16511                (" ", 1, true),
16512                ("hello", 5, false),
16513                (" ", 1, true),
16514                ("world", 5, false),
16515            ],
16516        ),
16517        (
16518            "这是什么 \n 钢笔",
16519            &[
16520                ("", 1, false),
16521                ("", 1, false),
16522                ("", 1, false),
16523                ("", 1, false),
16524                (" ", 1, true),
16525                ("", 1, false),
16526                ("", 1, false),
16527            ],
16528        ),
16529        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16530    ];
16531
16532    for (input, result) in tests {
16533        assert_eq!(
16534            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16535            result
16536                .iter()
16537                .copied()
16538                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16539                    token,
16540                    grapheme_len,
16541                    is_whitespace,
16542                })
16543                .collect::<Vec<_>>()
16544        );
16545    }
16546}
16547
16548fn wrap_with_prefix(
16549    line_prefix: String,
16550    unwrapped_text: String,
16551    wrap_column: usize,
16552    tab_size: NonZeroU32,
16553) -> String {
16554    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16555    let mut wrapped_text = String::new();
16556    let mut current_line = line_prefix.clone();
16557
16558    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16559    let mut current_line_len = line_prefix_len;
16560    for WordBreakToken {
16561        token,
16562        grapheme_len,
16563        is_whitespace,
16564    } in tokenizer
16565    {
16566        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16567            wrapped_text.push_str(current_line.trim_end());
16568            wrapped_text.push('\n');
16569            current_line.truncate(line_prefix.len());
16570            current_line_len = line_prefix_len;
16571            if !is_whitespace {
16572                current_line.push_str(token);
16573                current_line_len += grapheme_len;
16574            }
16575        } else if !is_whitespace {
16576            current_line.push_str(token);
16577            current_line_len += grapheme_len;
16578        } else if current_line_len != line_prefix_len {
16579            current_line.push(' ');
16580            current_line_len += 1;
16581        }
16582    }
16583
16584    if !current_line.is_empty() {
16585        wrapped_text.push_str(&current_line);
16586    }
16587    wrapped_text
16588}
16589
16590#[test]
16591fn test_wrap_with_prefix() {
16592    assert_eq!(
16593        wrap_with_prefix(
16594            "# ".to_string(),
16595            "abcdefg".to_string(),
16596            4,
16597            NonZeroU32::new(4).unwrap()
16598        ),
16599        "# abcdefg"
16600    );
16601    assert_eq!(
16602        wrap_with_prefix(
16603            "".to_string(),
16604            "\thello world".to_string(),
16605            8,
16606            NonZeroU32::new(4).unwrap()
16607        ),
16608        "hello\nworld"
16609    );
16610    assert_eq!(
16611        wrap_with_prefix(
16612            "// ".to_string(),
16613            "xx \nyy zz aa bb cc".to_string(),
16614            12,
16615            NonZeroU32::new(4).unwrap()
16616        ),
16617        "// xx yy zz\n// aa bb cc"
16618    );
16619    assert_eq!(
16620        wrap_with_prefix(
16621            String::new(),
16622            "这是什么 \n 钢笔".to_string(),
16623            3,
16624            NonZeroU32::new(4).unwrap()
16625        ),
16626        "这是什\n么 钢\n"
16627    );
16628}
16629
16630pub trait CollaborationHub {
16631    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16632    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16633    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16634}
16635
16636impl CollaborationHub for Entity<Project> {
16637    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16638        self.read(cx).collaborators()
16639    }
16640
16641    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16642        self.read(cx).user_store().read(cx).participant_indices()
16643    }
16644
16645    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16646        let this = self.read(cx);
16647        let user_ids = this.collaborators().values().map(|c| c.user_id);
16648        this.user_store().read_with(cx, |user_store, cx| {
16649            user_store.participant_names(user_ids, cx)
16650        })
16651    }
16652}
16653
16654pub trait SemanticsProvider {
16655    fn hover(
16656        &self,
16657        buffer: &Entity<Buffer>,
16658        position: text::Anchor,
16659        cx: &mut App,
16660    ) -> Option<Task<Vec<project::Hover>>>;
16661
16662    fn inlay_hints(
16663        &self,
16664        buffer_handle: Entity<Buffer>,
16665        range: Range<text::Anchor>,
16666        cx: &mut App,
16667    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16668
16669    fn resolve_inlay_hint(
16670        &self,
16671        hint: InlayHint,
16672        buffer_handle: Entity<Buffer>,
16673        server_id: LanguageServerId,
16674        cx: &mut App,
16675    ) -> Option<Task<anyhow::Result<InlayHint>>>;
16676
16677    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16678
16679    fn document_highlights(
16680        &self,
16681        buffer: &Entity<Buffer>,
16682        position: text::Anchor,
16683        cx: &mut App,
16684    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16685
16686    fn definitions(
16687        &self,
16688        buffer: &Entity<Buffer>,
16689        position: text::Anchor,
16690        kind: GotoDefinitionKind,
16691        cx: &mut App,
16692    ) -> Option<Task<Result<Vec<LocationLink>>>>;
16693
16694    fn range_for_rename(
16695        &self,
16696        buffer: &Entity<Buffer>,
16697        position: text::Anchor,
16698        cx: &mut App,
16699    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16700
16701    fn perform_rename(
16702        &self,
16703        buffer: &Entity<Buffer>,
16704        position: text::Anchor,
16705        new_name: String,
16706        cx: &mut App,
16707    ) -> Option<Task<Result<ProjectTransaction>>>;
16708}
16709
16710pub trait CompletionProvider {
16711    fn completions(
16712        &self,
16713        buffer: &Entity<Buffer>,
16714        buffer_position: text::Anchor,
16715        trigger: CompletionContext,
16716        window: &mut Window,
16717        cx: &mut Context<Editor>,
16718    ) -> Task<Result<Vec<Completion>>>;
16719
16720    fn resolve_completions(
16721        &self,
16722        buffer: Entity<Buffer>,
16723        completion_indices: Vec<usize>,
16724        completions: Rc<RefCell<Box<[Completion]>>>,
16725        cx: &mut Context<Editor>,
16726    ) -> Task<Result<bool>>;
16727
16728    fn apply_additional_edits_for_completion(
16729        &self,
16730        _buffer: Entity<Buffer>,
16731        _completions: Rc<RefCell<Box<[Completion]>>>,
16732        _completion_index: usize,
16733        _push_to_history: bool,
16734        _cx: &mut Context<Editor>,
16735    ) -> Task<Result<Option<language::Transaction>>> {
16736        Task::ready(Ok(None))
16737    }
16738
16739    fn is_completion_trigger(
16740        &self,
16741        buffer: &Entity<Buffer>,
16742        position: language::Anchor,
16743        text: &str,
16744        trigger_in_words: bool,
16745        cx: &mut Context<Editor>,
16746    ) -> bool;
16747
16748    fn sort_completions(&self) -> bool {
16749        true
16750    }
16751}
16752
16753pub trait CodeActionProvider {
16754    fn id(&self) -> Arc<str>;
16755
16756    fn code_actions(
16757        &self,
16758        buffer: &Entity<Buffer>,
16759        range: Range<text::Anchor>,
16760        window: &mut Window,
16761        cx: &mut App,
16762    ) -> Task<Result<Vec<CodeAction>>>;
16763
16764    fn apply_code_action(
16765        &self,
16766        buffer_handle: Entity<Buffer>,
16767        action: CodeAction,
16768        excerpt_id: ExcerptId,
16769        push_to_history: bool,
16770        window: &mut Window,
16771        cx: &mut App,
16772    ) -> Task<Result<ProjectTransaction>>;
16773}
16774
16775impl CodeActionProvider for Entity<Project> {
16776    fn id(&self) -> Arc<str> {
16777        "project".into()
16778    }
16779
16780    fn code_actions(
16781        &self,
16782        buffer: &Entity<Buffer>,
16783        range: Range<text::Anchor>,
16784        _window: &mut Window,
16785        cx: &mut App,
16786    ) -> Task<Result<Vec<CodeAction>>> {
16787        self.update(cx, |project, cx| {
16788            project.code_actions(buffer, range, None, cx)
16789        })
16790    }
16791
16792    fn apply_code_action(
16793        &self,
16794        buffer_handle: Entity<Buffer>,
16795        action: CodeAction,
16796        _excerpt_id: ExcerptId,
16797        push_to_history: bool,
16798        _window: &mut Window,
16799        cx: &mut App,
16800    ) -> Task<Result<ProjectTransaction>> {
16801        self.update(cx, |project, cx| {
16802            project.apply_code_action(buffer_handle, action, push_to_history, cx)
16803        })
16804    }
16805}
16806
16807fn snippet_completions(
16808    project: &Project,
16809    buffer: &Entity<Buffer>,
16810    buffer_position: text::Anchor,
16811    cx: &mut App,
16812) -> Task<Result<Vec<Completion>>> {
16813    let language = buffer.read(cx).language_at(buffer_position);
16814    let language_name = language.as_ref().map(|language| language.lsp_id());
16815    let snippet_store = project.snippets().read(cx);
16816    let snippets = snippet_store.snippets_for(language_name, cx);
16817
16818    if snippets.is_empty() {
16819        return Task::ready(Ok(vec![]));
16820    }
16821    let snapshot = buffer.read(cx).text_snapshot();
16822    let chars: String = snapshot
16823        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16824        .collect();
16825
16826    let scope = language.map(|language| language.default_scope());
16827    let executor = cx.background_executor().clone();
16828
16829    cx.background_spawn(async move {
16830        let classifier = CharClassifier::new(scope).for_completion(true);
16831        let mut last_word = chars
16832            .chars()
16833            .take_while(|c| classifier.is_word(*c))
16834            .collect::<String>();
16835        last_word = last_word.chars().rev().collect();
16836
16837        if last_word.is_empty() {
16838            return Ok(vec![]);
16839        }
16840
16841        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16842        let to_lsp = |point: &text::Anchor| {
16843            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16844            point_to_lsp(end)
16845        };
16846        let lsp_end = to_lsp(&buffer_position);
16847
16848        let candidates = snippets
16849            .iter()
16850            .enumerate()
16851            .flat_map(|(ix, snippet)| {
16852                snippet
16853                    .prefix
16854                    .iter()
16855                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16856            })
16857            .collect::<Vec<StringMatchCandidate>>();
16858
16859        let mut matches = fuzzy::match_strings(
16860            &candidates,
16861            &last_word,
16862            last_word.chars().any(|c| c.is_uppercase()),
16863            100,
16864            &Default::default(),
16865            executor,
16866        )
16867        .await;
16868
16869        // Remove all candidates where the query's start does not match the start of any word in the candidate
16870        if let Some(query_start) = last_word.chars().next() {
16871            matches.retain(|string_match| {
16872                split_words(&string_match.string).any(|word| {
16873                    // Check that the first codepoint of the word as lowercase matches the first
16874                    // codepoint of the query as lowercase
16875                    word.chars()
16876                        .flat_map(|codepoint| codepoint.to_lowercase())
16877                        .zip(query_start.to_lowercase())
16878                        .all(|(word_cp, query_cp)| word_cp == query_cp)
16879                })
16880            });
16881        }
16882
16883        let matched_strings = matches
16884            .into_iter()
16885            .map(|m| m.string)
16886            .collect::<HashSet<_>>();
16887
16888        let result: Vec<Completion> = snippets
16889            .into_iter()
16890            .filter_map(|snippet| {
16891                let matching_prefix = snippet
16892                    .prefix
16893                    .iter()
16894                    .find(|prefix| matched_strings.contains(*prefix))?;
16895                let start = as_offset - last_word.len();
16896                let start = snapshot.anchor_before(start);
16897                let range = start..buffer_position;
16898                let lsp_start = to_lsp(&start);
16899                let lsp_range = lsp::Range {
16900                    start: lsp_start,
16901                    end: lsp_end,
16902                };
16903                Some(Completion {
16904                    old_range: range,
16905                    new_text: snippet.body.clone(),
16906                    resolved: false,
16907                    label: CodeLabel {
16908                        text: matching_prefix.clone(),
16909                        runs: vec![],
16910                        filter_range: 0..matching_prefix.len(),
16911                    },
16912                    server_id: LanguageServerId(usize::MAX),
16913                    documentation: snippet
16914                        .description
16915                        .clone()
16916                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
16917                    lsp_completion: lsp::CompletionItem {
16918                        label: snippet.prefix.first().unwrap().clone(),
16919                        kind: Some(CompletionItemKind::SNIPPET),
16920                        label_details: snippet.description.as_ref().map(|description| {
16921                            lsp::CompletionItemLabelDetails {
16922                                detail: Some(description.clone()),
16923                                description: None,
16924                            }
16925                        }),
16926                        insert_text_format: Some(InsertTextFormat::SNIPPET),
16927                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16928                            lsp::InsertReplaceEdit {
16929                                new_text: snippet.body.clone(),
16930                                insert: lsp_range,
16931                                replace: lsp_range,
16932                            },
16933                        )),
16934                        filter_text: Some(snippet.body.clone()),
16935                        sort_text: Some(char::MAX.to_string()),
16936                        ..Default::default()
16937                    },
16938                    confirm: None,
16939                })
16940            })
16941            .collect();
16942
16943        Ok(result)
16944    })
16945}
16946
16947impl CompletionProvider for Entity<Project> {
16948    fn completions(
16949        &self,
16950        buffer: &Entity<Buffer>,
16951        buffer_position: text::Anchor,
16952        options: CompletionContext,
16953        _window: &mut Window,
16954        cx: &mut Context<Editor>,
16955    ) -> Task<Result<Vec<Completion>>> {
16956        self.update(cx, |project, cx| {
16957            let snippets = snippet_completions(project, buffer, buffer_position, cx);
16958            let project_completions = project.completions(buffer, buffer_position, options, cx);
16959            cx.background_spawn(async move {
16960                let mut completions = project_completions.await?;
16961                let snippets_completions = snippets.await?;
16962                completions.extend(snippets_completions);
16963                Ok(completions)
16964            })
16965        })
16966    }
16967
16968    fn resolve_completions(
16969        &self,
16970        buffer: Entity<Buffer>,
16971        completion_indices: Vec<usize>,
16972        completions: Rc<RefCell<Box<[Completion]>>>,
16973        cx: &mut Context<Editor>,
16974    ) -> Task<Result<bool>> {
16975        self.update(cx, |project, cx| {
16976            project.lsp_store().update(cx, |lsp_store, cx| {
16977                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16978            })
16979        })
16980    }
16981
16982    fn apply_additional_edits_for_completion(
16983        &self,
16984        buffer: Entity<Buffer>,
16985        completions: Rc<RefCell<Box<[Completion]>>>,
16986        completion_index: usize,
16987        push_to_history: bool,
16988        cx: &mut Context<Editor>,
16989    ) -> Task<Result<Option<language::Transaction>>> {
16990        self.update(cx, |project, cx| {
16991            project.lsp_store().update(cx, |lsp_store, cx| {
16992                lsp_store.apply_additional_edits_for_completion(
16993                    buffer,
16994                    completions,
16995                    completion_index,
16996                    push_to_history,
16997                    cx,
16998                )
16999            })
17000        })
17001    }
17002
17003    fn is_completion_trigger(
17004        &self,
17005        buffer: &Entity<Buffer>,
17006        position: language::Anchor,
17007        text: &str,
17008        trigger_in_words: bool,
17009        cx: &mut Context<Editor>,
17010    ) -> bool {
17011        let mut chars = text.chars();
17012        let char = if let Some(char) = chars.next() {
17013            char
17014        } else {
17015            return false;
17016        };
17017        if chars.next().is_some() {
17018            return false;
17019        }
17020
17021        let buffer = buffer.read(cx);
17022        let snapshot = buffer.snapshot();
17023        if !snapshot.settings_at(position, cx).show_completions_on_input {
17024            return false;
17025        }
17026        let classifier = snapshot.char_classifier_at(position).for_completion(true);
17027        if trigger_in_words && classifier.is_word(char) {
17028            return true;
17029        }
17030
17031        buffer.completion_triggers().contains(text)
17032    }
17033}
17034
17035impl SemanticsProvider for Entity<Project> {
17036    fn hover(
17037        &self,
17038        buffer: &Entity<Buffer>,
17039        position: text::Anchor,
17040        cx: &mut App,
17041    ) -> Option<Task<Vec<project::Hover>>> {
17042        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
17043    }
17044
17045    fn document_highlights(
17046        &self,
17047        buffer: &Entity<Buffer>,
17048        position: text::Anchor,
17049        cx: &mut App,
17050    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
17051        Some(self.update(cx, |project, cx| {
17052            project.document_highlights(buffer, position, cx)
17053        }))
17054    }
17055
17056    fn definitions(
17057        &self,
17058        buffer: &Entity<Buffer>,
17059        position: text::Anchor,
17060        kind: GotoDefinitionKind,
17061        cx: &mut App,
17062    ) -> Option<Task<Result<Vec<LocationLink>>>> {
17063        Some(self.update(cx, |project, cx| match kind {
17064            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
17065            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
17066            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
17067            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
17068        }))
17069    }
17070
17071    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
17072        // TODO: make this work for remote projects
17073        self.update(cx, |this, cx| {
17074            buffer.update(cx, |buffer, cx| {
17075                this.any_language_server_supports_inlay_hints(buffer, cx)
17076            })
17077        })
17078    }
17079
17080    fn inlay_hints(
17081        &self,
17082        buffer_handle: Entity<Buffer>,
17083        range: Range<text::Anchor>,
17084        cx: &mut App,
17085    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
17086        Some(self.update(cx, |project, cx| {
17087            project.inlay_hints(buffer_handle, range, cx)
17088        }))
17089    }
17090
17091    fn resolve_inlay_hint(
17092        &self,
17093        hint: InlayHint,
17094        buffer_handle: Entity<Buffer>,
17095        server_id: LanguageServerId,
17096        cx: &mut App,
17097    ) -> Option<Task<anyhow::Result<InlayHint>>> {
17098        Some(self.update(cx, |project, cx| {
17099            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
17100        }))
17101    }
17102
17103    fn range_for_rename(
17104        &self,
17105        buffer: &Entity<Buffer>,
17106        position: text::Anchor,
17107        cx: &mut App,
17108    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17109        Some(self.update(cx, |project, cx| {
17110            let buffer = buffer.clone();
17111            let task = project.prepare_rename(buffer.clone(), position, cx);
17112            cx.spawn(|_, mut cx| async move {
17113                Ok(match task.await? {
17114                    PrepareRenameResponse::Success(range) => Some(range),
17115                    PrepareRenameResponse::InvalidPosition => None,
17116                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17117                        // Fallback on using TreeSitter info to determine identifier range
17118                        buffer.update(&mut cx, |buffer, _| {
17119                            let snapshot = buffer.snapshot();
17120                            let (range, kind) = snapshot.surrounding_word(position);
17121                            if kind != Some(CharKind::Word) {
17122                                return None;
17123                            }
17124                            Some(
17125                                snapshot.anchor_before(range.start)
17126                                    ..snapshot.anchor_after(range.end),
17127                            )
17128                        })?
17129                    }
17130                })
17131            })
17132        }))
17133    }
17134
17135    fn perform_rename(
17136        &self,
17137        buffer: &Entity<Buffer>,
17138        position: text::Anchor,
17139        new_name: String,
17140        cx: &mut App,
17141    ) -> Option<Task<Result<ProjectTransaction>>> {
17142        Some(self.update(cx, |project, cx| {
17143            project.perform_rename(buffer.clone(), position, new_name, cx)
17144        }))
17145    }
17146}
17147
17148fn inlay_hint_settings(
17149    location: Anchor,
17150    snapshot: &MultiBufferSnapshot,
17151    cx: &mut Context<Editor>,
17152) -> InlayHintSettings {
17153    let file = snapshot.file_at(location);
17154    let language = snapshot.language_at(location).map(|l| l.name());
17155    language_settings(language, file, cx).inlay_hints
17156}
17157
17158fn consume_contiguous_rows(
17159    contiguous_row_selections: &mut Vec<Selection<Point>>,
17160    selection: &Selection<Point>,
17161    display_map: &DisplaySnapshot,
17162    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17163) -> (MultiBufferRow, MultiBufferRow) {
17164    contiguous_row_selections.push(selection.clone());
17165    let start_row = MultiBufferRow(selection.start.row);
17166    let mut end_row = ending_row(selection, display_map);
17167
17168    while let Some(next_selection) = selections.peek() {
17169        if next_selection.start.row <= end_row.0 {
17170            end_row = ending_row(next_selection, display_map);
17171            contiguous_row_selections.push(selections.next().unwrap().clone());
17172        } else {
17173            break;
17174        }
17175    }
17176    (start_row, end_row)
17177}
17178
17179fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17180    if next_selection.end.column > 0 || next_selection.is_empty() {
17181        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17182    } else {
17183        MultiBufferRow(next_selection.end.row)
17184    }
17185}
17186
17187impl EditorSnapshot {
17188    pub fn remote_selections_in_range<'a>(
17189        &'a self,
17190        range: &'a Range<Anchor>,
17191        collaboration_hub: &dyn CollaborationHub,
17192        cx: &'a App,
17193    ) -> impl 'a + Iterator<Item = RemoteSelection> {
17194        let participant_names = collaboration_hub.user_names(cx);
17195        let participant_indices = collaboration_hub.user_participant_indices(cx);
17196        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17197        let collaborators_by_replica_id = collaborators_by_peer_id
17198            .iter()
17199            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17200            .collect::<HashMap<_, _>>();
17201        self.buffer_snapshot
17202            .selections_in_range(range, false)
17203            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17204                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17205                let participant_index = participant_indices.get(&collaborator.user_id).copied();
17206                let user_name = participant_names.get(&collaborator.user_id).cloned();
17207                Some(RemoteSelection {
17208                    replica_id,
17209                    selection,
17210                    cursor_shape,
17211                    line_mode,
17212                    participant_index,
17213                    peer_id: collaborator.peer_id,
17214                    user_name,
17215                })
17216            })
17217    }
17218
17219    pub fn hunks_for_ranges(
17220        &self,
17221        ranges: impl IntoIterator<Item = Range<Point>>,
17222    ) -> Vec<MultiBufferDiffHunk> {
17223        let mut hunks = Vec::new();
17224        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17225            HashMap::default();
17226        for query_range in ranges {
17227            let query_rows =
17228                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17229            for hunk in self.buffer_snapshot.diff_hunks_in_range(
17230                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17231            ) {
17232                // Include deleted hunks that are adjacent to the query range, because
17233                // otherwise they would be missed.
17234                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
17235                if hunk.status().is_deleted() {
17236                    intersects_range |= hunk.row_range.start == query_rows.end;
17237                    intersects_range |= hunk.row_range.end == query_rows.start;
17238                }
17239                if intersects_range {
17240                    if !processed_buffer_rows
17241                        .entry(hunk.buffer_id)
17242                        .or_default()
17243                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17244                    {
17245                        continue;
17246                    }
17247                    hunks.push(hunk);
17248                }
17249            }
17250        }
17251
17252        hunks
17253    }
17254
17255    fn display_diff_hunks_for_rows<'a>(
17256        &'a self,
17257        display_rows: Range<DisplayRow>,
17258        folded_buffers: &'a HashSet<BufferId>,
17259    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17260        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17261        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17262
17263        self.buffer_snapshot
17264            .diff_hunks_in_range(buffer_start..buffer_end)
17265            .filter_map(|hunk| {
17266                if folded_buffers.contains(&hunk.buffer_id) {
17267                    return None;
17268                }
17269
17270                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17271                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17272
17273                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17274                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17275
17276                let display_hunk = if hunk_display_start.column() != 0 {
17277                    DisplayDiffHunk::Folded {
17278                        display_row: hunk_display_start.row(),
17279                    }
17280                } else {
17281                    let mut end_row = hunk_display_end.row();
17282                    if hunk_display_end.column() > 0 {
17283                        end_row.0 += 1;
17284                    }
17285                    DisplayDiffHunk::Unfolded {
17286                        status: hunk.status(),
17287                        diff_base_byte_range: hunk.diff_base_byte_range,
17288                        display_row_range: hunk_display_start.row()..end_row,
17289                        multi_buffer_range: Anchor::range_in_buffer(
17290                            hunk.excerpt_id,
17291                            hunk.buffer_id,
17292                            hunk.buffer_range,
17293                        ),
17294                    }
17295                };
17296
17297                Some(display_hunk)
17298            })
17299    }
17300
17301    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17302        self.display_snapshot.buffer_snapshot.language_at(position)
17303    }
17304
17305    pub fn is_focused(&self) -> bool {
17306        self.is_focused
17307    }
17308
17309    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17310        self.placeholder_text.as_ref()
17311    }
17312
17313    pub fn scroll_position(&self) -> gpui::Point<f32> {
17314        self.scroll_anchor.scroll_position(&self.display_snapshot)
17315    }
17316
17317    fn gutter_dimensions(
17318        &self,
17319        font_id: FontId,
17320        font_size: Pixels,
17321        max_line_number_width: Pixels,
17322        cx: &App,
17323    ) -> Option<GutterDimensions> {
17324        if !self.show_gutter {
17325            return None;
17326        }
17327
17328        let descent = cx.text_system().descent(font_id, font_size);
17329        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17330        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17331
17332        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17333            matches!(
17334                ProjectSettings::get_global(cx).git.git_gutter,
17335                Some(GitGutterSetting::TrackedFiles)
17336            )
17337        });
17338        let gutter_settings = EditorSettings::get_global(cx).gutter;
17339        let show_line_numbers = self
17340            .show_line_numbers
17341            .unwrap_or(gutter_settings.line_numbers);
17342        let line_gutter_width = if show_line_numbers {
17343            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17344            let min_width_for_number_on_gutter = em_advance * 4.0;
17345            max_line_number_width.max(min_width_for_number_on_gutter)
17346        } else {
17347            0.0.into()
17348        };
17349
17350        let show_code_actions = self
17351            .show_code_actions
17352            .unwrap_or(gutter_settings.code_actions);
17353
17354        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17355
17356        let git_blame_entries_width =
17357            self.git_blame_gutter_max_author_length
17358                .map(|max_author_length| {
17359                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17360
17361                    /// The number of characters to dedicate to gaps and margins.
17362                    const SPACING_WIDTH: usize = 4;
17363
17364                    let max_char_count = max_author_length
17365                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17366                        + ::git::SHORT_SHA_LENGTH
17367                        + MAX_RELATIVE_TIMESTAMP.len()
17368                        + SPACING_WIDTH;
17369
17370                    em_advance * max_char_count
17371                });
17372
17373        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17374        left_padding += if show_code_actions || show_runnables {
17375            em_width * 3.0
17376        } else if show_git_gutter && show_line_numbers {
17377            em_width * 2.0
17378        } else if show_git_gutter || show_line_numbers {
17379            em_width
17380        } else {
17381            px(0.)
17382        };
17383
17384        let right_padding = if gutter_settings.folds && show_line_numbers {
17385            em_width * 4.0
17386        } else if gutter_settings.folds {
17387            em_width * 3.0
17388        } else if show_line_numbers {
17389            em_width
17390        } else {
17391            px(0.)
17392        };
17393
17394        Some(GutterDimensions {
17395            left_padding,
17396            right_padding,
17397            width: line_gutter_width + left_padding + right_padding,
17398            margin: -descent,
17399            git_blame_entries_width,
17400        })
17401    }
17402
17403    pub fn render_crease_toggle(
17404        &self,
17405        buffer_row: MultiBufferRow,
17406        row_contains_cursor: bool,
17407        editor: Entity<Editor>,
17408        window: &mut Window,
17409        cx: &mut App,
17410    ) -> Option<AnyElement> {
17411        let folded = self.is_line_folded(buffer_row);
17412        let mut is_foldable = false;
17413
17414        if let Some(crease) = self
17415            .crease_snapshot
17416            .query_row(buffer_row, &self.buffer_snapshot)
17417        {
17418            is_foldable = true;
17419            match crease {
17420                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17421                    if let Some(render_toggle) = render_toggle {
17422                        let toggle_callback =
17423                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17424                                if folded {
17425                                    editor.update(cx, |editor, cx| {
17426                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17427                                    });
17428                                } else {
17429                                    editor.update(cx, |editor, cx| {
17430                                        editor.unfold_at(
17431                                            &crate::UnfoldAt { buffer_row },
17432                                            window,
17433                                            cx,
17434                                        )
17435                                    });
17436                                }
17437                            });
17438                        return Some((render_toggle)(
17439                            buffer_row,
17440                            folded,
17441                            toggle_callback,
17442                            window,
17443                            cx,
17444                        ));
17445                    }
17446                }
17447            }
17448        }
17449
17450        is_foldable |= self.starts_indent(buffer_row);
17451
17452        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17453            Some(
17454                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17455                    .toggle_state(folded)
17456                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17457                        if folded {
17458                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17459                        } else {
17460                            this.fold_at(&FoldAt { buffer_row }, window, cx);
17461                        }
17462                    }))
17463                    .into_any_element(),
17464            )
17465        } else {
17466            None
17467        }
17468    }
17469
17470    pub fn render_crease_trailer(
17471        &self,
17472        buffer_row: MultiBufferRow,
17473        window: &mut Window,
17474        cx: &mut App,
17475    ) -> Option<AnyElement> {
17476        let folded = self.is_line_folded(buffer_row);
17477        if let Crease::Inline { render_trailer, .. } = self
17478            .crease_snapshot
17479            .query_row(buffer_row, &self.buffer_snapshot)?
17480        {
17481            let render_trailer = render_trailer.as_ref()?;
17482            Some(render_trailer(buffer_row, folded, window, cx))
17483        } else {
17484            None
17485        }
17486    }
17487}
17488
17489impl Deref for EditorSnapshot {
17490    type Target = DisplaySnapshot;
17491
17492    fn deref(&self) -> &Self::Target {
17493        &self.display_snapshot
17494    }
17495}
17496
17497#[derive(Clone, Debug, PartialEq, Eq)]
17498pub enum EditorEvent {
17499    InputIgnored {
17500        text: Arc<str>,
17501    },
17502    InputHandled {
17503        utf16_range_to_replace: Option<Range<isize>>,
17504        text: Arc<str>,
17505    },
17506    ExcerptsAdded {
17507        buffer: Entity<Buffer>,
17508        predecessor: ExcerptId,
17509        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17510    },
17511    ExcerptsRemoved {
17512        ids: Vec<ExcerptId>,
17513    },
17514    BufferFoldToggled {
17515        ids: Vec<ExcerptId>,
17516        folded: bool,
17517    },
17518    ExcerptsEdited {
17519        ids: Vec<ExcerptId>,
17520    },
17521    ExcerptsExpanded {
17522        ids: Vec<ExcerptId>,
17523    },
17524    BufferEdited,
17525    Edited {
17526        transaction_id: clock::Lamport,
17527    },
17528    Reparsed(BufferId),
17529    Focused,
17530    FocusedIn,
17531    Blurred,
17532    DirtyChanged,
17533    Saved,
17534    TitleChanged,
17535    DiffBaseChanged,
17536    SelectionsChanged {
17537        local: bool,
17538    },
17539    ScrollPositionChanged {
17540        local: bool,
17541        autoscroll: bool,
17542    },
17543    Closed,
17544    TransactionUndone {
17545        transaction_id: clock::Lamport,
17546    },
17547    TransactionBegun {
17548        transaction_id: clock::Lamport,
17549    },
17550    Reloaded,
17551    CursorShapeChanged,
17552}
17553
17554impl EventEmitter<EditorEvent> for Editor {}
17555
17556impl Focusable for Editor {
17557    fn focus_handle(&self, _cx: &App) -> FocusHandle {
17558        self.focus_handle.clone()
17559    }
17560}
17561
17562impl Render for Editor {
17563    fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17564        let settings = ThemeSettings::get_global(cx);
17565
17566        let mut text_style = match self.mode {
17567            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17568                color: cx.theme().colors().editor_foreground,
17569                font_family: settings.ui_font.family.clone(),
17570                font_features: settings.ui_font.features.clone(),
17571                font_fallbacks: settings.ui_font.fallbacks.clone(),
17572                font_size: rems(0.875).into(),
17573                font_weight: settings.ui_font.weight,
17574                line_height: relative(settings.buffer_line_height.value()),
17575                ..Default::default()
17576            },
17577            EditorMode::Full => TextStyle {
17578                color: cx.theme().colors().editor_foreground,
17579                font_family: settings.buffer_font.family.clone(),
17580                font_features: settings.buffer_font.features.clone(),
17581                font_fallbacks: settings.buffer_font.fallbacks.clone(),
17582                font_size: settings.buffer_font_size(cx).into(),
17583                font_weight: settings.buffer_font.weight,
17584                line_height: relative(settings.buffer_line_height.value()),
17585                ..Default::default()
17586            },
17587        };
17588        if let Some(text_style_refinement) = &self.text_style_refinement {
17589            text_style.refine(text_style_refinement)
17590        }
17591
17592        let background = match self.mode {
17593            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17594            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17595            EditorMode::Full => cx.theme().colors().editor_background,
17596        };
17597
17598        EditorElement::new(
17599            &cx.entity(),
17600            EditorStyle {
17601                background,
17602                local_player: cx.theme().players().local(),
17603                text: text_style,
17604                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17605                syntax: cx.theme().syntax().clone(),
17606                status: cx.theme().status().clone(),
17607                inlay_hints_style: make_inlay_hints_style(cx),
17608                inline_completion_styles: make_suggestion_styles(cx),
17609                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17610            },
17611        )
17612    }
17613}
17614
17615impl EntityInputHandler for Editor {
17616    fn text_for_range(
17617        &mut self,
17618        range_utf16: Range<usize>,
17619        adjusted_range: &mut Option<Range<usize>>,
17620        _: &mut Window,
17621        cx: &mut Context<Self>,
17622    ) -> Option<String> {
17623        let snapshot = self.buffer.read(cx).read(cx);
17624        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17625        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17626        if (start.0..end.0) != range_utf16 {
17627            adjusted_range.replace(start.0..end.0);
17628        }
17629        Some(snapshot.text_for_range(start..end).collect())
17630    }
17631
17632    fn selected_text_range(
17633        &mut self,
17634        ignore_disabled_input: bool,
17635        _: &mut Window,
17636        cx: &mut Context<Self>,
17637    ) -> Option<UTF16Selection> {
17638        // Prevent the IME menu from appearing when holding down an alphabetic key
17639        // while input is disabled.
17640        if !ignore_disabled_input && !self.input_enabled {
17641            return None;
17642        }
17643
17644        let selection = self.selections.newest::<OffsetUtf16>(cx);
17645        let range = selection.range();
17646
17647        Some(UTF16Selection {
17648            range: range.start.0..range.end.0,
17649            reversed: selection.reversed,
17650        })
17651    }
17652
17653    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17654        let snapshot = self.buffer.read(cx).read(cx);
17655        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17656        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17657    }
17658
17659    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17660        self.clear_highlights::<InputComposition>(cx);
17661        self.ime_transaction.take();
17662    }
17663
17664    fn replace_text_in_range(
17665        &mut self,
17666        range_utf16: Option<Range<usize>>,
17667        text: &str,
17668        window: &mut Window,
17669        cx: &mut Context<Self>,
17670    ) {
17671        if !self.input_enabled {
17672            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17673            return;
17674        }
17675
17676        self.transact(window, cx, |this, window, cx| {
17677            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17678                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17679                Some(this.selection_replacement_ranges(range_utf16, cx))
17680            } else {
17681                this.marked_text_ranges(cx)
17682            };
17683
17684            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17685                let newest_selection_id = this.selections.newest_anchor().id;
17686                this.selections
17687                    .all::<OffsetUtf16>(cx)
17688                    .iter()
17689                    .zip(ranges_to_replace.iter())
17690                    .find_map(|(selection, range)| {
17691                        if selection.id == newest_selection_id {
17692                            Some(
17693                                (range.start.0 as isize - selection.head().0 as isize)
17694                                    ..(range.end.0 as isize - selection.head().0 as isize),
17695                            )
17696                        } else {
17697                            None
17698                        }
17699                    })
17700            });
17701
17702            cx.emit(EditorEvent::InputHandled {
17703                utf16_range_to_replace: range_to_replace,
17704                text: text.into(),
17705            });
17706
17707            if let Some(new_selected_ranges) = new_selected_ranges {
17708                this.change_selections(None, window, cx, |selections| {
17709                    selections.select_ranges(new_selected_ranges)
17710                });
17711                this.backspace(&Default::default(), window, cx);
17712            }
17713
17714            this.handle_input(text, window, cx);
17715        });
17716
17717        if let Some(transaction) = self.ime_transaction {
17718            self.buffer.update(cx, |buffer, cx| {
17719                buffer.group_until_transaction(transaction, cx);
17720            });
17721        }
17722
17723        self.unmark_text(window, cx);
17724    }
17725
17726    fn replace_and_mark_text_in_range(
17727        &mut self,
17728        range_utf16: Option<Range<usize>>,
17729        text: &str,
17730        new_selected_range_utf16: Option<Range<usize>>,
17731        window: &mut Window,
17732        cx: &mut Context<Self>,
17733    ) {
17734        if !self.input_enabled {
17735            return;
17736        }
17737
17738        let transaction = self.transact(window, cx, |this, window, cx| {
17739            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17740                let snapshot = this.buffer.read(cx).read(cx);
17741                if let Some(relative_range_utf16) = range_utf16.as_ref() {
17742                    for marked_range in &mut marked_ranges {
17743                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17744                        marked_range.start.0 += relative_range_utf16.start;
17745                        marked_range.start =
17746                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17747                        marked_range.end =
17748                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17749                    }
17750                }
17751                Some(marked_ranges)
17752            } else if let Some(range_utf16) = range_utf16 {
17753                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17754                Some(this.selection_replacement_ranges(range_utf16, cx))
17755            } else {
17756                None
17757            };
17758
17759            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17760                let newest_selection_id = this.selections.newest_anchor().id;
17761                this.selections
17762                    .all::<OffsetUtf16>(cx)
17763                    .iter()
17764                    .zip(ranges_to_replace.iter())
17765                    .find_map(|(selection, range)| {
17766                        if selection.id == newest_selection_id {
17767                            Some(
17768                                (range.start.0 as isize - selection.head().0 as isize)
17769                                    ..(range.end.0 as isize - selection.head().0 as isize),
17770                            )
17771                        } else {
17772                            None
17773                        }
17774                    })
17775            });
17776
17777            cx.emit(EditorEvent::InputHandled {
17778                utf16_range_to_replace: range_to_replace,
17779                text: text.into(),
17780            });
17781
17782            if let Some(ranges) = ranges_to_replace {
17783                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17784            }
17785
17786            let marked_ranges = {
17787                let snapshot = this.buffer.read(cx).read(cx);
17788                this.selections
17789                    .disjoint_anchors()
17790                    .iter()
17791                    .map(|selection| {
17792                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17793                    })
17794                    .collect::<Vec<_>>()
17795            };
17796
17797            if text.is_empty() {
17798                this.unmark_text(window, cx);
17799            } else {
17800                this.highlight_text::<InputComposition>(
17801                    marked_ranges.clone(),
17802                    HighlightStyle {
17803                        underline: Some(UnderlineStyle {
17804                            thickness: px(1.),
17805                            color: None,
17806                            wavy: false,
17807                        }),
17808                        ..Default::default()
17809                    },
17810                    cx,
17811                );
17812            }
17813
17814            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17815            let use_autoclose = this.use_autoclose;
17816            let use_auto_surround = this.use_auto_surround;
17817            this.set_use_autoclose(false);
17818            this.set_use_auto_surround(false);
17819            this.handle_input(text, window, cx);
17820            this.set_use_autoclose(use_autoclose);
17821            this.set_use_auto_surround(use_auto_surround);
17822
17823            if let Some(new_selected_range) = new_selected_range_utf16 {
17824                let snapshot = this.buffer.read(cx).read(cx);
17825                let new_selected_ranges = marked_ranges
17826                    .into_iter()
17827                    .map(|marked_range| {
17828                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17829                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17830                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17831                        snapshot.clip_offset_utf16(new_start, Bias::Left)
17832                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17833                    })
17834                    .collect::<Vec<_>>();
17835
17836                drop(snapshot);
17837                this.change_selections(None, window, cx, |selections| {
17838                    selections.select_ranges(new_selected_ranges)
17839                });
17840            }
17841        });
17842
17843        self.ime_transaction = self.ime_transaction.or(transaction);
17844        if let Some(transaction) = self.ime_transaction {
17845            self.buffer.update(cx, |buffer, cx| {
17846                buffer.group_until_transaction(transaction, cx);
17847            });
17848        }
17849
17850        if self.text_highlights::<InputComposition>(cx).is_none() {
17851            self.ime_transaction.take();
17852        }
17853    }
17854
17855    fn bounds_for_range(
17856        &mut self,
17857        range_utf16: Range<usize>,
17858        element_bounds: gpui::Bounds<Pixels>,
17859        window: &mut Window,
17860        cx: &mut Context<Self>,
17861    ) -> Option<gpui::Bounds<Pixels>> {
17862        let text_layout_details = self.text_layout_details(window);
17863        let gpui::Size {
17864            width: em_width,
17865            height: line_height,
17866        } = self.character_size(window);
17867
17868        let snapshot = self.snapshot(window, cx);
17869        let scroll_position = snapshot.scroll_position();
17870        let scroll_left = scroll_position.x * em_width;
17871
17872        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17873        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17874            + self.gutter_dimensions.width
17875            + self.gutter_dimensions.margin;
17876        let y = line_height * (start.row().as_f32() - scroll_position.y);
17877
17878        Some(Bounds {
17879            origin: element_bounds.origin + point(x, y),
17880            size: size(em_width, line_height),
17881        })
17882    }
17883
17884    fn character_index_for_point(
17885        &mut self,
17886        point: gpui::Point<Pixels>,
17887        _window: &mut Window,
17888        _cx: &mut Context<Self>,
17889    ) -> Option<usize> {
17890        let position_map = self.last_position_map.as_ref()?;
17891        if !position_map.text_hitbox.contains(&point) {
17892            return None;
17893        }
17894        let display_point = position_map.point_for_position(point).previous_valid;
17895        let anchor = position_map
17896            .snapshot
17897            .display_point_to_anchor(display_point, Bias::Left);
17898        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17899        Some(utf16_offset.0)
17900    }
17901}
17902
17903trait SelectionExt {
17904    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17905    fn spanned_rows(
17906        &self,
17907        include_end_if_at_line_start: bool,
17908        map: &DisplaySnapshot,
17909    ) -> Range<MultiBufferRow>;
17910}
17911
17912impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17913    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17914        let start = self
17915            .start
17916            .to_point(&map.buffer_snapshot)
17917            .to_display_point(map);
17918        let end = self
17919            .end
17920            .to_point(&map.buffer_snapshot)
17921            .to_display_point(map);
17922        if self.reversed {
17923            end..start
17924        } else {
17925            start..end
17926        }
17927    }
17928
17929    fn spanned_rows(
17930        &self,
17931        include_end_if_at_line_start: bool,
17932        map: &DisplaySnapshot,
17933    ) -> Range<MultiBufferRow> {
17934        let start = self.start.to_point(&map.buffer_snapshot);
17935        let mut end = self.end.to_point(&map.buffer_snapshot);
17936        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17937            end.row -= 1;
17938        }
17939
17940        let buffer_start = map.prev_line_boundary(start).0;
17941        let buffer_end = map.next_line_boundary(end).0;
17942        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17943    }
17944}
17945
17946impl<T: InvalidationRegion> InvalidationStack<T> {
17947    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17948    where
17949        S: Clone + ToOffset,
17950    {
17951        while let Some(region) = self.last() {
17952            let all_selections_inside_invalidation_ranges =
17953                if selections.len() == region.ranges().len() {
17954                    selections
17955                        .iter()
17956                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17957                        .all(|(selection, invalidation_range)| {
17958                            let head = selection.head().to_offset(buffer);
17959                            invalidation_range.start <= head && invalidation_range.end >= head
17960                        })
17961                } else {
17962                    false
17963                };
17964
17965            if all_selections_inside_invalidation_ranges {
17966                break;
17967            } else {
17968                self.pop();
17969            }
17970        }
17971    }
17972}
17973
17974impl<T> Default for InvalidationStack<T> {
17975    fn default() -> Self {
17976        Self(Default::default())
17977    }
17978}
17979
17980impl<T> Deref for InvalidationStack<T> {
17981    type Target = Vec<T>;
17982
17983    fn deref(&self) -> &Self::Target {
17984        &self.0
17985    }
17986}
17987
17988impl<T> DerefMut for InvalidationStack<T> {
17989    fn deref_mut(&mut self) -> &mut Self::Target {
17990        &mut self.0
17991    }
17992}
17993
17994impl InvalidationRegion for SnippetState {
17995    fn ranges(&self) -> &[Range<Anchor>] {
17996        &self.ranges[self.active_index]
17997    }
17998}
17999
18000pub fn diagnostic_block_renderer(
18001    diagnostic: Diagnostic,
18002    max_message_rows: Option<u8>,
18003    allow_closing: bool,
18004) -> RenderBlock {
18005    let (text_without_backticks, code_ranges) =
18006        highlight_diagnostic_message(&diagnostic, max_message_rows);
18007
18008    Arc::new(move |cx: &mut BlockContext| {
18009        let group_id: SharedString = cx.block_id.to_string().into();
18010
18011        let mut text_style = cx.window.text_style().clone();
18012        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
18013        let theme_settings = ThemeSettings::get_global(cx);
18014        text_style.font_family = theme_settings.buffer_font.family.clone();
18015        text_style.font_style = theme_settings.buffer_font.style;
18016        text_style.font_features = theme_settings.buffer_font.features.clone();
18017        text_style.font_weight = theme_settings.buffer_font.weight;
18018
18019        let multi_line_diagnostic = diagnostic.message.contains('\n');
18020
18021        let buttons = |diagnostic: &Diagnostic| {
18022            if multi_line_diagnostic {
18023                v_flex()
18024            } else {
18025                h_flex()
18026            }
18027            .when(allow_closing, |div| {
18028                div.children(diagnostic.is_primary.then(|| {
18029                    IconButton::new("close-block", IconName::XCircle)
18030                        .icon_color(Color::Muted)
18031                        .size(ButtonSize::Compact)
18032                        .style(ButtonStyle::Transparent)
18033                        .visible_on_hover(group_id.clone())
18034                        .on_click(move |_click, window, cx| {
18035                            window.dispatch_action(Box::new(Cancel), cx)
18036                        })
18037                        .tooltip(|window, cx| {
18038                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
18039                        })
18040                }))
18041            })
18042            .child(
18043                IconButton::new("copy-block", IconName::Copy)
18044                    .icon_color(Color::Muted)
18045                    .size(ButtonSize::Compact)
18046                    .style(ButtonStyle::Transparent)
18047                    .visible_on_hover(group_id.clone())
18048                    .on_click({
18049                        let message = diagnostic.message.clone();
18050                        move |_click, _, cx| {
18051                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
18052                        }
18053                    })
18054                    .tooltip(Tooltip::text("Copy diagnostic message")),
18055            )
18056        };
18057
18058        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
18059            AvailableSpace::min_size(),
18060            cx.window,
18061            cx.app,
18062        );
18063
18064        h_flex()
18065            .id(cx.block_id)
18066            .group(group_id.clone())
18067            .relative()
18068            .size_full()
18069            .block_mouse_down()
18070            .pl(cx.gutter_dimensions.width)
18071            .w(cx.max_width - cx.gutter_dimensions.full_width())
18072            .child(
18073                div()
18074                    .flex()
18075                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
18076                    .flex_shrink(),
18077            )
18078            .child(buttons(&diagnostic))
18079            .child(div().flex().flex_shrink_0().child(
18080                StyledText::new(text_without_backticks.clone()).with_default_highlights(
18081                    &text_style,
18082                    code_ranges.iter().map(|range| {
18083                        (
18084                            range.clone(),
18085                            HighlightStyle {
18086                                font_weight: Some(FontWeight::BOLD),
18087                                ..Default::default()
18088                            },
18089                        )
18090                    }),
18091                ),
18092            ))
18093            .into_any_element()
18094    })
18095}
18096
18097fn inline_completion_edit_text(
18098    current_snapshot: &BufferSnapshot,
18099    edits: &[(Range<Anchor>, String)],
18100    edit_preview: &EditPreview,
18101    include_deletions: bool,
18102    cx: &App,
18103) -> HighlightedText {
18104    let edits = edits
18105        .iter()
18106        .map(|(anchor, text)| {
18107            (
18108                anchor.start.text_anchor..anchor.end.text_anchor,
18109                text.clone(),
18110            )
18111        })
18112        .collect::<Vec<_>>();
18113
18114    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18115}
18116
18117pub fn highlight_diagnostic_message(
18118    diagnostic: &Diagnostic,
18119    mut max_message_rows: Option<u8>,
18120) -> (SharedString, Vec<Range<usize>>) {
18121    let mut text_without_backticks = String::new();
18122    let mut code_ranges = Vec::new();
18123
18124    if let Some(source) = &diagnostic.source {
18125        text_without_backticks.push_str(source);
18126        code_ranges.push(0..source.len());
18127        text_without_backticks.push_str(": ");
18128    }
18129
18130    let mut prev_offset = 0;
18131    let mut in_code_block = false;
18132    let has_row_limit = max_message_rows.is_some();
18133    let mut newline_indices = diagnostic
18134        .message
18135        .match_indices('\n')
18136        .filter(|_| has_row_limit)
18137        .map(|(ix, _)| ix)
18138        .fuse()
18139        .peekable();
18140
18141    for (quote_ix, _) in diagnostic
18142        .message
18143        .match_indices('`')
18144        .chain([(diagnostic.message.len(), "")])
18145    {
18146        let mut first_newline_ix = None;
18147        let mut last_newline_ix = None;
18148        while let Some(newline_ix) = newline_indices.peek() {
18149            if *newline_ix < quote_ix {
18150                if first_newline_ix.is_none() {
18151                    first_newline_ix = Some(*newline_ix);
18152                }
18153                last_newline_ix = Some(*newline_ix);
18154
18155                if let Some(rows_left) = &mut max_message_rows {
18156                    if *rows_left == 0 {
18157                        break;
18158                    } else {
18159                        *rows_left -= 1;
18160                    }
18161                }
18162                let _ = newline_indices.next();
18163            } else {
18164                break;
18165            }
18166        }
18167        let prev_len = text_without_backticks.len();
18168        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18169        text_without_backticks.push_str(new_text);
18170        if in_code_block {
18171            code_ranges.push(prev_len..text_without_backticks.len());
18172        }
18173        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18174        in_code_block = !in_code_block;
18175        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18176            text_without_backticks.push_str("...");
18177            break;
18178        }
18179    }
18180
18181    (text_without_backticks.into(), code_ranges)
18182}
18183
18184fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18185    match severity {
18186        DiagnosticSeverity::ERROR => colors.error,
18187        DiagnosticSeverity::WARNING => colors.warning,
18188        DiagnosticSeverity::INFORMATION => colors.info,
18189        DiagnosticSeverity::HINT => colors.info,
18190        _ => colors.ignored,
18191    }
18192}
18193
18194pub fn styled_runs_for_code_label<'a>(
18195    label: &'a CodeLabel,
18196    syntax_theme: &'a theme::SyntaxTheme,
18197) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18198    let fade_out = HighlightStyle {
18199        fade_out: Some(0.35),
18200        ..Default::default()
18201    };
18202
18203    let mut prev_end = label.filter_range.end;
18204    label
18205        .runs
18206        .iter()
18207        .enumerate()
18208        .flat_map(move |(ix, (range, highlight_id))| {
18209            let style = if let Some(style) = highlight_id.style(syntax_theme) {
18210                style
18211            } else {
18212                return Default::default();
18213            };
18214            let mut muted_style = style;
18215            muted_style.highlight(fade_out);
18216
18217            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18218            if range.start >= label.filter_range.end {
18219                if range.start > prev_end {
18220                    runs.push((prev_end..range.start, fade_out));
18221                }
18222                runs.push((range.clone(), muted_style));
18223            } else if range.end <= label.filter_range.end {
18224                runs.push((range.clone(), style));
18225            } else {
18226                runs.push((range.start..label.filter_range.end, style));
18227                runs.push((label.filter_range.end..range.end, muted_style));
18228            }
18229            prev_end = cmp::max(prev_end, range.end);
18230
18231            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18232                runs.push((prev_end..label.text.len(), fade_out));
18233            }
18234
18235            runs
18236        })
18237}
18238
18239pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18240    let mut prev_index = 0;
18241    let mut prev_codepoint: Option<char> = None;
18242    text.char_indices()
18243        .chain([(text.len(), '\0')])
18244        .filter_map(move |(index, codepoint)| {
18245            let prev_codepoint = prev_codepoint.replace(codepoint)?;
18246            let is_boundary = index == text.len()
18247                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18248                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18249            if is_boundary {
18250                let chunk = &text[prev_index..index];
18251                prev_index = index;
18252                Some(chunk)
18253            } else {
18254                None
18255            }
18256        })
18257}
18258
18259pub trait RangeToAnchorExt: Sized {
18260    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18261
18262    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18263        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18264        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18265    }
18266}
18267
18268impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18269    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18270        let start_offset = self.start.to_offset(snapshot);
18271        let end_offset = self.end.to_offset(snapshot);
18272        if start_offset == end_offset {
18273            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18274        } else {
18275            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18276        }
18277    }
18278}
18279
18280pub trait RowExt {
18281    fn as_f32(&self) -> f32;
18282
18283    fn next_row(&self) -> Self;
18284
18285    fn previous_row(&self) -> Self;
18286
18287    fn minus(&self, other: Self) -> u32;
18288}
18289
18290impl RowExt for DisplayRow {
18291    fn as_f32(&self) -> f32 {
18292        self.0 as f32
18293    }
18294
18295    fn next_row(&self) -> Self {
18296        Self(self.0 + 1)
18297    }
18298
18299    fn previous_row(&self) -> Self {
18300        Self(self.0.saturating_sub(1))
18301    }
18302
18303    fn minus(&self, other: Self) -> u32 {
18304        self.0 - other.0
18305    }
18306}
18307
18308impl RowExt for MultiBufferRow {
18309    fn as_f32(&self) -> f32 {
18310        self.0 as f32
18311    }
18312
18313    fn next_row(&self) -> Self {
18314        Self(self.0 + 1)
18315    }
18316
18317    fn previous_row(&self) -> Self {
18318        Self(self.0.saturating_sub(1))
18319    }
18320
18321    fn minus(&self, other: Self) -> u32 {
18322        self.0 - other.0
18323    }
18324}
18325
18326trait RowRangeExt {
18327    type Row;
18328
18329    fn len(&self) -> usize;
18330
18331    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18332}
18333
18334impl RowRangeExt for Range<MultiBufferRow> {
18335    type Row = MultiBufferRow;
18336
18337    fn len(&self) -> usize {
18338        (self.end.0 - self.start.0) as usize
18339    }
18340
18341    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18342        (self.start.0..self.end.0).map(MultiBufferRow)
18343    }
18344}
18345
18346impl RowRangeExt for Range<DisplayRow> {
18347    type Row = DisplayRow;
18348
18349    fn len(&self) -> usize {
18350        (self.end.0 - self.start.0) as usize
18351    }
18352
18353    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18354        (self.start.0..self.end.0).map(DisplayRow)
18355    }
18356}
18357
18358/// If select range has more than one line, we
18359/// just point the cursor to range.start.
18360fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18361    if range.start.row == range.end.row {
18362        range
18363    } else {
18364        range.start..range.start
18365    }
18366}
18367pub struct KillRing(ClipboardItem);
18368impl Global for KillRing {}
18369
18370const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18371
18372fn all_edits_insertions_or_deletions(
18373    edits: &Vec<(Range<Anchor>, String)>,
18374    snapshot: &MultiBufferSnapshot,
18375) -> bool {
18376    let mut all_insertions = true;
18377    let mut all_deletions = true;
18378
18379    for (range, new_text) in edits.iter() {
18380        let range_is_empty = range.to_offset(&snapshot).is_empty();
18381        let text_is_empty = new_text.is_empty();
18382
18383        if range_is_empty != text_is_empty {
18384            if range_is_empty {
18385                all_deletions = false;
18386            } else {
18387                all_insertions = false;
18388            }
18389        } else {
18390            return false;
18391        }
18392
18393        if !all_insertions && !all_deletions {
18394            return false;
18395        }
18396    }
18397    all_insertions || all_deletions
18398}
18399
18400struct MissingEditPredictionKeybindingTooltip;
18401
18402impl Render for MissingEditPredictionKeybindingTooltip {
18403    fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18404        ui::tooltip_container(window, cx, |container, _, cx| {
18405            container
18406                .flex_shrink_0()
18407                .max_w_80()
18408                .min_h(rems_from_px(124.))
18409                .justify_between()
18410                .child(
18411                    v_flex()
18412                        .flex_1()
18413                        .text_ui_sm(cx)
18414                        .child(Label::new("Conflict with Accept Keybinding"))
18415                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
18416                )
18417                .child(
18418                    h_flex()
18419                        .pb_1()
18420                        .gap_1()
18421                        .items_end()
18422                        .w_full()
18423                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
18424                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
18425                        }))
18426                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
18427                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
18428                        })),
18429                )
18430        })
18431    }
18432}