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 linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use buffer_diff::DiffHunkStatus;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{
   71    future::{self, Shared},
   72    FutureExt,
   73};
   74use fuzzy::StringMatchCandidate;
   75
   76use ::git::Restore;
   77use code_context_menus::{
   78    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   79    CompletionsMenu, ContextMenuOrigin,
   80};
   81use git::blame::GitBlame;
   82use gpui::{
   83    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   84    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   85    ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler,
   86    EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
   87    HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
   88    ParentElement, Pixels, Render, SharedString, Size, Stateful, Styled, StyledText, Subscription,
   89    Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   90    WeakEntity, WeakFocusHandle, Window,
   91};
   92use highlight_matching_bracket::refresh_matching_bracket_highlights;
   93use hover_popover::{hide_hover, HoverState};
   94use indent_guides::ActiveIndentGuidesState;
   95use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   96pub use inline_completion::Direction;
   97use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   98pub use items::MAX_TAB_TITLE_LEN;
   99use itertools::Itertools;
  100use language::{
  101    language_settings::{
  102        self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
  103    },
  104    point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
  105    Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, EditPredictionsMode,
  106    EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
  107    Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
  108};
  109use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  110use linked_editing_ranges::refresh_linked_ranges;
  111use mouse_context_menu::MouseContextMenu;
  112use persistence::DB;
  113pub use proposed_changes_editor::{
  114    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  115};
  116use smallvec::smallvec;
  117use std::iter::Peekable;
  118use task::{ResolvedTask, TaskTemplate, TaskVariables};
  119
  120use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  121pub use lsp::CompletionContext;
  122use lsp::{
  123    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  124    InsertTextFormat, LanguageServerId, LanguageServerName,
  125};
  126
  127use language::BufferSnapshot;
  128use movement::TextLayoutDetails;
  129pub use multi_buffer::{
  130    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  131    ToOffset, ToPoint,
  132};
  133use multi_buffer::{
  134    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  135    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  136};
  137use project::{
  138    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  139    project_settings::{GitGutterSetting, ProjectSettings},
  140    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  141    PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  142};
  143use rand::prelude::*;
  144use rpc::{proto::*, ErrorExt};
  145use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  146use selections_collection::{
  147    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  148};
  149use serde::{Deserialize, Serialize};
  150use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  151use smallvec::SmallVec;
  152use snippet::Snippet;
  153use std::{
  154    any::TypeId,
  155    borrow::Cow,
  156    cell::RefCell,
  157    cmp::{self, Ordering, Reverse},
  158    mem,
  159    num::NonZeroU32,
  160    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  161    path::{Path, PathBuf},
  162    rc::Rc,
  163    sync::Arc,
  164    time::{Duration, Instant},
  165};
  166pub use sum_tree::Bias;
  167use sum_tree::TreeMap;
  168use text::{BufferId, OffsetUtf16, Rope};
  169use theme::{
  170    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  171    ThemeColors, ThemeSettings,
  172};
  173use ui::{
  174    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  175    Tooltip,
  176};
  177use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  178use workspace::{
  179    item::{ItemHandle, PreviewTabsSettings},
  180    ItemId, RestoreOnStartupBehavior,
  181};
  182use workspace::{
  183    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  184    WorkspaceSettings,
  185};
  186use workspace::{
  187    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  188};
  189use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  190
  191use crate::hover_links::{find_url, find_url_from_range};
  192use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  193
  194pub const FILE_HEADER_HEIGHT: u32 = 2;
  195pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  196pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  197pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  198const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  199const MAX_LINE_LEN: usize = 1024;
  200const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  201const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  202pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  203#[doc(hidden)]
  204pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  205
  206pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  207pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  208pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  209
  210pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  211pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  212
  213const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  214    alt: true,
  215    shift: true,
  216    control: false,
  217    platform: false,
  218    function: false,
  219};
  220
  221#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  222pub enum InlayId {
  223    InlineCompletion(usize),
  224    Hint(usize),
  225}
  226
  227impl InlayId {
  228    fn id(&self) -> usize {
  229        match self {
  230            Self::InlineCompletion(id) => *id,
  231            Self::Hint(id) => *id,
  232        }
  233    }
  234}
  235
  236enum DocumentHighlightRead {}
  237enum DocumentHighlightWrite {}
  238enum InputComposition {}
  239enum SelectedTextHighlight {}
  240
  241#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  242pub enum Navigated {
  243    Yes,
  244    No,
  245}
  246
  247impl Navigated {
  248    pub fn from_bool(yes: bool) -> Navigated {
  249        if yes {
  250            Navigated::Yes
  251        } else {
  252            Navigated::No
  253        }
  254    }
  255}
  256
  257#[derive(Debug, Clone, PartialEq, Eq)]
  258enum DisplayDiffHunk {
  259    Folded {
  260        display_row: DisplayRow,
  261    },
  262    Unfolded {
  263        diff_base_byte_range: Range<usize>,
  264        display_row_range: Range<DisplayRow>,
  265        multi_buffer_range: Range<Anchor>,
  266        status: DiffHunkStatus,
  267    },
  268}
  269
  270pub fn init_settings(cx: &mut App) {
  271    EditorSettings::register(cx);
  272}
  273
  274pub fn init(cx: &mut App) {
  275    init_settings(cx);
  276
  277    workspace::register_project_item::<Editor>(cx);
  278    workspace::FollowableViewRegistry::register::<Editor>(cx);
  279    workspace::register_serializable_item::<Editor>(cx);
  280
  281    cx.observe_new(
  282        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  283            workspace.register_action(Editor::new_file);
  284            workspace.register_action(Editor::new_file_vertical);
  285            workspace.register_action(Editor::new_file_horizontal);
  286            workspace.register_action(Editor::cancel_language_server_work);
  287        },
  288    )
  289    .detach();
  290
  291    cx.on_action(move |_: &workspace::NewFile, cx| {
  292        let app_state = workspace::AppState::global(cx);
  293        if let Some(app_state) = app_state.upgrade() {
  294            workspace::open_new(
  295                Default::default(),
  296                app_state,
  297                cx,
  298                |workspace, window, cx| {
  299                    Editor::new_file(workspace, &Default::default(), window, cx)
  300                },
  301            )
  302            .detach();
  303        }
  304    });
  305    cx.on_action(move |_: &workspace::NewWindow, cx| {
  306        let app_state = workspace::AppState::global(cx);
  307        if let Some(app_state) = app_state.upgrade() {
  308            workspace::open_new(
  309                Default::default(),
  310                app_state,
  311                cx,
  312                |workspace, window, cx| {
  313                    cx.activate(true);
  314                    Editor::new_file(workspace, &Default::default(), window, cx)
  315                },
  316            )
  317            .detach();
  318        }
  319    });
  320}
  321
  322pub struct SearchWithinRange;
  323
  324trait InvalidationRegion {
  325    fn ranges(&self) -> &[Range<Anchor>];
  326}
  327
  328#[derive(Clone, Debug, PartialEq)]
  329pub enum SelectPhase {
  330    Begin {
  331        position: DisplayPoint,
  332        add: bool,
  333        click_count: usize,
  334    },
  335    BeginColumnar {
  336        position: DisplayPoint,
  337        reset: bool,
  338        goal_column: u32,
  339    },
  340    Extend {
  341        position: DisplayPoint,
  342        click_count: usize,
  343    },
  344    Update {
  345        position: DisplayPoint,
  346        goal_column: u32,
  347        scroll_delta: gpui::Point<f32>,
  348    },
  349    End,
  350}
  351
  352#[derive(Clone, Debug)]
  353pub enum SelectMode {
  354    Character,
  355    Word(Range<Anchor>),
  356    Line(Range<Anchor>),
  357    All,
  358}
  359
  360#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  361pub enum EditorMode {
  362    SingleLine { auto_width: bool },
  363    AutoHeight { max_lines: usize },
  364    Full,
  365}
  366
  367#[derive(Copy, Clone, Debug)]
  368pub enum SoftWrap {
  369    /// Prefer not to wrap at all.
  370    ///
  371    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  372    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  373    GitDiff,
  374    /// Prefer a single line generally, unless an overly long line is encountered.
  375    None,
  376    /// Soft wrap lines that exceed the editor width.
  377    EditorWidth,
  378    /// Soft wrap lines at the preferred line length.
  379    Column(u32),
  380    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  381    Bounded(u32),
  382}
  383
  384#[derive(Clone)]
  385pub struct EditorStyle {
  386    pub background: Hsla,
  387    pub local_player: PlayerColor,
  388    pub text: TextStyle,
  389    pub scrollbar_width: Pixels,
  390    pub syntax: Arc<SyntaxTheme>,
  391    pub status: StatusColors,
  392    pub inlay_hints_style: HighlightStyle,
  393    pub inline_completion_styles: InlineCompletionStyles,
  394    pub unnecessary_code_fade: f32,
  395}
  396
  397impl Default for EditorStyle {
  398    fn default() -> Self {
  399        Self {
  400            background: Hsla::default(),
  401            local_player: PlayerColor::default(),
  402            text: TextStyle::default(),
  403            scrollbar_width: Pixels::default(),
  404            syntax: Default::default(),
  405            // HACK: Status colors don't have a real default.
  406            // We should look into removing the status colors from the editor
  407            // style and retrieve them directly from the theme.
  408            status: StatusColors::dark(),
  409            inlay_hints_style: HighlightStyle::default(),
  410            inline_completion_styles: InlineCompletionStyles {
  411                insertion: HighlightStyle::default(),
  412                whitespace: HighlightStyle::default(),
  413            },
  414            unnecessary_code_fade: Default::default(),
  415        }
  416    }
  417}
  418
  419pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  420    let show_background = language_settings::language_settings(None, None, cx)
  421        .inlay_hints
  422        .show_background;
  423
  424    HighlightStyle {
  425        color: Some(cx.theme().status().hint),
  426        background_color: show_background.then(|| cx.theme().status().hint_background),
  427        ..HighlightStyle::default()
  428    }
  429}
  430
  431pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  432    InlineCompletionStyles {
  433        insertion: HighlightStyle {
  434            color: Some(cx.theme().status().predictive),
  435            ..HighlightStyle::default()
  436        },
  437        whitespace: HighlightStyle {
  438            background_color: Some(cx.theme().status().created_background),
  439            ..HighlightStyle::default()
  440        },
  441    }
  442}
  443
  444type CompletionId = usize;
  445
  446pub(crate) enum EditDisplayMode {
  447    TabAccept,
  448    DiffPopover,
  449    Inline,
  450}
  451
  452enum InlineCompletion {
  453    Edit {
  454        edits: Vec<(Range<Anchor>, String)>,
  455        edit_preview: Option<EditPreview>,
  456        display_mode: EditDisplayMode,
  457        snapshot: BufferSnapshot,
  458    },
  459    Move {
  460        target: Anchor,
  461        snapshot: BufferSnapshot,
  462    },
  463}
  464
  465struct InlineCompletionState {
  466    inlay_ids: Vec<InlayId>,
  467    completion: InlineCompletion,
  468    completion_id: Option<SharedString>,
  469    invalidation_range: Range<Anchor>,
  470}
  471
  472enum EditPredictionSettings {
  473    Disabled,
  474    Enabled {
  475        show_in_menu: bool,
  476        preview_requires_modifier: bool,
  477    },
  478}
  479
  480enum InlineCompletionHighlight {}
  481
  482#[derive(Debug, Clone)]
  483struct InlineDiagnostic {
  484    message: SharedString,
  485    group_id: usize,
  486    is_primary: bool,
  487    start: Point,
  488    severity: DiagnosticSeverity,
  489}
  490
  491pub enum MenuInlineCompletionsPolicy {
  492    Never,
  493    ByProvider,
  494}
  495
  496pub enum EditPredictionPreview {
  497    /// Modifier is not pressed
  498    Inactive { released_too_fast: bool },
  499    /// Modifier pressed
  500    Active {
  501        since: Instant,
  502        previous_scroll_position: Option<ScrollAnchor>,
  503    },
  504}
  505
  506impl EditPredictionPreview {
  507    pub fn released_too_fast(&self) -> bool {
  508        match self {
  509            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  510            EditPredictionPreview::Active { .. } => false,
  511        }
  512    }
  513
  514    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  515        if let EditPredictionPreview::Active {
  516            previous_scroll_position,
  517            ..
  518        } = self
  519        {
  520            *previous_scroll_position = scroll_position;
  521        }
  522    }
  523}
  524
  525#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  526struct EditorActionId(usize);
  527
  528impl EditorActionId {
  529    pub fn post_inc(&mut self) -> Self {
  530        let answer = self.0;
  531
  532        *self = Self(answer + 1);
  533
  534        Self(answer)
  535    }
  536}
  537
  538// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  539// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  540
  541type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  542type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  543
  544#[derive(Default)]
  545struct ScrollbarMarkerState {
  546    scrollbar_size: Size<Pixels>,
  547    dirty: bool,
  548    markers: Arc<[PaintQuad]>,
  549    pending_refresh: Option<Task<Result<()>>>,
  550}
  551
  552impl ScrollbarMarkerState {
  553    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  554        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  555    }
  556}
  557
  558#[derive(Clone, Debug)]
  559struct RunnableTasks {
  560    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  561    offset: multi_buffer::Anchor,
  562    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  563    column: u32,
  564    // Values of all named captures, including those starting with '_'
  565    extra_variables: HashMap<String, String>,
  566    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  567    context_range: Range<BufferOffset>,
  568}
  569
  570impl RunnableTasks {
  571    fn resolve<'a>(
  572        &'a self,
  573        cx: &'a task::TaskContext,
  574    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  575        self.templates.iter().filter_map(|(kind, template)| {
  576            template
  577                .resolve_task(&kind.to_id_base(), cx)
  578                .map(|task| (kind.clone(), task))
  579        })
  580    }
  581}
  582
  583#[derive(Clone)]
  584struct ResolvedTasks {
  585    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  586    position: Anchor,
  587}
  588#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  589struct BufferOffset(usize);
  590
  591// Addons allow storing per-editor state in other crates (e.g. Vim)
  592pub trait Addon: 'static {
  593    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  594
  595    fn render_buffer_header_controls(
  596        &self,
  597        _: &ExcerptInfo,
  598        _: &Window,
  599        _: &App,
  600    ) -> Option<AnyElement> {
  601        None
  602    }
  603
  604    fn to_any(&self) -> &dyn std::any::Any;
  605}
  606
  607#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  608pub enum IsVimMode {
  609    Yes,
  610    No,
  611}
  612
  613/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  614///
  615/// See the [module level documentation](self) for more information.
  616pub struct Editor {
  617    focus_handle: FocusHandle,
  618    last_focused_descendant: Option<WeakFocusHandle>,
  619    /// The text buffer being edited
  620    buffer: Entity<MultiBuffer>,
  621    /// Map of how text in the buffer should be displayed.
  622    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  623    pub display_map: Entity<DisplayMap>,
  624    pub selections: SelectionsCollection,
  625    pub scroll_manager: ScrollManager,
  626    /// When inline assist editors are linked, they all render cursors because
  627    /// typing enters text into each of them, even the ones that aren't focused.
  628    pub(crate) show_cursor_when_unfocused: bool,
  629    columnar_selection_tail: Option<Anchor>,
  630    add_selections_state: Option<AddSelectionsState>,
  631    select_next_state: Option<SelectNextState>,
  632    select_prev_state: Option<SelectNextState>,
  633    selection_history: SelectionHistory,
  634    autoclose_regions: Vec<AutocloseRegion>,
  635    snippet_stack: InvalidationStack<SnippetState>,
  636    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  637    ime_transaction: Option<TransactionId>,
  638    active_diagnostics: Option<ActiveDiagnosticGroup>,
  639    show_inline_diagnostics: bool,
  640    inline_diagnostics_update: Task<()>,
  641    inline_diagnostics_enabled: bool,
  642    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  643    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  644
  645    // TODO: make this a access method
  646    pub project: Option<Entity<Project>>,
  647    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  648    completion_provider: Option<Box<dyn CompletionProvider>>,
  649    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  650    blink_manager: Entity<BlinkManager>,
  651    show_cursor_names: bool,
  652    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  653    pub show_local_selections: bool,
  654    mode: EditorMode,
  655    show_breadcrumbs: bool,
  656    show_gutter: bool,
  657    show_scrollbars: bool,
  658    show_line_numbers: Option<bool>,
  659    use_relative_line_numbers: Option<bool>,
  660    show_git_diff_gutter: Option<bool>,
  661    show_code_actions: Option<bool>,
  662    show_runnables: Option<bool>,
  663    show_wrap_guides: Option<bool>,
  664    show_indent_guides: Option<bool>,
  665    placeholder_text: Option<Arc<str>>,
  666    highlight_order: usize,
  667    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  668    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  669    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  670    scrollbar_marker_state: ScrollbarMarkerState,
  671    active_indent_guides_state: ActiveIndentGuidesState,
  672    nav_history: Option<ItemNavHistory>,
  673    context_menu: RefCell<Option<CodeContextMenu>>,
  674    mouse_context_menu: Option<MouseContextMenu>,
  675    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  676    signature_help_state: SignatureHelpState,
  677    auto_signature_help: Option<bool>,
  678    find_all_references_task_sources: Vec<Anchor>,
  679    next_completion_id: CompletionId,
  680    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  681    code_actions_task: Option<Task<Result<()>>>,
  682    selection_highlight_task: Option<Task<()>>,
  683    document_highlights_task: Option<Task<()>>,
  684    linked_editing_range_task: Option<Task<Option<()>>>,
  685    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  686    pending_rename: Option<RenameState>,
  687    searchable: bool,
  688    cursor_shape: CursorShape,
  689    current_line_highlight: Option<CurrentLineHighlight>,
  690    collapse_matches: bool,
  691    autoindent_mode: Option<AutoindentMode>,
  692    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  693    input_enabled: bool,
  694    use_modal_editing: bool,
  695    read_only: bool,
  696    leader_peer_id: Option<PeerId>,
  697    remote_id: Option<ViewId>,
  698    hover_state: HoverState,
  699    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  700    gutter_hovered: bool,
  701    hovered_link_state: Option<HoveredLinkState>,
  702    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  703    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  704    active_inline_completion: Option<InlineCompletionState>,
  705    /// Used to prevent flickering as the user types while the menu is open
  706    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  707    edit_prediction_settings: EditPredictionSettings,
  708    inline_completions_hidden_for_vim_mode: bool,
  709    show_inline_completions_override: Option<bool>,
  710    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  711    edit_prediction_preview: EditPredictionPreview,
  712    edit_prediction_indent_conflict: bool,
  713    edit_prediction_requires_modifier_in_indent_conflict: bool,
  714    inlay_hint_cache: InlayHintCache,
  715    next_inlay_id: usize,
  716    _subscriptions: Vec<Subscription>,
  717    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  718    gutter_dimensions: GutterDimensions,
  719    style: Option<EditorStyle>,
  720    text_style_refinement: Option<TextStyleRefinement>,
  721    next_editor_action_id: EditorActionId,
  722    editor_actions:
  723        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  724    use_autoclose: bool,
  725    use_auto_surround: bool,
  726    auto_replace_emoji_shortcode: bool,
  727    show_git_blame_gutter: bool,
  728    show_git_blame_inline: bool,
  729    show_git_blame_inline_delay_task: Option<Task<()>>,
  730    git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
  731    git_blame_inline_enabled: bool,
  732    serialize_dirty_buffers: bool,
  733    show_selection_menu: Option<bool>,
  734    blame: Option<Entity<GitBlame>>,
  735    blame_subscription: Option<Subscription>,
  736    custom_context_menu: Option<
  737        Box<
  738            dyn 'static
  739                + Fn(
  740                    &mut Self,
  741                    DisplayPoint,
  742                    &mut Window,
  743                    &mut Context<Self>,
  744                ) -> Option<Entity<ui::ContextMenu>>,
  745        >,
  746    >,
  747    last_bounds: Option<Bounds<Pixels>>,
  748    last_position_map: Option<Rc<PositionMap>>,
  749    expect_bounds_change: Option<Bounds<Pixels>>,
  750    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  751    tasks_update_task: Option<Task<()>>,
  752    in_project_search: bool,
  753    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  754    breadcrumb_header: Option<String>,
  755    focused_block: Option<FocusedBlock>,
  756    next_scroll_position: NextScrollCursorCenterTopBottom,
  757    addons: HashMap<TypeId, Box<dyn Addon>>,
  758    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  759    load_diff_task: Option<Shared<Task<()>>>,
  760    selection_mark_mode: bool,
  761    toggle_fold_multiple_buffers: Task<()>,
  762    _scroll_cursor_center_top_bottom_task: Task<()>,
  763    serialize_selections: Task<()>,
  764}
  765
  766#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  767enum NextScrollCursorCenterTopBottom {
  768    #[default]
  769    Center,
  770    Top,
  771    Bottom,
  772}
  773
  774impl NextScrollCursorCenterTopBottom {
  775    fn next(&self) -> Self {
  776        match self {
  777            Self::Center => Self::Top,
  778            Self::Top => Self::Bottom,
  779            Self::Bottom => Self::Center,
  780        }
  781    }
  782}
  783
  784#[derive(Clone)]
  785pub struct EditorSnapshot {
  786    pub mode: EditorMode,
  787    show_gutter: bool,
  788    show_line_numbers: Option<bool>,
  789    show_git_diff_gutter: Option<bool>,
  790    show_code_actions: Option<bool>,
  791    show_runnables: Option<bool>,
  792    git_blame_gutter_max_author_length: Option<usize>,
  793    pub display_snapshot: DisplaySnapshot,
  794    pub placeholder_text: Option<Arc<str>>,
  795    is_focused: bool,
  796    scroll_anchor: ScrollAnchor,
  797    ongoing_scroll: OngoingScroll,
  798    current_line_highlight: CurrentLineHighlight,
  799    gutter_hovered: bool,
  800}
  801
  802const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  803
  804#[derive(Default, Debug, Clone, Copy)]
  805pub struct GutterDimensions {
  806    pub left_padding: Pixels,
  807    pub right_padding: Pixels,
  808    pub width: Pixels,
  809    pub margin: Pixels,
  810    pub git_blame_entries_width: Option<Pixels>,
  811}
  812
  813impl GutterDimensions {
  814    /// The full width of the space taken up by the gutter.
  815    pub fn full_width(&self) -> Pixels {
  816        self.margin + self.width
  817    }
  818
  819    /// The width of the space reserved for the fold indicators,
  820    /// use alongside 'justify_end' and `gutter_width` to
  821    /// right align content with the line numbers
  822    pub fn fold_area_width(&self) -> Pixels {
  823        self.margin + self.right_padding
  824    }
  825}
  826
  827#[derive(Debug)]
  828pub struct RemoteSelection {
  829    pub replica_id: ReplicaId,
  830    pub selection: Selection<Anchor>,
  831    pub cursor_shape: CursorShape,
  832    pub peer_id: PeerId,
  833    pub line_mode: bool,
  834    pub participant_index: Option<ParticipantIndex>,
  835    pub user_name: Option<SharedString>,
  836}
  837
  838#[derive(Clone, Debug)]
  839struct SelectionHistoryEntry {
  840    selections: Arc<[Selection<Anchor>]>,
  841    select_next_state: Option<SelectNextState>,
  842    select_prev_state: Option<SelectNextState>,
  843    add_selections_state: Option<AddSelectionsState>,
  844}
  845
  846enum SelectionHistoryMode {
  847    Normal,
  848    Undoing,
  849    Redoing,
  850}
  851
  852#[derive(Clone, PartialEq, Eq, Hash)]
  853struct HoveredCursor {
  854    replica_id: u16,
  855    selection_id: usize,
  856}
  857
  858impl Default for SelectionHistoryMode {
  859    fn default() -> Self {
  860        Self::Normal
  861    }
  862}
  863
  864#[derive(Default)]
  865struct SelectionHistory {
  866    #[allow(clippy::type_complexity)]
  867    selections_by_transaction:
  868        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  869    mode: SelectionHistoryMode,
  870    undo_stack: VecDeque<SelectionHistoryEntry>,
  871    redo_stack: VecDeque<SelectionHistoryEntry>,
  872}
  873
  874impl SelectionHistory {
  875    fn insert_transaction(
  876        &mut self,
  877        transaction_id: TransactionId,
  878        selections: Arc<[Selection<Anchor>]>,
  879    ) {
  880        self.selections_by_transaction
  881            .insert(transaction_id, (selections, None));
  882    }
  883
  884    #[allow(clippy::type_complexity)]
  885    fn transaction(
  886        &self,
  887        transaction_id: TransactionId,
  888    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  889        self.selections_by_transaction.get(&transaction_id)
  890    }
  891
  892    #[allow(clippy::type_complexity)]
  893    fn transaction_mut(
  894        &mut self,
  895        transaction_id: TransactionId,
  896    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  897        self.selections_by_transaction.get_mut(&transaction_id)
  898    }
  899
  900    fn push(&mut self, entry: SelectionHistoryEntry) {
  901        if !entry.selections.is_empty() {
  902            match self.mode {
  903                SelectionHistoryMode::Normal => {
  904                    self.push_undo(entry);
  905                    self.redo_stack.clear();
  906                }
  907                SelectionHistoryMode::Undoing => self.push_redo(entry),
  908                SelectionHistoryMode::Redoing => self.push_undo(entry),
  909            }
  910        }
  911    }
  912
  913    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  914        if self
  915            .undo_stack
  916            .back()
  917            .map_or(true, |e| e.selections != entry.selections)
  918        {
  919            self.undo_stack.push_back(entry);
  920            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  921                self.undo_stack.pop_front();
  922            }
  923        }
  924    }
  925
  926    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  927        if self
  928            .redo_stack
  929            .back()
  930            .map_or(true, |e| e.selections != entry.selections)
  931        {
  932            self.redo_stack.push_back(entry);
  933            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  934                self.redo_stack.pop_front();
  935            }
  936        }
  937    }
  938}
  939
  940struct RowHighlight {
  941    index: usize,
  942    range: Range<Anchor>,
  943    color: Hsla,
  944    should_autoscroll: bool,
  945}
  946
  947#[derive(Clone, Debug)]
  948struct AddSelectionsState {
  949    above: bool,
  950    stack: Vec<usize>,
  951}
  952
  953#[derive(Clone)]
  954struct SelectNextState {
  955    query: AhoCorasick,
  956    wordwise: bool,
  957    done: bool,
  958}
  959
  960impl std::fmt::Debug for SelectNextState {
  961    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  962        f.debug_struct(std::any::type_name::<Self>())
  963            .field("wordwise", &self.wordwise)
  964            .field("done", &self.done)
  965            .finish()
  966    }
  967}
  968
  969#[derive(Debug)]
  970struct AutocloseRegion {
  971    selection_id: usize,
  972    range: Range<Anchor>,
  973    pair: BracketPair,
  974}
  975
  976#[derive(Debug)]
  977struct SnippetState {
  978    ranges: Vec<Vec<Range<Anchor>>>,
  979    active_index: usize,
  980    choices: Vec<Option<Vec<String>>>,
  981}
  982
  983#[doc(hidden)]
  984pub struct RenameState {
  985    pub range: Range<Anchor>,
  986    pub old_name: Arc<str>,
  987    pub editor: Entity<Editor>,
  988    block_id: CustomBlockId,
  989}
  990
  991struct InvalidationStack<T>(Vec<T>);
  992
  993struct RegisteredInlineCompletionProvider {
  994    provider: Arc<dyn InlineCompletionProviderHandle>,
  995    _subscription: Subscription,
  996}
  997
  998#[derive(Debug, PartialEq, Eq)]
  999struct ActiveDiagnosticGroup {
 1000    primary_range: Range<Anchor>,
 1001    primary_message: String,
 1002    group_id: usize,
 1003    blocks: HashMap<CustomBlockId, Diagnostic>,
 1004    is_valid: bool,
 1005}
 1006
 1007#[derive(Serialize, Deserialize, Clone, Debug)]
 1008pub struct ClipboardSelection {
 1009    /// The number of bytes in this selection.
 1010    pub len: usize,
 1011    /// Whether this was a full-line selection.
 1012    pub is_entire_line: bool,
 1013    /// The column where this selection originally started.
 1014    pub start_column: u32,
 1015}
 1016
 1017#[derive(Debug)]
 1018pub(crate) struct NavigationData {
 1019    cursor_anchor: Anchor,
 1020    cursor_position: Point,
 1021    scroll_anchor: ScrollAnchor,
 1022    scroll_top_row: u32,
 1023}
 1024
 1025#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1026pub enum GotoDefinitionKind {
 1027    Symbol,
 1028    Declaration,
 1029    Type,
 1030    Implementation,
 1031}
 1032
 1033#[derive(Debug, Clone)]
 1034enum InlayHintRefreshReason {
 1035    ModifiersChanged(bool),
 1036    Toggle(bool),
 1037    SettingsChange(InlayHintSettings),
 1038    NewLinesShown,
 1039    BufferEdited(HashSet<Arc<Language>>),
 1040    RefreshRequested,
 1041    ExcerptsRemoved(Vec<ExcerptId>),
 1042}
 1043
 1044impl InlayHintRefreshReason {
 1045    fn description(&self) -> &'static str {
 1046        match self {
 1047            Self::ModifiersChanged(_) => "modifiers changed",
 1048            Self::Toggle(_) => "toggle",
 1049            Self::SettingsChange(_) => "settings change",
 1050            Self::NewLinesShown => "new lines shown",
 1051            Self::BufferEdited(_) => "buffer edited",
 1052            Self::RefreshRequested => "refresh requested",
 1053            Self::ExcerptsRemoved(_) => "excerpts removed",
 1054        }
 1055    }
 1056}
 1057
 1058pub enum FormatTarget {
 1059    Buffers,
 1060    Ranges(Vec<Range<MultiBufferPoint>>),
 1061}
 1062
 1063pub(crate) struct FocusedBlock {
 1064    id: BlockId,
 1065    focus_handle: WeakFocusHandle,
 1066}
 1067
 1068#[derive(Clone)]
 1069enum JumpData {
 1070    MultiBufferRow {
 1071        row: MultiBufferRow,
 1072        line_offset_from_top: u32,
 1073    },
 1074    MultiBufferPoint {
 1075        excerpt_id: ExcerptId,
 1076        position: Point,
 1077        anchor: text::Anchor,
 1078        line_offset_from_top: u32,
 1079    },
 1080}
 1081
 1082pub enum MultibufferSelectionMode {
 1083    First,
 1084    All,
 1085}
 1086
 1087impl Editor {
 1088    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1089        let buffer = cx.new(|cx| Buffer::local("", cx));
 1090        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1091        Self::new(
 1092            EditorMode::SingleLine { auto_width: false },
 1093            buffer,
 1094            None,
 1095            false,
 1096            window,
 1097            cx,
 1098        )
 1099    }
 1100
 1101    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1102        let buffer = cx.new(|cx| Buffer::local("", cx));
 1103        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1104        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1105    }
 1106
 1107    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1108        let buffer = cx.new(|cx| Buffer::local("", cx));
 1109        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1110        Self::new(
 1111            EditorMode::SingleLine { auto_width: true },
 1112            buffer,
 1113            None,
 1114            false,
 1115            window,
 1116            cx,
 1117        )
 1118    }
 1119
 1120    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1121        let buffer = cx.new(|cx| Buffer::local("", cx));
 1122        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1123        Self::new(
 1124            EditorMode::AutoHeight { max_lines },
 1125            buffer,
 1126            None,
 1127            false,
 1128            window,
 1129            cx,
 1130        )
 1131    }
 1132
 1133    pub fn for_buffer(
 1134        buffer: Entity<Buffer>,
 1135        project: Option<Entity<Project>>,
 1136        window: &mut Window,
 1137        cx: &mut Context<Self>,
 1138    ) -> Self {
 1139        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1140        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1141    }
 1142
 1143    pub fn for_multibuffer(
 1144        buffer: Entity<MultiBuffer>,
 1145        project: Option<Entity<Project>>,
 1146        show_excerpt_controls: bool,
 1147        window: &mut Window,
 1148        cx: &mut Context<Self>,
 1149    ) -> Self {
 1150        Self::new(
 1151            EditorMode::Full,
 1152            buffer,
 1153            project,
 1154            show_excerpt_controls,
 1155            window,
 1156            cx,
 1157        )
 1158    }
 1159
 1160    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1161        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1162        let mut clone = Self::new(
 1163            self.mode,
 1164            self.buffer.clone(),
 1165            self.project.clone(),
 1166            show_excerpt_controls,
 1167            window,
 1168            cx,
 1169        );
 1170        self.display_map.update(cx, |display_map, cx| {
 1171            let snapshot = display_map.snapshot(cx);
 1172            clone.display_map.update(cx, |display_map, cx| {
 1173                display_map.set_state(&snapshot, cx);
 1174            });
 1175        });
 1176        clone.selections.clone_state(&self.selections);
 1177        clone.scroll_manager.clone_state(&self.scroll_manager);
 1178        clone.searchable = self.searchable;
 1179        clone
 1180    }
 1181
 1182    pub fn new(
 1183        mode: EditorMode,
 1184        buffer: Entity<MultiBuffer>,
 1185        project: Option<Entity<Project>>,
 1186        show_excerpt_controls: bool,
 1187        window: &mut Window,
 1188        cx: &mut Context<Self>,
 1189    ) -> Self {
 1190        let style = window.text_style();
 1191        let font_size = style.font_size.to_pixels(window.rem_size());
 1192        let editor = cx.entity().downgrade();
 1193        let fold_placeholder = FoldPlaceholder {
 1194            constrain_width: true,
 1195            render: Arc::new(move |fold_id, fold_range, cx| {
 1196                let editor = editor.clone();
 1197                div()
 1198                    .id(fold_id)
 1199                    .bg(cx.theme().colors().ghost_element_background)
 1200                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1201                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1202                    .rounded_sm()
 1203                    .size_full()
 1204                    .cursor_pointer()
 1205                    .child("")
 1206                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1207                    .on_click(move |_, _window, cx| {
 1208                        editor
 1209                            .update(cx, |editor, cx| {
 1210                                editor.unfold_ranges(
 1211                                    &[fold_range.start..fold_range.end],
 1212                                    true,
 1213                                    false,
 1214                                    cx,
 1215                                );
 1216                                cx.stop_propagation();
 1217                            })
 1218                            .ok();
 1219                    })
 1220                    .into_any()
 1221            }),
 1222            merge_adjacent: true,
 1223            ..Default::default()
 1224        };
 1225        let display_map = cx.new(|cx| {
 1226            DisplayMap::new(
 1227                buffer.clone(),
 1228                style.font(),
 1229                font_size,
 1230                None,
 1231                show_excerpt_controls,
 1232                FILE_HEADER_HEIGHT,
 1233                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1234                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1235                fold_placeholder,
 1236                cx,
 1237            )
 1238        });
 1239
 1240        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1241
 1242        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1243
 1244        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1245            .then(|| language_settings::SoftWrap::None);
 1246
 1247        let mut project_subscriptions = Vec::new();
 1248        if mode == EditorMode::Full {
 1249            if let Some(project) = project.as_ref() {
 1250                if buffer.read(cx).is_singleton() {
 1251                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1252                        cx.emit(EditorEvent::TitleChanged);
 1253                    }));
 1254                }
 1255                project_subscriptions.push(cx.subscribe_in(
 1256                    project,
 1257                    window,
 1258                    |editor, _, event, window, cx| {
 1259                        if let project::Event::RefreshInlayHints = event {
 1260                            editor
 1261                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1262                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1263                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1264                                let focus_handle = editor.focus_handle(cx);
 1265                                if focus_handle.is_focused(window) {
 1266                                    let snapshot = buffer.read(cx).snapshot();
 1267                                    for (range, snippet) in snippet_edits {
 1268                                        let editor_range =
 1269                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1270                                        editor
 1271                                            .insert_snippet(
 1272                                                &[editor_range],
 1273                                                snippet.clone(),
 1274                                                window,
 1275                                                cx,
 1276                                            )
 1277                                            .ok();
 1278                                    }
 1279                                }
 1280                            }
 1281                        }
 1282                    },
 1283                ));
 1284                if let Some(task_inventory) = project
 1285                    .read(cx)
 1286                    .task_store()
 1287                    .read(cx)
 1288                    .task_inventory()
 1289                    .cloned()
 1290                {
 1291                    project_subscriptions.push(cx.observe_in(
 1292                        &task_inventory,
 1293                        window,
 1294                        |editor, _, window, cx| {
 1295                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1296                        },
 1297                    ));
 1298                }
 1299            }
 1300        }
 1301
 1302        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1303
 1304        let inlay_hint_settings =
 1305            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1306        let focus_handle = cx.focus_handle();
 1307        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1308            .detach();
 1309        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1310            .detach();
 1311        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1312            .detach();
 1313        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1314            .detach();
 1315
 1316        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1317            Some(false)
 1318        } else {
 1319            None
 1320        };
 1321
 1322        let mut code_action_providers = Vec::new();
 1323        let mut load_uncommitted_diff = None;
 1324        if let Some(project) = project.clone() {
 1325            load_uncommitted_diff = Some(
 1326                get_uncommitted_diff_for_buffer(
 1327                    &project,
 1328                    buffer.read(cx).all_buffers(),
 1329                    buffer.clone(),
 1330                    cx,
 1331                )
 1332                .shared(),
 1333            );
 1334            code_action_providers.push(Rc::new(project) as Rc<_>);
 1335        }
 1336
 1337        let mut this = Self {
 1338            focus_handle,
 1339            show_cursor_when_unfocused: false,
 1340            last_focused_descendant: None,
 1341            buffer: buffer.clone(),
 1342            display_map: display_map.clone(),
 1343            selections,
 1344            scroll_manager: ScrollManager::new(cx),
 1345            columnar_selection_tail: None,
 1346            add_selections_state: None,
 1347            select_next_state: None,
 1348            select_prev_state: None,
 1349            selection_history: Default::default(),
 1350            autoclose_regions: Default::default(),
 1351            snippet_stack: Default::default(),
 1352            select_larger_syntax_node_stack: Vec::new(),
 1353            ime_transaction: Default::default(),
 1354            active_diagnostics: None,
 1355            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1356            inline_diagnostics_update: Task::ready(()),
 1357            inline_diagnostics: Vec::new(),
 1358            soft_wrap_mode_override,
 1359            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1360            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1361            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1362            project,
 1363            blink_manager: blink_manager.clone(),
 1364            show_local_selections: true,
 1365            show_scrollbars: true,
 1366            mode,
 1367            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1368            show_gutter: mode == EditorMode::Full,
 1369            show_line_numbers: None,
 1370            use_relative_line_numbers: None,
 1371            show_git_diff_gutter: None,
 1372            show_code_actions: None,
 1373            show_runnables: None,
 1374            show_wrap_guides: None,
 1375            show_indent_guides,
 1376            placeholder_text: None,
 1377            highlight_order: 0,
 1378            highlighted_rows: HashMap::default(),
 1379            background_highlights: Default::default(),
 1380            gutter_highlights: TreeMap::default(),
 1381            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1382            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1383            nav_history: None,
 1384            context_menu: RefCell::new(None),
 1385            mouse_context_menu: None,
 1386            completion_tasks: Default::default(),
 1387            signature_help_state: SignatureHelpState::default(),
 1388            auto_signature_help: None,
 1389            find_all_references_task_sources: Vec::new(),
 1390            next_completion_id: 0,
 1391            next_inlay_id: 0,
 1392            code_action_providers,
 1393            available_code_actions: Default::default(),
 1394            code_actions_task: Default::default(),
 1395            selection_highlight_task: Default::default(),
 1396            document_highlights_task: Default::default(),
 1397            linked_editing_range_task: Default::default(),
 1398            pending_rename: Default::default(),
 1399            searchable: true,
 1400            cursor_shape: EditorSettings::get_global(cx)
 1401                .cursor_shape
 1402                .unwrap_or_default(),
 1403            current_line_highlight: None,
 1404            autoindent_mode: Some(AutoindentMode::EachLine),
 1405            collapse_matches: false,
 1406            workspace: None,
 1407            input_enabled: true,
 1408            use_modal_editing: mode == EditorMode::Full,
 1409            read_only: false,
 1410            use_autoclose: true,
 1411            use_auto_surround: true,
 1412            auto_replace_emoji_shortcode: false,
 1413            leader_peer_id: None,
 1414            remote_id: None,
 1415            hover_state: Default::default(),
 1416            pending_mouse_down: None,
 1417            hovered_link_state: Default::default(),
 1418            edit_prediction_provider: None,
 1419            active_inline_completion: None,
 1420            stale_inline_completion_in_menu: None,
 1421            edit_prediction_preview: EditPredictionPreview::Inactive {
 1422                released_too_fast: false,
 1423            },
 1424            inline_diagnostics_enabled: mode == EditorMode::Full,
 1425            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1426
 1427            gutter_hovered: false,
 1428            pixel_position_of_newest_cursor: None,
 1429            last_bounds: None,
 1430            last_position_map: None,
 1431            expect_bounds_change: None,
 1432            gutter_dimensions: GutterDimensions::default(),
 1433            style: None,
 1434            show_cursor_names: false,
 1435            hovered_cursors: Default::default(),
 1436            next_editor_action_id: EditorActionId::default(),
 1437            editor_actions: Rc::default(),
 1438            inline_completions_hidden_for_vim_mode: false,
 1439            show_inline_completions_override: None,
 1440            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1441            edit_prediction_settings: EditPredictionSettings::Disabled,
 1442            edit_prediction_indent_conflict: false,
 1443            edit_prediction_requires_modifier_in_indent_conflict: true,
 1444            custom_context_menu: None,
 1445            show_git_blame_gutter: false,
 1446            show_git_blame_inline: false,
 1447            show_selection_menu: None,
 1448            show_git_blame_inline_delay_task: None,
 1449            git_blame_inline_tooltip: None,
 1450            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1451            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1452                .session
 1453                .restore_unsaved_buffers,
 1454            blame: None,
 1455            blame_subscription: None,
 1456            tasks: Default::default(),
 1457            _subscriptions: vec![
 1458                cx.observe(&buffer, Self::on_buffer_changed),
 1459                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1460                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1461                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1462                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1463                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1464                cx.observe_window_activation(window, |editor, window, cx| {
 1465                    let active = window.is_window_active();
 1466                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1467                        if active {
 1468                            blink_manager.enable(cx);
 1469                        } else {
 1470                            blink_manager.disable(cx);
 1471                        }
 1472                    });
 1473                }),
 1474            ],
 1475            tasks_update_task: None,
 1476            linked_edit_ranges: Default::default(),
 1477            in_project_search: false,
 1478            previous_search_ranges: None,
 1479            breadcrumb_header: None,
 1480            focused_block: None,
 1481            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1482            addons: HashMap::default(),
 1483            registered_buffers: HashMap::default(),
 1484            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1485            selection_mark_mode: false,
 1486            toggle_fold_multiple_buffers: Task::ready(()),
 1487            serialize_selections: Task::ready(()),
 1488            text_style_refinement: None,
 1489            load_diff_task: load_uncommitted_diff,
 1490        };
 1491        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1492        this._subscriptions.extend(project_subscriptions);
 1493
 1494        this.end_selection(window, cx);
 1495        this.scroll_manager.show_scrollbar(window, cx);
 1496
 1497        if mode == EditorMode::Full {
 1498            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1499            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1500
 1501            if this.git_blame_inline_enabled {
 1502                this.git_blame_inline_enabled = true;
 1503                this.start_git_blame_inline(false, window, cx);
 1504            }
 1505
 1506            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1507                if let Some(project) = this.project.as_ref() {
 1508                    let handle = project.update(cx, |project, cx| {
 1509                        project.register_buffer_with_language_servers(&buffer, cx)
 1510                    });
 1511                    this.registered_buffers
 1512                        .insert(buffer.read(cx).remote_id(), handle);
 1513                }
 1514            }
 1515        }
 1516
 1517        this.report_editor_event("Editor Opened", None, cx);
 1518        this
 1519    }
 1520
 1521    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1522        self.mouse_context_menu
 1523            .as_ref()
 1524            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1525    }
 1526
 1527    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1528        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1529    }
 1530
 1531    fn key_context_internal(
 1532        &self,
 1533        has_active_edit_prediction: bool,
 1534        window: &Window,
 1535        cx: &App,
 1536    ) -> KeyContext {
 1537        let mut key_context = KeyContext::new_with_defaults();
 1538        key_context.add("Editor");
 1539        let mode = match self.mode {
 1540            EditorMode::SingleLine { .. } => "single_line",
 1541            EditorMode::AutoHeight { .. } => "auto_height",
 1542            EditorMode::Full => "full",
 1543        };
 1544
 1545        if EditorSettings::jupyter_enabled(cx) {
 1546            key_context.add("jupyter");
 1547        }
 1548
 1549        key_context.set("mode", mode);
 1550        if self.pending_rename.is_some() {
 1551            key_context.add("renaming");
 1552        }
 1553
 1554        match self.context_menu.borrow().as_ref() {
 1555            Some(CodeContextMenu::Completions(_)) => {
 1556                key_context.add("menu");
 1557                key_context.add("showing_completions");
 1558            }
 1559            Some(CodeContextMenu::CodeActions(_)) => {
 1560                key_context.add("menu");
 1561                key_context.add("showing_code_actions")
 1562            }
 1563            None => {}
 1564        }
 1565
 1566        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1567        if !self.focus_handle(cx).contains_focused(window, cx)
 1568            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1569        {
 1570            for addon in self.addons.values() {
 1571                addon.extend_key_context(&mut key_context, cx)
 1572            }
 1573        }
 1574
 1575        if let Some(extension) = self
 1576            .buffer
 1577            .read(cx)
 1578            .as_singleton()
 1579            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1580        {
 1581            key_context.set("extension", extension.to_string());
 1582        }
 1583
 1584        if has_active_edit_prediction {
 1585            if self.edit_prediction_in_conflict() {
 1586                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1587            } else {
 1588                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1589                key_context.add("copilot_suggestion");
 1590            }
 1591        }
 1592
 1593        if self.selection_mark_mode {
 1594            key_context.add("selection_mode");
 1595        }
 1596
 1597        key_context
 1598    }
 1599
 1600    pub fn edit_prediction_in_conflict(&self) -> bool {
 1601        if !self.show_edit_predictions_in_menu() {
 1602            return false;
 1603        }
 1604
 1605        let showing_completions = self
 1606            .context_menu
 1607            .borrow()
 1608            .as_ref()
 1609            .map_or(false, |context| {
 1610                matches!(context, CodeContextMenu::Completions(_))
 1611            });
 1612
 1613        showing_completions
 1614            || self.edit_prediction_requires_modifier()
 1615            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1616            // bindings to insert tab characters.
 1617            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1618    }
 1619
 1620    pub fn accept_edit_prediction_keybind(
 1621        &self,
 1622        window: &Window,
 1623        cx: &App,
 1624    ) -> AcceptEditPredictionBinding {
 1625        let key_context = self.key_context_internal(true, window, cx);
 1626        let in_conflict = self.edit_prediction_in_conflict();
 1627
 1628        AcceptEditPredictionBinding(
 1629            window
 1630                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1631                .into_iter()
 1632                .filter(|binding| {
 1633                    !in_conflict
 1634                        || binding
 1635                            .keystrokes()
 1636                            .first()
 1637                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1638                })
 1639                .rev()
 1640                .min_by_key(|binding| {
 1641                    binding
 1642                        .keystrokes()
 1643                        .first()
 1644                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1645                }),
 1646        )
 1647    }
 1648
 1649    pub fn new_file(
 1650        workspace: &mut Workspace,
 1651        _: &workspace::NewFile,
 1652        window: &mut Window,
 1653        cx: &mut Context<Workspace>,
 1654    ) {
 1655        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1656            "Failed to create buffer",
 1657            window,
 1658            cx,
 1659            |e, _, _| match e.error_code() {
 1660                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1661                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1662                e.error_tag("required").unwrap_or("the latest version")
 1663            )),
 1664                _ => None,
 1665            },
 1666        );
 1667    }
 1668
 1669    pub fn new_in_workspace(
 1670        workspace: &mut Workspace,
 1671        window: &mut Window,
 1672        cx: &mut Context<Workspace>,
 1673    ) -> Task<Result<Entity<Editor>>> {
 1674        let project = workspace.project().clone();
 1675        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1676
 1677        cx.spawn_in(window, |workspace, mut cx| async move {
 1678            let buffer = create.await?;
 1679            workspace.update_in(&mut cx, |workspace, window, cx| {
 1680                let editor =
 1681                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1682                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1683                editor
 1684            })
 1685        })
 1686    }
 1687
 1688    fn new_file_vertical(
 1689        workspace: &mut Workspace,
 1690        _: &workspace::NewFileSplitVertical,
 1691        window: &mut Window,
 1692        cx: &mut Context<Workspace>,
 1693    ) {
 1694        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1695    }
 1696
 1697    fn new_file_horizontal(
 1698        workspace: &mut Workspace,
 1699        _: &workspace::NewFileSplitHorizontal,
 1700        window: &mut Window,
 1701        cx: &mut Context<Workspace>,
 1702    ) {
 1703        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1704    }
 1705
 1706    fn new_file_in_direction(
 1707        workspace: &mut Workspace,
 1708        direction: SplitDirection,
 1709        window: &mut Window,
 1710        cx: &mut Context<Workspace>,
 1711    ) {
 1712        let project = workspace.project().clone();
 1713        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1714
 1715        cx.spawn_in(window, |workspace, mut cx| async move {
 1716            let buffer = create.await?;
 1717            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1718                workspace.split_item(
 1719                    direction,
 1720                    Box::new(
 1721                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1722                    ),
 1723                    window,
 1724                    cx,
 1725                )
 1726            })?;
 1727            anyhow::Ok(())
 1728        })
 1729        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1730            match e.error_code() {
 1731                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1732                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1733                e.error_tag("required").unwrap_or("the latest version")
 1734            )),
 1735                _ => None,
 1736            }
 1737        });
 1738    }
 1739
 1740    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1741        self.leader_peer_id
 1742    }
 1743
 1744    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1745        &self.buffer
 1746    }
 1747
 1748    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1749        self.workspace.as_ref()?.0.upgrade()
 1750    }
 1751
 1752    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1753        self.buffer().read(cx).title(cx)
 1754    }
 1755
 1756    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1757        let git_blame_gutter_max_author_length = self
 1758            .render_git_blame_gutter(cx)
 1759            .then(|| {
 1760                if let Some(blame) = self.blame.as_ref() {
 1761                    let max_author_length =
 1762                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1763                    Some(max_author_length)
 1764                } else {
 1765                    None
 1766                }
 1767            })
 1768            .flatten();
 1769
 1770        EditorSnapshot {
 1771            mode: self.mode,
 1772            show_gutter: self.show_gutter,
 1773            show_line_numbers: self.show_line_numbers,
 1774            show_git_diff_gutter: self.show_git_diff_gutter,
 1775            show_code_actions: self.show_code_actions,
 1776            show_runnables: self.show_runnables,
 1777            git_blame_gutter_max_author_length,
 1778            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1779            scroll_anchor: self.scroll_manager.anchor(),
 1780            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1781            placeholder_text: self.placeholder_text.clone(),
 1782            is_focused: self.focus_handle.is_focused(window),
 1783            current_line_highlight: self
 1784                .current_line_highlight
 1785                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1786            gutter_hovered: self.gutter_hovered,
 1787        }
 1788    }
 1789
 1790    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1791        self.buffer.read(cx).language_at(point, cx)
 1792    }
 1793
 1794    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1795        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1796    }
 1797
 1798    pub fn active_excerpt(
 1799        &self,
 1800        cx: &App,
 1801    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1802        self.buffer
 1803            .read(cx)
 1804            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1805    }
 1806
 1807    pub fn mode(&self) -> EditorMode {
 1808        self.mode
 1809    }
 1810
 1811    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1812        self.collaboration_hub.as_deref()
 1813    }
 1814
 1815    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1816        self.collaboration_hub = Some(hub);
 1817    }
 1818
 1819    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1820        self.in_project_search = in_project_search;
 1821    }
 1822
 1823    pub fn set_custom_context_menu(
 1824        &mut self,
 1825        f: impl 'static
 1826            + Fn(
 1827                &mut Self,
 1828                DisplayPoint,
 1829                &mut Window,
 1830                &mut Context<Self>,
 1831            ) -> Option<Entity<ui::ContextMenu>>,
 1832    ) {
 1833        self.custom_context_menu = Some(Box::new(f))
 1834    }
 1835
 1836    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1837        self.completion_provider = provider;
 1838    }
 1839
 1840    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1841        self.semantics_provider.clone()
 1842    }
 1843
 1844    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1845        self.semantics_provider = provider;
 1846    }
 1847
 1848    pub fn set_edit_prediction_provider<T>(
 1849        &mut self,
 1850        provider: Option<Entity<T>>,
 1851        window: &mut Window,
 1852        cx: &mut Context<Self>,
 1853    ) where
 1854        T: EditPredictionProvider,
 1855    {
 1856        self.edit_prediction_provider =
 1857            provider.map(|provider| RegisteredInlineCompletionProvider {
 1858                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1859                    if this.focus_handle.is_focused(window) {
 1860                        this.update_visible_inline_completion(window, cx);
 1861                    }
 1862                }),
 1863                provider: Arc::new(provider),
 1864            });
 1865        self.update_edit_prediction_settings(cx);
 1866        self.refresh_inline_completion(false, false, window, cx);
 1867    }
 1868
 1869    pub fn placeholder_text(&self) -> Option<&str> {
 1870        self.placeholder_text.as_deref()
 1871    }
 1872
 1873    pub fn set_placeholder_text(
 1874        &mut self,
 1875        placeholder_text: impl Into<Arc<str>>,
 1876        cx: &mut Context<Self>,
 1877    ) {
 1878        let placeholder_text = Some(placeholder_text.into());
 1879        if self.placeholder_text != placeholder_text {
 1880            self.placeholder_text = placeholder_text;
 1881            cx.notify();
 1882        }
 1883    }
 1884
 1885    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1886        self.cursor_shape = cursor_shape;
 1887
 1888        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1889        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1890
 1891        cx.notify();
 1892    }
 1893
 1894    pub fn set_current_line_highlight(
 1895        &mut self,
 1896        current_line_highlight: Option<CurrentLineHighlight>,
 1897    ) {
 1898        self.current_line_highlight = current_line_highlight;
 1899    }
 1900
 1901    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1902        self.collapse_matches = collapse_matches;
 1903    }
 1904
 1905    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1906        let buffers = self.buffer.read(cx).all_buffers();
 1907        let Some(project) = self.project.as_ref() else {
 1908            return;
 1909        };
 1910        project.update(cx, |project, cx| {
 1911            for buffer in buffers {
 1912                self.registered_buffers
 1913                    .entry(buffer.read(cx).remote_id())
 1914                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1915            }
 1916        })
 1917    }
 1918
 1919    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1920        if self.collapse_matches {
 1921            return range.start..range.start;
 1922        }
 1923        range.clone()
 1924    }
 1925
 1926    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1927        if self.display_map.read(cx).clip_at_line_ends != clip {
 1928            self.display_map
 1929                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1930        }
 1931    }
 1932
 1933    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1934        self.input_enabled = input_enabled;
 1935    }
 1936
 1937    pub fn set_inline_completions_hidden_for_vim_mode(
 1938        &mut self,
 1939        hidden: bool,
 1940        window: &mut Window,
 1941        cx: &mut Context<Self>,
 1942    ) {
 1943        if hidden != self.inline_completions_hidden_for_vim_mode {
 1944            self.inline_completions_hidden_for_vim_mode = hidden;
 1945            if hidden {
 1946                self.update_visible_inline_completion(window, cx);
 1947            } else {
 1948                self.refresh_inline_completion(true, false, window, cx);
 1949            }
 1950        }
 1951    }
 1952
 1953    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1954        self.menu_inline_completions_policy = value;
 1955    }
 1956
 1957    pub fn set_autoindent(&mut self, autoindent: bool) {
 1958        if autoindent {
 1959            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1960        } else {
 1961            self.autoindent_mode = None;
 1962        }
 1963    }
 1964
 1965    pub fn read_only(&self, cx: &App) -> bool {
 1966        self.read_only || self.buffer.read(cx).read_only()
 1967    }
 1968
 1969    pub fn set_read_only(&mut self, read_only: bool) {
 1970        self.read_only = read_only;
 1971    }
 1972
 1973    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1974        self.use_autoclose = autoclose;
 1975    }
 1976
 1977    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1978        self.use_auto_surround = auto_surround;
 1979    }
 1980
 1981    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1982        self.auto_replace_emoji_shortcode = auto_replace;
 1983    }
 1984
 1985    pub fn toggle_edit_predictions(
 1986        &mut self,
 1987        _: &ToggleEditPrediction,
 1988        window: &mut Window,
 1989        cx: &mut Context<Self>,
 1990    ) {
 1991        if self.show_inline_completions_override.is_some() {
 1992            self.set_show_edit_predictions(None, window, cx);
 1993        } else {
 1994            let show_edit_predictions = !self.edit_predictions_enabled();
 1995            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1996        }
 1997    }
 1998
 1999    pub fn set_show_edit_predictions(
 2000        &mut self,
 2001        show_edit_predictions: Option<bool>,
 2002        window: &mut Window,
 2003        cx: &mut Context<Self>,
 2004    ) {
 2005        self.show_inline_completions_override = show_edit_predictions;
 2006        self.update_edit_prediction_settings(cx);
 2007
 2008        if let Some(false) = show_edit_predictions {
 2009            self.discard_inline_completion(false, cx);
 2010        } else {
 2011            self.refresh_inline_completion(false, true, window, cx);
 2012        }
 2013    }
 2014
 2015    fn inline_completions_disabled_in_scope(
 2016        &self,
 2017        buffer: &Entity<Buffer>,
 2018        buffer_position: language::Anchor,
 2019        cx: &App,
 2020    ) -> bool {
 2021        let snapshot = buffer.read(cx).snapshot();
 2022        let settings = snapshot.settings_at(buffer_position, cx);
 2023
 2024        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2025            return false;
 2026        };
 2027
 2028        scope.override_name().map_or(false, |scope_name| {
 2029            settings
 2030                .edit_predictions_disabled_in
 2031                .iter()
 2032                .any(|s| s == scope_name)
 2033        })
 2034    }
 2035
 2036    pub fn set_use_modal_editing(&mut self, to: bool) {
 2037        self.use_modal_editing = to;
 2038    }
 2039
 2040    pub fn use_modal_editing(&self) -> bool {
 2041        self.use_modal_editing
 2042    }
 2043
 2044    fn selections_did_change(
 2045        &mut self,
 2046        local: bool,
 2047        old_cursor_position: &Anchor,
 2048        show_completions: bool,
 2049        window: &mut Window,
 2050        cx: &mut Context<Self>,
 2051    ) {
 2052        window.invalidate_character_coordinates();
 2053
 2054        // Copy selections to primary selection buffer
 2055        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2056        if local {
 2057            let selections = self.selections.all::<usize>(cx);
 2058            let buffer_handle = self.buffer.read(cx).read(cx);
 2059
 2060            let mut text = String::new();
 2061            for (index, selection) in selections.iter().enumerate() {
 2062                let text_for_selection = buffer_handle
 2063                    .text_for_range(selection.start..selection.end)
 2064                    .collect::<String>();
 2065
 2066                text.push_str(&text_for_selection);
 2067                if index != selections.len() - 1 {
 2068                    text.push('\n');
 2069                }
 2070            }
 2071
 2072            if !text.is_empty() {
 2073                cx.write_to_primary(ClipboardItem::new_string(text));
 2074            }
 2075        }
 2076
 2077        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2078            self.buffer.update(cx, |buffer, cx| {
 2079                buffer.set_active_selections(
 2080                    &self.selections.disjoint_anchors(),
 2081                    self.selections.line_mode,
 2082                    self.cursor_shape,
 2083                    cx,
 2084                )
 2085            });
 2086        }
 2087        let display_map = self
 2088            .display_map
 2089            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2090        let buffer = &display_map.buffer_snapshot;
 2091        self.add_selections_state = None;
 2092        self.select_next_state = None;
 2093        self.select_prev_state = None;
 2094        self.select_larger_syntax_node_stack.clear();
 2095        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2096        self.snippet_stack
 2097            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2098        self.take_rename(false, window, cx);
 2099
 2100        let new_cursor_position = self.selections.newest_anchor().head();
 2101
 2102        self.push_to_nav_history(
 2103            *old_cursor_position,
 2104            Some(new_cursor_position.to_point(buffer)),
 2105            cx,
 2106        );
 2107
 2108        if local {
 2109            let new_cursor_position = self.selections.newest_anchor().head();
 2110            let mut context_menu = self.context_menu.borrow_mut();
 2111            let completion_menu = match context_menu.as_ref() {
 2112                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2113                _ => {
 2114                    *context_menu = None;
 2115                    None
 2116                }
 2117            };
 2118            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2119                if !self.registered_buffers.contains_key(&buffer_id) {
 2120                    if let Some(project) = self.project.as_ref() {
 2121                        project.update(cx, |project, cx| {
 2122                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2123                                return;
 2124                            };
 2125                            self.registered_buffers.insert(
 2126                                buffer_id,
 2127                                project.register_buffer_with_language_servers(&buffer, cx),
 2128                            );
 2129                        })
 2130                    }
 2131                }
 2132            }
 2133
 2134            if let Some(completion_menu) = completion_menu {
 2135                let cursor_position = new_cursor_position.to_offset(buffer);
 2136                let (word_range, kind) =
 2137                    buffer.surrounding_word(completion_menu.initial_position, true);
 2138                if kind == Some(CharKind::Word)
 2139                    && word_range.to_inclusive().contains(&cursor_position)
 2140                {
 2141                    let mut completion_menu = completion_menu.clone();
 2142                    drop(context_menu);
 2143
 2144                    let query = Self::completion_query(buffer, cursor_position);
 2145                    cx.spawn(move |this, mut cx| async move {
 2146                        completion_menu
 2147                            .filter(query.as_deref(), cx.background_executor().clone())
 2148                            .await;
 2149
 2150                        this.update(&mut cx, |this, cx| {
 2151                            let mut context_menu = this.context_menu.borrow_mut();
 2152                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2153                            else {
 2154                                return;
 2155                            };
 2156
 2157                            if menu.id > completion_menu.id {
 2158                                return;
 2159                            }
 2160
 2161                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2162                            drop(context_menu);
 2163                            cx.notify();
 2164                        })
 2165                    })
 2166                    .detach();
 2167
 2168                    if show_completions {
 2169                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2170                    }
 2171                } else {
 2172                    drop(context_menu);
 2173                    self.hide_context_menu(window, cx);
 2174                }
 2175            } else {
 2176                drop(context_menu);
 2177            }
 2178
 2179            hide_hover(self, cx);
 2180
 2181            if old_cursor_position.to_display_point(&display_map).row()
 2182                != new_cursor_position.to_display_point(&display_map).row()
 2183            {
 2184                self.available_code_actions.take();
 2185            }
 2186            self.refresh_code_actions(window, cx);
 2187            self.refresh_document_highlights(cx);
 2188            self.refresh_selected_text_highlights(window, cx);
 2189            refresh_matching_bracket_highlights(self, window, cx);
 2190            self.update_visible_inline_completion(window, cx);
 2191            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2192            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2193            if self.git_blame_inline_enabled {
 2194                self.start_inline_blame_timer(window, cx);
 2195            }
 2196        }
 2197
 2198        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2199        cx.emit(EditorEvent::SelectionsChanged { local });
 2200
 2201        let selections = &self.selections.disjoint;
 2202        if selections.len() == 1 {
 2203            cx.emit(SearchEvent::ActiveMatchChanged)
 2204        }
 2205        if local
 2206            && self.is_singleton(cx)
 2207            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2208        {
 2209            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2210                let background_executor = cx.background_executor().clone();
 2211                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2212                let snapshot = self.buffer().read(cx).snapshot(cx);
 2213                let selections = selections.clone();
 2214                self.serialize_selections = cx.background_spawn(async move {
 2215                    background_executor.timer(Duration::from_millis(100)).await;
 2216                    let selections = selections
 2217                        .iter()
 2218                        .map(|selection| {
 2219                            (
 2220                                selection.start.to_offset(&snapshot),
 2221                                selection.end.to_offset(&snapshot),
 2222                            )
 2223                        })
 2224                        .collect();
 2225                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2226                        .await
 2227                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2228                        .log_err();
 2229                });
 2230            }
 2231        }
 2232
 2233        cx.notify();
 2234    }
 2235
 2236    pub fn sync_selections(
 2237        &mut self,
 2238        other: Entity<Editor>,
 2239        cx: &mut Context<Self>,
 2240    ) -> gpui::Subscription {
 2241        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2242        self.selections.change_with(cx, |selections| {
 2243            selections.select_anchors(other_selections);
 2244        });
 2245
 2246        let other_subscription =
 2247            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2248                EditorEvent::SelectionsChanged { local: true } => {
 2249                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2250                    this.selections.change_with(cx, |selections| {
 2251                        selections.select_anchors(other_selections);
 2252                    });
 2253                }
 2254                _ => {}
 2255            });
 2256
 2257        let this_subscription =
 2258            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2259                EditorEvent::SelectionsChanged { local: true } => {
 2260                    let these_selections = this.selections.disjoint.to_vec();
 2261                    other.update(cx, |other_editor, cx| {
 2262                        other_editor.selections.change_with(cx, |selections| {
 2263                            selections.select_anchors(these_selections);
 2264                        })
 2265                    });
 2266                }
 2267                _ => {}
 2268            });
 2269
 2270        Subscription::join(other_subscription, this_subscription)
 2271    }
 2272
 2273    pub fn change_selections<R>(
 2274        &mut self,
 2275        autoscroll: Option<Autoscroll>,
 2276        window: &mut Window,
 2277        cx: &mut Context<Self>,
 2278        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2279    ) -> R {
 2280        self.change_selections_inner(autoscroll, true, window, cx, change)
 2281    }
 2282
 2283    fn change_selections_inner<R>(
 2284        &mut self,
 2285        autoscroll: Option<Autoscroll>,
 2286        request_completions: bool,
 2287        window: &mut Window,
 2288        cx: &mut Context<Self>,
 2289        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2290    ) -> R {
 2291        let old_cursor_position = self.selections.newest_anchor().head();
 2292        self.push_to_selection_history();
 2293
 2294        let (changed, result) = self.selections.change_with(cx, change);
 2295
 2296        if changed {
 2297            if let Some(autoscroll) = autoscroll {
 2298                self.request_autoscroll(autoscroll, cx);
 2299            }
 2300            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2301
 2302            if self.should_open_signature_help_automatically(
 2303                &old_cursor_position,
 2304                self.signature_help_state.backspace_pressed(),
 2305                cx,
 2306            ) {
 2307                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2308            }
 2309            self.signature_help_state.set_backspace_pressed(false);
 2310        }
 2311
 2312        result
 2313    }
 2314
 2315    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2316    where
 2317        I: IntoIterator<Item = (Range<S>, T)>,
 2318        S: ToOffset,
 2319        T: Into<Arc<str>>,
 2320    {
 2321        if self.read_only(cx) {
 2322            return;
 2323        }
 2324
 2325        self.buffer
 2326            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2327    }
 2328
 2329    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2330    where
 2331        I: IntoIterator<Item = (Range<S>, T)>,
 2332        S: ToOffset,
 2333        T: Into<Arc<str>>,
 2334    {
 2335        if self.read_only(cx) {
 2336            return;
 2337        }
 2338
 2339        self.buffer.update(cx, |buffer, cx| {
 2340            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2341        });
 2342    }
 2343
 2344    pub fn edit_with_block_indent<I, S, T>(
 2345        &mut self,
 2346        edits: I,
 2347        original_start_columns: Vec<u32>,
 2348        cx: &mut Context<Self>,
 2349    ) where
 2350        I: IntoIterator<Item = (Range<S>, T)>,
 2351        S: ToOffset,
 2352        T: Into<Arc<str>>,
 2353    {
 2354        if self.read_only(cx) {
 2355            return;
 2356        }
 2357
 2358        self.buffer.update(cx, |buffer, cx| {
 2359            buffer.edit(
 2360                edits,
 2361                Some(AutoindentMode::Block {
 2362                    original_start_columns,
 2363                }),
 2364                cx,
 2365            )
 2366        });
 2367    }
 2368
 2369    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2370        self.hide_context_menu(window, cx);
 2371
 2372        match phase {
 2373            SelectPhase::Begin {
 2374                position,
 2375                add,
 2376                click_count,
 2377            } => self.begin_selection(position, add, click_count, window, cx),
 2378            SelectPhase::BeginColumnar {
 2379                position,
 2380                goal_column,
 2381                reset,
 2382            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2383            SelectPhase::Extend {
 2384                position,
 2385                click_count,
 2386            } => self.extend_selection(position, click_count, window, cx),
 2387            SelectPhase::Update {
 2388                position,
 2389                goal_column,
 2390                scroll_delta,
 2391            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2392            SelectPhase::End => self.end_selection(window, cx),
 2393        }
 2394    }
 2395
 2396    fn extend_selection(
 2397        &mut self,
 2398        position: DisplayPoint,
 2399        click_count: usize,
 2400        window: &mut Window,
 2401        cx: &mut Context<Self>,
 2402    ) {
 2403        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2404        let tail = self.selections.newest::<usize>(cx).tail();
 2405        self.begin_selection(position, false, click_count, window, cx);
 2406
 2407        let position = position.to_offset(&display_map, Bias::Left);
 2408        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2409
 2410        let mut pending_selection = self
 2411            .selections
 2412            .pending_anchor()
 2413            .expect("extend_selection not called with pending selection");
 2414        if position >= tail {
 2415            pending_selection.start = tail_anchor;
 2416        } else {
 2417            pending_selection.end = tail_anchor;
 2418            pending_selection.reversed = true;
 2419        }
 2420
 2421        let mut pending_mode = self.selections.pending_mode().unwrap();
 2422        match &mut pending_mode {
 2423            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2424            _ => {}
 2425        }
 2426
 2427        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2428            s.set_pending(pending_selection, pending_mode)
 2429        });
 2430    }
 2431
 2432    fn begin_selection(
 2433        &mut self,
 2434        position: DisplayPoint,
 2435        add: bool,
 2436        click_count: usize,
 2437        window: &mut Window,
 2438        cx: &mut Context<Self>,
 2439    ) {
 2440        if !self.focus_handle.is_focused(window) {
 2441            self.last_focused_descendant = None;
 2442            window.focus(&self.focus_handle);
 2443        }
 2444
 2445        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2446        let buffer = &display_map.buffer_snapshot;
 2447        let newest_selection = self.selections.newest_anchor().clone();
 2448        let position = display_map.clip_point(position, Bias::Left);
 2449
 2450        let start;
 2451        let end;
 2452        let mode;
 2453        let mut auto_scroll;
 2454        match click_count {
 2455            1 => {
 2456                start = buffer.anchor_before(position.to_point(&display_map));
 2457                end = start;
 2458                mode = SelectMode::Character;
 2459                auto_scroll = true;
 2460            }
 2461            2 => {
 2462                let range = movement::surrounding_word(&display_map, position);
 2463                start = buffer.anchor_before(range.start.to_point(&display_map));
 2464                end = buffer.anchor_before(range.end.to_point(&display_map));
 2465                mode = SelectMode::Word(start..end);
 2466                auto_scroll = true;
 2467            }
 2468            3 => {
 2469                let position = display_map
 2470                    .clip_point(position, Bias::Left)
 2471                    .to_point(&display_map);
 2472                let line_start = display_map.prev_line_boundary(position).0;
 2473                let next_line_start = buffer.clip_point(
 2474                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2475                    Bias::Left,
 2476                );
 2477                start = buffer.anchor_before(line_start);
 2478                end = buffer.anchor_before(next_line_start);
 2479                mode = SelectMode::Line(start..end);
 2480                auto_scroll = true;
 2481            }
 2482            _ => {
 2483                start = buffer.anchor_before(0);
 2484                end = buffer.anchor_before(buffer.len());
 2485                mode = SelectMode::All;
 2486                auto_scroll = false;
 2487            }
 2488        }
 2489        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2490
 2491        let point_to_delete: Option<usize> = {
 2492            let selected_points: Vec<Selection<Point>> =
 2493                self.selections.disjoint_in_range(start..end, cx);
 2494
 2495            if !add || click_count > 1 {
 2496                None
 2497            } else if !selected_points.is_empty() {
 2498                Some(selected_points[0].id)
 2499            } else {
 2500                let clicked_point_already_selected =
 2501                    self.selections.disjoint.iter().find(|selection| {
 2502                        selection.start.to_point(buffer) == start.to_point(buffer)
 2503                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2504                    });
 2505
 2506                clicked_point_already_selected.map(|selection| selection.id)
 2507            }
 2508        };
 2509
 2510        let selections_count = self.selections.count();
 2511
 2512        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2513            if let Some(point_to_delete) = point_to_delete {
 2514                s.delete(point_to_delete);
 2515
 2516                if selections_count == 1 {
 2517                    s.set_pending_anchor_range(start..end, mode);
 2518                }
 2519            } else {
 2520                if !add {
 2521                    s.clear_disjoint();
 2522                } else if click_count > 1 {
 2523                    s.delete(newest_selection.id)
 2524                }
 2525
 2526                s.set_pending_anchor_range(start..end, mode);
 2527            }
 2528        });
 2529    }
 2530
 2531    fn begin_columnar_selection(
 2532        &mut self,
 2533        position: DisplayPoint,
 2534        goal_column: u32,
 2535        reset: bool,
 2536        window: &mut Window,
 2537        cx: &mut Context<Self>,
 2538    ) {
 2539        if !self.focus_handle.is_focused(window) {
 2540            self.last_focused_descendant = None;
 2541            window.focus(&self.focus_handle);
 2542        }
 2543
 2544        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2545
 2546        if reset {
 2547            let pointer_position = display_map
 2548                .buffer_snapshot
 2549                .anchor_before(position.to_point(&display_map));
 2550
 2551            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2552                s.clear_disjoint();
 2553                s.set_pending_anchor_range(
 2554                    pointer_position..pointer_position,
 2555                    SelectMode::Character,
 2556                );
 2557            });
 2558        }
 2559
 2560        let tail = self.selections.newest::<Point>(cx).tail();
 2561        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2562
 2563        if !reset {
 2564            self.select_columns(
 2565                tail.to_display_point(&display_map),
 2566                position,
 2567                goal_column,
 2568                &display_map,
 2569                window,
 2570                cx,
 2571            );
 2572        }
 2573    }
 2574
 2575    fn update_selection(
 2576        &mut self,
 2577        position: DisplayPoint,
 2578        goal_column: u32,
 2579        scroll_delta: gpui::Point<f32>,
 2580        window: &mut Window,
 2581        cx: &mut Context<Self>,
 2582    ) {
 2583        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2584
 2585        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2586            let tail = tail.to_display_point(&display_map);
 2587            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2588        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2589            let buffer = self.buffer.read(cx).snapshot(cx);
 2590            let head;
 2591            let tail;
 2592            let mode = self.selections.pending_mode().unwrap();
 2593            match &mode {
 2594                SelectMode::Character => {
 2595                    head = position.to_point(&display_map);
 2596                    tail = pending.tail().to_point(&buffer);
 2597                }
 2598                SelectMode::Word(original_range) => {
 2599                    let original_display_range = original_range.start.to_display_point(&display_map)
 2600                        ..original_range.end.to_display_point(&display_map);
 2601                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2602                        ..original_display_range.end.to_point(&display_map);
 2603                    if movement::is_inside_word(&display_map, position)
 2604                        || original_display_range.contains(&position)
 2605                    {
 2606                        let word_range = movement::surrounding_word(&display_map, position);
 2607                        if word_range.start < original_display_range.start {
 2608                            head = word_range.start.to_point(&display_map);
 2609                        } else {
 2610                            head = word_range.end.to_point(&display_map);
 2611                        }
 2612                    } else {
 2613                        head = position.to_point(&display_map);
 2614                    }
 2615
 2616                    if head <= original_buffer_range.start {
 2617                        tail = original_buffer_range.end;
 2618                    } else {
 2619                        tail = original_buffer_range.start;
 2620                    }
 2621                }
 2622                SelectMode::Line(original_range) => {
 2623                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2624
 2625                    let position = display_map
 2626                        .clip_point(position, Bias::Left)
 2627                        .to_point(&display_map);
 2628                    let line_start = display_map.prev_line_boundary(position).0;
 2629                    let next_line_start = buffer.clip_point(
 2630                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2631                        Bias::Left,
 2632                    );
 2633
 2634                    if line_start < original_range.start {
 2635                        head = line_start
 2636                    } else {
 2637                        head = next_line_start
 2638                    }
 2639
 2640                    if head <= original_range.start {
 2641                        tail = original_range.end;
 2642                    } else {
 2643                        tail = original_range.start;
 2644                    }
 2645                }
 2646                SelectMode::All => {
 2647                    return;
 2648                }
 2649            };
 2650
 2651            if head < tail {
 2652                pending.start = buffer.anchor_before(head);
 2653                pending.end = buffer.anchor_before(tail);
 2654                pending.reversed = true;
 2655            } else {
 2656                pending.start = buffer.anchor_before(tail);
 2657                pending.end = buffer.anchor_before(head);
 2658                pending.reversed = false;
 2659            }
 2660
 2661            self.change_selections(None, window, cx, |s| {
 2662                s.set_pending(pending, mode);
 2663            });
 2664        } else {
 2665            log::error!("update_selection dispatched with no pending selection");
 2666            return;
 2667        }
 2668
 2669        self.apply_scroll_delta(scroll_delta, window, cx);
 2670        cx.notify();
 2671    }
 2672
 2673    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2674        self.columnar_selection_tail.take();
 2675        if self.selections.pending_anchor().is_some() {
 2676            let selections = self.selections.all::<usize>(cx);
 2677            self.change_selections(None, window, cx, |s| {
 2678                s.select(selections);
 2679                s.clear_pending();
 2680            });
 2681        }
 2682    }
 2683
 2684    fn select_columns(
 2685        &mut self,
 2686        tail: DisplayPoint,
 2687        head: DisplayPoint,
 2688        goal_column: u32,
 2689        display_map: &DisplaySnapshot,
 2690        window: &mut Window,
 2691        cx: &mut Context<Self>,
 2692    ) {
 2693        let start_row = cmp::min(tail.row(), head.row());
 2694        let end_row = cmp::max(tail.row(), head.row());
 2695        let start_column = cmp::min(tail.column(), goal_column);
 2696        let end_column = cmp::max(tail.column(), goal_column);
 2697        let reversed = start_column < tail.column();
 2698
 2699        let selection_ranges = (start_row.0..=end_row.0)
 2700            .map(DisplayRow)
 2701            .filter_map(|row| {
 2702                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2703                    let start = display_map
 2704                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2705                        .to_point(display_map);
 2706                    let end = display_map
 2707                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2708                        .to_point(display_map);
 2709                    if reversed {
 2710                        Some(end..start)
 2711                    } else {
 2712                        Some(start..end)
 2713                    }
 2714                } else {
 2715                    None
 2716                }
 2717            })
 2718            .collect::<Vec<_>>();
 2719
 2720        self.change_selections(None, window, cx, |s| {
 2721            s.select_ranges(selection_ranges);
 2722        });
 2723        cx.notify();
 2724    }
 2725
 2726    pub fn has_pending_nonempty_selection(&self) -> bool {
 2727        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2728            Some(Selection { start, end, .. }) => start != end,
 2729            None => false,
 2730        };
 2731
 2732        pending_nonempty_selection
 2733            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2734    }
 2735
 2736    pub fn has_pending_selection(&self) -> bool {
 2737        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2738    }
 2739
 2740    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2741        self.selection_mark_mode = false;
 2742
 2743        if self.clear_expanded_diff_hunks(cx) {
 2744            cx.notify();
 2745            return;
 2746        }
 2747        if self.dismiss_menus_and_popups(true, window, cx) {
 2748            return;
 2749        }
 2750
 2751        if self.mode == EditorMode::Full
 2752            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2753        {
 2754            return;
 2755        }
 2756
 2757        cx.propagate();
 2758    }
 2759
 2760    pub fn dismiss_menus_and_popups(
 2761        &mut self,
 2762        is_user_requested: bool,
 2763        window: &mut Window,
 2764        cx: &mut Context<Self>,
 2765    ) -> bool {
 2766        if self.take_rename(false, window, cx).is_some() {
 2767            return true;
 2768        }
 2769
 2770        if hide_hover(self, cx) {
 2771            return true;
 2772        }
 2773
 2774        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2775            return true;
 2776        }
 2777
 2778        if self.hide_context_menu(window, cx).is_some() {
 2779            return true;
 2780        }
 2781
 2782        if self.mouse_context_menu.take().is_some() {
 2783            return true;
 2784        }
 2785
 2786        if is_user_requested && self.discard_inline_completion(true, cx) {
 2787            return true;
 2788        }
 2789
 2790        if self.snippet_stack.pop().is_some() {
 2791            return true;
 2792        }
 2793
 2794        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2795            self.dismiss_diagnostics(cx);
 2796            return true;
 2797        }
 2798
 2799        false
 2800    }
 2801
 2802    fn linked_editing_ranges_for(
 2803        &self,
 2804        selection: Range<text::Anchor>,
 2805        cx: &App,
 2806    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2807        if self.linked_edit_ranges.is_empty() {
 2808            return None;
 2809        }
 2810        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2811            selection.end.buffer_id.and_then(|end_buffer_id| {
 2812                if selection.start.buffer_id != Some(end_buffer_id) {
 2813                    return None;
 2814                }
 2815                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2816                let snapshot = buffer.read(cx).snapshot();
 2817                self.linked_edit_ranges
 2818                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2819                    .map(|ranges| (ranges, snapshot, buffer))
 2820            })?;
 2821        use text::ToOffset as TO;
 2822        // find offset from the start of current range to current cursor position
 2823        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2824
 2825        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2826        let start_difference = start_offset - start_byte_offset;
 2827        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2828        let end_difference = end_offset - start_byte_offset;
 2829        // Current range has associated linked ranges.
 2830        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2831        for range in linked_ranges.iter() {
 2832            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2833            let end_offset = start_offset + end_difference;
 2834            let start_offset = start_offset + start_difference;
 2835            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2836                continue;
 2837            }
 2838            if self.selections.disjoint_anchor_ranges().any(|s| {
 2839                if s.start.buffer_id != selection.start.buffer_id
 2840                    || s.end.buffer_id != selection.end.buffer_id
 2841                {
 2842                    return false;
 2843                }
 2844                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2845                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2846            }) {
 2847                continue;
 2848            }
 2849            let start = buffer_snapshot.anchor_after(start_offset);
 2850            let end = buffer_snapshot.anchor_after(end_offset);
 2851            linked_edits
 2852                .entry(buffer.clone())
 2853                .or_default()
 2854                .push(start..end);
 2855        }
 2856        Some(linked_edits)
 2857    }
 2858
 2859    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2860        let text: Arc<str> = text.into();
 2861
 2862        if self.read_only(cx) {
 2863            return;
 2864        }
 2865
 2866        let selections = self.selections.all_adjusted(cx);
 2867        let mut bracket_inserted = false;
 2868        let mut edits = Vec::new();
 2869        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2870        let mut new_selections = Vec::with_capacity(selections.len());
 2871        let mut new_autoclose_regions = Vec::new();
 2872        let snapshot = self.buffer.read(cx).read(cx);
 2873
 2874        for (selection, autoclose_region) in
 2875            self.selections_with_autoclose_regions(selections, &snapshot)
 2876        {
 2877            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2878                // Determine if the inserted text matches the opening or closing
 2879                // bracket of any of this language's bracket pairs.
 2880                let mut bracket_pair = None;
 2881                let mut is_bracket_pair_start = false;
 2882                let mut is_bracket_pair_end = false;
 2883                if !text.is_empty() {
 2884                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2885                    //  and they are removing the character that triggered IME popup.
 2886                    for (pair, enabled) in scope.brackets() {
 2887                        if !pair.close && !pair.surround {
 2888                            continue;
 2889                        }
 2890
 2891                        if enabled && pair.start.ends_with(text.as_ref()) {
 2892                            let prefix_len = pair.start.len() - text.len();
 2893                            let preceding_text_matches_prefix = prefix_len == 0
 2894                                || (selection.start.column >= (prefix_len as u32)
 2895                                    && snapshot.contains_str_at(
 2896                                        Point::new(
 2897                                            selection.start.row,
 2898                                            selection.start.column - (prefix_len as u32),
 2899                                        ),
 2900                                        &pair.start[..prefix_len],
 2901                                    ));
 2902                            if preceding_text_matches_prefix {
 2903                                bracket_pair = Some(pair.clone());
 2904                                is_bracket_pair_start = true;
 2905                                break;
 2906                            }
 2907                        }
 2908                        if pair.end.as_str() == text.as_ref() {
 2909                            bracket_pair = Some(pair.clone());
 2910                            is_bracket_pair_end = true;
 2911                            break;
 2912                        }
 2913                    }
 2914                }
 2915
 2916                if let Some(bracket_pair) = bracket_pair {
 2917                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 2918                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2919                    let auto_surround =
 2920                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2921                    if selection.is_empty() {
 2922                        if is_bracket_pair_start {
 2923                            // If the inserted text is a suffix of an opening bracket and the
 2924                            // selection is preceded by the rest of the opening bracket, then
 2925                            // insert the closing bracket.
 2926                            let following_text_allows_autoclose = snapshot
 2927                                .chars_at(selection.start)
 2928                                .next()
 2929                                .map_or(true, |c| scope.should_autoclose_before(c));
 2930
 2931                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2932                                && bracket_pair.start.len() == 1
 2933                            {
 2934                                let target = bracket_pair.start.chars().next().unwrap();
 2935                                let current_line_count = snapshot
 2936                                    .reversed_chars_at(selection.start)
 2937                                    .take_while(|&c| c != '\n')
 2938                                    .filter(|&c| c == target)
 2939                                    .count();
 2940                                current_line_count % 2 == 1
 2941                            } else {
 2942                                false
 2943                            };
 2944
 2945                            if autoclose
 2946                                && bracket_pair.close
 2947                                && following_text_allows_autoclose
 2948                                && !is_closing_quote
 2949                            {
 2950                                let anchor = snapshot.anchor_before(selection.end);
 2951                                new_selections.push((selection.map(|_| anchor), text.len()));
 2952                                new_autoclose_regions.push((
 2953                                    anchor,
 2954                                    text.len(),
 2955                                    selection.id,
 2956                                    bracket_pair.clone(),
 2957                                ));
 2958                                edits.push((
 2959                                    selection.range(),
 2960                                    format!("{}{}", text, bracket_pair.end).into(),
 2961                                ));
 2962                                bracket_inserted = true;
 2963                                continue;
 2964                            }
 2965                        }
 2966
 2967                        if let Some(region) = autoclose_region {
 2968                            // If the selection is followed by an auto-inserted closing bracket,
 2969                            // then don't insert that closing bracket again; just move the selection
 2970                            // past the closing bracket.
 2971                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2972                                && text.as_ref() == region.pair.end.as_str();
 2973                            if should_skip {
 2974                                let anchor = snapshot.anchor_after(selection.end);
 2975                                new_selections
 2976                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2977                                continue;
 2978                            }
 2979                        }
 2980
 2981                        let always_treat_brackets_as_autoclosed = snapshot
 2982                            .language_settings_at(selection.start, cx)
 2983                            .always_treat_brackets_as_autoclosed;
 2984                        if always_treat_brackets_as_autoclosed
 2985                            && is_bracket_pair_end
 2986                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2987                        {
 2988                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2989                            // and the inserted text is a closing bracket and the selection is followed
 2990                            // by the closing bracket then move the selection past the closing bracket.
 2991                            let anchor = snapshot.anchor_after(selection.end);
 2992                            new_selections.push((selection.map(|_| anchor), text.len()));
 2993                            continue;
 2994                        }
 2995                    }
 2996                    // If an opening bracket is 1 character long and is typed while
 2997                    // text is selected, then surround that text with the bracket pair.
 2998                    else if auto_surround
 2999                        && bracket_pair.surround
 3000                        && is_bracket_pair_start
 3001                        && bracket_pair.start.chars().count() == 1
 3002                    {
 3003                        edits.push((selection.start..selection.start, text.clone()));
 3004                        edits.push((
 3005                            selection.end..selection.end,
 3006                            bracket_pair.end.as_str().into(),
 3007                        ));
 3008                        bracket_inserted = true;
 3009                        new_selections.push((
 3010                            Selection {
 3011                                id: selection.id,
 3012                                start: snapshot.anchor_after(selection.start),
 3013                                end: snapshot.anchor_before(selection.end),
 3014                                reversed: selection.reversed,
 3015                                goal: selection.goal,
 3016                            },
 3017                            0,
 3018                        ));
 3019                        continue;
 3020                    }
 3021                }
 3022            }
 3023
 3024            if self.auto_replace_emoji_shortcode
 3025                && selection.is_empty()
 3026                && text.as_ref().ends_with(':')
 3027            {
 3028                if let Some(possible_emoji_short_code) =
 3029                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3030                {
 3031                    if !possible_emoji_short_code.is_empty() {
 3032                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3033                            let emoji_shortcode_start = Point::new(
 3034                                selection.start.row,
 3035                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3036                            );
 3037
 3038                            // Remove shortcode from buffer
 3039                            edits.push((
 3040                                emoji_shortcode_start..selection.start,
 3041                                "".to_string().into(),
 3042                            ));
 3043                            new_selections.push((
 3044                                Selection {
 3045                                    id: selection.id,
 3046                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3047                                    end: snapshot.anchor_before(selection.start),
 3048                                    reversed: selection.reversed,
 3049                                    goal: selection.goal,
 3050                                },
 3051                                0,
 3052                            ));
 3053
 3054                            // Insert emoji
 3055                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3056                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3057                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3058
 3059                            continue;
 3060                        }
 3061                    }
 3062                }
 3063            }
 3064
 3065            // If not handling any auto-close operation, then just replace the selected
 3066            // text with the given input and move the selection to the end of the
 3067            // newly inserted text.
 3068            let anchor = snapshot.anchor_after(selection.end);
 3069            if !self.linked_edit_ranges.is_empty() {
 3070                let start_anchor = snapshot.anchor_before(selection.start);
 3071
 3072                let is_word_char = text.chars().next().map_or(true, |char| {
 3073                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3074                    classifier.is_word(char)
 3075                });
 3076
 3077                if is_word_char {
 3078                    if let Some(ranges) = self
 3079                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3080                    {
 3081                        for (buffer, edits) in ranges {
 3082                            linked_edits
 3083                                .entry(buffer.clone())
 3084                                .or_default()
 3085                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3086                        }
 3087                    }
 3088                }
 3089            }
 3090
 3091            new_selections.push((selection.map(|_| anchor), 0));
 3092            edits.push((selection.start..selection.end, text.clone()));
 3093        }
 3094
 3095        drop(snapshot);
 3096
 3097        self.transact(window, cx, |this, window, cx| {
 3098            this.buffer.update(cx, |buffer, cx| {
 3099                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3100            });
 3101            for (buffer, edits) in linked_edits {
 3102                buffer.update(cx, |buffer, cx| {
 3103                    let snapshot = buffer.snapshot();
 3104                    let edits = edits
 3105                        .into_iter()
 3106                        .map(|(range, text)| {
 3107                            use text::ToPoint as TP;
 3108                            let end_point = TP::to_point(&range.end, &snapshot);
 3109                            let start_point = TP::to_point(&range.start, &snapshot);
 3110                            (start_point..end_point, text)
 3111                        })
 3112                        .sorted_by_key(|(range, _)| range.start)
 3113                        .collect::<Vec<_>>();
 3114                    buffer.edit(edits, None, cx);
 3115                })
 3116            }
 3117            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3118            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3119            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3120            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3121                .zip(new_selection_deltas)
 3122                .map(|(selection, delta)| Selection {
 3123                    id: selection.id,
 3124                    start: selection.start + delta,
 3125                    end: selection.end + delta,
 3126                    reversed: selection.reversed,
 3127                    goal: SelectionGoal::None,
 3128                })
 3129                .collect::<Vec<_>>();
 3130
 3131            let mut i = 0;
 3132            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3133                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3134                let start = map.buffer_snapshot.anchor_before(position);
 3135                let end = map.buffer_snapshot.anchor_after(position);
 3136                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3137                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3138                        Ordering::Less => i += 1,
 3139                        Ordering::Greater => break,
 3140                        Ordering::Equal => {
 3141                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3142                                Ordering::Less => i += 1,
 3143                                Ordering::Equal => break,
 3144                                Ordering::Greater => break,
 3145                            }
 3146                        }
 3147                    }
 3148                }
 3149                this.autoclose_regions.insert(
 3150                    i,
 3151                    AutocloseRegion {
 3152                        selection_id,
 3153                        range: start..end,
 3154                        pair,
 3155                    },
 3156                );
 3157            }
 3158
 3159            let had_active_inline_completion = this.has_active_inline_completion();
 3160            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3161                s.select(new_selections)
 3162            });
 3163
 3164            if !bracket_inserted {
 3165                if let Some(on_type_format_task) =
 3166                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3167                {
 3168                    on_type_format_task.detach_and_log_err(cx);
 3169                }
 3170            }
 3171
 3172            let editor_settings = EditorSettings::get_global(cx);
 3173            if bracket_inserted
 3174                && (editor_settings.auto_signature_help
 3175                    || editor_settings.show_signature_help_after_edits)
 3176            {
 3177                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3178            }
 3179
 3180            let trigger_in_words =
 3181                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3182            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3183            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3184            this.refresh_inline_completion(true, false, window, cx);
 3185        });
 3186    }
 3187
 3188    fn find_possible_emoji_shortcode_at_position(
 3189        snapshot: &MultiBufferSnapshot,
 3190        position: Point,
 3191    ) -> Option<String> {
 3192        let mut chars = Vec::new();
 3193        let mut found_colon = false;
 3194        for char in snapshot.reversed_chars_at(position).take(100) {
 3195            // Found a possible emoji shortcode in the middle of the buffer
 3196            if found_colon {
 3197                if char.is_whitespace() {
 3198                    chars.reverse();
 3199                    return Some(chars.iter().collect());
 3200                }
 3201                // If the previous character is not a whitespace, we are in the middle of a word
 3202                // and we only want to complete the shortcode if the word is made up of other emojis
 3203                let mut containing_word = String::new();
 3204                for ch in snapshot
 3205                    .reversed_chars_at(position)
 3206                    .skip(chars.len() + 1)
 3207                    .take(100)
 3208                {
 3209                    if ch.is_whitespace() {
 3210                        break;
 3211                    }
 3212                    containing_word.push(ch);
 3213                }
 3214                let containing_word = containing_word.chars().rev().collect::<String>();
 3215                if util::word_consists_of_emojis(containing_word.as_str()) {
 3216                    chars.reverse();
 3217                    return Some(chars.iter().collect());
 3218                }
 3219            }
 3220
 3221            if char.is_whitespace() || !char.is_ascii() {
 3222                return None;
 3223            }
 3224            if char == ':' {
 3225                found_colon = true;
 3226            } else {
 3227                chars.push(char);
 3228            }
 3229        }
 3230        // Found a possible emoji shortcode at the beginning of the buffer
 3231        chars.reverse();
 3232        Some(chars.iter().collect())
 3233    }
 3234
 3235    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3236        self.transact(window, cx, |this, window, cx| {
 3237            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3238                let selections = this.selections.all::<usize>(cx);
 3239                let multi_buffer = this.buffer.read(cx);
 3240                let buffer = multi_buffer.snapshot(cx);
 3241                selections
 3242                    .iter()
 3243                    .map(|selection| {
 3244                        let start_point = selection.start.to_point(&buffer);
 3245                        let mut indent =
 3246                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3247                        indent.len = cmp::min(indent.len, start_point.column);
 3248                        let start = selection.start;
 3249                        let end = selection.end;
 3250                        let selection_is_empty = start == end;
 3251                        let language_scope = buffer.language_scope_at(start);
 3252                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3253                            &language_scope
 3254                        {
 3255                            let insert_extra_newline =
 3256                                insert_extra_newline_brackets(&buffer, start..end, language)
 3257                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3258
 3259                            // Comment extension on newline is allowed only for cursor selections
 3260                            let comment_delimiter = maybe!({
 3261                                if !selection_is_empty {
 3262                                    return None;
 3263                                }
 3264
 3265                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3266                                    return None;
 3267                                }
 3268
 3269                                let delimiters = language.line_comment_prefixes();
 3270                                let max_len_of_delimiter =
 3271                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3272                                let (snapshot, range) =
 3273                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3274
 3275                                let mut index_of_first_non_whitespace = 0;
 3276                                let comment_candidate = snapshot
 3277                                    .chars_for_range(range)
 3278                                    .skip_while(|c| {
 3279                                        let should_skip = c.is_whitespace();
 3280                                        if should_skip {
 3281                                            index_of_first_non_whitespace += 1;
 3282                                        }
 3283                                        should_skip
 3284                                    })
 3285                                    .take(max_len_of_delimiter)
 3286                                    .collect::<String>();
 3287                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3288                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3289                                })?;
 3290                                let cursor_is_placed_after_comment_marker =
 3291                                    index_of_first_non_whitespace + comment_prefix.len()
 3292                                        <= start_point.column as usize;
 3293                                if cursor_is_placed_after_comment_marker {
 3294                                    Some(comment_prefix.clone())
 3295                                } else {
 3296                                    None
 3297                                }
 3298                            });
 3299                            (comment_delimiter, insert_extra_newline)
 3300                        } else {
 3301                            (None, false)
 3302                        };
 3303
 3304                        let capacity_for_delimiter = comment_delimiter
 3305                            .as_deref()
 3306                            .map(str::len)
 3307                            .unwrap_or_default();
 3308                        let mut new_text =
 3309                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3310                        new_text.push('\n');
 3311                        new_text.extend(indent.chars());
 3312                        if let Some(delimiter) = &comment_delimiter {
 3313                            new_text.push_str(delimiter);
 3314                        }
 3315                        if insert_extra_newline {
 3316                            new_text = new_text.repeat(2);
 3317                        }
 3318
 3319                        let anchor = buffer.anchor_after(end);
 3320                        let new_selection = selection.map(|_| anchor);
 3321                        (
 3322                            (start..end, new_text),
 3323                            (insert_extra_newline, new_selection),
 3324                        )
 3325                    })
 3326                    .unzip()
 3327            };
 3328
 3329            this.edit_with_autoindent(edits, cx);
 3330            let buffer = this.buffer.read(cx).snapshot(cx);
 3331            let new_selections = selection_fixup_info
 3332                .into_iter()
 3333                .map(|(extra_newline_inserted, new_selection)| {
 3334                    let mut cursor = new_selection.end.to_point(&buffer);
 3335                    if extra_newline_inserted {
 3336                        cursor.row -= 1;
 3337                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3338                    }
 3339                    new_selection.map(|_| cursor)
 3340                })
 3341                .collect();
 3342
 3343            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3344                s.select(new_selections)
 3345            });
 3346            this.refresh_inline_completion(true, false, window, cx);
 3347        });
 3348    }
 3349
 3350    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3351        let buffer = self.buffer.read(cx);
 3352        let snapshot = buffer.snapshot(cx);
 3353
 3354        let mut edits = Vec::new();
 3355        let mut rows = Vec::new();
 3356
 3357        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3358            let cursor = selection.head();
 3359            let row = cursor.row;
 3360
 3361            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3362
 3363            let newline = "\n".to_string();
 3364            edits.push((start_of_line..start_of_line, newline));
 3365
 3366            rows.push(row + rows_inserted as u32);
 3367        }
 3368
 3369        self.transact(window, cx, |editor, window, cx| {
 3370            editor.edit(edits, cx);
 3371
 3372            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3373                let mut index = 0;
 3374                s.move_cursors_with(|map, _, _| {
 3375                    let row = rows[index];
 3376                    index += 1;
 3377
 3378                    let point = Point::new(row, 0);
 3379                    let boundary = map.next_line_boundary(point).1;
 3380                    let clipped = map.clip_point(boundary, Bias::Left);
 3381
 3382                    (clipped, SelectionGoal::None)
 3383                });
 3384            });
 3385
 3386            let mut indent_edits = Vec::new();
 3387            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3388            for row in rows {
 3389                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3390                for (row, indent) in indents {
 3391                    if indent.len == 0 {
 3392                        continue;
 3393                    }
 3394
 3395                    let text = match indent.kind {
 3396                        IndentKind::Space => " ".repeat(indent.len as usize),
 3397                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3398                    };
 3399                    let point = Point::new(row.0, 0);
 3400                    indent_edits.push((point..point, text));
 3401                }
 3402            }
 3403            editor.edit(indent_edits, cx);
 3404        });
 3405    }
 3406
 3407    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3408        let buffer = self.buffer.read(cx);
 3409        let snapshot = buffer.snapshot(cx);
 3410
 3411        let mut edits = Vec::new();
 3412        let mut rows = Vec::new();
 3413        let mut rows_inserted = 0;
 3414
 3415        for selection in self.selections.all_adjusted(cx) {
 3416            let cursor = selection.head();
 3417            let row = cursor.row;
 3418
 3419            let point = Point::new(row + 1, 0);
 3420            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3421
 3422            let newline = "\n".to_string();
 3423            edits.push((start_of_line..start_of_line, newline));
 3424
 3425            rows_inserted += 1;
 3426            rows.push(row + rows_inserted);
 3427        }
 3428
 3429        self.transact(window, cx, |editor, window, cx| {
 3430            editor.edit(edits, cx);
 3431
 3432            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3433                let mut index = 0;
 3434                s.move_cursors_with(|map, _, _| {
 3435                    let row = rows[index];
 3436                    index += 1;
 3437
 3438                    let point = Point::new(row, 0);
 3439                    let boundary = map.next_line_boundary(point).1;
 3440                    let clipped = map.clip_point(boundary, Bias::Left);
 3441
 3442                    (clipped, SelectionGoal::None)
 3443                });
 3444            });
 3445
 3446            let mut indent_edits = Vec::new();
 3447            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3448            for row in rows {
 3449                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3450                for (row, indent) in indents {
 3451                    if indent.len == 0 {
 3452                        continue;
 3453                    }
 3454
 3455                    let text = match indent.kind {
 3456                        IndentKind::Space => " ".repeat(indent.len as usize),
 3457                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3458                    };
 3459                    let point = Point::new(row.0, 0);
 3460                    indent_edits.push((point..point, text));
 3461                }
 3462            }
 3463            editor.edit(indent_edits, cx);
 3464        });
 3465    }
 3466
 3467    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3468        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3469            original_start_columns: Vec::new(),
 3470        });
 3471        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3472    }
 3473
 3474    fn insert_with_autoindent_mode(
 3475        &mut self,
 3476        text: &str,
 3477        autoindent_mode: Option<AutoindentMode>,
 3478        window: &mut Window,
 3479        cx: &mut Context<Self>,
 3480    ) {
 3481        if self.read_only(cx) {
 3482            return;
 3483        }
 3484
 3485        let text: Arc<str> = text.into();
 3486        self.transact(window, cx, |this, window, cx| {
 3487            let old_selections = this.selections.all_adjusted(cx);
 3488            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3489                let anchors = {
 3490                    let snapshot = buffer.read(cx);
 3491                    old_selections
 3492                        .iter()
 3493                        .map(|s| {
 3494                            let anchor = snapshot.anchor_after(s.head());
 3495                            s.map(|_| anchor)
 3496                        })
 3497                        .collect::<Vec<_>>()
 3498                };
 3499                buffer.edit(
 3500                    old_selections
 3501                        .iter()
 3502                        .map(|s| (s.start..s.end, text.clone())),
 3503                    autoindent_mode,
 3504                    cx,
 3505                );
 3506                anchors
 3507            });
 3508
 3509            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3510                s.select_anchors(selection_anchors);
 3511            });
 3512
 3513            cx.notify();
 3514        });
 3515    }
 3516
 3517    fn trigger_completion_on_input(
 3518        &mut self,
 3519        text: &str,
 3520        trigger_in_words: bool,
 3521        window: &mut Window,
 3522        cx: &mut Context<Self>,
 3523    ) {
 3524        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3525            self.show_completions(
 3526                &ShowCompletions {
 3527                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3528                },
 3529                window,
 3530                cx,
 3531            );
 3532        } else {
 3533            self.hide_context_menu(window, cx);
 3534        }
 3535    }
 3536
 3537    fn is_completion_trigger(
 3538        &self,
 3539        text: &str,
 3540        trigger_in_words: bool,
 3541        cx: &mut Context<Self>,
 3542    ) -> bool {
 3543        let position = self.selections.newest_anchor().head();
 3544        let multibuffer = self.buffer.read(cx);
 3545        let Some(buffer) = position
 3546            .buffer_id
 3547            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3548        else {
 3549            return false;
 3550        };
 3551
 3552        if let Some(completion_provider) = &self.completion_provider {
 3553            completion_provider.is_completion_trigger(
 3554                &buffer,
 3555                position.text_anchor,
 3556                text,
 3557                trigger_in_words,
 3558                cx,
 3559            )
 3560        } else {
 3561            false
 3562        }
 3563    }
 3564
 3565    /// If any empty selections is touching the start of its innermost containing autoclose
 3566    /// region, expand it to select the brackets.
 3567    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3568        let selections = self.selections.all::<usize>(cx);
 3569        let buffer = self.buffer.read(cx).read(cx);
 3570        let new_selections = self
 3571            .selections_with_autoclose_regions(selections, &buffer)
 3572            .map(|(mut selection, region)| {
 3573                if !selection.is_empty() {
 3574                    return selection;
 3575                }
 3576
 3577                if let Some(region) = region {
 3578                    let mut range = region.range.to_offset(&buffer);
 3579                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3580                        range.start -= region.pair.start.len();
 3581                        if buffer.contains_str_at(range.start, &region.pair.start)
 3582                            && buffer.contains_str_at(range.end, &region.pair.end)
 3583                        {
 3584                            range.end += region.pair.end.len();
 3585                            selection.start = range.start;
 3586                            selection.end = range.end;
 3587
 3588                            return selection;
 3589                        }
 3590                    }
 3591                }
 3592
 3593                let always_treat_brackets_as_autoclosed = buffer
 3594                    .language_settings_at(selection.start, cx)
 3595                    .always_treat_brackets_as_autoclosed;
 3596
 3597                if !always_treat_brackets_as_autoclosed {
 3598                    return selection;
 3599                }
 3600
 3601                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3602                    for (pair, enabled) in scope.brackets() {
 3603                        if !enabled || !pair.close {
 3604                            continue;
 3605                        }
 3606
 3607                        if buffer.contains_str_at(selection.start, &pair.end) {
 3608                            let pair_start_len = pair.start.len();
 3609                            if buffer.contains_str_at(
 3610                                selection.start.saturating_sub(pair_start_len),
 3611                                &pair.start,
 3612                            ) {
 3613                                selection.start -= pair_start_len;
 3614                                selection.end += pair.end.len();
 3615
 3616                                return selection;
 3617                            }
 3618                        }
 3619                    }
 3620                }
 3621
 3622                selection
 3623            })
 3624            .collect();
 3625
 3626        drop(buffer);
 3627        self.change_selections(None, window, cx, |selections| {
 3628            selections.select(new_selections)
 3629        });
 3630    }
 3631
 3632    /// Iterate the given selections, and for each one, find the smallest surrounding
 3633    /// autoclose region. This uses the ordering of the selections and the autoclose
 3634    /// regions to avoid repeated comparisons.
 3635    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3636        &'a self,
 3637        selections: impl IntoIterator<Item = Selection<D>>,
 3638        buffer: &'a MultiBufferSnapshot,
 3639    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3640        let mut i = 0;
 3641        let mut regions = self.autoclose_regions.as_slice();
 3642        selections.into_iter().map(move |selection| {
 3643            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3644
 3645            let mut enclosing = None;
 3646            while let Some(pair_state) = regions.get(i) {
 3647                if pair_state.range.end.to_offset(buffer) < range.start {
 3648                    regions = &regions[i + 1..];
 3649                    i = 0;
 3650                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3651                    break;
 3652                } else {
 3653                    if pair_state.selection_id == selection.id {
 3654                        enclosing = Some(pair_state);
 3655                    }
 3656                    i += 1;
 3657                }
 3658            }
 3659
 3660            (selection, enclosing)
 3661        })
 3662    }
 3663
 3664    /// Remove any autoclose regions that no longer contain their selection.
 3665    fn invalidate_autoclose_regions(
 3666        &mut self,
 3667        mut selections: &[Selection<Anchor>],
 3668        buffer: &MultiBufferSnapshot,
 3669    ) {
 3670        self.autoclose_regions.retain(|state| {
 3671            let mut i = 0;
 3672            while let Some(selection) = selections.get(i) {
 3673                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3674                    selections = &selections[1..];
 3675                    continue;
 3676                }
 3677                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3678                    break;
 3679                }
 3680                if selection.id == state.selection_id {
 3681                    return true;
 3682                } else {
 3683                    i += 1;
 3684                }
 3685            }
 3686            false
 3687        });
 3688    }
 3689
 3690    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3691        let offset = position.to_offset(buffer);
 3692        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3693        if offset > word_range.start && kind == Some(CharKind::Word) {
 3694            Some(
 3695                buffer
 3696                    .text_for_range(word_range.start..offset)
 3697                    .collect::<String>(),
 3698            )
 3699        } else {
 3700            None
 3701        }
 3702    }
 3703
 3704    pub fn toggle_inlay_hints(
 3705        &mut self,
 3706        _: &ToggleInlayHints,
 3707        _: &mut Window,
 3708        cx: &mut Context<Self>,
 3709    ) {
 3710        self.refresh_inlay_hints(
 3711            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 3712            cx,
 3713        );
 3714    }
 3715
 3716    pub fn inlay_hints_enabled(&self) -> bool {
 3717        self.inlay_hint_cache.enabled
 3718    }
 3719
 3720    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3721        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3722            return;
 3723        }
 3724
 3725        let reason_description = reason.description();
 3726        let ignore_debounce = matches!(
 3727            reason,
 3728            InlayHintRefreshReason::SettingsChange(_)
 3729                | InlayHintRefreshReason::Toggle(_)
 3730                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3731                | InlayHintRefreshReason::ModifiersChanged(_)
 3732        );
 3733        let (invalidate_cache, required_languages) = match reason {
 3734            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 3735                match self.inlay_hint_cache.modifiers_override(enabled) {
 3736                    Some(enabled) => {
 3737                        if enabled {
 3738                            (InvalidationStrategy::RefreshRequested, None)
 3739                        } else {
 3740                            self.splice_inlays(
 3741                                &self
 3742                                    .visible_inlay_hints(cx)
 3743                                    .iter()
 3744                                    .map(|inlay| inlay.id)
 3745                                    .collect::<Vec<InlayId>>(),
 3746                                Vec::new(),
 3747                                cx,
 3748                            );
 3749                            return;
 3750                        }
 3751                    }
 3752                    None => return,
 3753                }
 3754            }
 3755            InlayHintRefreshReason::Toggle(enabled) => {
 3756                if self.inlay_hint_cache.toggle(enabled) {
 3757                    if enabled {
 3758                        (InvalidationStrategy::RefreshRequested, None)
 3759                    } else {
 3760                        self.splice_inlays(
 3761                            &self
 3762                                .visible_inlay_hints(cx)
 3763                                .iter()
 3764                                .map(|inlay| inlay.id)
 3765                                .collect::<Vec<InlayId>>(),
 3766                            Vec::new(),
 3767                            cx,
 3768                        );
 3769                        return;
 3770                    }
 3771                } else {
 3772                    return;
 3773                }
 3774            }
 3775            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3776                match self.inlay_hint_cache.update_settings(
 3777                    &self.buffer,
 3778                    new_settings,
 3779                    self.visible_inlay_hints(cx),
 3780                    cx,
 3781                ) {
 3782                    ControlFlow::Break(Some(InlaySplice {
 3783                        to_remove,
 3784                        to_insert,
 3785                    })) => {
 3786                        self.splice_inlays(&to_remove, to_insert, cx);
 3787                        return;
 3788                    }
 3789                    ControlFlow::Break(None) => return,
 3790                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3791                }
 3792            }
 3793            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3794                if let Some(InlaySplice {
 3795                    to_remove,
 3796                    to_insert,
 3797                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3798                {
 3799                    self.splice_inlays(&to_remove, to_insert, cx);
 3800                }
 3801                return;
 3802            }
 3803            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3804            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3805                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3806            }
 3807            InlayHintRefreshReason::RefreshRequested => {
 3808                (InvalidationStrategy::RefreshRequested, None)
 3809            }
 3810        };
 3811
 3812        if let Some(InlaySplice {
 3813            to_remove,
 3814            to_insert,
 3815        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3816            reason_description,
 3817            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3818            invalidate_cache,
 3819            ignore_debounce,
 3820            cx,
 3821        ) {
 3822            self.splice_inlays(&to_remove, to_insert, cx);
 3823        }
 3824    }
 3825
 3826    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3827        self.display_map
 3828            .read(cx)
 3829            .current_inlays()
 3830            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3831            .cloned()
 3832            .collect()
 3833    }
 3834
 3835    pub fn excerpts_for_inlay_hints_query(
 3836        &self,
 3837        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3838        cx: &mut Context<Editor>,
 3839    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3840        let Some(project) = self.project.as_ref() else {
 3841            return HashMap::default();
 3842        };
 3843        let project = project.read(cx);
 3844        let multi_buffer = self.buffer().read(cx);
 3845        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3846        let multi_buffer_visible_start = self
 3847            .scroll_manager
 3848            .anchor()
 3849            .anchor
 3850            .to_point(&multi_buffer_snapshot);
 3851        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3852            multi_buffer_visible_start
 3853                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3854            Bias::Left,
 3855        );
 3856        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3857        multi_buffer_snapshot
 3858            .range_to_buffer_ranges(multi_buffer_visible_range)
 3859            .into_iter()
 3860            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3861            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3862                let buffer_file = project::File::from_dyn(buffer.file())?;
 3863                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3864                let worktree_entry = buffer_worktree
 3865                    .read(cx)
 3866                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3867                if worktree_entry.is_ignored {
 3868                    return None;
 3869                }
 3870
 3871                let language = buffer.language()?;
 3872                if let Some(restrict_to_languages) = restrict_to_languages {
 3873                    if !restrict_to_languages.contains(language) {
 3874                        return None;
 3875                    }
 3876                }
 3877                Some((
 3878                    excerpt_id,
 3879                    (
 3880                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3881                        buffer.version().clone(),
 3882                        excerpt_visible_range,
 3883                    ),
 3884                ))
 3885            })
 3886            .collect()
 3887    }
 3888
 3889    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3890        TextLayoutDetails {
 3891            text_system: window.text_system().clone(),
 3892            editor_style: self.style.clone().unwrap(),
 3893            rem_size: window.rem_size(),
 3894            scroll_anchor: self.scroll_manager.anchor(),
 3895            visible_rows: self.visible_line_count(),
 3896            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3897        }
 3898    }
 3899
 3900    pub fn splice_inlays(
 3901        &self,
 3902        to_remove: &[InlayId],
 3903        to_insert: Vec<Inlay>,
 3904        cx: &mut Context<Self>,
 3905    ) {
 3906        self.display_map.update(cx, |display_map, cx| {
 3907            display_map.splice_inlays(to_remove, to_insert, cx)
 3908        });
 3909        cx.notify();
 3910    }
 3911
 3912    fn trigger_on_type_formatting(
 3913        &self,
 3914        input: String,
 3915        window: &mut Window,
 3916        cx: &mut Context<Self>,
 3917    ) -> Option<Task<Result<()>>> {
 3918        if input.len() != 1 {
 3919            return None;
 3920        }
 3921
 3922        let project = self.project.as_ref()?;
 3923        let position = self.selections.newest_anchor().head();
 3924        let (buffer, buffer_position) = self
 3925            .buffer
 3926            .read(cx)
 3927            .text_anchor_for_position(position, cx)?;
 3928
 3929        let settings = language_settings::language_settings(
 3930            buffer
 3931                .read(cx)
 3932                .language_at(buffer_position)
 3933                .map(|l| l.name()),
 3934            buffer.read(cx).file(),
 3935            cx,
 3936        );
 3937        if !settings.use_on_type_format {
 3938            return None;
 3939        }
 3940
 3941        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3942        // hence we do LSP request & edit on host side only — add formats to host's history.
 3943        let push_to_lsp_host_history = true;
 3944        // If this is not the host, append its history with new edits.
 3945        let push_to_client_history = project.read(cx).is_via_collab();
 3946
 3947        let on_type_formatting = project.update(cx, |project, cx| {
 3948            project.on_type_format(
 3949                buffer.clone(),
 3950                buffer_position,
 3951                input,
 3952                push_to_lsp_host_history,
 3953                cx,
 3954            )
 3955        });
 3956        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3957            if let Some(transaction) = on_type_formatting.await? {
 3958                if push_to_client_history {
 3959                    buffer
 3960                        .update(&mut cx, |buffer, _| {
 3961                            buffer.push_transaction(transaction, Instant::now());
 3962                        })
 3963                        .ok();
 3964                }
 3965                editor.update(&mut cx, |editor, cx| {
 3966                    editor.refresh_document_highlights(cx);
 3967                })?;
 3968            }
 3969            Ok(())
 3970        }))
 3971    }
 3972
 3973    pub fn show_completions(
 3974        &mut self,
 3975        options: &ShowCompletions,
 3976        window: &mut Window,
 3977        cx: &mut Context<Self>,
 3978    ) {
 3979        if self.pending_rename.is_some() {
 3980            return;
 3981        }
 3982
 3983        let Some(provider) = self.completion_provider.as_ref() else {
 3984            return;
 3985        };
 3986
 3987        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3988            return;
 3989        }
 3990
 3991        let position = self.selections.newest_anchor().head();
 3992        if position.diff_base_anchor.is_some() {
 3993            return;
 3994        }
 3995        let (buffer, buffer_position) =
 3996            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3997                output
 3998            } else {
 3999                return;
 4000            };
 4001        let show_completion_documentation = buffer
 4002            .read(cx)
 4003            .snapshot()
 4004            .settings_at(buffer_position, cx)
 4005            .show_completion_documentation;
 4006
 4007        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4008
 4009        let trigger_kind = match &options.trigger {
 4010            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4011                CompletionTriggerKind::TRIGGER_CHARACTER
 4012            }
 4013            _ => CompletionTriggerKind::INVOKED,
 4014        };
 4015        let completion_context = CompletionContext {
 4016            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4017                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4018                    Some(String::from(trigger))
 4019                } else {
 4020                    None
 4021                }
 4022            }),
 4023            trigger_kind,
 4024        };
 4025        let completions =
 4026            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 4027        let sort_completions = provider.sort_completions();
 4028
 4029        let id = post_inc(&mut self.next_completion_id);
 4030        let task = cx.spawn_in(window, |editor, mut cx| {
 4031            async move {
 4032                editor.update(&mut cx, |this, _| {
 4033                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4034                })?;
 4035                let completions = completions.await.log_err();
 4036                let menu = if let Some(completions) = completions {
 4037                    let mut menu = CompletionsMenu::new(
 4038                        id,
 4039                        sort_completions,
 4040                        show_completion_documentation,
 4041                        position,
 4042                        buffer.clone(),
 4043                        completions.into(),
 4044                    );
 4045
 4046                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4047                        .await;
 4048
 4049                    menu.visible().then_some(menu)
 4050                } else {
 4051                    None
 4052                };
 4053
 4054                editor.update_in(&mut cx, |editor, window, cx| {
 4055                    match editor.context_menu.borrow().as_ref() {
 4056                        None => {}
 4057                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4058                            if prev_menu.id > id {
 4059                                return;
 4060                            }
 4061                        }
 4062                        _ => return,
 4063                    }
 4064
 4065                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4066                        let mut menu = menu.unwrap();
 4067                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4068
 4069                        *editor.context_menu.borrow_mut() =
 4070                            Some(CodeContextMenu::Completions(menu));
 4071
 4072                        if editor.show_edit_predictions_in_menu() {
 4073                            editor.update_visible_inline_completion(window, cx);
 4074                        } else {
 4075                            editor.discard_inline_completion(false, cx);
 4076                        }
 4077
 4078                        cx.notify();
 4079                    } else if editor.completion_tasks.len() <= 1 {
 4080                        // If there are no more completion tasks and the last menu was
 4081                        // empty, we should hide it.
 4082                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4083                        // If it was already hidden and we don't show inline
 4084                        // completions in the menu, we should also show the
 4085                        // inline-completion when available.
 4086                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4087                            editor.update_visible_inline_completion(window, cx);
 4088                        }
 4089                    }
 4090                })?;
 4091
 4092                Ok::<_, anyhow::Error>(())
 4093            }
 4094            .log_err()
 4095        });
 4096
 4097        self.completion_tasks.push((id, task));
 4098    }
 4099
 4100    pub fn confirm_completion(
 4101        &mut self,
 4102        action: &ConfirmCompletion,
 4103        window: &mut Window,
 4104        cx: &mut Context<Self>,
 4105    ) -> Option<Task<Result<()>>> {
 4106        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4107    }
 4108
 4109    pub fn compose_completion(
 4110        &mut self,
 4111        action: &ComposeCompletion,
 4112        window: &mut Window,
 4113        cx: &mut Context<Self>,
 4114    ) -> Option<Task<Result<()>>> {
 4115        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4116    }
 4117
 4118    fn do_completion(
 4119        &mut self,
 4120        item_ix: Option<usize>,
 4121        intent: CompletionIntent,
 4122        window: &mut Window,
 4123        cx: &mut Context<Editor>,
 4124    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4125        use language::ToOffset as _;
 4126
 4127        let completions_menu =
 4128            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4129                menu
 4130            } else {
 4131                return None;
 4132            };
 4133
 4134        let entries = completions_menu.entries.borrow();
 4135        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4136        if self.show_edit_predictions_in_menu() {
 4137            self.discard_inline_completion(true, cx);
 4138        }
 4139        let candidate_id = mat.candidate_id;
 4140        drop(entries);
 4141
 4142        let buffer_handle = completions_menu.buffer;
 4143        let completion = completions_menu
 4144            .completions
 4145            .borrow()
 4146            .get(candidate_id)?
 4147            .clone();
 4148        cx.stop_propagation();
 4149
 4150        let snippet;
 4151        let text;
 4152
 4153        if completion.is_snippet() {
 4154            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4155            text = snippet.as_ref().unwrap().text.clone();
 4156        } else {
 4157            snippet = None;
 4158            text = completion.new_text.clone();
 4159        };
 4160        let selections = self.selections.all::<usize>(cx);
 4161        let buffer = buffer_handle.read(cx);
 4162        let old_range = completion.old_range.to_offset(buffer);
 4163        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4164
 4165        let newest_selection = self.selections.newest_anchor();
 4166        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4167            return None;
 4168        }
 4169
 4170        let lookbehind = newest_selection
 4171            .start
 4172            .text_anchor
 4173            .to_offset(buffer)
 4174            .saturating_sub(old_range.start);
 4175        let lookahead = old_range
 4176            .end
 4177            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4178        let mut common_prefix_len = old_text
 4179            .bytes()
 4180            .zip(text.bytes())
 4181            .take_while(|(a, b)| a == b)
 4182            .count();
 4183
 4184        let snapshot = self.buffer.read(cx).snapshot(cx);
 4185        let mut range_to_replace: Option<Range<isize>> = None;
 4186        let mut ranges = Vec::new();
 4187        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4188        for selection in &selections {
 4189            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4190                let start = selection.start.saturating_sub(lookbehind);
 4191                let end = selection.end + lookahead;
 4192                if selection.id == newest_selection.id {
 4193                    range_to_replace = Some(
 4194                        ((start + common_prefix_len) as isize - selection.start as isize)
 4195                            ..(end as isize - selection.start as isize),
 4196                    );
 4197                }
 4198                ranges.push(start + common_prefix_len..end);
 4199            } else {
 4200                common_prefix_len = 0;
 4201                ranges.clear();
 4202                ranges.extend(selections.iter().map(|s| {
 4203                    if s.id == newest_selection.id {
 4204                        range_to_replace = Some(
 4205                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4206                                - selection.start as isize
 4207                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4208                                    - selection.start as isize,
 4209                        );
 4210                        old_range.clone()
 4211                    } else {
 4212                        s.start..s.end
 4213                    }
 4214                }));
 4215                break;
 4216            }
 4217            if !self.linked_edit_ranges.is_empty() {
 4218                let start_anchor = snapshot.anchor_before(selection.head());
 4219                let end_anchor = snapshot.anchor_after(selection.tail());
 4220                if let Some(ranges) = self
 4221                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4222                {
 4223                    for (buffer, edits) in ranges {
 4224                        linked_edits.entry(buffer.clone()).or_default().extend(
 4225                            edits
 4226                                .into_iter()
 4227                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4228                        );
 4229                    }
 4230                }
 4231            }
 4232        }
 4233        let text = &text[common_prefix_len..];
 4234
 4235        cx.emit(EditorEvent::InputHandled {
 4236            utf16_range_to_replace: range_to_replace,
 4237            text: text.into(),
 4238        });
 4239
 4240        self.transact(window, cx, |this, window, cx| {
 4241            if let Some(mut snippet) = snippet {
 4242                snippet.text = text.to_string();
 4243                for tabstop in snippet
 4244                    .tabstops
 4245                    .iter_mut()
 4246                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4247                {
 4248                    tabstop.start -= common_prefix_len as isize;
 4249                    tabstop.end -= common_prefix_len as isize;
 4250                }
 4251
 4252                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4253            } else {
 4254                this.buffer.update(cx, |buffer, cx| {
 4255                    buffer.edit(
 4256                        ranges.iter().map(|range| (range.clone(), text)),
 4257                        this.autoindent_mode.clone(),
 4258                        cx,
 4259                    );
 4260                });
 4261            }
 4262            for (buffer, edits) in linked_edits {
 4263                buffer.update(cx, |buffer, cx| {
 4264                    let snapshot = buffer.snapshot();
 4265                    let edits = edits
 4266                        .into_iter()
 4267                        .map(|(range, text)| {
 4268                            use text::ToPoint as TP;
 4269                            let end_point = TP::to_point(&range.end, &snapshot);
 4270                            let start_point = TP::to_point(&range.start, &snapshot);
 4271                            (start_point..end_point, text)
 4272                        })
 4273                        .sorted_by_key(|(range, _)| range.start)
 4274                        .collect::<Vec<_>>();
 4275                    buffer.edit(edits, None, cx);
 4276                })
 4277            }
 4278
 4279            this.refresh_inline_completion(true, false, window, cx);
 4280        });
 4281
 4282        let show_new_completions_on_confirm = completion
 4283            .confirm
 4284            .as_ref()
 4285            .map_or(false, |confirm| confirm(intent, window, cx));
 4286        if show_new_completions_on_confirm {
 4287            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4288        }
 4289
 4290        let provider = self.completion_provider.as_ref()?;
 4291        drop(completion);
 4292        let apply_edits = provider.apply_additional_edits_for_completion(
 4293            buffer_handle,
 4294            completions_menu.completions.clone(),
 4295            candidate_id,
 4296            true,
 4297            cx,
 4298        );
 4299
 4300        let editor_settings = EditorSettings::get_global(cx);
 4301        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4302            // After the code completion is finished, users often want to know what signatures are needed.
 4303            // so we should automatically call signature_help
 4304            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4305        }
 4306
 4307        Some(cx.foreground_executor().spawn(async move {
 4308            apply_edits.await?;
 4309            Ok(())
 4310        }))
 4311    }
 4312
 4313    pub fn toggle_code_actions(
 4314        &mut self,
 4315        action: &ToggleCodeActions,
 4316        window: &mut Window,
 4317        cx: &mut Context<Self>,
 4318    ) {
 4319        let mut context_menu = self.context_menu.borrow_mut();
 4320        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4321            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4322                // Toggle if we're selecting the same one
 4323                *context_menu = None;
 4324                cx.notify();
 4325                return;
 4326            } else {
 4327                // Otherwise, clear it and start a new one
 4328                *context_menu = None;
 4329                cx.notify();
 4330            }
 4331        }
 4332        drop(context_menu);
 4333        let snapshot = self.snapshot(window, cx);
 4334        let deployed_from_indicator = action.deployed_from_indicator;
 4335        let mut task = self.code_actions_task.take();
 4336        let action = action.clone();
 4337        cx.spawn_in(window, |editor, mut cx| async move {
 4338            while let Some(prev_task) = task {
 4339                prev_task.await.log_err();
 4340                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4341            }
 4342
 4343            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4344                if editor.focus_handle.is_focused(window) {
 4345                    let multibuffer_point = action
 4346                        .deployed_from_indicator
 4347                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4348                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4349                    let (buffer, buffer_row) = snapshot
 4350                        .buffer_snapshot
 4351                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4352                        .and_then(|(buffer_snapshot, range)| {
 4353                            editor
 4354                                .buffer
 4355                                .read(cx)
 4356                                .buffer(buffer_snapshot.remote_id())
 4357                                .map(|buffer| (buffer, range.start.row))
 4358                        })?;
 4359                    let (_, code_actions) = editor
 4360                        .available_code_actions
 4361                        .clone()
 4362                        .and_then(|(location, code_actions)| {
 4363                            let snapshot = location.buffer.read(cx).snapshot();
 4364                            let point_range = location.range.to_point(&snapshot);
 4365                            let point_range = point_range.start.row..=point_range.end.row;
 4366                            if point_range.contains(&buffer_row) {
 4367                                Some((location, code_actions))
 4368                            } else {
 4369                                None
 4370                            }
 4371                        })
 4372                        .unzip();
 4373                    let buffer_id = buffer.read(cx).remote_id();
 4374                    let tasks = editor
 4375                        .tasks
 4376                        .get(&(buffer_id, buffer_row))
 4377                        .map(|t| Arc::new(t.to_owned()));
 4378                    if tasks.is_none() && code_actions.is_none() {
 4379                        return None;
 4380                    }
 4381
 4382                    editor.completion_tasks.clear();
 4383                    editor.discard_inline_completion(false, cx);
 4384                    let task_context =
 4385                        tasks
 4386                            .as_ref()
 4387                            .zip(editor.project.clone())
 4388                            .map(|(tasks, project)| {
 4389                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4390                            });
 4391
 4392                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4393                        let task_context = match task_context {
 4394                            Some(task_context) => task_context.await,
 4395                            None => None,
 4396                        };
 4397                        let resolved_tasks =
 4398                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4399                                Rc::new(ResolvedTasks {
 4400                                    templates: tasks.resolve(&task_context).collect(),
 4401                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4402                                        multibuffer_point.row,
 4403                                        tasks.column,
 4404                                    )),
 4405                                })
 4406                            });
 4407                        let spawn_straight_away = resolved_tasks
 4408                            .as_ref()
 4409                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4410                            && code_actions
 4411                                .as_ref()
 4412                                .map_or(true, |actions| actions.is_empty());
 4413                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4414                            *editor.context_menu.borrow_mut() =
 4415                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4416                                    buffer,
 4417                                    actions: CodeActionContents {
 4418                                        tasks: resolved_tasks,
 4419                                        actions: code_actions,
 4420                                    },
 4421                                    selected_item: Default::default(),
 4422                                    scroll_handle: UniformListScrollHandle::default(),
 4423                                    deployed_from_indicator,
 4424                                }));
 4425                            if spawn_straight_away {
 4426                                if let Some(task) = editor.confirm_code_action(
 4427                                    &ConfirmCodeAction { item_ix: Some(0) },
 4428                                    window,
 4429                                    cx,
 4430                                ) {
 4431                                    cx.notify();
 4432                                    return task;
 4433                                }
 4434                            }
 4435                            cx.notify();
 4436                            Task::ready(Ok(()))
 4437                        }) {
 4438                            task.await
 4439                        } else {
 4440                            Ok(())
 4441                        }
 4442                    }))
 4443                } else {
 4444                    Some(Task::ready(Ok(())))
 4445                }
 4446            })?;
 4447            if let Some(task) = spawned_test_task {
 4448                task.await?;
 4449            }
 4450
 4451            Ok::<_, anyhow::Error>(())
 4452        })
 4453        .detach_and_log_err(cx);
 4454    }
 4455
 4456    pub fn confirm_code_action(
 4457        &mut self,
 4458        action: &ConfirmCodeAction,
 4459        window: &mut Window,
 4460        cx: &mut Context<Self>,
 4461    ) -> Option<Task<Result<()>>> {
 4462        let actions_menu =
 4463            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4464                menu
 4465            } else {
 4466                return None;
 4467            };
 4468        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4469        let action = actions_menu.actions.get(action_ix)?;
 4470        let title = action.label();
 4471        let buffer = actions_menu.buffer;
 4472        let workspace = self.workspace()?;
 4473
 4474        match action {
 4475            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4476                workspace.update(cx, |workspace, cx| {
 4477                    workspace::tasks::schedule_resolved_task(
 4478                        workspace,
 4479                        task_source_kind,
 4480                        resolved_task,
 4481                        false,
 4482                        cx,
 4483                    );
 4484
 4485                    Some(Task::ready(Ok(())))
 4486                })
 4487            }
 4488            CodeActionsItem::CodeAction {
 4489                excerpt_id,
 4490                action,
 4491                provider,
 4492            } => {
 4493                let apply_code_action =
 4494                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4495                let workspace = workspace.downgrade();
 4496                Some(cx.spawn_in(window, |editor, cx| async move {
 4497                    let project_transaction = apply_code_action.await?;
 4498                    Self::open_project_transaction(
 4499                        &editor,
 4500                        workspace,
 4501                        project_transaction,
 4502                        title,
 4503                        cx,
 4504                    )
 4505                    .await
 4506                }))
 4507            }
 4508        }
 4509    }
 4510
 4511    pub async fn open_project_transaction(
 4512        this: &WeakEntity<Editor>,
 4513        workspace: WeakEntity<Workspace>,
 4514        transaction: ProjectTransaction,
 4515        title: String,
 4516        mut cx: AsyncWindowContext,
 4517    ) -> Result<()> {
 4518        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4519        cx.update(|_, cx| {
 4520            entries.sort_unstable_by_key(|(buffer, _)| {
 4521                buffer.read(cx).file().map(|f| f.path().clone())
 4522            });
 4523        })?;
 4524
 4525        // If the project transaction's edits are all contained within this editor, then
 4526        // avoid opening a new editor to display them.
 4527
 4528        if let Some((buffer, transaction)) = entries.first() {
 4529            if entries.len() == 1 {
 4530                let excerpt = this.update(&mut cx, |editor, cx| {
 4531                    editor
 4532                        .buffer()
 4533                        .read(cx)
 4534                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4535                })?;
 4536                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4537                    if excerpted_buffer == *buffer {
 4538                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4539                            let excerpt_range = excerpt_range.to_offset(buffer);
 4540                            buffer
 4541                                .edited_ranges_for_transaction::<usize>(transaction)
 4542                                .all(|range| {
 4543                                    excerpt_range.start <= range.start
 4544                                        && excerpt_range.end >= range.end
 4545                                })
 4546                        })?;
 4547
 4548                        if all_edits_within_excerpt {
 4549                            return Ok(());
 4550                        }
 4551                    }
 4552                }
 4553            }
 4554        } else {
 4555            return Ok(());
 4556        }
 4557
 4558        let mut ranges_to_highlight = Vec::new();
 4559        let excerpt_buffer = cx.new(|cx| {
 4560            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4561            for (buffer_handle, transaction) in &entries {
 4562                let buffer = buffer_handle.read(cx);
 4563                ranges_to_highlight.extend(
 4564                    multibuffer.push_excerpts_with_context_lines(
 4565                        buffer_handle.clone(),
 4566                        buffer
 4567                            .edited_ranges_for_transaction::<usize>(transaction)
 4568                            .collect(),
 4569                        DEFAULT_MULTIBUFFER_CONTEXT,
 4570                        cx,
 4571                    ),
 4572                );
 4573            }
 4574            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4575            multibuffer
 4576        })?;
 4577
 4578        workspace.update_in(&mut cx, |workspace, window, cx| {
 4579            let project = workspace.project().clone();
 4580            let editor = cx
 4581                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4582            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4583            editor.update(cx, |editor, cx| {
 4584                editor.highlight_background::<Self>(
 4585                    &ranges_to_highlight,
 4586                    |theme| theme.editor_highlighted_line_background,
 4587                    cx,
 4588                );
 4589            });
 4590        })?;
 4591
 4592        Ok(())
 4593    }
 4594
 4595    pub fn clear_code_action_providers(&mut self) {
 4596        self.code_action_providers.clear();
 4597        self.available_code_actions.take();
 4598    }
 4599
 4600    pub fn add_code_action_provider(
 4601        &mut self,
 4602        provider: Rc<dyn CodeActionProvider>,
 4603        window: &mut Window,
 4604        cx: &mut Context<Self>,
 4605    ) {
 4606        if self
 4607            .code_action_providers
 4608            .iter()
 4609            .any(|existing_provider| existing_provider.id() == provider.id())
 4610        {
 4611            return;
 4612        }
 4613
 4614        self.code_action_providers.push(provider);
 4615        self.refresh_code_actions(window, cx);
 4616    }
 4617
 4618    pub fn remove_code_action_provider(
 4619        &mut self,
 4620        id: Arc<str>,
 4621        window: &mut Window,
 4622        cx: &mut Context<Self>,
 4623    ) {
 4624        self.code_action_providers
 4625            .retain(|provider| provider.id() != id);
 4626        self.refresh_code_actions(window, cx);
 4627    }
 4628
 4629    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4630        let buffer = self.buffer.read(cx);
 4631        let newest_selection = self.selections.newest_anchor().clone();
 4632        if newest_selection.head().diff_base_anchor.is_some() {
 4633            return None;
 4634        }
 4635        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4636        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4637        if start_buffer != end_buffer {
 4638            return None;
 4639        }
 4640
 4641        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4642            cx.background_executor()
 4643                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4644                .await;
 4645
 4646            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4647                let providers = this.code_action_providers.clone();
 4648                let tasks = this
 4649                    .code_action_providers
 4650                    .iter()
 4651                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4652                    .collect::<Vec<_>>();
 4653                (providers, tasks)
 4654            })?;
 4655
 4656            let mut actions = Vec::new();
 4657            for (provider, provider_actions) in
 4658                providers.into_iter().zip(future::join_all(tasks).await)
 4659            {
 4660                if let Some(provider_actions) = provider_actions.log_err() {
 4661                    actions.extend(provider_actions.into_iter().map(|action| {
 4662                        AvailableCodeAction {
 4663                            excerpt_id: newest_selection.start.excerpt_id,
 4664                            action,
 4665                            provider: provider.clone(),
 4666                        }
 4667                    }));
 4668                }
 4669            }
 4670
 4671            this.update(&mut cx, |this, cx| {
 4672                this.available_code_actions = if actions.is_empty() {
 4673                    None
 4674                } else {
 4675                    Some((
 4676                        Location {
 4677                            buffer: start_buffer,
 4678                            range: start..end,
 4679                        },
 4680                        actions.into(),
 4681                    ))
 4682                };
 4683                cx.notify();
 4684            })
 4685        }));
 4686        None
 4687    }
 4688
 4689    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4690        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4691            self.show_git_blame_inline = false;
 4692
 4693            self.show_git_blame_inline_delay_task =
 4694                Some(cx.spawn_in(window, |this, mut cx| async move {
 4695                    cx.background_executor().timer(delay).await;
 4696
 4697                    this.update(&mut cx, |this, cx| {
 4698                        this.show_git_blame_inline = true;
 4699                        cx.notify();
 4700                    })
 4701                    .log_err();
 4702                }));
 4703        }
 4704    }
 4705
 4706    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4707        if self.pending_rename.is_some() {
 4708            return None;
 4709        }
 4710
 4711        let provider = self.semantics_provider.clone()?;
 4712        let buffer = self.buffer.read(cx);
 4713        let newest_selection = self.selections.newest_anchor().clone();
 4714        let cursor_position = newest_selection.head();
 4715        let (cursor_buffer, cursor_buffer_position) =
 4716            buffer.text_anchor_for_position(cursor_position, cx)?;
 4717        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4718        if cursor_buffer != tail_buffer {
 4719            return None;
 4720        }
 4721        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4722        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4723            cx.background_executor()
 4724                .timer(Duration::from_millis(debounce))
 4725                .await;
 4726
 4727            let highlights = if let Some(highlights) = cx
 4728                .update(|cx| {
 4729                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4730                })
 4731                .ok()
 4732                .flatten()
 4733            {
 4734                highlights.await.log_err()
 4735            } else {
 4736                None
 4737            };
 4738
 4739            if let Some(highlights) = highlights {
 4740                this.update(&mut cx, |this, cx| {
 4741                    if this.pending_rename.is_some() {
 4742                        return;
 4743                    }
 4744
 4745                    let buffer_id = cursor_position.buffer_id;
 4746                    let buffer = this.buffer.read(cx);
 4747                    if !buffer
 4748                        .text_anchor_for_position(cursor_position, cx)
 4749                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4750                    {
 4751                        return;
 4752                    }
 4753
 4754                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4755                    let mut write_ranges = Vec::new();
 4756                    let mut read_ranges = Vec::new();
 4757                    for highlight in highlights {
 4758                        for (excerpt_id, excerpt_range) in
 4759                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4760                        {
 4761                            let start = highlight
 4762                                .range
 4763                                .start
 4764                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4765                            let end = highlight
 4766                                .range
 4767                                .end
 4768                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4769                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4770                                continue;
 4771                            }
 4772
 4773                            let range = Anchor {
 4774                                buffer_id,
 4775                                excerpt_id,
 4776                                text_anchor: start,
 4777                                diff_base_anchor: None,
 4778                            }..Anchor {
 4779                                buffer_id,
 4780                                excerpt_id,
 4781                                text_anchor: end,
 4782                                diff_base_anchor: None,
 4783                            };
 4784                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4785                                write_ranges.push(range);
 4786                            } else {
 4787                                read_ranges.push(range);
 4788                            }
 4789                        }
 4790                    }
 4791
 4792                    this.highlight_background::<DocumentHighlightRead>(
 4793                        &read_ranges,
 4794                        |theme| theme.editor_document_highlight_read_background,
 4795                        cx,
 4796                    );
 4797                    this.highlight_background::<DocumentHighlightWrite>(
 4798                        &write_ranges,
 4799                        |theme| theme.editor_document_highlight_write_background,
 4800                        cx,
 4801                    );
 4802                    cx.notify();
 4803                })
 4804                .log_err();
 4805            }
 4806        }));
 4807        None
 4808    }
 4809
 4810    pub fn refresh_selected_text_highlights(
 4811        &mut self,
 4812        window: &mut Window,
 4813        cx: &mut Context<Editor>,
 4814    ) {
 4815        self.selection_highlight_task.take();
 4816        if !EditorSettings::get_global(cx).selection_highlight {
 4817            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4818            return;
 4819        }
 4820        if self.selections.count() != 1 || self.selections.line_mode {
 4821            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4822            return;
 4823        }
 4824        let selection = self.selections.newest::<Point>(cx);
 4825        if selection.is_empty() || selection.start.row != selection.end.row {
 4826            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4827            return;
 4828        }
 4829        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4830        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4831            cx.background_executor()
 4832                .timer(Duration::from_millis(debounce))
 4833                .await;
 4834            let Some(Some(matches_task)) = editor
 4835                .update_in(&mut cx, |editor, _, cx| {
 4836                    if editor.selections.count() != 1 || editor.selections.line_mode {
 4837                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4838                        return None;
 4839                    }
 4840                    let selection = editor.selections.newest::<Point>(cx);
 4841                    if selection.is_empty() || selection.start.row != selection.end.row {
 4842                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4843                        return None;
 4844                    }
 4845                    let buffer = editor.buffer().read(cx).snapshot(cx);
 4846                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 4847                    if query.trim().is_empty() {
 4848                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4849                        return None;
 4850                    }
 4851                    Some(cx.background_spawn(async move {
 4852                        let mut ranges = Vec::new();
 4853                        let selection_anchors = selection.range().to_anchors(&buffer);
 4854                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 4855                            for (search_buffer, search_range, excerpt_id) in
 4856                                buffer.range_to_buffer_ranges(range)
 4857                            {
 4858                                ranges.extend(
 4859                                    project::search::SearchQuery::text(
 4860                                        query.clone(),
 4861                                        false,
 4862                                        false,
 4863                                        false,
 4864                                        Default::default(),
 4865                                        Default::default(),
 4866                                        None,
 4867                                    )
 4868                                    .unwrap()
 4869                                    .search(search_buffer, Some(search_range.clone()))
 4870                                    .await
 4871                                    .into_iter()
 4872                                    .filter_map(
 4873                                        |match_range| {
 4874                                            let start = search_buffer.anchor_after(
 4875                                                search_range.start + match_range.start,
 4876                                            );
 4877                                            let end = search_buffer.anchor_before(
 4878                                                search_range.start + match_range.end,
 4879                                            );
 4880                                            let range = Anchor::range_in_buffer(
 4881                                                excerpt_id,
 4882                                                search_buffer.remote_id(),
 4883                                                start..end,
 4884                                            );
 4885                                            (range != selection_anchors).then_some(range)
 4886                                        },
 4887                                    ),
 4888                                );
 4889                            }
 4890                        }
 4891                        ranges
 4892                    }))
 4893                })
 4894                .log_err()
 4895            else {
 4896                return;
 4897            };
 4898            let matches = matches_task.await;
 4899            editor
 4900                .update_in(&mut cx, |editor, _, cx| {
 4901                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4902                    if !matches.is_empty() {
 4903                        editor.highlight_background::<SelectedTextHighlight>(
 4904                            &matches,
 4905                            |theme| theme.editor_document_highlight_bracket_background,
 4906                            cx,
 4907                        )
 4908                    }
 4909                })
 4910                .log_err();
 4911        }));
 4912    }
 4913
 4914    pub fn refresh_inline_completion(
 4915        &mut self,
 4916        debounce: bool,
 4917        user_requested: bool,
 4918        window: &mut Window,
 4919        cx: &mut Context<Self>,
 4920    ) -> Option<()> {
 4921        let provider = self.edit_prediction_provider()?;
 4922        let cursor = self.selections.newest_anchor().head();
 4923        let (buffer, cursor_buffer_position) =
 4924            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4925
 4926        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4927            self.discard_inline_completion(false, cx);
 4928            return None;
 4929        }
 4930
 4931        if !user_requested
 4932            && (!self.should_show_edit_predictions()
 4933                || !self.is_focused(window)
 4934                || buffer.read(cx).is_empty())
 4935        {
 4936            self.discard_inline_completion(false, cx);
 4937            return None;
 4938        }
 4939
 4940        self.update_visible_inline_completion(window, cx);
 4941        provider.refresh(
 4942            self.project.clone(),
 4943            buffer,
 4944            cursor_buffer_position,
 4945            debounce,
 4946            cx,
 4947        );
 4948        Some(())
 4949    }
 4950
 4951    fn show_edit_predictions_in_menu(&self) -> bool {
 4952        match self.edit_prediction_settings {
 4953            EditPredictionSettings::Disabled => false,
 4954            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4955        }
 4956    }
 4957
 4958    pub fn edit_predictions_enabled(&self) -> bool {
 4959        match self.edit_prediction_settings {
 4960            EditPredictionSettings::Disabled => false,
 4961            EditPredictionSettings::Enabled { .. } => true,
 4962        }
 4963    }
 4964
 4965    fn edit_prediction_requires_modifier(&self) -> bool {
 4966        match self.edit_prediction_settings {
 4967            EditPredictionSettings::Disabled => false,
 4968            EditPredictionSettings::Enabled {
 4969                preview_requires_modifier,
 4970                ..
 4971            } => preview_requires_modifier,
 4972        }
 4973    }
 4974
 4975    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 4976        if self.edit_prediction_provider.is_none() {
 4977            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 4978        } else {
 4979            let selection = self.selections.newest_anchor();
 4980            let cursor = selection.head();
 4981
 4982            if let Some((buffer, cursor_buffer_position)) =
 4983                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4984            {
 4985                self.edit_prediction_settings =
 4986                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 4987            }
 4988        }
 4989    }
 4990
 4991    fn edit_prediction_settings_at_position(
 4992        &self,
 4993        buffer: &Entity<Buffer>,
 4994        buffer_position: language::Anchor,
 4995        cx: &App,
 4996    ) -> EditPredictionSettings {
 4997        if self.mode != EditorMode::Full
 4998            || !self.show_inline_completions_override.unwrap_or(true)
 4999            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5000        {
 5001            return EditPredictionSettings::Disabled;
 5002        }
 5003
 5004        let buffer = buffer.read(cx);
 5005
 5006        let file = buffer.file();
 5007
 5008        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5009            return EditPredictionSettings::Disabled;
 5010        };
 5011
 5012        let by_provider = matches!(
 5013            self.menu_inline_completions_policy,
 5014            MenuInlineCompletionsPolicy::ByProvider
 5015        );
 5016
 5017        let show_in_menu = by_provider
 5018            && self
 5019                .edit_prediction_provider
 5020                .as_ref()
 5021                .map_or(false, |provider| {
 5022                    provider.provider.show_completions_in_menu()
 5023                });
 5024
 5025        let preview_requires_modifier =
 5026            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5027
 5028        EditPredictionSettings::Enabled {
 5029            show_in_menu,
 5030            preview_requires_modifier,
 5031        }
 5032    }
 5033
 5034    fn should_show_edit_predictions(&self) -> bool {
 5035        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5036    }
 5037
 5038    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5039        matches!(
 5040            self.edit_prediction_preview,
 5041            EditPredictionPreview::Active { .. }
 5042        )
 5043    }
 5044
 5045    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5046        let cursor = self.selections.newest_anchor().head();
 5047        if let Some((buffer, cursor_position)) =
 5048            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5049        {
 5050            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5051        } else {
 5052            false
 5053        }
 5054    }
 5055
 5056    fn edit_predictions_enabled_in_buffer(
 5057        &self,
 5058        buffer: &Entity<Buffer>,
 5059        buffer_position: language::Anchor,
 5060        cx: &App,
 5061    ) -> bool {
 5062        maybe!({
 5063            let provider = self.edit_prediction_provider()?;
 5064            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5065                return Some(false);
 5066            }
 5067            let buffer = buffer.read(cx);
 5068            let Some(file) = buffer.file() else {
 5069                return Some(true);
 5070            };
 5071            let settings = all_language_settings(Some(file), cx);
 5072            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5073        })
 5074        .unwrap_or(false)
 5075    }
 5076
 5077    fn cycle_inline_completion(
 5078        &mut self,
 5079        direction: Direction,
 5080        window: &mut Window,
 5081        cx: &mut Context<Self>,
 5082    ) -> Option<()> {
 5083        let provider = self.edit_prediction_provider()?;
 5084        let cursor = self.selections.newest_anchor().head();
 5085        let (buffer, cursor_buffer_position) =
 5086            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5087        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5088            return None;
 5089        }
 5090
 5091        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5092        self.update_visible_inline_completion(window, cx);
 5093
 5094        Some(())
 5095    }
 5096
 5097    pub fn show_inline_completion(
 5098        &mut self,
 5099        _: &ShowEditPrediction,
 5100        window: &mut Window,
 5101        cx: &mut Context<Self>,
 5102    ) {
 5103        if !self.has_active_inline_completion() {
 5104            self.refresh_inline_completion(false, true, window, cx);
 5105            return;
 5106        }
 5107
 5108        self.update_visible_inline_completion(window, cx);
 5109    }
 5110
 5111    pub fn display_cursor_names(
 5112        &mut self,
 5113        _: &DisplayCursorNames,
 5114        window: &mut Window,
 5115        cx: &mut Context<Self>,
 5116    ) {
 5117        self.show_cursor_names(window, cx);
 5118    }
 5119
 5120    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5121        self.show_cursor_names = true;
 5122        cx.notify();
 5123        cx.spawn_in(window, |this, mut cx| async move {
 5124            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5125            this.update(&mut cx, |this, cx| {
 5126                this.show_cursor_names = false;
 5127                cx.notify()
 5128            })
 5129            .ok()
 5130        })
 5131        .detach();
 5132    }
 5133
 5134    pub fn next_edit_prediction(
 5135        &mut self,
 5136        _: &NextEditPrediction,
 5137        window: &mut Window,
 5138        cx: &mut Context<Self>,
 5139    ) {
 5140        if self.has_active_inline_completion() {
 5141            self.cycle_inline_completion(Direction::Next, window, cx);
 5142        } else {
 5143            let is_copilot_disabled = self
 5144                .refresh_inline_completion(false, true, window, cx)
 5145                .is_none();
 5146            if is_copilot_disabled {
 5147                cx.propagate();
 5148            }
 5149        }
 5150    }
 5151
 5152    pub fn previous_edit_prediction(
 5153        &mut self,
 5154        _: &PreviousEditPrediction,
 5155        window: &mut Window,
 5156        cx: &mut Context<Self>,
 5157    ) {
 5158        if self.has_active_inline_completion() {
 5159            self.cycle_inline_completion(Direction::Prev, window, cx);
 5160        } else {
 5161            let is_copilot_disabled = self
 5162                .refresh_inline_completion(false, true, window, cx)
 5163                .is_none();
 5164            if is_copilot_disabled {
 5165                cx.propagate();
 5166            }
 5167        }
 5168    }
 5169
 5170    pub fn accept_edit_prediction(
 5171        &mut self,
 5172        _: &AcceptEditPrediction,
 5173        window: &mut Window,
 5174        cx: &mut Context<Self>,
 5175    ) {
 5176        if self.show_edit_predictions_in_menu() {
 5177            self.hide_context_menu(window, cx);
 5178        }
 5179
 5180        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5181            return;
 5182        };
 5183
 5184        self.report_inline_completion_event(
 5185            active_inline_completion.completion_id.clone(),
 5186            true,
 5187            cx,
 5188        );
 5189
 5190        match &active_inline_completion.completion {
 5191            InlineCompletion::Move { target, .. } => {
 5192                let target = *target;
 5193
 5194                if let Some(position_map) = &self.last_position_map {
 5195                    if position_map
 5196                        .visible_row_range
 5197                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5198                        || !self.edit_prediction_requires_modifier()
 5199                    {
 5200                        self.unfold_ranges(&[target..target], true, false, cx);
 5201                        // Note that this is also done in vim's handler of the Tab action.
 5202                        self.change_selections(
 5203                            Some(Autoscroll::newest()),
 5204                            window,
 5205                            cx,
 5206                            |selections| {
 5207                                selections.select_anchor_ranges([target..target]);
 5208                            },
 5209                        );
 5210                        self.clear_row_highlights::<EditPredictionPreview>();
 5211
 5212                        self.edit_prediction_preview
 5213                            .set_previous_scroll_position(None);
 5214                    } else {
 5215                        self.edit_prediction_preview
 5216                            .set_previous_scroll_position(Some(
 5217                                position_map.snapshot.scroll_anchor,
 5218                            ));
 5219
 5220                        self.highlight_rows::<EditPredictionPreview>(
 5221                            target..target,
 5222                            cx.theme().colors().editor_highlighted_line_background,
 5223                            true,
 5224                            cx,
 5225                        );
 5226                        self.request_autoscroll(Autoscroll::fit(), cx);
 5227                    }
 5228                }
 5229            }
 5230            InlineCompletion::Edit { edits, .. } => {
 5231                if let Some(provider) = self.edit_prediction_provider() {
 5232                    provider.accept(cx);
 5233                }
 5234
 5235                let snapshot = self.buffer.read(cx).snapshot(cx);
 5236                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5237
 5238                self.buffer.update(cx, |buffer, cx| {
 5239                    buffer.edit(edits.iter().cloned(), None, cx)
 5240                });
 5241
 5242                self.change_selections(None, window, cx, |s| {
 5243                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5244                });
 5245
 5246                self.update_visible_inline_completion(window, cx);
 5247                if self.active_inline_completion.is_none() {
 5248                    self.refresh_inline_completion(true, true, window, cx);
 5249                }
 5250
 5251                cx.notify();
 5252            }
 5253        }
 5254
 5255        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5256    }
 5257
 5258    pub fn accept_partial_inline_completion(
 5259        &mut self,
 5260        _: &AcceptPartialEditPrediction,
 5261        window: &mut Window,
 5262        cx: &mut Context<Self>,
 5263    ) {
 5264        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5265            return;
 5266        };
 5267        if self.selections.count() != 1 {
 5268            return;
 5269        }
 5270
 5271        self.report_inline_completion_event(
 5272            active_inline_completion.completion_id.clone(),
 5273            true,
 5274            cx,
 5275        );
 5276
 5277        match &active_inline_completion.completion {
 5278            InlineCompletion::Move { target, .. } => {
 5279                let target = *target;
 5280                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5281                    selections.select_anchor_ranges([target..target]);
 5282                });
 5283            }
 5284            InlineCompletion::Edit { edits, .. } => {
 5285                // Find an insertion that starts at the cursor position.
 5286                let snapshot = self.buffer.read(cx).snapshot(cx);
 5287                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5288                let insertion = edits.iter().find_map(|(range, text)| {
 5289                    let range = range.to_offset(&snapshot);
 5290                    if range.is_empty() && range.start == cursor_offset {
 5291                        Some(text)
 5292                    } else {
 5293                        None
 5294                    }
 5295                });
 5296
 5297                if let Some(text) = insertion {
 5298                    let mut partial_completion = text
 5299                        .chars()
 5300                        .by_ref()
 5301                        .take_while(|c| c.is_alphabetic())
 5302                        .collect::<String>();
 5303                    if partial_completion.is_empty() {
 5304                        partial_completion = text
 5305                            .chars()
 5306                            .by_ref()
 5307                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5308                            .collect::<String>();
 5309                    }
 5310
 5311                    cx.emit(EditorEvent::InputHandled {
 5312                        utf16_range_to_replace: None,
 5313                        text: partial_completion.clone().into(),
 5314                    });
 5315
 5316                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5317
 5318                    self.refresh_inline_completion(true, true, window, cx);
 5319                    cx.notify();
 5320                } else {
 5321                    self.accept_edit_prediction(&Default::default(), window, cx);
 5322                }
 5323            }
 5324        }
 5325    }
 5326
 5327    fn discard_inline_completion(
 5328        &mut self,
 5329        should_report_inline_completion_event: bool,
 5330        cx: &mut Context<Self>,
 5331    ) -> bool {
 5332        if should_report_inline_completion_event {
 5333            let completion_id = self
 5334                .active_inline_completion
 5335                .as_ref()
 5336                .and_then(|active_completion| active_completion.completion_id.clone());
 5337
 5338            self.report_inline_completion_event(completion_id, false, cx);
 5339        }
 5340
 5341        if let Some(provider) = self.edit_prediction_provider() {
 5342            provider.discard(cx);
 5343        }
 5344
 5345        self.take_active_inline_completion(cx)
 5346    }
 5347
 5348    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5349        let Some(provider) = self.edit_prediction_provider() else {
 5350            return;
 5351        };
 5352
 5353        let Some((_, buffer, _)) = self
 5354            .buffer
 5355            .read(cx)
 5356            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5357        else {
 5358            return;
 5359        };
 5360
 5361        let extension = buffer
 5362            .read(cx)
 5363            .file()
 5364            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5365
 5366        let event_type = match accepted {
 5367            true => "Edit Prediction Accepted",
 5368            false => "Edit Prediction Discarded",
 5369        };
 5370        telemetry::event!(
 5371            event_type,
 5372            provider = provider.name(),
 5373            prediction_id = id,
 5374            suggestion_accepted = accepted,
 5375            file_extension = extension,
 5376        );
 5377    }
 5378
 5379    pub fn has_active_inline_completion(&self) -> bool {
 5380        self.active_inline_completion.is_some()
 5381    }
 5382
 5383    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5384        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5385            return false;
 5386        };
 5387
 5388        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5389        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5390        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5391        true
 5392    }
 5393
 5394    /// Returns true when we're displaying the edit prediction popover below the cursor
 5395    /// like we are not previewing and the LSP autocomplete menu is visible
 5396    /// or we are in `when_holding_modifier` mode.
 5397    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5398        if self.edit_prediction_preview_is_active()
 5399            || !self.show_edit_predictions_in_menu()
 5400            || !self.edit_predictions_enabled()
 5401        {
 5402            return false;
 5403        }
 5404
 5405        if self.has_visible_completions_menu() {
 5406            return true;
 5407        }
 5408
 5409        has_completion && self.edit_prediction_requires_modifier()
 5410    }
 5411
 5412    fn handle_modifiers_changed(
 5413        &mut self,
 5414        modifiers: Modifiers,
 5415        position_map: &PositionMap,
 5416        window: &mut Window,
 5417        cx: &mut Context<Self>,
 5418    ) {
 5419        if self.show_edit_predictions_in_menu() {
 5420            self.update_edit_prediction_preview(&modifiers, window, cx);
 5421        }
 5422
 5423        self.update_selection_mode(&modifiers, position_map, window, cx);
 5424
 5425        let mouse_position = window.mouse_position();
 5426        if !position_map.text_hitbox.is_hovered(window) {
 5427            return;
 5428        }
 5429
 5430        self.update_hovered_link(
 5431            position_map.point_for_position(mouse_position),
 5432            &position_map.snapshot,
 5433            modifiers,
 5434            window,
 5435            cx,
 5436        )
 5437    }
 5438
 5439    fn update_selection_mode(
 5440        &mut self,
 5441        modifiers: &Modifiers,
 5442        position_map: &PositionMap,
 5443        window: &mut Window,
 5444        cx: &mut Context<Self>,
 5445    ) {
 5446        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5447            return;
 5448        }
 5449
 5450        let mouse_position = window.mouse_position();
 5451        let point_for_position = position_map.point_for_position(mouse_position);
 5452        let position = point_for_position.previous_valid;
 5453
 5454        self.select(
 5455            SelectPhase::BeginColumnar {
 5456                position,
 5457                reset: false,
 5458                goal_column: point_for_position.exact_unclipped.column(),
 5459            },
 5460            window,
 5461            cx,
 5462        );
 5463    }
 5464
 5465    fn update_edit_prediction_preview(
 5466        &mut self,
 5467        modifiers: &Modifiers,
 5468        window: &mut Window,
 5469        cx: &mut Context<Self>,
 5470    ) {
 5471        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5472        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5473            return;
 5474        };
 5475
 5476        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5477            if matches!(
 5478                self.edit_prediction_preview,
 5479                EditPredictionPreview::Inactive { .. }
 5480            ) {
 5481                self.edit_prediction_preview = EditPredictionPreview::Active {
 5482                    previous_scroll_position: None,
 5483                    since: Instant::now(),
 5484                };
 5485
 5486                self.update_visible_inline_completion(window, cx);
 5487                cx.notify();
 5488            }
 5489        } else if let EditPredictionPreview::Active {
 5490            previous_scroll_position,
 5491            since,
 5492        } = self.edit_prediction_preview
 5493        {
 5494            if let (Some(previous_scroll_position), Some(position_map)) =
 5495                (previous_scroll_position, self.last_position_map.as_ref())
 5496            {
 5497                self.set_scroll_position(
 5498                    previous_scroll_position
 5499                        .scroll_position(&position_map.snapshot.display_snapshot),
 5500                    window,
 5501                    cx,
 5502                );
 5503            }
 5504
 5505            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 5506                released_too_fast: since.elapsed() < Duration::from_millis(200),
 5507            };
 5508            self.clear_row_highlights::<EditPredictionPreview>();
 5509            self.update_visible_inline_completion(window, cx);
 5510            cx.notify();
 5511        }
 5512    }
 5513
 5514    fn update_visible_inline_completion(
 5515        &mut self,
 5516        _window: &mut Window,
 5517        cx: &mut Context<Self>,
 5518    ) -> Option<()> {
 5519        let selection = self.selections.newest_anchor();
 5520        let cursor = selection.head();
 5521        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5522        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5523        let excerpt_id = cursor.excerpt_id;
 5524
 5525        let show_in_menu = self.show_edit_predictions_in_menu();
 5526        let completions_menu_has_precedence = !show_in_menu
 5527            && (self.context_menu.borrow().is_some()
 5528                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5529
 5530        if completions_menu_has_precedence
 5531            || !offset_selection.is_empty()
 5532            || self
 5533                .active_inline_completion
 5534                .as_ref()
 5535                .map_or(false, |completion| {
 5536                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5537                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5538                    !invalidation_range.contains(&offset_selection.head())
 5539                })
 5540        {
 5541            self.discard_inline_completion(false, cx);
 5542            return None;
 5543        }
 5544
 5545        self.take_active_inline_completion(cx);
 5546        let Some(provider) = self.edit_prediction_provider() else {
 5547            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5548            return None;
 5549        };
 5550
 5551        let (buffer, cursor_buffer_position) =
 5552            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5553
 5554        self.edit_prediction_settings =
 5555            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5556
 5557        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 5558
 5559        if self.edit_prediction_indent_conflict {
 5560            let cursor_point = cursor.to_point(&multibuffer);
 5561
 5562            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 5563
 5564            if let Some((_, indent)) = indents.iter().next() {
 5565                if indent.len == cursor_point.column {
 5566                    self.edit_prediction_indent_conflict = false;
 5567                }
 5568            }
 5569        }
 5570
 5571        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5572        let edits = inline_completion
 5573            .edits
 5574            .into_iter()
 5575            .flat_map(|(range, new_text)| {
 5576                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5577                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5578                Some((start..end, new_text))
 5579            })
 5580            .collect::<Vec<_>>();
 5581        if edits.is_empty() {
 5582            return None;
 5583        }
 5584
 5585        let first_edit_start = edits.first().unwrap().0.start;
 5586        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5587        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5588
 5589        let last_edit_end = edits.last().unwrap().0.end;
 5590        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5591        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5592
 5593        let cursor_row = cursor.to_point(&multibuffer).row;
 5594
 5595        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5596
 5597        let mut inlay_ids = Vec::new();
 5598        let invalidation_row_range;
 5599        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5600            Some(cursor_row..edit_end_row)
 5601        } else if cursor_row > edit_end_row {
 5602            Some(edit_start_row..cursor_row)
 5603        } else {
 5604            None
 5605        };
 5606        let is_move =
 5607            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5608        let completion = if is_move {
 5609            invalidation_row_range =
 5610                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5611            let target = first_edit_start;
 5612            InlineCompletion::Move { target, snapshot }
 5613        } else {
 5614            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5615                && !self.inline_completions_hidden_for_vim_mode;
 5616
 5617            if show_completions_in_buffer {
 5618                if edits
 5619                    .iter()
 5620                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5621                {
 5622                    let mut inlays = Vec::new();
 5623                    for (range, new_text) in &edits {
 5624                        let inlay = Inlay::inline_completion(
 5625                            post_inc(&mut self.next_inlay_id),
 5626                            range.start,
 5627                            new_text.as_str(),
 5628                        );
 5629                        inlay_ids.push(inlay.id);
 5630                        inlays.push(inlay);
 5631                    }
 5632
 5633                    self.splice_inlays(&[], inlays, cx);
 5634                } else {
 5635                    let background_color = cx.theme().status().deleted_background;
 5636                    self.highlight_text::<InlineCompletionHighlight>(
 5637                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5638                        HighlightStyle {
 5639                            background_color: Some(background_color),
 5640                            ..Default::default()
 5641                        },
 5642                        cx,
 5643                    );
 5644                }
 5645            }
 5646
 5647            invalidation_row_range = edit_start_row..edit_end_row;
 5648
 5649            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5650                if provider.show_tab_accept_marker() {
 5651                    EditDisplayMode::TabAccept
 5652                } else {
 5653                    EditDisplayMode::Inline
 5654                }
 5655            } else {
 5656                EditDisplayMode::DiffPopover
 5657            };
 5658
 5659            InlineCompletion::Edit {
 5660                edits,
 5661                edit_preview: inline_completion.edit_preview,
 5662                display_mode,
 5663                snapshot,
 5664            }
 5665        };
 5666
 5667        let invalidation_range = multibuffer
 5668            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5669            ..multibuffer.anchor_after(Point::new(
 5670                invalidation_row_range.end,
 5671                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5672            ));
 5673
 5674        self.stale_inline_completion_in_menu = None;
 5675        self.active_inline_completion = Some(InlineCompletionState {
 5676            inlay_ids,
 5677            completion,
 5678            completion_id: inline_completion.id,
 5679            invalidation_range,
 5680        });
 5681
 5682        cx.notify();
 5683
 5684        Some(())
 5685    }
 5686
 5687    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5688        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5689    }
 5690
 5691    fn render_code_actions_indicator(
 5692        &self,
 5693        _style: &EditorStyle,
 5694        row: DisplayRow,
 5695        is_active: bool,
 5696        cx: &mut Context<Self>,
 5697    ) -> Option<IconButton> {
 5698        if self.available_code_actions.is_some() {
 5699            Some(
 5700                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5701                    .shape(ui::IconButtonShape::Square)
 5702                    .icon_size(IconSize::XSmall)
 5703                    .icon_color(Color::Muted)
 5704                    .toggle_state(is_active)
 5705                    .tooltip({
 5706                        let focus_handle = self.focus_handle.clone();
 5707                        move |window, cx| {
 5708                            Tooltip::for_action_in(
 5709                                "Toggle Code Actions",
 5710                                &ToggleCodeActions {
 5711                                    deployed_from_indicator: None,
 5712                                },
 5713                                &focus_handle,
 5714                                window,
 5715                                cx,
 5716                            )
 5717                        }
 5718                    })
 5719                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5720                        window.focus(&editor.focus_handle(cx));
 5721                        editor.toggle_code_actions(
 5722                            &ToggleCodeActions {
 5723                                deployed_from_indicator: Some(row),
 5724                            },
 5725                            window,
 5726                            cx,
 5727                        );
 5728                    })),
 5729            )
 5730        } else {
 5731            None
 5732        }
 5733    }
 5734
 5735    fn clear_tasks(&mut self) {
 5736        self.tasks.clear()
 5737    }
 5738
 5739    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5740        if self.tasks.insert(key, value).is_some() {
 5741            // This case should hopefully be rare, but just in case...
 5742            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5743        }
 5744    }
 5745
 5746    fn build_tasks_context(
 5747        project: &Entity<Project>,
 5748        buffer: &Entity<Buffer>,
 5749        buffer_row: u32,
 5750        tasks: &Arc<RunnableTasks>,
 5751        cx: &mut Context<Self>,
 5752    ) -> Task<Option<task::TaskContext>> {
 5753        let position = Point::new(buffer_row, tasks.column);
 5754        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5755        let location = Location {
 5756            buffer: buffer.clone(),
 5757            range: range_start..range_start,
 5758        };
 5759        // Fill in the environmental variables from the tree-sitter captures
 5760        let mut captured_task_variables = TaskVariables::default();
 5761        for (capture_name, value) in tasks.extra_variables.clone() {
 5762            captured_task_variables.insert(
 5763                task::VariableName::Custom(capture_name.into()),
 5764                value.clone(),
 5765            );
 5766        }
 5767        project.update(cx, |project, cx| {
 5768            project.task_store().update(cx, |task_store, cx| {
 5769                task_store.task_context_for_location(captured_task_variables, location, cx)
 5770            })
 5771        })
 5772    }
 5773
 5774    pub fn spawn_nearest_task(
 5775        &mut self,
 5776        action: &SpawnNearestTask,
 5777        window: &mut Window,
 5778        cx: &mut Context<Self>,
 5779    ) {
 5780        let Some((workspace, _)) = self.workspace.clone() else {
 5781            return;
 5782        };
 5783        let Some(project) = self.project.clone() else {
 5784            return;
 5785        };
 5786
 5787        // Try to find a closest, enclosing node using tree-sitter that has a
 5788        // task
 5789        let Some((buffer, buffer_row, tasks)) = self
 5790            .find_enclosing_node_task(cx)
 5791            // Or find the task that's closest in row-distance.
 5792            .or_else(|| self.find_closest_task(cx))
 5793        else {
 5794            return;
 5795        };
 5796
 5797        let reveal_strategy = action.reveal;
 5798        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5799        cx.spawn_in(window, |_, mut cx| async move {
 5800            let context = task_context.await?;
 5801            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5802
 5803            let resolved = resolved_task.resolved.as_mut()?;
 5804            resolved.reveal = reveal_strategy;
 5805
 5806            workspace
 5807                .update(&mut cx, |workspace, cx| {
 5808                    workspace::tasks::schedule_resolved_task(
 5809                        workspace,
 5810                        task_source_kind,
 5811                        resolved_task,
 5812                        false,
 5813                        cx,
 5814                    );
 5815                })
 5816                .ok()
 5817        })
 5818        .detach();
 5819    }
 5820
 5821    fn find_closest_task(
 5822        &mut self,
 5823        cx: &mut Context<Self>,
 5824    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5825        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5826
 5827        let ((buffer_id, row), tasks) = self
 5828            .tasks
 5829            .iter()
 5830            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5831
 5832        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5833        let tasks = Arc::new(tasks.to_owned());
 5834        Some((buffer, *row, tasks))
 5835    }
 5836
 5837    fn find_enclosing_node_task(
 5838        &mut self,
 5839        cx: &mut Context<Self>,
 5840    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5841        let snapshot = self.buffer.read(cx).snapshot(cx);
 5842        let offset = self.selections.newest::<usize>(cx).head();
 5843        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5844        let buffer_id = excerpt.buffer().remote_id();
 5845
 5846        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5847        let mut cursor = layer.node().walk();
 5848
 5849        while cursor.goto_first_child_for_byte(offset).is_some() {
 5850            if cursor.node().end_byte() == offset {
 5851                cursor.goto_next_sibling();
 5852            }
 5853        }
 5854
 5855        // Ascend to the smallest ancestor that contains the range and has a task.
 5856        loop {
 5857            let node = cursor.node();
 5858            let node_range = node.byte_range();
 5859            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5860
 5861            // Check if this node contains our offset
 5862            if node_range.start <= offset && node_range.end >= offset {
 5863                // If it contains offset, check for task
 5864                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5865                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5866                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5867                }
 5868            }
 5869
 5870            if !cursor.goto_parent() {
 5871                break;
 5872            }
 5873        }
 5874        None
 5875    }
 5876
 5877    fn render_run_indicator(
 5878        &self,
 5879        _style: &EditorStyle,
 5880        is_active: bool,
 5881        row: DisplayRow,
 5882        cx: &mut Context<Self>,
 5883    ) -> IconButton {
 5884        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5885            .shape(ui::IconButtonShape::Square)
 5886            .icon_size(IconSize::XSmall)
 5887            .icon_color(Color::Muted)
 5888            .toggle_state(is_active)
 5889            .on_click(cx.listener(move |editor, _e, window, cx| {
 5890                window.focus(&editor.focus_handle(cx));
 5891                editor.toggle_code_actions(
 5892                    &ToggleCodeActions {
 5893                        deployed_from_indicator: Some(row),
 5894                    },
 5895                    window,
 5896                    cx,
 5897                );
 5898            }))
 5899    }
 5900
 5901    pub fn context_menu_visible(&self) -> bool {
 5902        !self.edit_prediction_preview_is_active()
 5903            && self
 5904                .context_menu
 5905                .borrow()
 5906                .as_ref()
 5907                .map_or(false, |menu| menu.visible())
 5908    }
 5909
 5910    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5911        self.context_menu
 5912            .borrow()
 5913            .as_ref()
 5914            .map(|menu| menu.origin())
 5915    }
 5916
 5917    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 5918    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 5919
 5920    #[allow(clippy::too_many_arguments)]
 5921    fn render_edit_prediction_popover(
 5922        &mut self,
 5923        text_bounds: &Bounds<Pixels>,
 5924        content_origin: gpui::Point<Pixels>,
 5925        editor_snapshot: &EditorSnapshot,
 5926        visible_row_range: Range<DisplayRow>,
 5927        scroll_top: f32,
 5928        scroll_bottom: f32,
 5929        line_layouts: &[LineWithInvisibles],
 5930        line_height: Pixels,
 5931        scroll_pixel_position: gpui::Point<Pixels>,
 5932        newest_selection_head: Option<DisplayPoint>,
 5933        editor_width: Pixels,
 5934        style: &EditorStyle,
 5935        window: &mut Window,
 5936        cx: &mut App,
 5937    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5938        let active_inline_completion = self.active_inline_completion.as_ref()?;
 5939
 5940        if self.edit_prediction_visible_in_cursor_popover(true) {
 5941            return None;
 5942        }
 5943
 5944        match &active_inline_completion.completion {
 5945            InlineCompletion::Move { target, .. } => {
 5946                let target_display_point = target.to_display_point(editor_snapshot);
 5947
 5948                if self.edit_prediction_requires_modifier() {
 5949                    if !self.edit_prediction_preview_is_active() {
 5950                        return None;
 5951                    }
 5952
 5953                    self.render_edit_prediction_modifier_jump_popover(
 5954                        text_bounds,
 5955                        content_origin,
 5956                        visible_row_range,
 5957                        line_layouts,
 5958                        line_height,
 5959                        scroll_pixel_position,
 5960                        newest_selection_head,
 5961                        target_display_point,
 5962                        window,
 5963                        cx,
 5964                    )
 5965                } else {
 5966                    self.render_edit_prediction_eager_jump_popover(
 5967                        text_bounds,
 5968                        content_origin,
 5969                        editor_snapshot,
 5970                        visible_row_range,
 5971                        scroll_top,
 5972                        scroll_bottom,
 5973                        line_height,
 5974                        scroll_pixel_position,
 5975                        target_display_point,
 5976                        editor_width,
 5977                        window,
 5978                        cx,
 5979                    )
 5980                }
 5981            }
 5982            InlineCompletion::Edit {
 5983                display_mode: EditDisplayMode::Inline,
 5984                ..
 5985            } => None,
 5986            InlineCompletion::Edit {
 5987                display_mode: EditDisplayMode::TabAccept,
 5988                edits,
 5989                ..
 5990            } => {
 5991                let range = &edits.first()?.0;
 5992                let target_display_point = range.end.to_display_point(editor_snapshot);
 5993
 5994                self.render_edit_prediction_end_of_line_popover(
 5995                    "Accept",
 5996                    editor_snapshot,
 5997                    visible_row_range,
 5998                    target_display_point,
 5999                    line_height,
 6000                    scroll_pixel_position,
 6001                    content_origin,
 6002                    editor_width,
 6003                    window,
 6004                    cx,
 6005                )
 6006            }
 6007            InlineCompletion::Edit {
 6008                edits,
 6009                edit_preview,
 6010                display_mode: EditDisplayMode::DiffPopover,
 6011                snapshot,
 6012            } => self.render_edit_prediction_diff_popover(
 6013                text_bounds,
 6014                content_origin,
 6015                editor_snapshot,
 6016                visible_row_range,
 6017                line_layouts,
 6018                line_height,
 6019                scroll_pixel_position,
 6020                newest_selection_head,
 6021                editor_width,
 6022                style,
 6023                edits,
 6024                edit_preview,
 6025                snapshot,
 6026                window,
 6027                cx,
 6028            ),
 6029        }
 6030    }
 6031
 6032    #[allow(clippy::too_many_arguments)]
 6033    fn render_edit_prediction_modifier_jump_popover(
 6034        &mut self,
 6035        text_bounds: &Bounds<Pixels>,
 6036        content_origin: gpui::Point<Pixels>,
 6037        visible_row_range: Range<DisplayRow>,
 6038        line_layouts: &[LineWithInvisibles],
 6039        line_height: Pixels,
 6040        scroll_pixel_position: gpui::Point<Pixels>,
 6041        newest_selection_head: Option<DisplayPoint>,
 6042        target_display_point: DisplayPoint,
 6043        window: &mut Window,
 6044        cx: &mut App,
 6045    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6046        let scrolled_content_origin =
 6047            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 6048
 6049        const SCROLL_PADDING_Y: Pixels = px(12.);
 6050
 6051        if target_display_point.row() < visible_row_range.start {
 6052            return self.render_edit_prediction_scroll_popover(
 6053                |_| SCROLL_PADDING_Y,
 6054                IconName::ArrowUp,
 6055                visible_row_range,
 6056                line_layouts,
 6057                newest_selection_head,
 6058                scrolled_content_origin,
 6059                window,
 6060                cx,
 6061            );
 6062        } else if target_display_point.row() >= visible_row_range.end {
 6063            return self.render_edit_prediction_scroll_popover(
 6064                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 6065                IconName::ArrowDown,
 6066                visible_row_range,
 6067                line_layouts,
 6068                newest_selection_head,
 6069                scrolled_content_origin,
 6070                window,
 6071                cx,
 6072            );
 6073        }
 6074
 6075        const POLE_WIDTH: Pixels = px(2.);
 6076
 6077        let line_layout =
 6078            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 6079        let target_column = target_display_point.column() as usize;
 6080
 6081        let target_x = line_layout.x_for_index(target_column);
 6082        let target_y =
 6083            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 6084
 6085        let flag_on_right = target_x < text_bounds.size.width / 2.;
 6086
 6087        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 6088        border_color.l += 0.001;
 6089
 6090        let mut element = v_flex()
 6091            .items_end()
 6092            .when(flag_on_right, |el| el.items_start())
 6093            .child(if flag_on_right {
 6094                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6095                    .rounded_bl(px(0.))
 6096                    .rounded_tl(px(0.))
 6097                    .border_l_2()
 6098                    .border_color(border_color)
 6099            } else {
 6100                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6101                    .rounded_br(px(0.))
 6102                    .rounded_tr(px(0.))
 6103                    .border_r_2()
 6104                    .border_color(border_color)
 6105            })
 6106            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 6107            .into_any();
 6108
 6109        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6110
 6111        let mut origin = scrolled_content_origin + point(target_x, target_y)
 6112            - point(
 6113                if flag_on_right {
 6114                    POLE_WIDTH
 6115                } else {
 6116                    size.width - POLE_WIDTH
 6117                },
 6118                size.height - line_height,
 6119            );
 6120
 6121        origin.x = origin.x.max(content_origin.x);
 6122
 6123        element.prepaint_at(origin, window, cx);
 6124
 6125        Some((element, origin))
 6126    }
 6127
 6128    #[allow(clippy::too_many_arguments)]
 6129    fn render_edit_prediction_scroll_popover(
 6130        &mut self,
 6131        to_y: impl Fn(Size<Pixels>) -> Pixels,
 6132        scroll_icon: IconName,
 6133        visible_row_range: Range<DisplayRow>,
 6134        line_layouts: &[LineWithInvisibles],
 6135        newest_selection_head: Option<DisplayPoint>,
 6136        scrolled_content_origin: gpui::Point<Pixels>,
 6137        window: &mut Window,
 6138        cx: &mut App,
 6139    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6140        let mut element = self
 6141            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 6142            .into_any();
 6143
 6144        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6145
 6146        let cursor = newest_selection_head?;
 6147        let cursor_row_layout =
 6148            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6149        let cursor_column = cursor.column() as usize;
 6150
 6151        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6152
 6153        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6154
 6155        element.prepaint_at(origin, window, cx);
 6156        Some((element, origin))
 6157    }
 6158
 6159    #[allow(clippy::too_many_arguments)]
 6160    fn render_edit_prediction_eager_jump_popover(
 6161        &mut self,
 6162        text_bounds: &Bounds<Pixels>,
 6163        content_origin: gpui::Point<Pixels>,
 6164        editor_snapshot: &EditorSnapshot,
 6165        visible_row_range: Range<DisplayRow>,
 6166        scroll_top: f32,
 6167        scroll_bottom: f32,
 6168        line_height: Pixels,
 6169        scroll_pixel_position: gpui::Point<Pixels>,
 6170        target_display_point: DisplayPoint,
 6171        editor_width: Pixels,
 6172        window: &mut Window,
 6173        cx: &mut App,
 6174    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6175        if target_display_point.row().as_f32() < scroll_top {
 6176            let mut element = self
 6177                .render_edit_prediction_line_popover(
 6178                    "Jump to Edit",
 6179                    Some(IconName::ArrowUp),
 6180                    window,
 6181                    cx,
 6182                )?
 6183                .into_any();
 6184
 6185            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6186            let offset = point(
 6187                (text_bounds.size.width - size.width) / 2.,
 6188                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6189            );
 6190
 6191            let origin = text_bounds.origin + offset;
 6192            element.prepaint_at(origin, window, cx);
 6193            Some((element, origin))
 6194        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6195            let mut element = self
 6196                .render_edit_prediction_line_popover(
 6197                    "Jump to Edit",
 6198                    Some(IconName::ArrowDown),
 6199                    window,
 6200                    cx,
 6201                )?
 6202                .into_any();
 6203
 6204            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6205            let offset = point(
 6206                (text_bounds.size.width - size.width) / 2.,
 6207                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6208            );
 6209
 6210            let origin = text_bounds.origin + offset;
 6211            element.prepaint_at(origin, window, cx);
 6212            Some((element, origin))
 6213        } else {
 6214            self.render_edit_prediction_end_of_line_popover(
 6215                "Jump to Edit",
 6216                editor_snapshot,
 6217                visible_row_range,
 6218                target_display_point,
 6219                line_height,
 6220                scroll_pixel_position,
 6221                content_origin,
 6222                editor_width,
 6223                window,
 6224                cx,
 6225            )
 6226        }
 6227    }
 6228
 6229    #[allow(clippy::too_many_arguments)]
 6230    fn render_edit_prediction_end_of_line_popover(
 6231        self: &mut Editor,
 6232        label: &'static str,
 6233        editor_snapshot: &EditorSnapshot,
 6234        visible_row_range: Range<DisplayRow>,
 6235        target_display_point: DisplayPoint,
 6236        line_height: Pixels,
 6237        scroll_pixel_position: gpui::Point<Pixels>,
 6238        content_origin: gpui::Point<Pixels>,
 6239        editor_width: Pixels,
 6240        window: &mut Window,
 6241        cx: &mut App,
 6242    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6243        let target_line_end = DisplayPoint::new(
 6244            target_display_point.row(),
 6245            editor_snapshot.line_len(target_display_point.row()),
 6246        );
 6247
 6248        let mut element = self
 6249            .render_edit_prediction_line_popover(label, None, window, cx)?
 6250            .into_any();
 6251
 6252        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6253
 6254        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 6255
 6256        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 6257        let mut origin = start_point
 6258            + line_origin
 6259            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 6260        origin.x = origin.x.max(content_origin.x);
 6261
 6262        let max_x = content_origin.x + editor_width - size.width;
 6263
 6264        if origin.x > max_x {
 6265            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 6266
 6267            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 6268                origin.y += offset;
 6269                IconName::ArrowUp
 6270            } else {
 6271                origin.y -= offset;
 6272                IconName::ArrowDown
 6273            };
 6274
 6275            element = self
 6276                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 6277                .into_any();
 6278
 6279            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6280
 6281            origin.x = content_origin.x + editor_width - size.width - px(2.);
 6282        }
 6283
 6284        element.prepaint_at(origin, window, cx);
 6285        Some((element, origin))
 6286    }
 6287
 6288    #[allow(clippy::too_many_arguments)]
 6289    fn render_edit_prediction_diff_popover(
 6290        self: &Editor,
 6291        text_bounds: &Bounds<Pixels>,
 6292        content_origin: gpui::Point<Pixels>,
 6293        editor_snapshot: &EditorSnapshot,
 6294        visible_row_range: Range<DisplayRow>,
 6295        line_layouts: &[LineWithInvisibles],
 6296        line_height: Pixels,
 6297        scroll_pixel_position: gpui::Point<Pixels>,
 6298        newest_selection_head: Option<DisplayPoint>,
 6299        editor_width: Pixels,
 6300        style: &EditorStyle,
 6301        edits: &Vec<(Range<Anchor>, String)>,
 6302        edit_preview: &Option<language::EditPreview>,
 6303        snapshot: &language::BufferSnapshot,
 6304        window: &mut Window,
 6305        cx: &mut App,
 6306    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6307        let edit_start = edits
 6308            .first()
 6309            .unwrap()
 6310            .0
 6311            .start
 6312            .to_display_point(editor_snapshot);
 6313        let edit_end = edits
 6314            .last()
 6315            .unwrap()
 6316            .0
 6317            .end
 6318            .to_display_point(editor_snapshot);
 6319
 6320        let is_visible = visible_row_range.contains(&edit_start.row())
 6321            || visible_row_range.contains(&edit_end.row());
 6322        if !is_visible {
 6323            return None;
 6324        }
 6325
 6326        let highlighted_edits =
 6327            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 6328
 6329        let styled_text = highlighted_edits.to_styled_text(&style.text);
 6330        let line_count = highlighted_edits.text.lines().count();
 6331
 6332        const BORDER_WIDTH: Pixels = px(1.);
 6333
 6334        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 6335        let has_keybind = keybind.is_some();
 6336
 6337        let mut element = h_flex()
 6338            .items_start()
 6339            .child(
 6340                h_flex()
 6341                    .bg(cx.theme().colors().editor_background)
 6342                    .border(BORDER_WIDTH)
 6343                    .shadow_sm()
 6344                    .border_color(cx.theme().colors().border)
 6345                    .rounded_l_lg()
 6346                    .when(line_count > 1, |el| el.rounded_br_lg())
 6347                    .pr_1()
 6348                    .child(styled_text),
 6349            )
 6350            .child(
 6351                h_flex()
 6352                    .h(line_height + BORDER_WIDTH * px(2.))
 6353                    .px_1p5()
 6354                    .gap_1()
 6355                    // Workaround: For some reason, there's a gap if we don't do this
 6356                    .ml(-BORDER_WIDTH)
 6357                    .shadow(smallvec![gpui::BoxShadow {
 6358                        color: gpui::black().opacity(0.05),
 6359                        offset: point(px(1.), px(1.)),
 6360                        blur_radius: px(2.),
 6361                        spread_radius: px(0.),
 6362                    }])
 6363                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 6364                    .border(BORDER_WIDTH)
 6365                    .border_color(cx.theme().colors().border)
 6366                    .rounded_r_lg()
 6367                    .id("edit_prediction_diff_popover_keybind")
 6368                    .when(!has_keybind, |el| {
 6369                        let status_colors = cx.theme().status();
 6370
 6371                        el.bg(status_colors.error_background)
 6372                            .border_color(status_colors.error.opacity(0.6))
 6373                            .child(Icon::new(IconName::Info).color(Color::Error))
 6374                            .cursor_default()
 6375                            .hoverable_tooltip(move |_window, cx| {
 6376                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 6377                            })
 6378                    })
 6379                    .children(keybind),
 6380            )
 6381            .into_any();
 6382
 6383        let longest_row =
 6384            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 6385        let longest_line_width = if visible_row_range.contains(&longest_row) {
 6386            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 6387        } else {
 6388            layout_line(
 6389                longest_row,
 6390                editor_snapshot,
 6391                style,
 6392                editor_width,
 6393                |_| false,
 6394                window,
 6395                cx,
 6396            )
 6397            .width
 6398        };
 6399
 6400        let viewport_bounds =
 6401            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 6402                right: -EditorElement::SCROLLBAR_WIDTH,
 6403                ..Default::default()
 6404            });
 6405
 6406        let x_after_longest =
 6407            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 6408                - scroll_pixel_position.x;
 6409
 6410        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6411
 6412        // Fully visible if it can be displayed within the window (allow overlapping other
 6413        // panes). However, this is only allowed if the popover starts within text_bounds.
 6414        let can_position_to_the_right = x_after_longest < text_bounds.right()
 6415            && x_after_longest + element_bounds.width < viewport_bounds.right();
 6416
 6417        let mut origin = if can_position_to_the_right {
 6418            point(
 6419                x_after_longest,
 6420                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 6421                    - scroll_pixel_position.y,
 6422            )
 6423        } else {
 6424            let cursor_row = newest_selection_head.map(|head| head.row());
 6425            let above_edit = edit_start
 6426                .row()
 6427                .0
 6428                .checked_sub(line_count as u32)
 6429                .map(DisplayRow);
 6430            let below_edit = Some(edit_end.row() + 1);
 6431            let above_cursor =
 6432                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 6433            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 6434
 6435            // Place the edit popover adjacent to the edit if there is a location
 6436            // available that is onscreen and does not obscure the cursor. Otherwise,
 6437            // place it adjacent to the cursor.
 6438            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 6439                .into_iter()
 6440                .flatten()
 6441                .find(|&start_row| {
 6442                    let end_row = start_row + line_count as u32;
 6443                    visible_row_range.contains(&start_row)
 6444                        && visible_row_range.contains(&end_row)
 6445                        && cursor_row.map_or(true, |cursor_row| {
 6446                            !((start_row..end_row).contains(&cursor_row))
 6447                        })
 6448                })?;
 6449
 6450            content_origin
 6451                + point(
 6452                    -scroll_pixel_position.x,
 6453                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 6454                )
 6455        };
 6456
 6457        origin.x -= BORDER_WIDTH;
 6458
 6459        window.defer_draw(element, origin, 1);
 6460
 6461        // Do not return an element, since it will already be drawn due to defer_draw.
 6462        None
 6463    }
 6464
 6465    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 6466        px(30.)
 6467    }
 6468
 6469    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 6470        if self.read_only(cx) {
 6471            cx.theme().players().read_only()
 6472        } else {
 6473            self.style.as_ref().unwrap().local_player
 6474        }
 6475    }
 6476
 6477    fn render_edit_prediction_accept_keybind(
 6478        &self,
 6479        window: &mut Window,
 6480        cx: &App,
 6481    ) -> Option<AnyElement> {
 6482        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 6483        let accept_keystroke = accept_binding.keystroke()?;
 6484
 6485        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6486
 6487        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 6488            Color::Accent
 6489        } else {
 6490            Color::Muted
 6491        };
 6492
 6493        h_flex()
 6494            .px_0p5()
 6495            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 6496            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6497            .text_size(TextSize::XSmall.rems(cx))
 6498            .child(h_flex().children(ui::render_modifiers(
 6499                &accept_keystroke.modifiers,
 6500                PlatformStyle::platform(),
 6501                Some(modifiers_color),
 6502                Some(IconSize::XSmall.rems().into()),
 6503                true,
 6504            )))
 6505            .when(is_platform_style_mac, |parent| {
 6506                parent.child(accept_keystroke.key.clone())
 6507            })
 6508            .when(!is_platform_style_mac, |parent| {
 6509                parent.child(
 6510                    Key::new(
 6511                        util::capitalize(&accept_keystroke.key),
 6512                        Some(Color::Default),
 6513                    )
 6514                    .size(Some(IconSize::XSmall.rems().into())),
 6515                )
 6516            })
 6517            .into_any()
 6518            .into()
 6519    }
 6520
 6521    fn render_edit_prediction_line_popover(
 6522        &self,
 6523        label: impl Into<SharedString>,
 6524        icon: Option<IconName>,
 6525        window: &mut Window,
 6526        cx: &App,
 6527    ) -> Option<Stateful<Div>> {
 6528        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 6529
 6530        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 6531        let has_keybind = keybind.is_some();
 6532
 6533        let result = h_flex()
 6534            .id("ep-line-popover")
 6535            .py_0p5()
 6536            .pl_1()
 6537            .pr(padding_right)
 6538            .gap_1()
 6539            .rounded(px(6.))
 6540            .border_1()
 6541            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6542            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 6543            .shadow_sm()
 6544            .when(!has_keybind, |el| {
 6545                let status_colors = cx.theme().status();
 6546
 6547                el.bg(status_colors.error_background)
 6548                    .border_color(status_colors.error.opacity(0.6))
 6549                    .pl_2()
 6550                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 6551                    .cursor_default()
 6552                    .hoverable_tooltip(move |_window, cx| {
 6553                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 6554                    })
 6555            })
 6556            .children(keybind)
 6557            .child(
 6558                Label::new(label)
 6559                    .size(LabelSize::Small)
 6560                    .when(!has_keybind, |el| {
 6561                        el.color(cx.theme().status().error.into()).strikethrough()
 6562                    }),
 6563            )
 6564            .when(!has_keybind, |el| {
 6565                el.child(
 6566                    h_flex().ml_1().child(
 6567                        Icon::new(IconName::Info)
 6568                            .size(IconSize::Small)
 6569                            .color(cx.theme().status().error.into()),
 6570                    ),
 6571                )
 6572            })
 6573            .when_some(icon, |element, icon| {
 6574                element.child(
 6575                    div()
 6576                        .mt(px(1.5))
 6577                        .child(Icon::new(icon).size(IconSize::Small)),
 6578                )
 6579            });
 6580
 6581        Some(result)
 6582    }
 6583
 6584    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 6585        let accent_color = cx.theme().colors().text_accent;
 6586        let editor_bg_color = cx.theme().colors().editor_background;
 6587        editor_bg_color.blend(accent_color.opacity(0.1))
 6588    }
 6589
 6590    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 6591        let accent_color = cx.theme().colors().text_accent;
 6592        let editor_bg_color = cx.theme().colors().editor_background;
 6593        editor_bg_color.blend(accent_color.opacity(0.6))
 6594    }
 6595
 6596    #[allow(clippy::too_many_arguments)]
 6597    fn render_edit_prediction_cursor_popover(
 6598        &self,
 6599        min_width: Pixels,
 6600        max_width: Pixels,
 6601        cursor_point: Point,
 6602        style: &EditorStyle,
 6603        accept_keystroke: Option<&gpui::Keystroke>,
 6604        _window: &Window,
 6605        cx: &mut Context<Editor>,
 6606    ) -> Option<AnyElement> {
 6607        let provider = self.edit_prediction_provider.as_ref()?;
 6608
 6609        if provider.provider.needs_terms_acceptance(cx) {
 6610            return Some(
 6611                h_flex()
 6612                    .min_w(min_width)
 6613                    .flex_1()
 6614                    .px_2()
 6615                    .py_1()
 6616                    .gap_3()
 6617                    .elevation_2(cx)
 6618                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 6619                    .id("accept-terms")
 6620                    .cursor_pointer()
 6621                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 6622                    .on_click(cx.listener(|this, _event, window, cx| {
 6623                        cx.stop_propagation();
 6624                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 6625                        window.dispatch_action(
 6626                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 6627                            cx,
 6628                        );
 6629                    }))
 6630                    .child(
 6631                        h_flex()
 6632                            .flex_1()
 6633                            .gap_2()
 6634                            .child(Icon::new(IconName::ZedPredict))
 6635                            .child(Label::new("Accept Terms of Service"))
 6636                            .child(div().w_full())
 6637                            .child(
 6638                                Icon::new(IconName::ArrowUpRight)
 6639                                    .color(Color::Muted)
 6640                                    .size(IconSize::Small),
 6641                            )
 6642                            .into_any_element(),
 6643                    )
 6644                    .into_any(),
 6645            );
 6646        }
 6647
 6648        let is_refreshing = provider.provider.is_refreshing(cx);
 6649
 6650        fn pending_completion_container() -> Div {
 6651            h_flex()
 6652                .h_full()
 6653                .flex_1()
 6654                .gap_2()
 6655                .child(Icon::new(IconName::ZedPredict))
 6656        }
 6657
 6658        let completion = match &self.active_inline_completion {
 6659            Some(prediction) => {
 6660                if !self.has_visible_completions_menu() {
 6661                    const RADIUS: Pixels = px(6.);
 6662                    const BORDER_WIDTH: Pixels = px(1.);
 6663
 6664                    return Some(
 6665                        h_flex()
 6666                            .elevation_2(cx)
 6667                            .border(BORDER_WIDTH)
 6668                            .border_color(cx.theme().colors().border)
 6669                            .when(accept_keystroke.is_none(), |el| {
 6670                                el.border_color(cx.theme().status().error)
 6671                            })
 6672                            .rounded(RADIUS)
 6673                            .rounded_tl(px(0.))
 6674                            .overflow_hidden()
 6675                            .child(div().px_1p5().child(match &prediction.completion {
 6676                                InlineCompletion::Move { target, snapshot } => {
 6677                                    use text::ToPoint as _;
 6678                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 6679                                    {
 6680                                        Icon::new(IconName::ZedPredictDown)
 6681                                    } else {
 6682                                        Icon::new(IconName::ZedPredictUp)
 6683                                    }
 6684                                }
 6685                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 6686                            }))
 6687                            .child(
 6688                                h_flex()
 6689                                    .gap_1()
 6690                                    .py_1()
 6691                                    .px_2()
 6692                                    .rounded_r(RADIUS - BORDER_WIDTH)
 6693                                    .border_l_1()
 6694                                    .border_color(cx.theme().colors().border)
 6695                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6696                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 6697                                        el.child(
 6698                                            Label::new("Hold")
 6699                                                .size(LabelSize::Small)
 6700                                                .when(accept_keystroke.is_none(), |el| {
 6701                                                    el.strikethrough()
 6702                                                })
 6703                                                .line_height_style(LineHeightStyle::UiLabel),
 6704                                        )
 6705                                    })
 6706                                    .id("edit_prediction_cursor_popover_keybind")
 6707                                    .when(accept_keystroke.is_none(), |el| {
 6708                                        let status_colors = cx.theme().status();
 6709
 6710                                        el.bg(status_colors.error_background)
 6711                                            .border_color(status_colors.error.opacity(0.6))
 6712                                            .child(Icon::new(IconName::Info).color(Color::Error))
 6713                                            .cursor_default()
 6714                                            .hoverable_tooltip(move |_window, cx| {
 6715                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 6716                                                    .into()
 6717                                            })
 6718                                    })
 6719                                    .when_some(
 6720                                        accept_keystroke.as_ref(),
 6721                                        |el, accept_keystroke| {
 6722                                            el.child(h_flex().children(ui::render_modifiers(
 6723                                                &accept_keystroke.modifiers,
 6724                                                PlatformStyle::platform(),
 6725                                                Some(Color::Default),
 6726                                                Some(IconSize::XSmall.rems().into()),
 6727                                                false,
 6728                                            )))
 6729                                        },
 6730                                    ),
 6731                            )
 6732                            .into_any(),
 6733                    );
 6734                }
 6735
 6736                self.render_edit_prediction_cursor_popover_preview(
 6737                    prediction,
 6738                    cursor_point,
 6739                    style,
 6740                    cx,
 6741                )?
 6742            }
 6743
 6744            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 6745                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 6746                    stale_completion,
 6747                    cursor_point,
 6748                    style,
 6749                    cx,
 6750                )?,
 6751
 6752                None => {
 6753                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6754                }
 6755            },
 6756
 6757            None => pending_completion_container().child(Label::new("No Prediction")),
 6758        };
 6759
 6760        let completion = if is_refreshing {
 6761            completion
 6762                .with_animation(
 6763                    "loading-completion",
 6764                    Animation::new(Duration::from_secs(2))
 6765                        .repeat()
 6766                        .with_easing(pulsating_between(0.4, 0.8)),
 6767                    |label, delta| label.opacity(delta),
 6768                )
 6769                .into_any_element()
 6770        } else {
 6771            completion.into_any_element()
 6772        };
 6773
 6774        let has_completion = self.active_inline_completion.is_some();
 6775
 6776        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6777        Some(
 6778            h_flex()
 6779                .min_w(min_width)
 6780                .max_w(max_width)
 6781                .flex_1()
 6782                .elevation_2(cx)
 6783                .border_color(cx.theme().colors().border)
 6784                .child(
 6785                    div()
 6786                        .flex_1()
 6787                        .py_1()
 6788                        .px_2()
 6789                        .overflow_hidden()
 6790                        .child(completion),
 6791                )
 6792                .when_some(accept_keystroke, |el, accept_keystroke| {
 6793                    if !accept_keystroke.modifiers.modified() {
 6794                        return el;
 6795                    }
 6796
 6797                    el.child(
 6798                        h_flex()
 6799                            .h_full()
 6800                            .border_l_1()
 6801                            .rounded_r_lg()
 6802                            .border_color(cx.theme().colors().border)
 6803                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6804                            .gap_1()
 6805                            .py_1()
 6806                            .px_2()
 6807                            .child(
 6808                                h_flex()
 6809                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6810                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6811                                    .child(h_flex().children(ui::render_modifiers(
 6812                                        &accept_keystroke.modifiers,
 6813                                        PlatformStyle::platform(),
 6814                                        Some(if !has_completion {
 6815                                            Color::Muted
 6816                                        } else {
 6817                                            Color::Default
 6818                                        }),
 6819                                        None,
 6820                                        false,
 6821                                    ))),
 6822                            )
 6823                            .child(Label::new("Preview").into_any_element())
 6824                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6825                    )
 6826                })
 6827                .into_any(),
 6828        )
 6829    }
 6830
 6831    fn render_edit_prediction_cursor_popover_preview(
 6832        &self,
 6833        completion: &InlineCompletionState,
 6834        cursor_point: Point,
 6835        style: &EditorStyle,
 6836        cx: &mut Context<Editor>,
 6837    ) -> Option<Div> {
 6838        use text::ToPoint as _;
 6839
 6840        fn render_relative_row_jump(
 6841            prefix: impl Into<String>,
 6842            current_row: u32,
 6843            target_row: u32,
 6844        ) -> Div {
 6845            let (row_diff, arrow) = if target_row < current_row {
 6846                (current_row - target_row, IconName::ArrowUp)
 6847            } else {
 6848                (target_row - current_row, IconName::ArrowDown)
 6849            };
 6850
 6851            h_flex()
 6852                .child(
 6853                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6854                        .color(Color::Muted)
 6855                        .size(LabelSize::Small),
 6856                )
 6857                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6858        }
 6859
 6860        match &completion.completion {
 6861            InlineCompletion::Move {
 6862                target, snapshot, ..
 6863            } => Some(
 6864                h_flex()
 6865                    .px_2()
 6866                    .gap_2()
 6867                    .flex_1()
 6868                    .child(
 6869                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6870                            Icon::new(IconName::ZedPredictDown)
 6871                        } else {
 6872                            Icon::new(IconName::ZedPredictUp)
 6873                        },
 6874                    )
 6875                    .child(Label::new("Jump to Edit")),
 6876            ),
 6877
 6878            InlineCompletion::Edit {
 6879                edits,
 6880                edit_preview,
 6881                snapshot,
 6882                display_mode: _,
 6883            } => {
 6884                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6885
 6886                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6887                    &snapshot,
 6888                    &edits,
 6889                    edit_preview.as_ref()?,
 6890                    true,
 6891                    cx,
 6892                )
 6893                .first_line_preview();
 6894
 6895                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6896                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 6897
 6898                let preview = h_flex()
 6899                    .gap_1()
 6900                    .min_w_16()
 6901                    .child(styled_text)
 6902                    .when(has_more_lines, |parent| parent.child(""));
 6903
 6904                let left = if first_edit_row != cursor_point.row {
 6905                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6906                        .into_any_element()
 6907                } else {
 6908                    Icon::new(IconName::ZedPredict).into_any_element()
 6909                };
 6910
 6911                Some(
 6912                    h_flex()
 6913                        .h_full()
 6914                        .flex_1()
 6915                        .gap_2()
 6916                        .pr_1()
 6917                        .overflow_x_hidden()
 6918                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6919                        .child(left)
 6920                        .child(preview),
 6921                )
 6922            }
 6923        }
 6924    }
 6925
 6926    fn render_context_menu(
 6927        &self,
 6928        style: &EditorStyle,
 6929        max_height_in_lines: u32,
 6930        y_flipped: bool,
 6931        window: &mut Window,
 6932        cx: &mut Context<Editor>,
 6933    ) -> Option<AnyElement> {
 6934        let menu = self.context_menu.borrow();
 6935        let menu = menu.as_ref()?;
 6936        if !menu.visible() {
 6937            return None;
 6938        };
 6939        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6940    }
 6941
 6942    fn render_context_menu_aside(
 6943        &mut self,
 6944        max_size: Size<Pixels>,
 6945        window: &mut Window,
 6946        cx: &mut Context<Editor>,
 6947    ) -> Option<AnyElement> {
 6948        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 6949            if menu.visible() {
 6950                menu.render_aside(self, max_size, window, cx)
 6951            } else {
 6952                None
 6953            }
 6954        })
 6955    }
 6956
 6957    fn hide_context_menu(
 6958        &mut self,
 6959        window: &mut Window,
 6960        cx: &mut Context<Self>,
 6961    ) -> Option<CodeContextMenu> {
 6962        cx.notify();
 6963        self.completion_tasks.clear();
 6964        let context_menu = self.context_menu.borrow_mut().take();
 6965        self.stale_inline_completion_in_menu.take();
 6966        self.update_visible_inline_completion(window, cx);
 6967        context_menu
 6968    }
 6969
 6970    fn show_snippet_choices(
 6971        &mut self,
 6972        choices: &Vec<String>,
 6973        selection: Range<Anchor>,
 6974        cx: &mut Context<Self>,
 6975    ) {
 6976        if selection.start.buffer_id.is_none() {
 6977            return;
 6978        }
 6979        let buffer_id = selection.start.buffer_id.unwrap();
 6980        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6981        let id = post_inc(&mut self.next_completion_id);
 6982
 6983        if let Some(buffer) = buffer {
 6984            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6985                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6986            ));
 6987        }
 6988    }
 6989
 6990    pub fn insert_snippet(
 6991        &mut self,
 6992        insertion_ranges: &[Range<usize>],
 6993        snippet: Snippet,
 6994        window: &mut Window,
 6995        cx: &mut Context<Self>,
 6996    ) -> Result<()> {
 6997        struct Tabstop<T> {
 6998            is_end_tabstop: bool,
 6999            ranges: Vec<Range<T>>,
 7000            choices: Option<Vec<String>>,
 7001        }
 7002
 7003        let tabstops = self.buffer.update(cx, |buffer, cx| {
 7004            let snippet_text: Arc<str> = snippet.text.clone().into();
 7005            buffer.edit(
 7006                insertion_ranges
 7007                    .iter()
 7008                    .cloned()
 7009                    .map(|range| (range, snippet_text.clone())),
 7010                Some(AutoindentMode::EachLine),
 7011                cx,
 7012            );
 7013
 7014            let snapshot = &*buffer.read(cx);
 7015            let snippet = &snippet;
 7016            snippet
 7017                .tabstops
 7018                .iter()
 7019                .map(|tabstop| {
 7020                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 7021                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 7022                    });
 7023                    let mut tabstop_ranges = tabstop
 7024                        .ranges
 7025                        .iter()
 7026                        .flat_map(|tabstop_range| {
 7027                            let mut delta = 0_isize;
 7028                            insertion_ranges.iter().map(move |insertion_range| {
 7029                                let insertion_start = insertion_range.start as isize + delta;
 7030                                delta +=
 7031                                    snippet.text.len() as isize - insertion_range.len() as isize;
 7032
 7033                                let start = ((insertion_start + tabstop_range.start) as usize)
 7034                                    .min(snapshot.len());
 7035                                let end = ((insertion_start + tabstop_range.end) as usize)
 7036                                    .min(snapshot.len());
 7037                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 7038                            })
 7039                        })
 7040                        .collect::<Vec<_>>();
 7041                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 7042
 7043                    Tabstop {
 7044                        is_end_tabstop,
 7045                        ranges: tabstop_ranges,
 7046                        choices: tabstop.choices.clone(),
 7047                    }
 7048                })
 7049                .collect::<Vec<_>>()
 7050        });
 7051        if let Some(tabstop) = tabstops.first() {
 7052            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7053                s.select_ranges(tabstop.ranges.iter().cloned());
 7054            });
 7055
 7056            if let Some(choices) = &tabstop.choices {
 7057                if let Some(selection) = tabstop.ranges.first() {
 7058                    self.show_snippet_choices(choices, selection.clone(), cx)
 7059                }
 7060            }
 7061
 7062            // If we're already at the last tabstop and it's at the end of the snippet,
 7063            // we're done, we don't need to keep the state around.
 7064            if !tabstop.is_end_tabstop {
 7065                let choices = tabstops
 7066                    .iter()
 7067                    .map(|tabstop| tabstop.choices.clone())
 7068                    .collect();
 7069
 7070                let ranges = tabstops
 7071                    .into_iter()
 7072                    .map(|tabstop| tabstop.ranges)
 7073                    .collect::<Vec<_>>();
 7074
 7075                self.snippet_stack.push(SnippetState {
 7076                    active_index: 0,
 7077                    ranges,
 7078                    choices,
 7079                });
 7080            }
 7081
 7082            // Check whether the just-entered snippet ends with an auto-closable bracket.
 7083            if self.autoclose_regions.is_empty() {
 7084                let snapshot = self.buffer.read(cx).snapshot(cx);
 7085                for selection in &mut self.selections.all::<Point>(cx) {
 7086                    let selection_head = selection.head();
 7087                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 7088                        continue;
 7089                    };
 7090
 7091                    let mut bracket_pair = None;
 7092                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 7093                    let prev_chars = snapshot
 7094                        .reversed_chars_at(selection_head)
 7095                        .collect::<String>();
 7096                    for (pair, enabled) in scope.brackets() {
 7097                        if enabled
 7098                            && pair.close
 7099                            && prev_chars.starts_with(pair.start.as_str())
 7100                            && next_chars.starts_with(pair.end.as_str())
 7101                        {
 7102                            bracket_pair = Some(pair.clone());
 7103                            break;
 7104                        }
 7105                    }
 7106                    if let Some(pair) = bracket_pair {
 7107                        let start = snapshot.anchor_after(selection_head);
 7108                        let end = snapshot.anchor_after(selection_head);
 7109                        self.autoclose_regions.push(AutocloseRegion {
 7110                            selection_id: selection.id,
 7111                            range: start..end,
 7112                            pair,
 7113                        });
 7114                    }
 7115                }
 7116            }
 7117        }
 7118        Ok(())
 7119    }
 7120
 7121    pub fn move_to_next_snippet_tabstop(
 7122        &mut self,
 7123        window: &mut Window,
 7124        cx: &mut Context<Self>,
 7125    ) -> bool {
 7126        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 7127    }
 7128
 7129    pub fn move_to_prev_snippet_tabstop(
 7130        &mut self,
 7131        window: &mut Window,
 7132        cx: &mut Context<Self>,
 7133    ) -> bool {
 7134        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 7135    }
 7136
 7137    pub fn move_to_snippet_tabstop(
 7138        &mut self,
 7139        bias: Bias,
 7140        window: &mut Window,
 7141        cx: &mut Context<Self>,
 7142    ) -> bool {
 7143        if let Some(mut snippet) = self.snippet_stack.pop() {
 7144            match bias {
 7145                Bias::Left => {
 7146                    if snippet.active_index > 0 {
 7147                        snippet.active_index -= 1;
 7148                    } else {
 7149                        self.snippet_stack.push(snippet);
 7150                        return false;
 7151                    }
 7152                }
 7153                Bias::Right => {
 7154                    if snippet.active_index + 1 < snippet.ranges.len() {
 7155                        snippet.active_index += 1;
 7156                    } else {
 7157                        self.snippet_stack.push(snippet);
 7158                        return false;
 7159                    }
 7160                }
 7161            }
 7162            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 7163                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7164                    s.select_anchor_ranges(current_ranges.iter().cloned())
 7165                });
 7166
 7167                if let Some(choices) = &snippet.choices[snippet.active_index] {
 7168                    if let Some(selection) = current_ranges.first() {
 7169                        self.show_snippet_choices(&choices, selection.clone(), cx);
 7170                    }
 7171                }
 7172
 7173                // If snippet state is not at the last tabstop, push it back on the stack
 7174                if snippet.active_index + 1 < snippet.ranges.len() {
 7175                    self.snippet_stack.push(snippet);
 7176                }
 7177                return true;
 7178            }
 7179        }
 7180
 7181        false
 7182    }
 7183
 7184    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 7185        self.transact(window, cx, |this, window, cx| {
 7186            this.select_all(&SelectAll, window, cx);
 7187            this.insert("", window, cx);
 7188        });
 7189    }
 7190
 7191    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 7192        self.transact(window, cx, |this, window, cx| {
 7193            this.select_autoclose_pair(window, cx);
 7194            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 7195            if !this.linked_edit_ranges.is_empty() {
 7196                let selections = this.selections.all::<MultiBufferPoint>(cx);
 7197                let snapshot = this.buffer.read(cx).snapshot(cx);
 7198
 7199                for selection in selections.iter() {
 7200                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 7201                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 7202                    if selection_start.buffer_id != selection_end.buffer_id {
 7203                        continue;
 7204                    }
 7205                    if let Some(ranges) =
 7206                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 7207                    {
 7208                        for (buffer, entries) in ranges {
 7209                            linked_ranges.entry(buffer).or_default().extend(entries);
 7210                        }
 7211                    }
 7212                }
 7213            }
 7214
 7215            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7216            if !this.selections.line_mode {
 7217                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 7218                for selection in &mut selections {
 7219                    if selection.is_empty() {
 7220                        let old_head = selection.head();
 7221                        let mut new_head =
 7222                            movement::left(&display_map, old_head.to_display_point(&display_map))
 7223                                .to_point(&display_map);
 7224                        if let Some((buffer, line_buffer_range)) = display_map
 7225                            .buffer_snapshot
 7226                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 7227                        {
 7228                            let indent_size =
 7229                                buffer.indent_size_for_line(line_buffer_range.start.row);
 7230                            let indent_len = match indent_size.kind {
 7231                                IndentKind::Space => {
 7232                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 7233                                }
 7234                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 7235                            };
 7236                            if old_head.column <= indent_size.len && old_head.column > 0 {
 7237                                let indent_len = indent_len.get();
 7238                                new_head = cmp::min(
 7239                                    new_head,
 7240                                    MultiBufferPoint::new(
 7241                                        old_head.row,
 7242                                        ((old_head.column - 1) / indent_len) * indent_len,
 7243                                    ),
 7244                                );
 7245                            }
 7246                        }
 7247
 7248                        selection.set_head(new_head, SelectionGoal::None);
 7249                    }
 7250                }
 7251            }
 7252
 7253            this.signature_help_state.set_backspace_pressed(true);
 7254            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7255                s.select(selections)
 7256            });
 7257            this.insert("", window, cx);
 7258            let empty_str: Arc<str> = Arc::from("");
 7259            for (buffer, edits) in linked_ranges {
 7260                let snapshot = buffer.read(cx).snapshot();
 7261                use text::ToPoint as TP;
 7262
 7263                let edits = edits
 7264                    .into_iter()
 7265                    .map(|range| {
 7266                        let end_point = TP::to_point(&range.end, &snapshot);
 7267                        let mut start_point = TP::to_point(&range.start, &snapshot);
 7268
 7269                        if end_point == start_point {
 7270                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 7271                                .saturating_sub(1);
 7272                            start_point =
 7273                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 7274                        };
 7275
 7276                        (start_point..end_point, empty_str.clone())
 7277                    })
 7278                    .sorted_by_key(|(range, _)| range.start)
 7279                    .collect::<Vec<_>>();
 7280                buffer.update(cx, |this, cx| {
 7281                    this.edit(edits, None, cx);
 7282                })
 7283            }
 7284            this.refresh_inline_completion(true, false, window, cx);
 7285            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 7286        });
 7287    }
 7288
 7289    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 7290        self.transact(window, cx, |this, window, cx| {
 7291            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7292                let line_mode = s.line_mode;
 7293                s.move_with(|map, selection| {
 7294                    if selection.is_empty() && !line_mode {
 7295                        let cursor = movement::right(map, selection.head());
 7296                        selection.end = cursor;
 7297                        selection.reversed = true;
 7298                        selection.goal = SelectionGoal::None;
 7299                    }
 7300                })
 7301            });
 7302            this.insert("", window, cx);
 7303            this.refresh_inline_completion(true, false, window, cx);
 7304        });
 7305    }
 7306
 7307    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 7308        if self.move_to_prev_snippet_tabstop(window, cx) {
 7309            return;
 7310        }
 7311
 7312        self.outdent(&Outdent, window, cx);
 7313    }
 7314
 7315    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 7316        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 7317            return;
 7318        }
 7319
 7320        let mut selections = self.selections.all_adjusted(cx);
 7321        let buffer = self.buffer.read(cx);
 7322        let snapshot = buffer.snapshot(cx);
 7323        let rows_iter = selections.iter().map(|s| s.head().row);
 7324        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 7325
 7326        let mut edits = Vec::new();
 7327        let mut prev_edited_row = 0;
 7328        let mut row_delta = 0;
 7329        for selection in &mut selections {
 7330            if selection.start.row != prev_edited_row {
 7331                row_delta = 0;
 7332            }
 7333            prev_edited_row = selection.end.row;
 7334
 7335            // If the selection is non-empty, then increase the indentation of the selected lines.
 7336            if !selection.is_empty() {
 7337                row_delta =
 7338                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7339                continue;
 7340            }
 7341
 7342            // If the selection is empty and the cursor is in the leading whitespace before the
 7343            // suggested indentation, then auto-indent the line.
 7344            let cursor = selection.head();
 7345            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 7346            if let Some(suggested_indent) =
 7347                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 7348            {
 7349                if cursor.column < suggested_indent.len
 7350                    && cursor.column <= current_indent.len
 7351                    && current_indent.len <= suggested_indent.len
 7352                {
 7353                    selection.start = Point::new(cursor.row, suggested_indent.len);
 7354                    selection.end = selection.start;
 7355                    if row_delta == 0 {
 7356                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 7357                            cursor.row,
 7358                            current_indent,
 7359                            suggested_indent,
 7360                        ));
 7361                        row_delta = suggested_indent.len - current_indent.len;
 7362                    }
 7363                    continue;
 7364                }
 7365            }
 7366
 7367            // Otherwise, insert a hard or soft tab.
 7368            let settings = buffer.language_settings_at(cursor, cx);
 7369            let tab_size = if settings.hard_tabs {
 7370                IndentSize::tab()
 7371            } else {
 7372                let tab_size = settings.tab_size.get();
 7373                let char_column = snapshot
 7374                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 7375                    .flat_map(str::chars)
 7376                    .count()
 7377                    + row_delta as usize;
 7378                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 7379                IndentSize::spaces(chars_to_next_tab_stop)
 7380            };
 7381            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 7382            selection.end = selection.start;
 7383            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 7384            row_delta += tab_size.len;
 7385        }
 7386
 7387        self.transact(window, cx, |this, window, cx| {
 7388            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7389            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7390                s.select(selections)
 7391            });
 7392            this.refresh_inline_completion(true, false, window, cx);
 7393        });
 7394    }
 7395
 7396    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 7397        if self.read_only(cx) {
 7398            return;
 7399        }
 7400        let mut selections = self.selections.all::<Point>(cx);
 7401        let mut prev_edited_row = 0;
 7402        let mut row_delta = 0;
 7403        let mut edits = Vec::new();
 7404        let buffer = self.buffer.read(cx);
 7405        let snapshot = buffer.snapshot(cx);
 7406        for selection in &mut selections {
 7407            if selection.start.row != prev_edited_row {
 7408                row_delta = 0;
 7409            }
 7410            prev_edited_row = selection.end.row;
 7411
 7412            row_delta =
 7413                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7414        }
 7415
 7416        self.transact(window, cx, |this, window, cx| {
 7417            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7418            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7419                s.select(selections)
 7420            });
 7421        });
 7422    }
 7423
 7424    fn indent_selection(
 7425        buffer: &MultiBuffer,
 7426        snapshot: &MultiBufferSnapshot,
 7427        selection: &mut Selection<Point>,
 7428        edits: &mut Vec<(Range<Point>, String)>,
 7429        delta_for_start_row: u32,
 7430        cx: &App,
 7431    ) -> u32 {
 7432        let settings = buffer.language_settings_at(selection.start, cx);
 7433        let tab_size = settings.tab_size.get();
 7434        let indent_kind = if settings.hard_tabs {
 7435            IndentKind::Tab
 7436        } else {
 7437            IndentKind::Space
 7438        };
 7439        let mut start_row = selection.start.row;
 7440        let mut end_row = selection.end.row + 1;
 7441
 7442        // If a selection ends at the beginning of a line, don't indent
 7443        // that last line.
 7444        if selection.end.column == 0 && selection.end.row > selection.start.row {
 7445            end_row -= 1;
 7446        }
 7447
 7448        // Avoid re-indenting a row that has already been indented by a
 7449        // previous selection, but still update this selection's column
 7450        // to reflect that indentation.
 7451        if delta_for_start_row > 0 {
 7452            start_row += 1;
 7453            selection.start.column += delta_for_start_row;
 7454            if selection.end.row == selection.start.row {
 7455                selection.end.column += delta_for_start_row;
 7456            }
 7457        }
 7458
 7459        let mut delta_for_end_row = 0;
 7460        let has_multiple_rows = start_row + 1 != end_row;
 7461        for row in start_row..end_row {
 7462            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 7463            let indent_delta = match (current_indent.kind, indent_kind) {
 7464                (IndentKind::Space, IndentKind::Space) => {
 7465                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 7466                    IndentSize::spaces(columns_to_next_tab_stop)
 7467                }
 7468                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 7469                (_, IndentKind::Tab) => IndentSize::tab(),
 7470            };
 7471
 7472            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 7473                0
 7474            } else {
 7475                selection.start.column
 7476            };
 7477            let row_start = Point::new(row, start);
 7478            edits.push((
 7479                row_start..row_start,
 7480                indent_delta.chars().collect::<String>(),
 7481            ));
 7482
 7483            // Update this selection's endpoints to reflect the indentation.
 7484            if row == selection.start.row {
 7485                selection.start.column += indent_delta.len;
 7486            }
 7487            if row == selection.end.row {
 7488                selection.end.column += indent_delta.len;
 7489                delta_for_end_row = indent_delta.len;
 7490            }
 7491        }
 7492
 7493        if selection.start.row == selection.end.row {
 7494            delta_for_start_row + delta_for_end_row
 7495        } else {
 7496            delta_for_end_row
 7497        }
 7498    }
 7499
 7500    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 7501        if self.read_only(cx) {
 7502            return;
 7503        }
 7504        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7505        let selections = self.selections.all::<Point>(cx);
 7506        let mut deletion_ranges = Vec::new();
 7507        let mut last_outdent = None;
 7508        {
 7509            let buffer = self.buffer.read(cx);
 7510            let snapshot = buffer.snapshot(cx);
 7511            for selection in &selections {
 7512                let settings = buffer.language_settings_at(selection.start, cx);
 7513                let tab_size = settings.tab_size.get();
 7514                let mut rows = selection.spanned_rows(false, &display_map);
 7515
 7516                // Avoid re-outdenting a row that has already been outdented by a
 7517                // previous selection.
 7518                if let Some(last_row) = last_outdent {
 7519                    if last_row == rows.start {
 7520                        rows.start = rows.start.next_row();
 7521                    }
 7522                }
 7523                let has_multiple_rows = rows.len() > 1;
 7524                for row in rows.iter_rows() {
 7525                    let indent_size = snapshot.indent_size_for_line(row);
 7526                    if indent_size.len > 0 {
 7527                        let deletion_len = match indent_size.kind {
 7528                            IndentKind::Space => {
 7529                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 7530                                if columns_to_prev_tab_stop == 0 {
 7531                                    tab_size
 7532                                } else {
 7533                                    columns_to_prev_tab_stop
 7534                                }
 7535                            }
 7536                            IndentKind::Tab => 1,
 7537                        };
 7538                        let start = if has_multiple_rows
 7539                            || deletion_len > selection.start.column
 7540                            || indent_size.len < selection.start.column
 7541                        {
 7542                            0
 7543                        } else {
 7544                            selection.start.column - deletion_len
 7545                        };
 7546                        deletion_ranges.push(
 7547                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 7548                        );
 7549                        last_outdent = Some(row);
 7550                    }
 7551                }
 7552            }
 7553        }
 7554
 7555        self.transact(window, cx, |this, window, cx| {
 7556            this.buffer.update(cx, |buffer, cx| {
 7557                let empty_str: Arc<str> = Arc::default();
 7558                buffer.edit(
 7559                    deletion_ranges
 7560                        .into_iter()
 7561                        .map(|range| (range, empty_str.clone())),
 7562                    None,
 7563                    cx,
 7564                );
 7565            });
 7566            let selections = this.selections.all::<usize>(cx);
 7567            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7568                s.select(selections)
 7569            });
 7570        });
 7571    }
 7572
 7573    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 7574        if self.read_only(cx) {
 7575            return;
 7576        }
 7577        let selections = self
 7578            .selections
 7579            .all::<usize>(cx)
 7580            .into_iter()
 7581            .map(|s| s.range());
 7582
 7583        self.transact(window, cx, |this, window, cx| {
 7584            this.buffer.update(cx, |buffer, cx| {
 7585                buffer.autoindent_ranges(selections, cx);
 7586            });
 7587            let selections = this.selections.all::<usize>(cx);
 7588            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7589                s.select(selections)
 7590            });
 7591        });
 7592    }
 7593
 7594    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 7595        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7596        let selections = self.selections.all::<Point>(cx);
 7597
 7598        let mut new_cursors = Vec::new();
 7599        let mut edit_ranges = Vec::new();
 7600        let mut selections = selections.iter().peekable();
 7601        while let Some(selection) = selections.next() {
 7602            let mut rows = selection.spanned_rows(false, &display_map);
 7603            let goal_display_column = selection.head().to_display_point(&display_map).column();
 7604
 7605            // Accumulate contiguous regions of rows that we want to delete.
 7606            while let Some(next_selection) = selections.peek() {
 7607                let next_rows = next_selection.spanned_rows(false, &display_map);
 7608                if next_rows.start <= rows.end {
 7609                    rows.end = next_rows.end;
 7610                    selections.next().unwrap();
 7611                } else {
 7612                    break;
 7613                }
 7614            }
 7615
 7616            let buffer = &display_map.buffer_snapshot;
 7617            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 7618            let edit_end;
 7619            let cursor_buffer_row;
 7620            if buffer.max_point().row >= rows.end.0 {
 7621                // If there's a line after the range, delete the \n from the end of the row range
 7622                // and position the cursor on the next line.
 7623                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 7624                cursor_buffer_row = rows.end;
 7625            } else {
 7626                // If there isn't a line after the range, delete the \n from the line before the
 7627                // start of the row range and position the cursor there.
 7628                edit_start = edit_start.saturating_sub(1);
 7629                edit_end = buffer.len();
 7630                cursor_buffer_row = rows.start.previous_row();
 7631            }
 7632
 7633            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 7634            *cursor.column_mut() =
 7635                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 7636
 7637            new_cursors.push((
 7638                selection.id,
 7639                buffer.anchor_after(cursor.to_point(&display_map)),
 7640            ));
 7641            edit_ranges.push(edit_start..edit_end);
 7642        }
 7643
 7644        self.transact(window, cx, |this, window, cx| {
 7645            let buffer = this.buffer.update(cx, |buffer, cx| {
 7646                let empty_str: Arc<str> = Arc::default();
 7647                buffer.edit(
 7648                    edit_ranges
 7649                        .into_iter()
 7650                        .map(|range| (range, empty_str.clone())),
 7651                    None,
 7652                    cx,
 7653                );
 7654                buffer.snapshot(cx)
 7655            });
 7656            let new_selections = new_cursors
 7657                .into_iter()
 7658                .map(|(id, cursor)| {
 7659                    let cursor = cursor.to_point(&buffer);
 7660                    Selection {
 7661                        id,
 7662                        start: cursor,
 7663                        end: cursor,
 7664                        reversed: false,
 7665                        goal: SelectionGoal::None,
 7666                    }
 7667                })
 7668                .collect();
 7669
 7670            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7671                s.select(new_selections);
 7672            });
 7673        });
 7674    }
 7675
 7676    pub fn join_lines_impl(
 7677        &mut self,
 7678        insert_whitespace: bool,
 7679        window: &mut Window,
 7680        cx: &mut Context<Self>,
 7681    ) {
 7682        if self.read_only(cx) {
 7683            return;
 7684        }
 7685        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 7686        for selection in self.selections.all::<Point>(cx) {
 7687            let start = MultiBufferRow(selection.start.row);
 7688            // Treat single line selections as if they include the next line. Otherwise this action
 7689            // would do nothing for single line selections individual cursors.
 7690            let end = if selection.start.row == selection.end.row {
 7691                MultiBufferRow(selection.start.row + 1)
 7692            } else {
 7693                MultiBufferRow(selection.end.row)
 7694            };
 7695
 7696            if let Some(last_row_range) = row_ranges.last_mut() {
 7697                if start <= last_row_range.end {
 7698                    last_row_range.end = end;
 7699                    continue;
 7700                }
 7701            }
 7702            row_ranges.push(start..end);
 7703        }
 7704
 7705        let snapshot = self.buffer.read(cx).snapshot(cx);
 7706        let mut cursor_positions = Vec::new();
 7707        for row_range in &row_ranges {
 7708            let anchor = snapshot.anchor_before(Point::new(
 7709                row_range.end.previous_row().0,
 7710                snapshot.line_len(row_range.end.previous_row()),
 7711            ));
 7712            cursor_positions.push(anchor..anchor);
 7713        }
 7714
 7715        self.transact(window, cx, |this, window, cx| {
 7716            for row_range in row_ranges.into_iter().rev() {
 7717                for row in row_range.iter_rows().rev() {
 7718                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 7719                    let next_line_row = row.next_row();
 7720                    let indent = snapshot.indent_size_for_line(next_line_row);
 7721                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7722
 7723                    let replace =
 7724                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7725                            " "
 7726                        } else {
 7727                            ""
 7728                        };
 7729
 7730                    this.buffer.update(cx, |buffer, cx| {
 7731                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7732                    });
 7733                }
 7734            }
 7735
 7736            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7737                s.select_anchor_ranges(cursor_positions)
 7738            });
 7739        });
 7740    }
 7741
 7742    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7743        self.join_lines_impl(true, window, cx);
 7744    }
 7745
 7746    pub fn sort_lines_case_sensitive(
 7747        &mut self,
 7748        _: &SortLinesCaseSensitive,
 7749        window: &mut Window,
 7750        cx: &mut Context<Self>,
 7751    ) {
 7752        self.manipulate_lines(window, cx, |lines| lines.sort())
 7753    }
 7754
 7755    pub fn sort_lines_case_insensitive(
 7756        &mut self,
 7757        _: &SortLinesCaseInsensitive,
 7758        window: &mut Window,
 7759        cx: &mut Context<Self>,
 7760    ) {
 7761        self.manipulate_lines(window, cx, |lines| {
 7762            lines.sort_by_key(|line| line.to_lowercase())
 7763        })
 7764    }
 7765
 7766    pub fn unique_lines_case_insensitive(
 7767        &mut self,
 7768        _: &UniqueLinesCaseInsensitive,
 7769        window: &mut Window,
 7770        cx: &mut Context<Self>,
 7771    ) {
 7772        self.manipulate_lines(window, cx, |lines| {
 7773            let mut seen = HashSet::default();
 7774            lines.retain(|line| seen.insert(line.to_lowercase()));
 7775        })
 7776    }
 7777
 7778    pub fn unique_lines_case_sensitive(
 7779        &mut self,
 7780        _: &UniqueLinesCaseSensitive,
 7781        window: &mut Window,
 7782        cx: &mut Context<Self>,
 7783    ) {
 7784        self.manipulate_lines(window, cx, |lines| {
 7785            let mut seen = HashSet::default();
 7786            lines.retain(|line| seen.insert(*line));
 7787        })
 7788    }
 7789
 7790    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7791        let Some(project) = self.project.clone() else {
 7792            return;
 7793        };
 7794        self.reload(project, window, cx)
 7795            .detach_and_notify_err(window, cx);
 7796    }
 7797
 7798    pub fn restore_file(
 7799        &mut self,
 7800        _: &::git::RestoreFile,
 7801        window: &mut Window,
 7802        cx: &mut Context<Self>,
 7803    ) {
 7804        let mut buffer_ids = HashSet::default();
 7805        let snapshot = self.buffer().read(cx).snapshot(cx);
 7806        for selection in self.selections.all::<usize>(cx) {
 7807            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 7808        }
 7809
 7810        let buffer = self.buffer().read(cx);
 7811        let ranges = buffer_ids
 7812            .into_iter()
 7813            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 7814            .collect::<Vec<_>>();
 7815
 7816        self.restore_hunks_in_ranges(ranges, window, cx);
 7817    }
 7818
 7819    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 7820        let selections = self
 7821            .selections
 7822            .all(cx)
 7823            .into_iter()
 7824            .map(|s| s.range())
 7825            .collect();
 7826        self.restore_hunks_in_ranges(selections, window, cx);
 7827    }
 7828
 7829    fn restore_hunks_in_ranges(
 7830        &mut self,
 7831        ranges: Vec<Range<Point>>,
 7832        window: &mut Window,
 7833        cx: &mut Context<Editor>,
 7834    ) {
 7835        let mut revert_changes = HashMap::default();
 7836        let chunk_by = self
 7837            .snapshot(window, cx)
 7838            .hunks_for_ranges(ranges)
 7839            .into_iter()
 7840            .chunk_by(|hunk| hunk.buffer_id);
 7841        for (buffer_id, hunks) in &chunk_by {
 7842            let hunks = hunks.collect::<Vec<_>>();
 7843            for hunk in &hunks {
 7844                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 7845            }
 7846            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), window, cx);
 7847        }
 7848        drop(chunk_by);
 7849        if !revert_changes.is_empty() {
 7850            self.transact(window, cx, |editor, window, cx| {
 7851                editor.restore(revert_changes, window, cx);
 7852            });
 7853        }
 7854    }
 7855
 7856    pub fn open_active_item_in_terminal(
 7857        &mut self,
 7858        _: &OpenInTerminal,
 7859        window: &mut Window,
 7860        cx: &mut Context<Self>,
 7861    ) {
 7862        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7863            let project_path = buffer.read(cx).project_path(cx)?;
 7864            let project = self.project.as_ref()?.read(cx);
 7865            let entry = project.entry_for_path(&project_path, cx)?;
 7866            let parent = match &entry.canonical_path {
 7867                Some(canonical_path) => canonical_path.to_path_buf(),
 7868                None => project.absolute_path(&project_path, cx)?,
 7869            }
 7870            .parent()?
 7871            .to_path_buf();
 7872            Some(parent)
 7873        }) {
 7874            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7875        }
 7876    }
 7877
 7878    pub fn prepare_restore_change(
 7879        &self,
 7880        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7881        hunk: &MultiBufferDiffHunk,
 7882        cx: &mut App,
 7883    ) -> Option<()> {
 7884        let buffer = self.buffer.read(cx);
 7885        let diff = buffer.diff_for(hunk.buffer_id)?;
 7886        let buffer = buffer.buffer(hunk.buffer_id)?;
 7887        let buffer = buffer.read(cx);
 7888        let original_text = diff
 7889            .read(cx)
 7890            .base_text()
 7891            .as_rope()
 7892            .slice(hunk.diff_base_byte_range.clone());
 7893        let buffer_snapshot = buffer.snapshot();
 7894        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7895        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7896            probe
 7897                .0
 7898                .start
 7899                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7900                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7901        }) {
 7902            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7903            Some(())
 7904        } else {
 7905            None
 7906        }
 7907    }
 7908
 7909    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7910        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7911    }
 7912
 7913    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7914        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7915    }
 7916
 7917    fn manipulate_lines<Fn>(
 7918        &mut self,
 7919        window: &mut Window,
 7920        cx: &mut Context<Self>,
 7921        mut callback: Fn,
 7922    ) where
 7923        Fn: FnMut(&mut Vec<&str>),
 7924    {
 7925        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7926        let buffer = self.buffer.read(cx).snapshot(cx);
 7927
 7928        let mut edits = Vec::new();
 7929
 7930        let selections = self.selections.all::<Point>(cx);
 7931        let mut selections = selections.iter().peekable();
 7932        let mut contiguous_row_selections = Vec::new();
 7933        let mut new_selections = Vec::new();
 7934        let mut added_lines = 0;
 7935        let mut removed_lines = 0;
 7936
 7937        while let Some(selection) = selections.next() {
 7938            let (start_row, end_row) = consume_contiguous_rows(
 7939                &mut contiguous_row_selections,
 7940                selection,
 7941                &display_map,
 7942                &mut selections,
 7943            );
 7944
 7945            let start_point = Point::new(start_row.0, 0);
 7946            let end_point = Point::new(
 7947                end_row.previous_row().0,
 7948                buffer.line_len(end_row.previous_row()),
 7949            );
 7950            let text = buffer
 7951                .text_for_range(start_point..end_point)
 7952                .collect::<String>();
 7953
 7954            let mut lines = text.split('\n').collect_vec();
 7955
 7956            let lines_before = lines.len();
 7957            callback(&mut lines);
 7958            let lines_after = lines.len();
 7959
 7960            edits.push((start_point..end_point, lines.join("\n")));
 7961
 7962            // Selections must change based on added and removed line count
 7963            let start_row =
 7964                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7965            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7966            new_selections.push(Selection {
 7967                id: selection.id,
 7968                start: start_row,
 7969                end: end_row,
 7970                goal: SelectionGoal::None,
 7971                reversed: selection.reversed,
 7972            });
 7973
 7974            if lines_after > lines_before {
 7975                added_lines += lines_after - lines_before;
 7976            } else if lines_before > lines_after {
 7977                removed_lines += lines_before - lines_after;
 7978            }
 7979        }
 7980
 7981        self.transact(window, cx, |this, window, cx| {
 7982            let buffer = this.buffer.update(cx, |buffer, cx| {
 7983                buffer.edit(edits, None, cx);
 7984                buffer.snapshot(cx)
 7985            });
 7986
 7987            // Recalculate offsets on newly edited buffer
 7988            let new_selections = new_selections
 7989                .iter()
 7990                .map(|s| {
 7991                    let start_point = Point::new(s.start.0, 0);
 7992                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7993                    Selection {
 7994                        id: s.id,
 7995                        start: buffer.point_to_offset(start_point),
 7996                        end: buffer.point_to_offset(end_point),
 7997                        goal: s.goal,
 7998                        reversed: s.reversed,
 7999                    }
 8000                })
 8001                .collect();
 8002
 8003            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8004                s.select(new_selections);
 8005            });
 8006
 8007            this.request_autoscroll(Autoscroll::fit(), cx);
 8008        });
 8009    }
 8010
 8011    pub fn convert_to_upper_case(
 8012        &mut self,
 8013        _: &ConvertToUpperCase,
 8014        window: &mut Window,
 8015        cx: &mut Context<Self>,
 8016    ) {
 8017        self.manipulate_text(window, cx, |text| text.to_uppercase())
 8018    }
 8019
 8020    pub fn convert_to_lower_case(
 8021        &mut self,
 8022        _: &ConvertToLowerCase,
 8023        window: &mut Window,
 8024        cx: &mut Context<Self>,
 8025    ) {
 8026        self.manipulate_text(window, cx, |text| text.to_lowercase())
 8027    }
 8028
 8029    pub fn convert_to_title_case(
 8030        &mut self,
 8031        _: &ConvertToTitleCase,
 8032        window: &mut Window,
 8033        cx: &mut Context<Self>,
 8034    ) {
 8035        self.manipulate_text(window, cx, |text| {
 8036            text.split('\n')
 8037                .map(|line| line.to_case(Case::Title))
 8038                .join("\n")
 8039        })
 8040    }
 8041
 8042    pub fn convert_to_snake_case(
 8043        &mut self,
 8044        _: &ConvertToSnakeCase,
 8045        window: &mut Window,
 8046        cx: &mut Context<Self>,
 8047    ) {
 8048        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 8049    }
 8050
 8051    pub fn convert_to_kebab_case(
 8052        &mut self,
 8053        _: &ConvertToKebabCase,
 8054        window: &mut Window,
 8055        cx: &mut Context<Self>,
 8056    ) {
 8057        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 8058    }
 8059
 8060    pub fn convert_to_upper_camel_case(
 8061        &mut self,
 8062        _: &ConvertToUpperCamelCase,
 8063        window: &mut Window,
 8064        cx: &mut Context<Self>,
 8065    ) {
 8066        self.manipulate_text(window, cx, |text| {
 8067            text.split('\n')
 8068                .map(|line| line.to_case(Case::UpperCamel))
 8069                .join("\n")
 8070        })
 8071    }
 8072
 8073    pub fn convert_to_lower_camel_case(
 8074        &mut self,
 8075        _: &ConvertToLowerCamelCase,
 8076        window: &mut Window,
 8077        cx: &mut Context<Self>,
 8078    ) {
 8079        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 8080    }
 8081
 8082    pub fn convert_to_opposite_case(
 8083        &mut self,
 8084        _: &ConvertToOppositeCase,
 8085        window: &mut Window,
 8086        cx: &mut Context<Self>,
 8087    ) {
 8088        self.manipulate_text(window, cx, |text| {
 8089            text.chars()
 8090                .fold(String::with_capacity(text.len()), |mut t, c| {
 8091                    if c.is_uppercase() {
 8092                        t.extend(c.to_lowercase());
 8093                    } else {
 8094                        t.extend(c.to_uppercase());
 8095                    }
 8096                    t
 8097                })
 8098        })
 8099    }
 8100
 8101    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 8102    where
 8103        Fn: FnMut(&str) -> String,
 8104    {
 8105        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8106        let buffer = self.buffer.read(cx).snapshot(cx);
 8107
 8108        let mut new_selections = Vec::new();
 8109        let mut edits = Vec::new();
 8110        let mut selection_adjustment = 0i32;
 8111
 8112        for selection in self.selections.all::<usize>(cx) {
 8113            let selection_is_empty = selection.is_empty();
 8114
 8115            let (start, end) = if selection_is_empty {
 8116                let word_range = movement::surrounding_word(
 8117                    &display_map,
 8118                    selection.start.to_display_point(&display_map),
 8119                );
 8120                let start = word_range.start.to_offset(&display_map, Bias::Left);
 8121                let end = word_range.end.to_offset(&display_map, Bias::Left);
 8122                (start, end)
 8123            } else {
 8124                (selection.start, selection.end)
 8125            };
 8126
 8127            let text = buffer.text_for_range(start..end).collect::<String>();
 8128            let old_length = text.len() as i32;
 8129            let text = callback(&text);
 8130
 8131            new_selections.push(Selection {
 8132                start: (start as i32 - selection_adjustment) as usize,
 8133                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 8134                goal: SelectionGoal::None,
 8135                ..selection
 8136            });
 8137
 8138            selection_adjustment += old_length - text.len() as i32;
 8139
 8140            edits.push((start..end, text));
 8141        }
 8142
 8143        self.transact(window, cx, |this, window, cx| {
 8144            this.buffer.update(cx, |buffer, cx| {
 8145                buffer.edit(edits, None, cx);
 8146            });
 8147
 8148            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8149                s.select(new_selections);
 8150            });
 8151
 8152            this.request_autoscroll(Autoscroll::fit(), cx);
 8153        });
 8154    }
 8155
 8156    pub fn duplicate(
 8157        &mut self,
 8158        upwards: bool,
 8159        whole_lines: bool,
 8160        window: &mut Window,
 8161        cx: &mut Context<Self>,
 8162    ) {
 8163        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8164        let buffer = &display_map.buffer_snapshot;
 8165        let selections = self.selections.all::<Point>(cx);
 8166
 8167        let mut edits = Vec::new();
 8168        let mut selections_iter = selections.iter().peekable();
 8169        while let Some(selection) = selections_iter.next() {
 8170            let mut rows = selection.spanned_rows(false, &display_map);
 8171            // duplicate line-wise
 8172            if whole_lines || selection.start == selection.end {
 8173                // Avoid duplicating the same lines twice.
 8174                while let Some(next_selection) = selections_iter.peek() {
 8175                    let next_rows = next_selection.spanned_rows(false, &display_map);
 8176                    if next_rows.start < rows.end {
 8177                        rows.end = next_rows.end;
 8178                        selections_iter.next().unwrap();
 8179                    } else {
 8180                        break;
 8181                    }
 8182                }
 8183
 8184                // Copy the text from the selected row region and splice it either at the start
 8185                // or end of the region.
 8186                let start = Point::new(rows.start.0, 0);
 8187                let end = Point::new(
 8188                    rows.end.previous_row().0,
 8189                    buffer.line_len(rows.end.previous_row()),
 8190                );
 8191                let text = buffer
 8192                    .text_for_range(start..end)
 8193                    .chain(Some("\n"))
 8194                    .collect::<String>();
 8195                let insert_location = if upwards {
 8196                    Point::new(rows.end.0, 0)
 8197                } else {
 8198                    start
 8199                };
 8200                edits.push((insert_location..insert_location, text));
 8201            } else {
 8202                // duplicate character-wise
 8203                let start = selection.start;
 8204                let end = selection.end;
 8205                let text = buffer.text_for_range(start..end).collect::<String>();
 8206                edits.push((selection.end..selection.end, text));
 8207            }
 8208        }
 8209
 8210        self.transact(window, cx, |this, _, cx| {
 8211            this.buffer.update(cx, |buffer, cx| {
 8212                buffer.edit(edits, None, cx);
 8213            });
 8214
 8215            this.request_autoscroll(Autoscroll::fit(), cx);
 8216        });
 8217    }
 8218
 8219    pub fn duplicate_line_up(
 8220        &mut self,
 8221        _: &DuplicateLineUp,
 8222        window: &mut Window,
 8223        cx: &mut Context<Self>,
 8224    ) {
 8225        self.duplicate(true, true, window, cx);
 8226    }
 8227
 8228    pub fn duplicate_line_down(
 8229        &mut self,
 8230        _: &DuplicateLineDown,
 8231        window: &mut Window,
 8232        cx: &mut Context<Self>,
 8233    ) {
 8234        self.duplicate(false, true, window, cx);
 8235    }
 8236
 8237    pub fn duplicate_selection(
 8238        &mut self,
 8239        _: &DuplicateSelection,
 8240        window: &mut Window,
 8241        cx: &mut Context<Self>,
 8242    ) {
 8243        self.duplicate(false, false, window, cx);
 8244    }
 8245
 8246    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 8247        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8248        let buffer = self.buffer.read(cx).snapshot(cx);
 8249
 8250        let mut edits = Vec::new();
 8251        let mut unfold_ranges = Vec::new();
 8252        let mut refold_creases = Vec::new();
 8253
 8254        let selections = self.selections.all::<Point>(cx);
 8255        let mut selections = selections.iter().peekable();
 8256        let mut contiguous_row_selections = Vec::new();
 8257        let mut new_selections = Vec::new();
 8258
 8259        while let Some(selection) = selections.next() {
 8260            // Find all the selections that span a contiguous row range
 8261            let (start_row, end_row) = consume_contiguous_rows(
 8262                &mut contiguous_row_selections,
 8263                selection,
 8264                &display_map,
 8265                &mut selections,
 8266            );
 8267
 8268            // Move the text spanned by the row range to be before the line preceding the row range
 8269            if start_row.0 > 0 {
 8270                let range_to_move = Point::new(
 8271                    start_row.previous_row().0,
 8272                    buffer.line_len(start_row.previous_row()),
 8273                )
 8274                    ..Point::new(
 8275                        end_row.previous_row().0,
 8276                        buffer.line_len(end_row.previous_row()),
 8277                    );
 8278                let insertion_point = display_map
 8279                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 8280                    .0;
 8281
 8282                // Don't move lines across excerpts
 8283                if buffer
 8284                    .excerpt_containing(insertion_point..range_to_move.end)
 8285                    .is_some()
 8286                {
 8287                    let text = buffer
 8288                        .text_for_range(range_to_move.clone())
 8289                        .flat_map(|s| s.chars())
 8290                        .skip(1)
 8291                        .chain(['\n'])
 8292                        .collect::<String>();
 8293
 8294                    edits.push((
 8295                        buffer.anchor_after(range_to_move.start)
 8296                            ..buffer.anchor_before(range_to_move.end),
 8297                        String::new(),
 8298                    ));
 8299                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8300                    edits.push((insertion_anchor..insertion_anchor, text));
 8301
 8302                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 8303
 8304                    // Move selections up
 8305                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8306                        |mut selection| {
 8307                            selection.start.row -= row_delta;
 8308                            selection.end.row -= row_delta;
 8309                            selection
 8310                        },
 8311                    ));
 8312
 8313                    // Move folds up
 8314                    unfold_ranges.push(range_to_move.clone());
 8315                    for fold in display_map.folds_in_range(
 8316                        buffer.anchor_before(range_to_move.start)
 8317                            ..buffer.anchor_after(range_to_move.end),
 8318                    ) {
 8319                        let mut start = fold.range.start.to_point(&buffer);
 8320                        let mut end = fold.range.end.to_point(&buffer);
 8321                        start.row -= row_delta;
 8322                        end.row -= row_delta;
 8323                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8324                    }
 8325                }
 8326            }
 8327
 8328            // If we didn't move line(s), preserve the existing selections
 8329            new_selections.append(&mut contiguous_row_selections);
 8330        }
 8331
 8332        self.transact(window, cx, |this, window, cx| {
 8333            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8334            this.buffer.update(cx, |buffer, cx| {
 8335                for (range, text) in edits {
 8336                    buffer.edit([(range, text)], None, cx);
 8337                }
 8338            });
 8339            this.fold_creases(refold_creases, true, window, cx);
 8340            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8341                s.select(new_selections);
 8342            })
 8343        });
 8344    }
 8345
 8346    pub fn move_line_down(
 8347        &mut self,
 8348        _: &MoveLineDown,
 8349        window: &mut Window,
 8350        cx: &mut Context<Self>,
 8351    ) {
 8352        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8353        let buffer = self.buffer.read(cx).snapshot(cx);
 8354
 8355        let mut edits = Vec::new();
 8356        let mut unfold_ranges = Vec::new();
 8357        let mut refold_creases = Vec::new();
 8358
 8359        let selections = self.selections.all::<Point>(cx);
 8360        let mut selections = selections.iter().peekable();
 8361        let mut contiguous_row_selections = Vec::new();
 8362        let mut new_selections = Vec::new();
 8363
 8364        while let Some(selection) = selections.next() {
 8365            // Find all the selections that span a contiguous row range
 8366            let (start_row, end_row) = consume_contiguous_rows(
 8367                &mut contiguous_row_selections,
 8368                selection,
 8369                &display_map,
 8370                &mut selections,
 8371            );
 8372
 8373            // Move the text spanned by the row range to be after the last line of the row range
 8374            if end_row.0 <= buffer.max_point().row {
 8375                let range_to_move =
 8376                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 8377                let insertion_point = display_map
 8378                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 8379                    .0;
 8380
 8381                // Don't move lines across excerpt boundaries
 8382                if buffer
 8383                    .excerpt_containing(range_to_move.start..insertion_point)
 8384                    .is_some()
 8385                {
 8386                    let mut text = String::from("\n");
 8387                    text.extend(buffer.text_for_range(range_to_move.clone()));
 8388                    text.pop(); // Drop trailing newline
 8389                    edits.push((
 8390                        buffer.anchor_after(range_to_move.start)
 8391                            ..buffer.anchor_before(range_to_move.end),
 8392                        String::new(),
 8393                    ));
 8394                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8395                    edits.push((insertion_anchor..insertion_anchor, text));
 8396
 8397                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 8398
 8399                    // Move selections down
 8400                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8401                        |mut selection| {
 8402                            selection.start.row += row_delta;
 8403                            selection.end.row += row_delta;
 8404                            selection
 8405                        },
 8406                    ));
 8407
 8408                    // Move folds down
 8409                    unfold_ranges.push(range_to_move.clone());
 8410                    for fold in display_map.folds_in_range(
 8411                        buffer.anchor_before(range_to_move.start)
 8412                            ..buffer.anchor_after(range_to_move.end),
 8413                    ) {
 8414                        let mut start = fold.range.start.to_point(&buffer);
 8415                        let mut end = fold.range.end.to_point(&buffer);
 8416                        start.row += row_delta;
 8417                        end.row += row_delta;
 8418                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8419                    }
 8420                }
 8421            }
 8422
 8423            // If we didn't move line(s), preserve the existing selections
 8424            new_selections.append(&mut contiguous_row_selections);
 8425        }
 8426
 8427        self.transact(window, cx, |this, window, cx| {
 8428            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8429            this.buffer.update(cx, |buffer, cx| {
 8430                for (range, text) in edits {
 8431                    buffer.edit([(range, text)], None, cx);
 8432                }
 8433            });
 8434            this.fold_creases(refold_creases, true, window, cx);
 8435            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8436                s.select(new_selections)
 8437            });
 8438        });
 8439    }
 8440
 8441    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 8442        let text_layout_details = &self.text_layout_details(window);
 8443        self.transact(window, cx, |this, window, cx| {
 8444            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8445                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 8446                let line_mode = s.line_mode;
 8447                s.move_with(|display_map, selection| {
 8448                    if !selection.is_empty() || line_mode {
 8449                        return;
 8450                    }
 8451
 8452                    let mut head = selection.head();
 8453                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 8454                    if head.column() == display_map.line_len(head.row()) {
 8455                        transpose_offset = display_map
 8456                            .buffer_snapshot
 8457                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8458                    }
 8459
 8460                    if transpose_offset == 0 {
 8461                        return;
 8462                    }
 8463
 8464                    *head.column_mut() += 1;
 8465                    head = display_map.clip_point(head, Bias::Right);
 8466                    let goal = SelectionGoal::HorizontalPosition(
 8467                        display_map
 8468                            .x_for_display_point(head, text_layout_details)
 8469                            .into(),
 8470                    );
 8471                    selection.collapse_to(head, goal);
 8472
 8473                    let transpose_start = display_map
 8474                        .buffer_snapshot
 8475                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8476                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 8477                        let transpose_end = display_map
 8478                            .buffer_snapshot
 8479                            .clip_offset(transpose_offset + 1, Bias::Right);
 8480                        if let Some(ch) =
 8481                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 8482                        {
 8483                            edits.push((transpose_start..transpose_offset, String::new()));
 8484                            edits.push((transpose_end..transpose_end, ch.to_string()));
 8485                        }
 8486                    }
 8487                });
 8488                edits
 8489            });
 8490            this.buffer
 8491                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8492            let selections = this.selections.all::<usize>(cx);
 8493            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8494                s.select(selections);
 8495            });
 8496        });
 8497    }
 8498
 8499    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 8500        self.rewrap_impl(IsVimMode::No, cx)
 8501    }
 8502
 8503    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 8504        let buffer = self.buffer.read(cx).snapshot(cx);
 8505        let selections = self.selections.all::<Point>(cx);
 8506        let mut selections = selections.iter().peekable();
 8507
 8508        let mut edits = Vec::new();
 8509        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 8510
 8511        while let Some(selection) = selections.next() {
 8512            let mut start_row = selection.start.row;
 8513            let mut end_row = selection.end.row;
 8514
 8515            // Skip selections that overlap with a range that has already been rewrapped.
 8516            let selection_range = start_row..end_row;
 8517            if rewrapped_row_ranges
 8518                .iter()
 8519                .any(|range| range.overlaps(&selection_range))
 8520            {
 8521                continue;
 8522            }
 8523
 8524            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 8525
 8526            // Since not all lines in the selection may be at the same indent
 8527            // level, choose the indent size that is the most common between all
 8528            // of the lines.
 8529            //
 8530            // If there is a tie, we use the deepest indent.
 8531            let (indent_size, indent_end) = {
 8532                let mut indent_size_occurrences = HashMap::default();
 8533                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 8534
 8535                for row in start_row..=end_row {
 8536                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 8537                    rows_by_indent_size.entry(indent).or_default().push(row);
 8538                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 8539                }
 8540
 8541                let indent_size = indent_size_occurrences
 8542                    .into_iter()
 8543                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 8544                    .map(|(indent, _)| indent)
 8545                    .unwrap_or_default();
 8546                let row = rows_by_indent_size[&indent_size][0];
 8547                let indent_end = Point::new(row, indent_size.len);
 8548
 8549                (indent_size, indent_end)
 8550            };
 8551
 8552            let mut line_prefix = indent_size.chars().collect::<String>();
 8553
 8554            let mut inside_comment = false;
 8555            if let Some(comment_prefix) =
 8556                buffer
 8557                    .language_scope_at(selection.head())
 8558                    .and_then(|language| {
 8559                        language
 8560                            .line_comment_prefixes()
 8561                            .iter()
 8562                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 8563                            .cloned()
 8564                    })
 8565            {
 8566                line_prefix.push_str(&comment_prefix);
 8567                inside_comment = true;
 8568            }
 8569
 8570            let language_settings = buffer.language_settings_at(selection.head(), cx);
 8571            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 8572                RewrapBehavior::InComments => inside_comment,
 8573                RewrapBehavior::InSelections => !selection.is_empty(),
 8574                RewrapBehavior::Anywhere => true,
 8575            };
 8576
 8577            let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
 8578            if !should_rewrap {
 8579                continue;
 8580            }
 8581
 8582            if selection.is_empty() {
 8583                'expand_upwards: while start_row > 0 {
 8584                    let prev_row = start_row - 1;
 8585                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 8586                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 8587                    {
 8588                        start_row = prev_row;
 8589                    } else {
 8590                        break 'expand_upwards;
 8591                    }
 8592                }
 8593
 8594                'expand_downwards: while end_row < buffer.max_point().row {
 8595                    let next_row = end_row + 1;
 8596                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 8597                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 8598                    {
 8599                        end_row = next_row;
 8600                    } else {
 8601                        break 'expand_downwards;
 8602                    }
 8603                }
 8604            }
 8605
 8606            let start = Point::new(start_row, 0);
 8607            let start_offset = start.to_offset(&buffer);
 8608            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 8609            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 8610            let Some(lines_without_prefixes) = selection_text
 8611                .lines()
 8612                .map(|line| {
 8613                    line.strip_prefix(&line_prefix)
 8614                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 8615                        .ok_or_else(|| {
 8616                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 8617                        })
 8618                })
 8619                .collect::<Result<Vec<_>, _>>()
 8620                .log_err()
 8621            else {
 8622                continue;
 8623            };
 8624
 8625            let wrap_column = buffer
 8626                .language_settings_at(Point::new(start_row, 0), cx)
 8627                .preferred_line_length as usize;
 8628            let wrapped_text = wrap_with_prefix(
 8629                line_prefix,
 8630                lines_without_prefixes.join(" "),
 8631                wrap_column,
 8632                tab_size,
 8633            );
 8634
 8635            // TODO: should always use char-based diff while still supporting cursor behavior that
 8636            // matches vim.
 8637            let mut diff_options = DiffOptions::default();
 8638            if is_vim_mode == IsVimMode::Yes {
 8639                diff_options.max_word_diff_len = 0;
 8640                diff_options.max_word_diff_line_count = 0;
 8641            } else {
 8642                diff_options.max_word_diff_len = usize::MAX;
 8643                diff_options.max_word_diff_line_count = usize::MAX;
 8644            }
 8645
 8646            for (old_range, new_text) in
 8647                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 8648            {
 8649                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 8650                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 8651                edits.push((edit_start..edit_end, new_text));
 8652            }
 8653
 8654            rewrapped_row_ranges.push(start_row..=end_row);
 8655        }
 8656
 8657        self.buffer
 8658            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8659    }
 8660
 8661    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 8662        let mut text = String::new();
 8663        let buffer = self.buffer.read(cx).snapshot(cx);
 8664        let mut selections = self.selections.all::<Point>(cx);
 8665        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8666        {
 8667            let max_point = buffer.max_point();
 8668            let mut is_first = true;
 8669            for selection in &mut selections {
 8670                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8671                if is_entire_line {
 8672                    selection.start = Point::new(selection.start.row, 0);
 8673                    if !selection.is_empty() && selection.end.column == 0 {
 8674                        selection.end = cmp::min(max_point, selection.end);
 8675                    } else {
 8676                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 8677                    }
 8678                    selection.goal = SelectionGoal::None;
 8679                }
 8680                if is_first {
 8681                    is_first = false;
 8682                } else {
 8683                    text += "\n";
 8684                }
 8685                let mut len = 0;
 8686                for chunk in buffer.text_for_range(selection.start..selection.end) {
 8687                    text.push_str(chunk);
 8688                    len += chunk.len();
 8689                }
 8690                clipboard_selections.push(ClipboardSelection {
 8691                    len,
 8692                    is_entire_line,
 8693                    start_column: selection.start.column,
 8694                });
 8695            }
 8696        }
 8697
 8698        self.transact(window, cx, |this, window, cx| {
 8699            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8700                s.select(selections);
 8701            });
 8702            this.insert("", window, cx);
 8703        });
 8704        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 8705    }
 8706
 8707    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8708        let item = self.cut_common(window, cx);
 8709        cx.write_to_clipboard(item);
 8710    }
 8711
 8712    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8713        self.change_selections(None, window, cx, |s| {
 8714            s.move_with(|snapshot, sel| {
 8715                if sel.is_empty() {
 8716                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8717                }
 8718            });
 8719        });
 8720        let item = self.cut_common(window, cx);
 8721        cx.set_global(KillRing(item))
 8722    }
 8723
 8724    pub fn kill_ring_yank(
 8725        &mut self,
 8726        _: &KillRingYank,
 8727        window: &mut Window,
 8728        cx: &mut Context<Self>,
 8729    ) {
 8730        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8731            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8732                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8733            } else {
 8734                return;
 8735            }
 8736        } else {
 8737            return;
 8738        };
 8739        self.do_paste(&text, metadata, false, window, cx);
 8740    }
 8741
 8742    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8743        let selections = self.selections.all::<Point>(cx);
 8744        let buffer = self.buffer.read(cx).read(cx);
 8745        let mut text = String::new();
 8746
 8747        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8748        {
 8749            let max_point = buffer.max_point();
 8750            let mut is_first = true;
 8751            for selection in selections.iter() {
 8752                let mut start = selection.start;
 8753                let mut end = selection.end;
 8754                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8755                if is_entire_line {
 8756                    start = Point::new(start.row, 0);
 8757                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8758                }
 8759                if is_first {
 8760                    is_first = false;
 8761                } else {
 8762                    text += "\n";
 8763                }
 8764                let mut len = 0;
 8765                for chunk in buffer.text_for_range(start..end) {
 8766                    text.push_str(chunk);
 8767                    len += chunk.len();
 8768                }
 8769                clipboard_selections.push(ClipboardSelection {
 8770                    len,
 8771                    is_entire_line,
 8772                    start_column: start.column,
 8773                });
 8774            }
 8775        }
 8776
 8777        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8778            text,
 8779            clipboard_selections,
 8780        ));
 8781    }
 8782
 8783    pub fn do_paste(
 8784        &mut self,
 8785        text: &String,
 8786        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8787        handle_entire_lines: bool,
 8788        window: &mut Window,
 8789        cx: &mut Context<Self>,
 8790    ) {
 8791        if self.read_only(cx) {
 8792            return;
 8793        }
 8794
 8795        let clipboard_text = Cow::Borrowed(text);
 8796
 8797        self.transact(window, cx, |this, window, cx| {
 8798            if let Some(mut clipboard_selections) = clipboard_selections {
 8799                let old_selections = this.selections.all::<usize>(cx);
 8800                let all_selections_were_entire_line =
 8801                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8802                let first_selection_start_column =
 8803                    clipboard_selections.first().map(|s| s.start_column);
 8804                if clipboard_selections.len() != old_selections.len() {
 8805                    clipboard_selections.drain(..);
 8806                }
 8807                let cursor_offset = this.selections.last::<usize>(cx).head();
 8808                let mut auto_indent_on_paste = true;
 8809
 8810                this.buffer.update(cx, |buffer, cx| {
 8811                    let snapshot = buffer.read(cx);
 8812                    auto_indent_on_paste = snapshot
 8813                        .language_settings_at(cursor_offset, cx)
 8814                        .auto_indent_on_paste;
 8815
 8816                    let mut start_offset = 0;
 8817                    let mut edits = Vec::new();
 8818                    let mut original_start_columns = Vec::new();
 8819                    for (ix, selection) in old_selections.iter().enumerate() {
 8820                        let to_insert;
 8821                        let entire_line;
 8822                        let original_start_column;
 8823                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8824                            let end_offset = start_offset + clipboard_selection.len;
 8825                            to_insert = &clipboard_text[start_offset..end_offset];
 8826                            entire_line = clipboard_selection.is_entire_line;
 8827                            start_offset = end_offset + 1;
 8828                            original_start_column = Some(clipboard_selection.start_column);
 8829                        } else {
 8830                            to_insert = clipboard_text.as_str();
 8831                            entire_line = all_selections_were_entire_line;
 8832                            original_start_column = first_selection_start_column
 8833                        }
 8834
 8835                        // If the corresponding selection was empty when this slice of the
 8836                        // clipboard text was written, then the entire line containing the
 8837                        // selection was copied. If this selection is also currently empty,
 8838                        // then paste the line before the current line of the buffer.
 8839                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8840                            let column = selection.start.to_point(&snapshot).column as usize;
 8841                            let line_start = selection.start - column;
 8842                            line_start..line_start
 8843                        } else {
 8844                            selection.range()
 8845                        };
 8846
 8847                        edits.push((range, to_insert));
 8848                        original_start_columns.extend(original_start_column);
 8849                    }
 8850                    drop(snapshot);
 8851
 8852                    buffer.edit(
 8853                        edits,
 8854                        if auto_indent_on_paste {
 8855                            Some(AutoindentMode::Block {
 8856                                original_start_columns,
 8857                            })
 8858                        } else {
 8859                            None
 8860                        },
 8861                        cx,
 8862                    );
 8863                });
 8864
 8865                let selections = this.selections.all::<usize>(cx);
 8866                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8867                    s.select(selections)
 8868                });
 8869            } else {
 8870                this.insert(&clipboard_text, window, cx);
 8871            }
 8872        });
 8873    }
 8874
 8875    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8876        if let Some(item) = cx.read_from_clipboard() {
 8877            let entries = item.entries();
 8878
 8879            match entries.first() {
 8880                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8881                // of all the pasted entries.
 8882                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8883                    .do_paste(
 8884                        clipboard_string.text(),
 8885                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8886                        true,
 8887                        window,
 8888                        cx,
 8889                    ),
 8890                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8891            }
 8892        }
 8893    }
 8894
 8895    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8896        if self.read_only(cx) {
 8897            return;
 8898        }
 8899
 8900        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8901            if let Some((selections, _)) =
 8902                self.selection_history.transaction(transaction_id).cloned()
 8903            {
 8904                self.change_selections(None, window, cx, |s| {
 8905                    s.select_anchors(selections.to_vec());
 8906                });
 8907            } else {
 8908                log::error!(
 8909                    "No entry in selection_history found for undo. \
 8910                     This may correspond to a bug where undo does not update the selection. \
 8911                     If this is occurring, please add details to \
 8912                     https://github.com/zed-industries/zed/issues/22692"
 8913                );
 8914            }
 8915            self.request_autoscroll(Autoscroll::fit(), cx);
 8916            self.unmark_text(window, cx);
 8917            self.refresh_inline_completion(true, false, window, cx);
 8918            cx.emit(EditorEvent::Edited { transaction_id });
 8919            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8920        }
 8921    }
 8922
 8923    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8924        if self.read_only(cx) {
 8925            return;
 8926        }
 8927
 8928        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8929            if let Some((_, Some(selections))) =
 8930                self.selection_history.transaction(transaction_id).cloned()
 8931            {
 8932                self.change_selections(None, window, cx, |s| {
 8933                    s.select_anchors(selections.to_vec());
 8934                });
 8935            } else {
 8936                log::error!(
 8937                    "No entry in selection_history found for redo. \
 8938                     This may correspond to a bug where undo does not update the selection. \
 8939                     If this is occurring, please add details to \
 8940                     https://github.com/zed-industries/zed/issues/22692"
 8941                );
 8942            }
 8943            self.request_autoscroll(Autoscroll::fit(), cx);
 8944            self.unmark_text(window, cx);
 8945            self.refresh_inline_completion(true, false, window, cx);
 8946            cx.emit(EditorEvent::Edited { transaction_id });
 8947        }
 8948    }
 8949
 8950    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8951        self.buffer
 8952            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8953    }
 8954
 8955    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8956        self.buffer
 8957            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8958    }
 8959
 8960    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8961        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8962            let line_mode = s.line_mode;
 8963            s.move_with(|map, selection| {
 8964                let cursor = if selection.is_empty() && !line_mode {
 8965                    movement::left(map, selection.start)
 8966                } else {
 8967                    selection.start
 8968                };
 8969                selection.collapse_to(cursor, SelectionGoal::None);
 8970            });
 8971        })
 8972    }
 8973
 8974    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8975        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8976            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8977        })
 8978    }
 8979
 8980    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8981        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8982            let line_mode = s.line_mode;
 8983            s.move_with(|map, selection| {
 8984                let cursor = if selection.is_empty() && !line_mode {
 8985                    movement::right(map, selection.end)
 8986                } else {
 8987                    selection.end
 8988                };
 8989                selection.collapse_to(cursor, SelectionGoal::None)
 8990            });
 8991        })
 8992    }
 8993
 8994    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8995        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8996            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8997        })
 8998    }
 8999
 9000    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 9001        if self.take_rename(true, window, cx).is_some() {
 9002            return;
 9003        }
 9004
 9005        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9006            cx.propagate();
 9007            return;
 9008        }
 9009
 9010        let text_layout_details = &self.text_layout_details(window);
 9011        let selection_count = self.selections.count();
 9012        let first_selection = self.selections.first_anchor();
 9013
 9014        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9015            let line_mode = s.line_mode;
 9016            s.move_with(|map, selection| {
 9017                if !selection.is_empty() && !line_mode {
 9018                    selection.goal = SelectionGoal::None;
 9019                }
 9020                let (cursor, goal) = movement::up(
 9021                    map,
 9022                    selection.start,
 9023                    selection.goal,
 9024                    false,
 9025                    text_layout_details,
 9026                );
 9027                selection.collapse_to(cursor, goal);
 9028            });
 9029        });
 9030
 9031        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9032        {
 9033            cx.propagate();
 9034        }
 9035    }
 9036
 9037    pub fn move_up_by_lines(
 9038        &mut self,
 9039        action: &MoveUpByLines,
 9040        window: &mut Window,
 9041        cx: &mut Context<Self>,
 9042    ) {
 9043        if self.take_rename(true, window, cx).is_some() {
 9044            return;
 9045        }
 9046
 9047        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9048            cx.propagate();
 9049            return;
 9050        }
 9051
 9052        let text_layout_details = &self.text_layout_details(window);
 9053
 9054        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9055            let line_mode = s.line_mode;
 9056            s.move_with(|map, selection| {
 9057                if !selection.is_empty() && !line_mode {
 9058                    selection.goal = SelectionGoal::None;
 9059                }
 9060                let (cursor, goal) = movement::up_by_rows(
 9061                    map,
 9062                    selection.start,
 9063                    action.lines,
 9064                    selection.goal,
 9065                    false,
 9066                    text_layout_details,
 9067                );
 9068                selection.collapse_to(cursor, goal);
 9069            });
 9070        })
 9071    }
 9072
 9073    pub fn move_down_by_lines(
 9074        &mut self,
 9075        action: &MoveDownByLines,
 9076        window: &mut Window,
 9077        cx: &mut Context<Self>,
 9078    ) {
 9079        if self.take_rename(true, window, cx).is_some() {
 9080            return;
 9081        }
 9082
 9083        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9084            cx.propagate();
 9085            return;
 9086        }
 9087
 9088        let text_layout_details = &self.text_layout_details(window);
 9089
 9090        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9091            let line_mode = s.line_mode;
 9092            s.move_with(|map, selection| {
 9093                if !selection.is_empty() && !line_mode {
 9094                    selection.goal = SelectionGoal::None;
 9095                }
 9096                let (cursor, goal) = movement::down_by_rows(
 9097                    map,
 9098                    selection.start,
 9099                    action.lines,
 9100                    selection.goal,
 9101                    false,
 9102                    text_layout_details,
 9103                );
 9104                selection.collapse_to(cursor, goal);
 9105            });
 9106        })
 9107    }
 9108
 9109    pub fn select_down_by_lines(
 9110        &mut self,
 9111        action: &SelectDownByLines,
 9112        window: &mut Window,
 9113        cx: &mut Context<Self>,
 9114    ) {
 9115        let text_layout_details = &self.text_layout_details(window);
 9116        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9117            s.move_heads_with(|map, head, goal| {
 9118                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9119            })
 9120        })
 9121    }
 9122
 9123    pub fn select_up_by_lines(
 9124        &mut self,
 9125        action: &SelectUpByLines,
 9126        window: &mut Window,
 9127        cx: &mut Context<Self>,
 9128    ) {
 9129        let text_layout_details = &self.text_layout_details(window);
 9130        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9131            s.move_heads_with(|map, head, goal| {
 9132                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9133            })
 9134        })
 9135    }
 9136
 9137    pub fn select_page_up(
 9138        &mut self,
 9139        _: &SelectPageUp,
 9140        window: &mut Window,
 9141        cx: &mut Context<Self>,
 9142    ) {
 9143        let Some(row_count) = self.visible_row_count() else {
 9144            return;
 9145        };
 9146
 9147        let text_layout_details = &self.text_layout_details(window);
 9148
 9149        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9150            s.move_heads_with(|map, head, goal| {
 9151                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 9152            })
 9153        })
 9154    }
 9155
 9156    pub fn move_page_up(
 9157        &mut self,
 9158        action: &MovePageUp,
 9159        window: &mut Window,
 9160        cx: &mut Context<Self>,
 9161    ) {
 9162        if self.take_rename(true, window, cx).is_some() {
 9163            return;
 9164        }
 9165
 9166        if self
 9167            .context_menu
 9168            .borrow_mut()
 9169            .as_mut()
 9170            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 9171            .unwrap_or(false)
 9172        {
 9173            return;
 9174        }
 9175
 9176        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9177            cx.propagate();
 9178            return;
 9179        }
 9180
 9181        let Some(row_count) = self.visible_row_count() else {
 9182            return;
 9183        };
 9184
 9185        let autoscroll = if action.center_cursor {
 9186            Autoscroll::center()
 9187        } else {
 9188            Autoscroll::fit()
 9189        };
 9190
 9191        let text_layout_details = &self.text_layout_details(window);
 9192
 9193        self.change_selections(Some(autoscroll), window, cx, |s| {
 9194            let line_mode = s.line_mode;
 9195            s.move_with(|map, selection| {
 9196                if !selection.is_empty() && !line_mode {
 9197                    selection.goal = SelectionGoal::None;
 9198                }
 9199                let (cursor, goal) = movement::up_by_rows(
 9200                    map,
 9201                    selection.end,
 9202                    row_count,
 9203                    selection.goal,
 9204                    false,
 9205                    text_layout_details,
 9206                );
 9207                selection.collapse_to(cursor, goal);
 9208            });
 9209        });
 9210    }
 9211
 9212    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 9213        let text_layout_details = &self.text_layout_details(window);
 9214        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9215            s.move_heads_with(|map, head, goal| {
 9216                movement::up(map, head, goal, false, text_layout_details)
 9217            })
 9218        })
 9219    }
 9220
 9221    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 9222        self.take_rename(true, window, cx);
 9223
 9224        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9225            cx.propagate();
 9226            return;
 9227        }
 9228
 9229        let text_layout_details = &self.text_layout_details(window);
 9230        let selection_count = self.selections.count();
 9231        let first_selection = self.selections.first_anchor();
 9232
 9233        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9234            let line_mode = s.line_mode;
 9235            s.move_with(|map, selection| {
 9236                if !selection.is_empty() && !line_mode {
 9237                    selection.goal = SelectionGoal::None;
 9238                }
 9239                let (cursor, goal) = movement::down(
 9240                    map,
 9241                    selection.end,
 9242                    selection.goal,
 9243                    false,
 9244                    text_layout_details,
 9245                );
 9246                selection.collapse_to(cursor, goal);
 9247            });
 9248        });
 9249
 9250        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9251        {
 9252            cx.propagate();
 9253        }
 9254    }
 9255
 9256    pub fn select_page_down(
 9257        &mut self,
 9258        _: &SelectPageDown,
 9259        window: &mut Window,
 9260        cx: &mut Context<Self>,
 9261    ) {
 9262        let Some(row_count) = self.visible_row_count() else {
 9263            return;
 9264        };
 9265
 9266        let text_layout_details = &self.text_layout_details(window);
 9267
 9268        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9269            s.move_heads_with(|map, head, goal| {
 9270                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 9271            })
 9272        })
 9273    }
 9274
 9275    pub fn move_page_down(
 9276        &mut self,
 9277        action: &MovePageDown,
 9278        window: &mut Window,
 9279        cx: &mut Context<Self>,
 9280    ) {
 9281        if self.take_rename(true, window, cx).is_some() {
 9282            return;
 9283        }
 9284
 9285        if self
 9286            .context_menu
 9287            .borrow_mut()
 9288            .as_mut()
 9289            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 9290            .unwrap_or(false)
 9291        {
 9292            return;
 9293        }
 9294
 9295        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9296            cx.propagate();
 9297            return;
 9298        }
 9299
 9300        let Some(row_count) = self.visible_row_count() else {
 9301            return;
 9302        };
 9303
 9304        let autoscroll = if action.center_cursor {
 9305            Autoscroll::center()
 9306        } else {
 9307            Autoscroll::fit()
 9308        };
 9309
 9310        let text_layout_details = &self.text_layout_details(window);
 9311        self.change_selections(Some(autoscroll), window, cx, |s| {
 9312            let line_mode = s.line_mode;
 9313            s.move_with(|map, selection| {
 9314                if !selection.is_empty() && !line_mode {
 9315                    selection.goal = SelectionGoal::None;
 9316                }
 9317                let (cursor, goal) = movement::down_by_rows(
 9318                    map,
 9319                    selection.end,
 9320                    row_count,
 9321                    selection.goal,
 9322                    false,
 9323                    text_layout_details,
 9324                );
 9325                selection.collapse_to(cursor, goal);
 9326            });
 9327        });
 9328    }
 9329
 9330    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 9331        let text_layout_details = &self.text_layout_details(window);
 9332        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9333            s.move_heads_with(|map, head, goal| {
 9334                movement::down(map, head, goal, false, text_layout_details)
 9335            })
 9336        });
 9337    }
 9338
 9339    pub fn context_menu_first(
 9340        &mut self,
 9341        _: &ContextMenuFirst,
 9342        _window: &mut Window,
 9343        cx: &mut Context<Self>,
 9344    ) {
 9345        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9346            context_menu.select_first(self.completion_provider.as_deref(), cx);
 9347        }
 9348    }
 9349
 9350    pub fn context_menu_prev(
 9351        &mut self,
 9352        _: &ContextMenuPrevious,
 9353        _window: &mut Window,
 9354        cx: &mut Context<Self>,
 9355    ) {
 9356        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9357            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 9358        }
 9359    }
 9360
 9361    pub fn context_menu_next(
 9362        &mut self,
 9363        _: &ContextMenuNext,
 9364        _window: &mut Window,
 9365        cx: &mut Context<Self>,
 9366    ) {
 9367        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9368            context_menu.select_next(self.completion_provider.as_deref(), cx);
 9369        }
 9370    }
 9371
 9372    pub fn context_menu_last(
 9373        &mut self,
 9374        _: &ContextMenuLast,
 9375        _window: &mut Window,
 9376        cx: &mut Context<Self>,
 9377    ) {
 9378        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9379            context_menu.select_last(self.completion_provider.as_deref(), cx);
 9380        }
 9381    }
 9382
 9383    pub fn move_to_previous_word_start(
 9384        &mut self,
 9385        _: &MoveToPreviousWordStart,
 9386        window: &mut Window,
 9387        cx: &mut Context<Self>,
 9388    ) {
 9389        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9390            s.move_cursors_with(|map, head, _| {
 9391                (
 9392                    movement::previous_word_start(map, head),
 9393                    SelectionGoal::None,
 9394                )
 9395            });
 9396        })
 9397    }
 9398
 9399    pub fn move_to_previous_subword_start(
 9400        &mut self,
 9401        _: &MoveToPreviousSubwordStart,
 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_subword_start(map, head),
 9409                    SelectionGoal::None,
 9410                )
 9411            });
 9412        })
 9413    }
 9414
 9415    pub fn select_to_previous_word_start(
 9416        &mut self,
 9417        _: &SelectToPreviousWordStart,
 9418        window: &mut Window,
 9419        cx: &mut Context<Self>,
 9420    ) {
 9421        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9422            s.move_heads_with(|map, head, _| {
 9423                (
 9424                    movement::previous_word_start(map, head),
 9425                    SelectionGoal::None,
 9426                )
 9427            });
 9428        })
 9429    }
 9430
 9431    pub fn select_to_previous_subword_start(
 9432        &mut self,
 9433        _: &SelectToPreviousSubwordStart,
 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_subword_start(map, head),
 9441                    SelectionGoal::None,
 9442                )
 9443            });
 9444        })
 9445    }
 9446
 9447    pub fn delete_to_previous_word_start(
 9448        &mut self,
 9449        action: &DeleteToPreviousWordStart,
 9450        window: &mut Window,
 9451        cx: &mut Context<Self>,
 9452    ) {
 9453        self.transact(window, cx, |this, window, cx| {
 9454            this.select_autoclose_pair(window, cx);
 9455            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9456                let line_mode = s.line_mode;
 9457                s.move_with(|map, selection| {
 9458                    if selection.is_empty() && !line_mode {
 9459                        let cursor = if action.ignore_newlines {
 9460                            movement::previous_word_start(map, selection.head())
 9461                        } else {
 9462                            movement::previous_word_start_or_newline(map, selection.head())
 9463                        };
 9464                        selection.set_head(cursor, SelectionGoal::None);
 9465                    }
 9466                });
 9467            });
 9468            this.insert("", window, cx);
 9469        });
 9470    }
 9471
 9472    pub fn delete_to_previous_subword_start(
 9473        &mut self,
 9474        _: &DeleteToPreviousSubwordStart,
 9475        window: &mut Window,
 9476        cx: &mut Context<Self>,
 9477    ) {
 9478        self.transact(window, cx, |this, window, cx| {
 9479            this.select_autoclose_pair(window, cx);
 9480            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9481                let line_mode = s.line_mode;
 9482                s.move_with(|map, selection| {
 9483                    if selection.is_empty() && !line_mode {
 9484                        let cursor = movement::previous_subword_start(map, selection.head());
 9485                        selection.set_head(cursor, SelectionGoal::None);
 9486                    }
 9487                });
 9488            });
 9489            this.insert("", window, cx);
 9490        });
 9491    }
 9492
 9493    pub fn move_to_next_word_end(
 9494        &mut self,
 9495        _: &MoveToNextWordEnd,
 9496        window: &mut Window,
 9497        cx: &mut Context<Self>,
 9498    ) {
 9499        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9500            s.move_cursors_with(|map, head, _| {
 9501                (movement::next_word_end(map, head), SelectionGoal::None)
 9502            });
 9503        })
 9504    }
 9505
 9506    pub fn move_to_next_subword_end(
 9507        &mut self,
 9508        _: &MoveToNextSubwordEnd,
 9509        window: &mut Window,
 9510        cx: &mut Context<Self>,
 9511    ) {
 9512        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9513            s.move_cursors_with(|map, head, _| {
 9514                (movement::next_subword_end(map, head), SelectionGoal::None)
 9515            });
 9516        })
 9517    }
 9518
 9519    pub fn select_to_next_word_end(
 9520        &mut self,
 9521        _: &SelectToNextWordEnd,
 9522        window: &mut Window,
 9523        cx: &mut Context<Self>,
 9524    ) {
 9525        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9526            s.move_heads_with(|map, head, _| {
 9527                (movement::next_word_end(map, head), SelectionGoal::None)
 9528            });
 9529        })
 9530    }
 9531
 9532    pub fn select_to_next_subword_end(
 9533        &mut self,
 9534        _: &SelectToNextSubwordEnd,
 9535        window: &mut Window,
 9536        cx: &mut Context<Self>,
 9537    ) {
 9538        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9539            s.move_heads_with(|map, head, _| {
 9540                (movement::next_subword_end(map, head), SelectionGoal::None)
 9541            });
 9542        })
 9543    }
 9544
 9545    pub fn delete_to_next_word_end(
 9546        &mut self,
 9547        action: &DeleteToNextWordEnd,
 9548        window: &mut Window,
 9549        cx: &mut Context<Self>,
 9550    ) {
 9551        self.transact(window, cx, |this, window, cx| {
 9552            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9553                let line_mode = s.line_mode;
 9554                s.move_with(|map, selection| {
 9555                    if selection.is_empty() && !line_mode {
 9556                        let cursor = if action.ignore_newlines {
 9557                            movement::next_word_end(map, selection.head())
 9558                        } else {
 9559                            movement::next_word_end_or_newline(map, selection.head())
 9560                        };
 9561                        selection.set_head(cursor, SelectionGoal::None);
 9562                    }
 9563                });
 9564            });
 9565            this.insert("", window, cx);
 9566        });
 9567    }
 9568
 9569    pub fn delete_to_next_subword_end(
 9570        &mut self,
 9571        _: &DeleteToNextSubwordEnd,
 9572        window: &mut Window,
 9573        cx: &mut Context<Self>,
 9574    ) {
 9575        self.transact(window, cx, |this, window, cx| {
 9576            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9577                s.move_with(|map, selection| {
 9578                    if selection.is_empty() {
 9579                        let cursor = movement::next_subword_end(map, selection.head());
 9580                        selection.set_head(cursor, SelectionGoal::None);
 9581                    }
 9582                });
 9583            });
 9584            this.insert("", window, cx);
 9585        });
 9586    }
 9587
 9588    pub fn move_to_beginning_of_line(
 9589        &mut self,
 9590        action: &MoveToBeginningOfLine,
 9591        window: &mut Window,
 9592        cx: &mut Context<Self>,
 9593    ) {
 9594        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9595            s.move_cursors_with(|map, head, _| {
 9596                (
 9597                    movement::indented_line_beginning(
 9598                        map,
 9599                        head,
 9600                        action.stop_at_soft_wraps,
 9601                        action.stop_at_indent,
 9602                    ),
 9603                    SelectionGoal::None,
 9604                )
 9605            });
 9606        })
 9607    }
 9608
 9609    pub fn select_to_beginning_of_line(
 9610        &mut self,
 9611        action: &SelectToBeginningOfLine,
 9612        window: &mut Window,
 9613        cx: &mut Context<Self>,
 9614    ) {
 9615        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9616            s.move_heads_with(|map, head, _| {
 9617                (
 9618                    movement::indented_line_beginning(
 9619                        map,
 9620                        head,
 9621                        action.stop_at_soft_wraps,
 9622                        action.stop_at_indent,
 9623                    ),
 9624                    SelectionGoal::None,
 9625                )
 9626            });
 9627        });
 9628    }
 9629
 9630    pub fn delete_to_beginning_of_line(
 9631        &mut self,
 9632        action: &DeleteToBeginningOfLine,
 9633        window: &mut Window,
 9634        cx: &mut Context<Self>,
 9635    ) {
 9636        self.transact(window, cx, |this, window, cx| {
 9637            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9638                s.move_with(|_, selection| {
 9639                    selection.reversed = true;
 9640                });
 9641            });
 9642
 9643            this.select_to_beginning_of_line(
 9644                &SelectToBeginningOfLine {
 9645                    stop_at_soft_wraps: false,
 9646                    stop_at_indent: action.stop_at_indent,
 9647                },
 9648                window,
 9649                cx,
 9650            );
 9651            this.backspace(&Backspace, window, cx);
 9652        });
 9653    }
 9654
 9655    pub fn move_to_end_of_line(
 9656        &mut self,
 9657        action: &MoveToEndOfLine,
 9658        window: &mut Window,
 9659        cx: &mut Context<Self>,
 9660    ) {
 9661        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9662            s.move_cursors_with(|map, head, _| {
 9663                (
 9664                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9665                    SelectionGoal::None,
 9666                )
 9667            });
 9668        })
 9669    }
 9670
 9671    pub fn select_to_end_of_line(
 9672        &mut self,
 9673        action: &SelectToEndOfLine,
 9674        window: &mut Window,
 9675        cx: &mut Context<Self>,
 9676    ) {
 9677        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9678            s.move_heads_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 delete_to_end_of_line(
 9688        &mut self,
 9689        _: &DeleteToEndOfLine,
 9690        window: &mut Window,
 9691        cx: &mut Context<Self>,
 9692    ) {
 9693        self.transact(window, cx, |this, window, cx| {
 9694            this.select_to_end_of_line(
 9695                &SelectToEndOfLine {
 9696                    stop_at_soft_wraps: false,
 9697                },
 9698                window,
 9699                cx,
 9700            );
 9701            this.delete(&Delete, window, cx);
 9702        });
 9703    }
 9704
 9705    pub fn cut_to_end_of_line(
 9706        &mut self,
 9707        _: &CutToEndOfLine,
 9708        window: &mut Window,
 9709        cx: &mut Context<Self>,
 9710    ) {
 9711        self.transact(window, cx, |this, window, cx| {
 9712            this.select_to_end_of_line(
 9713                &SelectToEndOfLine {
 9714                    stop_at_soft_wraps: false,
 9715                },
 9716                window,
 9717                cx,
 9718            );
 9719            this.cut(&Cut, window, cx);
 9720        });
 9721    }
 9722
 9723    pub fn move_to_start_of_paragraph(
 9724        &mut self,
 9725        _: &MoveToStartOfParagraph,
 9726        window: &mut Window,
 9727        cx: &mut Context<Self>,
 9728    ) {
 9729        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9730            cx.propagate();
 9731            return;
 9732        }
 9733
 9734        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9735            s.move_with(|map, selection| {
 9736                selection.collapse_to(
 9737                    movement::start_of_paragraph(map, selection.head(), 1),
 9738                    SelectionGoal::None,
 9739                )
 9740            });
 9741        })
 9742    }
 9743
 9744    pub fn move_to_end_of_paragraph(
 9745        &mut self,
 9746        _: &MoveToEndOfParagraph,
 9747        window: &mut Window,
 9748        cx: &mut Context<Self>,
 9749    ) {
 9750        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9751            cx.propagate();
 9752            return;
 9753        }
 9754
 9755        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9756            s.move_with(|map, selection| {
 9757                selection.collapse_to(
 9758                    movement::end_of_paragraph(map, selection.head(), 1),
 9759                    SelectionGoal::None,
 9760                )
 9761            });
 9762        })
 9763    }
 9764
 9765    pub fn select_to_start_of_paragraph(
 9766        &mut self,
 9767        _: &SelectToStartOfParagraph,
 9768        window: &mut Window,
 9769        cx: &mut Context<Self>,
 9770    ) {
 9771        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9772            cx.propagate();
 9773            return;
 9774        }
 9775
 9776        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9777            s.move_heads_with(|map, head, _| {
 9778                (
 9779                    movement::start_of_paragraph(map, head, 1),
 9780                    SelectionGoal::None,
 9781                )
 9782            });
 9783        })
 9784    }
 9785
 9786    pub fn select_to_end_of_paragraph(
 9787        &mut self,
 9788        _: &SelectToEndOfParagraph,
 9789        window: &mut Window,
 9790        cx: &mut Context<Self>,
 9791    ) {
 9792        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9793            cx.propagate();
 9794            return;
 9795        }
 9796
 9797        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9798            s.move_heads_with(|map, head, _| {
 9799                (
 9800                    movement::end_of_paragraph(map, head, 1),
 9801                    SelectionGoal::None,
 9802                )
 9803            });
 9804        })
 9805    }
 9806
 9807    pub fn move_to_start_of_excerpt(
 9808        &mut self,
 9809        _: &MoveToStartOfExcerpt,
 9810        window: &mut Window,
 9811        cx: &mut Context<Self>,
 9812    ) {
 9813        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9814            cx.propagate();
 9815            return;
 9816        }
 9817
 9818        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9819            s.move_with(|map, selection| {
 9820                selection.collapse_to(
 9821                    movement::start_of_excerpt(
 9822                        map,
 9823                        selection.head(),
 9824                        workspace::searchable::Direction::Prev,
 9825                    ),
 9826                    SelectionGoal::None,
 9827                )
 9828            });
 9829        })
 9830    }
 9831
 9832    pub fn move_to_end_of_excerpt(
 9833        &mut self,
 9834        _: &MoveToEndOfExcerpt,
 9835        window: &mut Window,
 9836        cx: &mut Context<Self>,
 9837    ) {
 9838        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9839            cx.propagate();
 9840            return;
 9841        }
 9842
 9843        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9844            s.move_with(|map, selection| {
 9845                selection.collapse_to(
 9846                    movement::end_of_excerpt(
 9847                        map,
 9848                        selection.head(),
 9849                        workspace::searchable::Direction::Next,
 9850                    ),
 9851                    SelectionGoal::None,
 9852                )
 9853            });
 9854        })
 9855    }
 9856
 9857    pub fn select_to_start_of_excerpt(
 9858        &mut self,
 9859        _: &SelectToStartOfExcerpt,
 9860        window: &mut Window,
 9861        cx: &mut Context<Self>,
 9862    ) {
 9863        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9864            cx.propagate();
 9865            return;
 9866        }
 9867
 9868        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9869            s.move_heads_with(|map, head, _| {
 9870                (
 9871                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
 9872                    SelectionGoal::None,
 9873                )
 9874            });
 9875        })
 9876    }
 9877
 9878    pub fn select_to_end_of_excerpt(
 9879        &mut self,
 9880        _: &SelectToEndOfExcerpt,
 9881        window: &mut Window,
 9882        cx: &mut Context<Self>,
 9883    ) {
 9884        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9885            cx.propagate();
 9886            return;
 9887        }
 9888
 9889        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9890            s.move_heads_with(|map, head, _| {
 9891                (
 9892                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
 9893                    SelectionGoal::None,
 9894                )
 9895            });
 9896        })
 9897    }
 9898
 9899    pub fn move_to_beginning(
 9900        &mut self,
 9901        _: &MoveToBeginning,
 9902        window: &mut Window,
 9903        cx: &mut Context<Self>,
 9904    ) {
 9905        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9906            cx.propagate();
 9907            return;
 9908        }
 9909
 9910        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9911            s.select_ranges(vec![0..0]);
 9912        });
 9913    }
 9914
 9915    pub fn select_to_beginning(
 9916        &mut self,
 9917        _: &SelectToBeginning,
 9918        window: &mut Window,
 9919        cx: &mut Context<Self>,
 9920    ) {
 9921        let mut selection = self.selections.last::<Point>(cx);
 9922        selection.set_head(Point::zero(), SelectionGoal::None);
 9923
 9924        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9925            s.select(vec![selection]);
 9926        });
 9927    }
 9928
 9929    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9930        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9931            cx.propagate();
 9932            return;
 9933        }
 9934
 9935        let cursor = self.buffer.read(cx).read(cx).len();
 9936        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9937            s.select_ranges(vec![cursor..cursor])
 9938        });
 9939    }
 9940
 9941    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9942        self.nav_history = nav_history;
 9943    }
 9944
 9945    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9946        self.nav_history.as_ref()
 9947    }
 9948
 9949    fn push_to_nav_history(
 9950        &mut self,
 9951        cursor_anchor: Anchor,
 9952        new_position: Option<Point>,
 9953        cx: &mut Context<Self>,
 9954    ) {
 9955        if let Some(nav_history) = self.nav_history.as_mut() {
 9956            let buffer = self.buffer.read(cx).read(cx);
 9957            let cursor_position = cursor_anchor.to_point(&buffer);
 9958            let scroll_state = self.scroll_manager.anchor();
 9959            let scroll_top_row = scroll_state.top_row(&buffer);
 9960            drop(buffer);
 9961
 9962            if let Some(new_position) = new_position {
 9963                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9964                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9965                    return;
 9966                }
 9967            }
 9968
 9969            nav_history.push(
 9970                Some(NavigationData {
 9971                    cursor_anchor,
 9972                    cursor_position,
 9973                    scroll_anchor: scroll_state,
 9974                    scroll_top_row,
 9975                }),
 9976                cx,
 9977            );
 9978        }
 9979    }
 9980
 9981    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9982        let buffer = self.buffer.read(cx).snapshot(cx);
 9983        let mut selection = self.selections.first::<usize>(cx);
 9984        selection.set_head(buffer.len(), SelectionGoal::None);
 9985        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9986            s.select(vec![selection]);
 9987        });
 9988    }
 9989
 9990    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9991        let end = self.buffer.read(cx).read(cx).len();
 9992        self.change_selections(None, window, cx, |s| {
 9993            s.select_ranges(vec![0..end]);
 9994        });
 9995    }
 9996
 9997    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9998        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9999        let mut selections = self.selections.all::<Point>(cx);
10000        let max_point = display_map.buffer_snapshot.max_point();
10001        for selection in &mut selections {
10002            let rows = selection.spanned_rows(true, &display_map);
10003            selection.start = Point::new(rows.start.0, 0);
10004            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
10005            selection.reversed = false;
10006        }
10007        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10008            s.select(selections);
10009        });
10010    }
10011
10012    pub fn split_selection_into_lines(
10013        &mut self,
10014        _: &SplitSelectionIntoLines,
10015        window: &mut Window,
10016        cx: &mut Context<Self>,
10017    ) {
10018        let selections = self
10019            .selections
10020            .all::<Point>(cx)
10021            .into_iter()
10022            .map(|selection| selection.start..selection.end)
10023            .collect::<Vec<_>>();
10024        self.unfold_ranges(&selections, true, true, cx);
10025
10026        let mut new_selection_ranges = Vec::new();
10027        {
10028            let buffer = self.buffer.read(cx).read(cx);
10029            for selection in selections {
10030                for row in selection.start.row..selection.end.row {
10031                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
10032                    new_selection_ranges.push(cursor..cursor);
10033                }
10034
10035                let is_multiline_selection = selection.start.row != selection.end.row;
10036                // Don't insert last one if it's a multi-line selection ending at the start of a line,
10037                // so this action feels more ergonomic when paired with other selection operations
10038                let should_skip_last = is_multiline_selection && selection.end.column == 0;
10039                if !should_skip_last {
10040                    new_selection_ranges.push(selection.end..selection.end);
10041                }
10042            }
10043        }
10044        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10045            s.select_ranges(new_selection_ranges);
10046        });
10047    }
10048
10049    pub fn add_selection_above(
10050        &mut self,
10051        _: &AddSelectionAbove,
10052        window: &mut Window,
10053        cx: &mut Context<Self>,
10054    ) {
10055        self.add_selection(true, window, cx);
10056    }
10057
10058    pub fn add_selection_below(
10059        &mut self,
10060        _: &AddSelectionBelow,
10061        window: &mut Window,
10062        cx: &mut Context<Self>,
10063    ) {
10064        self.add_selection(false, window, cx);
10065    }
10066
10067    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
10068        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10069        let mut selections = self.selections.all::<Point>(cx);
10070        let text_layout_details = self.text_layout_details(window);
10071        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10072            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10073            let range = oldest_selection.display_range(&display_map).sorted();
10074
10075            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10076            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10077            let positions = start_x.min(end_x)..start_x.max(end_x);
10078
10079            selections.clear();
10080            let mut stack = Vec::new();
10081            for row in range.start.row().0..=range.end.row().0 {
10082                if let Some(selection) = self.selections.build_columnar_selection(
10083                    &display_map,
10084                    DisplayRow(row),
10085                    &positions,
10086                    oldest_selection.reversed,
10087                    &text_layout_details,
10088                ) {
10089                    stack.push(selection.id);
10090                    selections.push(selection);
10091                }
10092            }
10093
10094            if above {
10095                stack.reverse();
10096            }
10097
10098            AddSelectionsState { above, stack }
10099        });
10100
10101        let last_added_selection = *state.stack.last().unwrap();
10102        let mut new_selections = Vec::new();
10103        if above == state.above {
10104            let end_row = if above {
10105                DisplayRow(0)
10106            } else {
10107                display_map.max_point().row()
10108            };
10109
10110            'outer: for selection in selections {
10111                if selection.id == last_added_selection {
10112                    let range = selection.display_range(&display_map).sorted();
10113                    debug_assert_eq!(range.start.row(), range.end.row());
10114                    let mut row = range.start.row();
10115                    let positions =
10116                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10117                            px(start)..px(end)
10118                        } else {
10119                            let start_x =
10120                                display_map.x_for_display_point(range.start, &text_layout_details);
10121                            let end_x =
10122                                display_map.x_for_display_point(range.end, &text_layout_details);
10123                            start_x.min(end_x)..start_x.max(end_x)
10124                        };
10125
10126                    while row != end_row {
10127                        if above {
10128                            row.0 -= 1;
10129                        } else {
10130                            row.0 += 1;
10131                        }
10132
10133                        if let Some(new_selection) = self.selections.build_columnar_selection(
10134                            &display_map,
10135                            row,
10136                            &positions,
10137                            selection.reversed,
10138                            &text_layout_details,
10139                        ) {
10140                            state.stack.push(new_selection.id);
10141                            if above {
10142                                new_selections.push(new_selection);
10143                                new_selections.push(selection);
10144                            } else {
10145                                new_selections.push(selection);
10146                                new_selections.push(new_selection);
10147                            }
10148
10149                            continue 'outer;
10150                        }
10151                    }
10152                }
10153
10154                new_selections.push(selection);
10155            }
10156        } else {
10157            new_selections = selections;
10158            new_selections.retain(|s| s.id != last_added_selection);
10159            state.stack.pop();
10160        }
10161
10162        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10163            s.select(new_selections);
10164        });
10165        if state.stack.len() > 1 {
10166            self.add_selections_state = Some(state);
10167        }
10168    }
10169
10170    pub fn select_next_match_internal(
10171        &mut self,
10172        display_map: &DisplaySnapshot,
10173        replace_newest: bool,
10174        autoscroll: Option<Autoscroll>,
10175        window: &mut Window,
10176        cx: &mut Context<Self>,
10177    ) -> Result<()> {
10178        fn select_next_match_ranges(
10179            this: &mut Editor,
10180            range: Range<usize>,
10181            replace_newest: bool,
10182            auto_scroll: Option<Autoscroll>,
10183            window: &mut Window,
10184            cx: &mut Context<Editor>,
10185        ) {
10186            this.unfold_ranges(&[range.clone()], false, true, cx);
10187            this.change_selections(auto_scroll, window, cx, |s| {
10188                if replace_newest {
10189                    s.delete(s.newest_anchor().id);
10190                }
10191                s.insert_range(range.clone());
10192            });
10193        }
10194
10195        let buffer = &display_map.buffer_snapshot;
10196        let mut selections = self.selections.all::<usize>(cx);
10197        if let Some(mut select_next_state) = self.select_next_state.take() {
10198            let query = &select_next_state.query;
10199            if !select_next_state.done {
10200                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10201                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10202                let mut next_selected_range = None;
10203
10204                let bytes_after_last_selection =
10205                    buffer.bytes_in_range(last_selection.end..buffer.len());
10206                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10207                let query_matches = query
10208                    .stream_find_iter(bytes_after_last_selection)
10209                    .map(|result| (last_selection.end, result))
10210                    .chain(
10211                        query
10212                            .stream_find_iter(bytes_before_first_selection)
10213                            .map(|result| (0, result)),
10214                    );
10215
10216                for (start_offset, query_match) in query_matches {
10217                    let query_match = query_match.unwrap(); // can only fail due to I/O
10218                    let offset_range =
10219                        start_offset + query_match.start()..start_offset + query_match.end();
10220                    let display_range = offset_range.start.to_display_point(display_map)
10221                        ..offset_range.end.to_display_point(display_map);
10222
10223                    if !select_next_state.wordwise
10224                        || (!movement::is_inside_word(display_map, display_range.start)
10225                            && !movement::is_inside_word(display_map, display_range.end))
10226                    {
10227                        // TODO: This is n^2, because we might check all the selections
10228                        if !selections
10229                            .iter()
10230                            .any(|selection| selection.range().overlaps(&offset_range))
10231                        {
10232                            next_selected_range = Some(offset_range);
10233                            break;
10234                        }
10235                    }
10236                }
10237
10238                if let Some(next_selected_range) = next_selected_range {
10239                    select_next_match_ranges(
10240                        self,
10241                        next_selected_range,
10242                        replace_newest,
10243                        autoscroll,
10244                        window,
10245                        cx,
10246                    );
10247                } else {
10248                    select_next_state.done = true;
10249                }
10250            }
10251
10252            self.select_next_state = Some(select_next_state);
10253        } else {
10254            let mut only_carets = true;
10255            let mut same_text_selected = true;
10256            let mut selected_text = None;
10257
10258            let mut selections_iter = selections.iter().peekable();
10259            while let Some(selection) = selections_iter.next() {
10260                if selection.start != selection.end {
10261                    only_carets = false;
10262                }
10263
10264                if same_text_selected {
10265                    if selected_text.is_none() {
10266                        selected_text =
10267                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10268                    }
10269
10270                    if let Some(next_selection) = selections_iter.peek() {
10271                        if next_selection.range().len() == selection.range().len() {
10272                            let next_selected_text = buffer
10273                                .text_for_range(next_selection.range())
10274                                .collect::<String>();
10275                            if Some(next_selected_text) != selected_text {
10276                                same_text_selected = false;
10277                                selected_text = None;
10278                            }
10279                        } else {
10280                            same_text_selected = false;
10281                            selected_text = None;
10282                        }
10283                    }
10284                }
10285            }
10286
10287            if only_carets {
10288                for selection in &mut selections {
10289                    let word_range = movement::surrounding_word(
10290                        display_map,
10291                        selection.start.to_display_point(display_map),
10292                    );
10293                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
10294                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
10295                    selection.goal = SelectionGoal::None;
10296                    selection.reversed = false;
10297                    select_next_match_ranges(
10298                        self,
10299                        selection.start..selection.end,
10300                        replace_newest,
10301                        autoscroll,
10302                        window,
10303                        cx,
10304                    );
10305                }
10306
10307                if selections.len() == 1 {
10308                    let selection = selections
10309                        .last()
10310                        .expect("ensured that there's only one selection");
10311                    let query = buffer
10312                        .text_for_range(selection.start..selection.end)
10313                        .collect::<String>();
10314                    let is_empty = query.is_empty();
10315                    let select_state = SelectNextState {
10316                        query: AhoCorasick::new(&[query])?,
10317                        wordwise: true,
10318                        done: is_empty,
10319                    };
10320                    self.select_next_state = Some(select_state);
10321                } else {
10322                    self.select_next_state = None;
10323                }
10324            } else if let Some(selected_text) = selected_text {
10325                self.select_next_state = Some(SelectNextState {
10326                    query: AhoCorasick::new(&[selected_text])?,
10327                    wordwise: false,
10328                    done: false,
10329                });
10330                self.select_next_match_internal(
10331                    display_map,
10332                    replace_newest,
10333                    autoscroll,
10334                    window,
10335                    cx,
10336                )?;
10337            }
10338        }
10339        Ok(())
10340    }
10341
10342    pub fn select_all_matches(
10343        &mut self,
10344        _action: &SelectAllMatches,
10345        window: &mut Window,
10346        cx: &mut Context<Self>,
10347    ) -> Result<()> {
10348        self.push_to_selection_history();
10349        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10350
10351        self.select_next_match_internal(&display_map, false, None, window, cx)?;
10352        let Some(select_next_state) = self.select_next_state.as_mut() else {
10353            return Ok(());
10354        };
10355        if select_next_state.done {
10356            return Ok(());
10357        }
10358
10359        let mut new_selections = self.selections.all::<usize>(cx);
10360
10361        let buffer = &display_map.buffer_snapshot;
10362        let query_matches = select_next_state
10363            .query
10364            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10365
10366        for query_match in query_matches {
10367            let query_match = query_match.unwrap(); // can only fail due to I/O
10368            let offset_range = query_match.start()..query_match.end();
10369            let display_range = offset_range.start.to_display_point(&display_map)
10370                ..offset_range.end.to_display_point(&display_map);
10371
10372            if !select_next_state.wordwise
10373                || (!movement::is_inside_word(&display_map, display_range.start)
10374                    && !movement::is_inside_word(&display_map, display_range.end))
10375            {
10376                self.selections.change_with(cx, |selections| {
10377                    new_selections.push(Selection {
10378                        id: selections.new_selection_id(),
10379                        start: offset_range.start,
10380                        end: offset_range.end,
10381                        reversed: false,
10382                        goal: SelectionGoal::None,
10383                    });
10384                });
10385            }
10386        }
10387
10388        new_selections.sort_by_key(|selection| selection.start);
10389        let mut ix = 0;
10390        while ix + 1 < new_selections.len() {
10391            let current_selection = &new_selections[ix];
10392            let next_selection = &new_selections[ix + 1];
10393            if current_selection.range().overlaps(&next_selection.range()) {
10394                if current_selection.id < next_selection.id {
10395                    new_selections.remove(ix + 1);
10396                } else {
10397                    new_selections.remove(ix);
10398                }
10399            } else {
10400                ix += 1;
10401            }
10402        }
10403
10404        let reversed = self.selections.oldest::<usize>(cx).reversed;
10405
10406        for selection in new_selections.iter_mut() {
10407            selection.reversed = reversed;
10408        }
10409
10410        select_next_state.done = true;
10411        self.unfold_ranges(
10412            &new_selections
10413                .iter()
10414                .map(|selection| selection.range())
10415                .collect::<Vec<_>>(),
10416            false,
10417            false,
10418            cx,
10419        );
10420        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10421            selections.select(new_selections)
10422        });
10423
10424        Ok(())
10425    }
10426
10427    pub fn select_next(
10428        &mut self,
10429        action: &SelectNext,
10430        window: &mut Window,
10431        cx: &mut Context<Self>,
10432    ) -> Result<()> {
10433        self.push_to_selection_history();
10434        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10435        self.select_next_match_internal(
10436            &display_map,
10437            action.replace_newest,
10438            Some(Autoscroll::newest()),
10439            window,
10440            cx,
10441        )?;
10442        Ok(())
10443    }
10444
10445    pub fn select_previous(
10446        &mut self,
10447        action: &SelectPrevious,
10448        window: &mut Window,
10449        cx: &mut Context<Self>,
10450    ) -> Result<()> {
10451        self.push_to_selection_history();
10452        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10453        let buffer = &display_map.buffer_snapshot;
10454        let mut selections = self.selections.all::<usize>(cx);
10455        if let Some(mut select_prev_state) = self.select_prev_state.take() {
10456            let query = &select_prev_state.query;
10457            if !select_prev_state.done {
10458                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10459                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10460                let mut next_selected_range = None;
10461                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10462                let bytes_before_last_selection =
10463                    buffer.reversed_bytes_in_range(0..last_selection.start);
10464                let bytes_after_first_selection =
10465                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10466                let query_matches = query
10467                    .stream_find_iter(bytes_before_last_selection)
10468                    .map(|result| (last_selection.start, result))
10469                    .chain(
10470                        query
10471                            .stream_find_iter(bytes_after_first_selection)
10472                            .map(|result| (buffer.len(), result)),
10473                    );
10474                for (end_offset, query_match) in query_matches {
10475                    let query_match = query_match.unwrap(); // can only fail due to I/O
10476                    let offset_range =
10477                        end_offset - query_match.end()..end_offset - query_match.start();
10478                    let display_range = offset_range.start.to_display_point(&display_map)
10479                        ..offset_range.end.to_display_point(&display_map);
10480
10481                    if !select_prev_state.wordwise
10482                        || (!movement::is_inside_word(&display_map, display_range.start)
10483                            && !movement::is_inside_word(&display_map, display_range.end))
10484                    {
10485                        next_selected_range = Some(offset_range);
10486                        break;
10487                    }
10488                }
10489
10490                if let Some(next_selected_range) = next_selected_range {
10491                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10492                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10493                        if action.replace_newest {
10494                            s.delete(s.newest_anchor().id);
10495                        }
10496                        s.insert_range(next_selected_range);
10497                    });
10498                } else {
10499                    select_prev_state.done = true;
10500                }
10501            }
10502
10503            self.select_prev_state = Some(select_prev_state);
10504        } else {
10505            let mut only_carets = true;
10506            let mut same_text_selected = true;
10507            let mut selected_text = None;
10508
10509            let mut selections_iter = selections.iter().peekable();
10510            while let Some(selection) = selections_iter.next() {
10511                if selection.start != selection.end {
10512                    only_carets = false;
10513                }
10514
10515                if same_text_selected {
10516                    if selected_text.is_none() {
10517                        selected_text =
10518                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10519                    }
10520
10521                    if let Some(next_selection) = selections_iter.peek() {
10522                        if next_selection.range().len() == selection.range().len() {
10523                            let next_selected_text = buffer
10524                                .text_for_range(next_selection.range())
10525                                .collect::<String>();
10526                            if Some(next_selected_text) != selected_text {
10527                                same_text_selected = false;
10528                                selected_text = None;
10529                            }
10530                        } else {
10531                            same_text_selected = false;
10532                            selected_text = None;
10533                        }
10534                    }
10535                }
10536            }
10537
10538            if only_carets {
10539                for selection in &mut selections {
10540                    let word_range = movement::surrounding_word(
10541                        &display_map,
10542                        selection.start.to_display_point(&display_map),
10543                    );
10544                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10545                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10546                    selection.goal = SelectionGoal::None;
10547                    selection.reversed = false;
10548                }
10549                if selections.len() == 1 {
10550                    let selection = selections
10551                        .last()
10552                        .expect("ensured that there's only one selection");
10553                    let query = buffer
10554                        .text_for_range(selection.start..selection.end)
10555                        .collect::<String>();
10556                    let is_empty = query.is_empty();
10557                    let select_state = SelectNextState {
10558                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10559                        wordwise: true,
10560                        done: is_empty,
10561                    };
10562                    self.select_prev_state = Some(select_state);
10563                } else {
10564                    self.select_prev_state = None;
10565                }
10566
10567                self.unfold_ranges(
10568                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10569                    false,
10570                    true,
10571                    cx,
10572                );
10573                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10574                    s.select(selections);
10575                });
10576            } else if let Some(selected_text) = selected_text {
10577                self.select_prev_state = Some(SelectNextState {
10578                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10579                    wordwise: false,
10580                    done: false,
10581                });
10582                self.select_previous(action, window, cx)?;
10583            }
10584        }
10585        Ok(())
10586    }
10587
10588    pub fn toggle_comments(
10589        &mut self,
10590        action: &ToggleComments,
10591        window: &mut Window,
10592        cx: &mut Context<Self>,
10593    ) {
10594        if self.read_only(cx) {
10595            return;
10596        }
10597        let text_layout_details = &self.text_layout_details(window);
10598        self.transact(window, cx, |this, window, cx| {
10599            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10600            let mut edits = Vec::new();
10601            let mut selection_edit_ranges = Vec::new();
10602            let mut last_toggled_row = None;
10603            let snapshot = this.buffer.read(cx).read(cx);
10604            let empty_str: Arc<str> = Arc::default();
10605            let mut suffixes_inserted = Vec::new();
10606            let ignore_indent = action.ignore_indent;
10607
10608            fn comment_prefix_range(
10609                snapshot: &MultiBufferSnapshot,
10610                row: MultiBufferRow,
10611                comment_prefix: &str,
10612                comment_prefix_whitespace: &str,
10613                ignore_indent: bool,
10614            ) -> Range<Point> {
10615                let indent_size = if ignore_indent {
10616                    0
10617                } else {
10618                    snapshot.indent_size_for_line(row).len
10619                };
10620
10621                let start = Point::new(row.0, indent_size);
10622
10623                let mut line_bytes = snapshot
10624                    .bytes_in_range(start..snapshot.max_point())
10625                    .flatten()
10626                    .copied();
10627
10628                // If this line currently begins with the line comment prefix, then record
10629                // the range containing the prefix.
10630                if line_bytes
10631                    .by_ref()
10632                    .take(comment_prefix.len())
10633                    .eq(comment_prefix.bytes())
10634                {
10635                    // Include any whitespace that matches the comment prefix.
10636                    let matching_whitespace_len = line_bytes
10637                        .zip(comment_prefix_whitespace.bytes())
10638                        .take_while(|(a, b)| a == b)
10639                        .count() as u32;
10640                    let end = Point::new(
10641                        start.row,
10642                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10643                    );
10644                    start..end
10645                } else {
10646                    start..start
10647                }
10648            }
10649
10650            fn comment_suffix_range(
10651                snapshot: &MultiBufferSnapshot,
10652                row: MultiBufferRow,
10653                comment_suffix: &str,
10654                comment_suffix_has_leading_space: bool,
10655            ) -> Range<Point> {
10656                let end = Point::new(row.0, snapshot.line_len(row));
10657                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10658
10659                let mut line_end_bytes = snapshot
10660                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10661                    .flatten()
10662                    .copied();
10663
10664                let leading_space_len = if suffix_start_column > 0
10665                    && line_end_bytes.next() == Some(b' ')
10666                    && comment_suffix_has_leading_space
10667                {
10668                    1
10669                } else {
10670                    0
10671                };
10672
10673                // If this line currently begins with the line comment prefix, then record
10674                // the range containing the prefix.
10675                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10676                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
10677                    start..end
10678                } else {
10679                    end..end
10680                }
10681            }
10682
10683            // TODO: Handle selections that cross excerpts
10684            for selection in &mut selections {
10685                let start_column = snapshot
10686                    .indent_size_for_line(MultiBufferRow(selection.start.row))
10687                    .len;
10688                let language = if let Some(language) =
10689                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10690                {
10691                    language
10692                } else {
10693                    continue;
10694                };
10695
10696                selection_edit_ranges.clear();
10697
10698                // If multiple selections contain a given row, avoid processing that
10699                // row more than once.
10700                let mut start_row = MultiBufferRow(selection.start.row);
10701                if last_toggled_row == Some(start_row) {
10702                    start_row = start_row.next_row();
10703                }
10704                let end_row =
10705                    if selection.end.row > selection.start.row && selection.end.column == 0 {
10706                        MultiBufferRow(selection.end.row - 1)
10707                    } else {
10708                        MultiBufferRow(selection.end.row)
10709                    };
10710                last_toggled_row = Some(end_row);
10711
10712                if start_row > end_row {
10713                    continue;
10714                }
10715
10716                // If the language has line comments, toggle those.
10717                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10718
10719                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10720                if ignore_indent {
10721                    full_comment_prefixes = full_comment_prefixes
10722                        .into_iter()
10723                        .map(|s| Arc::from(s.trim_end()))
10724                        .collect();
10725                }
10726
10727                if !full_comment_prefixes.is_empty() {
10728                    let first_prefix = full_comment_prefixes
10729                        .first()
10730                        .expect("prefixes is non-empty");
10731                    let prefix_trimmed_lengths = full_comment_prefixes
10732                        .iter()
10733                        .map(|p| p.trim_end_matches(' ').len())
10734                        .collect::<SmallVec<[usize; 4]>>();
10735
10736                    let mut all_selection_lines_are_comments = true;
10737
10738                    for row in start_row.0..=end_row.0 {
10739                        let row = MultiBufferRow(row);
10740                        if start_row < end_row && snapshot.is_line_blank(row) {
10741                            continue;
10742                        }
10743
10744                        let prefix_range = full_comment_prefixes
10745                            .iter()
10746                            .zip(prefix_trimmed_lengths.iter().copied())
10747                            .map(|(prefix, trimmed_prefix_len)| {
10748                                comment_prefix_range(
10749                                    snapshot.deref(),
10750                                    row,
10751                                    &prefix[..trimmed_prefix_len],
10752                                    &prefix[trimmed_prefix_len..],
10753                                    ignore_indent,
10754                                )
10755                            })
10756                            .max_by_key(|range| range.end.column - range.start.column)
10757                            .expect("prefixes is non-empty");
10758
10759                        if prefix_range.is_empty() {
10760                            all_selection_lines_are_comments = false;
10761                        }
10762
10763                        selection_edit_ranges.push(prefix_range);
10764                    }
10765
10766                    if all_selection_lines_are_comments {
10767                        edits.extend(
10768                            selection_edit_ranges
10769                                .iter()
10770                                .cloned()
10771                                .map(|range| (range, empty_str.clone())),
10772                        );
10773                    } else {
10774                        let min_column = selection_edit_ranges
10775                            .iter()
10776                            .map(|range| range.start.column)
10777                            .min()
10778                            .unwrap_or(0);
10779                        edits.extend(selection_edit_ranges.iter().map(|range| {
10780                            let position = Point::new(range.start.row, min_column);
10781                            (position..position, first_prefix.clone())
10782                        }));
10783                    }
10784                } else if let Some((full_comment_prefix, comment_suffix)) =
10785                    language.block_comment_delimiters()
10786                {
10787                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10788                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10789                    let prefix_range = comment_prefix_range(
10790                        snapshot.deref(),
10791                        start_row,
10792                        comment_prefix,
10793                        comment_prefix_whitespace,
10794                        ignore_indent,
10795                    );
10796                    let suffix_range = comment_suffix_range(
10797                        snapshot.deref(),
10798                        end_row,
10799                        comment_suffix.trim_start_matches(' '),
10800                        comment_suffix.starts_with(' '),
10801                    );
10802
10803                    if prefix_range.is_empty() || suffix_range.is_empty() {
10804                        edits.push((
10805                            prefix_range.start..prefix_range.start,
10806                            full_comment_prefix.clone(),
10807                        ));
10808                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10809                        suffixes_inserted.push((end_row, comment_suffix.len()));
10810                    } else {
10811                        edits.push((prefix_range, empty_str.clone()));
10812                        edits.push((suffix_range, empty_str.clone()));
10813                    }
10814                } else {
10815                    continue;
10816                }
10817            }
10818
10819            drop(snapshot);
10820            this.buffer.update(cx, |buffer, cx| {
10821                buffer.edit(edits, None, cx);
10822            });
10823
10824            // Adjust selections so that they end before any comment suffixes that
10825            // were inserted.
10826            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10827            let mut selections = this.selections.all::<Point>(cx);
10828            let snapshot = this.buffer.read(cx).read(cx);
10829            for selection in &mut selections {
10830                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10831                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10832                        Ordering::Less => {
10833                            suffixes_inserted.next();
10834                            continue;
10835                        }
10836                        Ordering::Greater => break,
10837                        Ordering::Equal => {
10838                            if selection.end.column == snapshot.line_len(row) {
10839                                if selection.is_empty() {
10840                                    selection.start.column -= suffix_len as u32;
10841                                }
10842                                selection.end.column -= suffix_len as u32;
10843                            }
10844                            break;
10845                        }
10846                    }
10847                }
10848            }
10849
10850            drop(snapshot);
10851            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10852                s.select(selections)
10853            });
10854
10855            let selections = this.selections.all::<Point>(cx);
10856            let selections_on_single_row = selections.windows(2).all(|selections| {
10857                selections[0].start.row == selections[1].start.row
10858                    && selections[0].end.row == selections[1].end.row
10859                    && selections[0].start.row == selections[0].end.row
10860            });
10861            let selections_selecting = selections
10862                .iter()
10863                .any(|selection| selection.start != selection.end);
10864            let advance_downwards = action.advance_downwards
10865                && selections_on_single_row
10866                && !selections_selecting
10867                && !matches!(this.mode, EditorMode::SingleLine { .. });
10868
10869            if advance_downwards {
10870                let snapshot = this.buffer.read(cx).snapshot(cx);
10871
10872                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10873                    s.move_cursors_with(|display_snapshot, display_point, _| {
10874                        let mut point = display_point.to_point(display_snapshot);
10875                        point.row += 1;
10876                        point = snapshot.clip_point(point, Bias::Left);
10877                        let display_point = point.to_display_point(display_snapshot);
10878                        let goal = SelectionGoal::HorizontalPosition(
10879                            display_snapshot
10880                                .x_for_display_point(display_point, text_layout_details)
10881                                .into(),
10882                        );
10883                        (display_point, goal)
10884                    })
10885                });
10886            }
10887        });
10888    }
10889
10890    pub fn select_enclosing_symbol(
10891        &mut self,
10892        _: &SelectEnclosingSymbol,
10893        window: &mut Window,
10894        cx: &mut Context<Self>,
10895    ) {
10896        let buffer = self.buffer.read(cx).snapshot(cx);
10897        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10898
10899        fn update_selection(
10900            selection: &Selection<usize>,
10901            buffer_snap: &MultiBufferSnapshot,
10902        ) -> Option<Selection<usize>> {
10903            let cursor = selection.head();
10904            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10905            for symbol in symbols.iter().rev() {
10906                let start = symbol.range.start.to_offset(buffer_snap);
10907                let end = symbol.range.end.to_offset(buffer_snap);
10908                let new_range = start..end;
10909                if start < selection.start || end > selection.end {
10910                    return Some(Selection {
10911                        id: selection.id,
10912                        start: new_range.start,
10913                        end: new_range.end,
10914                        goal: SelectionGoal::None,
10915                        reversed: selection.reversed,
10916                    });
10917                }
10918            }
10919            None
10920        }
10921
10922        let mut selected_larger_symbol = false;
10923        let new_selections = old_selections
10924            .iter()
10925            .map(|selection| match update_selection(selection, &buffer) {
10926                Some(new_selection) => {
10927                    if new_selection.range() != selection.range() {
10928                        selected_larger_symbol = true;
10929                    }
10930                    new_selection
10931                }
10932                None => selection.clone(),
10933            })
10934            .collect::<Vec<_>>();
10935
10936        if selected_larger_symbol {
10937            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10938                s.select(new_selections);
10939            });
10940        }
10941    }
10942
10943    pub fn select_larger_syntax_node(
10944        &mut self,
10945        _: &SelectLargerSyntaxNode,
10946        window: &mut Window,
10947        cx: &mut Context<Self>,
10948    ) {
10949        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10950        let buffer = self.buffer.read(cx).snapshot(cx);
10951        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10952
10953        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10954        let mut selected_larger_node = false;
10955        let new_selections = old_selections
10956            .iter()
10957            .map(|selection| {
10958                let old_range = selection.start..selection.end;
10959                let mut new_range = old_range.clone();
10960                let mut new_node = None;
10961                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10962                {
10963                    new_node = Some(node);
10964                    new_range = match containing_range {
10965                        MultiOrSingleBufferOffsetRange::Single(_) => break,
10966                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
10967                    };
10968                    if !display_map.intersects_fold(new_range.start)
10969                        && !display_map.intersects_fold(new_range.end)
10970                    {
10971                        break;
10972                    }
10973                }
10974
10975                if let Some(node) = new_node {
10976                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10977                    // nodes. Parent and grandparent are also logged because this operation will not
10978                    // visit nodes that have the same range as their parent.
10979                    log::info!("Node: {node:?}");
10980                    let parent = node.parent();
10981                    log::info!("Parent: {parent:?}");
10982                    let grandparent = parent.and_then(|x| x.parent());
10983                    log::info!("Grandparent: {grandparent:?}");
10984                }
10985
10986                selected_larger_node |= new_range != old_range;
10987                Selection {
10988                    id: selection.id,
10989                    start: new_range.start,
10990                    end: new_range.end,
10991                    goal: SelectionGoal::None,
10992                    reversed: selection.reversed,
10993                }
10994            })
10995            .collect::<Vec<_>>();
10996
10997        if selected_larger_node {
10998            stack.push(old_selections);
10999            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11000                s.select(new_selections);
11001            });
11002        }
11003        self.select_larger_syntax_node_stack = stack;
11004    }
11005
11006    pub fn select_smaller_syntax_node(
11007        &mut self,
11008        _: &SelectSmallerSyntaxNode,
11009        window: &mut Window,
11010        cx: &mut Context<Self>,
11011    ) {
11012        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11013        if let Some(selections) = stack.pop() {
11014            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11015                s.select(selections.to_vec());
11016            });
11017        }
11018        self.select_larger_syntax_node_stack = stack;
11019    }
11020
11021    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
11022        if !EditorSettings::get_global(cx).gutter.runnables {
11023            self.clear_tasks();
11024            return Task::ready(());
11025        }
11026        let project = self.project.as_ref().map(Entity::downgrade);
11027        cx.spawn_in(window, |this, mut cx| async move {
11028            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
11029            let Some(project) = project.and_then(|p| p.upgrade()) else {
11030                return;
11031            };
11032            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
11033                this.display_map.update(cx, |map, cx| map.snapshot(cx))
11034            }) else {
11035                return;
11036            };
11037
11038            let hide_runnables = project
11039                .update(&mut cx, |project, cx| {
11040                    // Do not display any test indicators in non-dev server remote projects.
11041                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
11042                })
11043                .unwrap_or(true);
11044            if hide_runnables {
11045                return;
11046            }
11047            let new_rows =
11048                cx.background_spawn({
11049                    let snapshot = display_snapshot.clone();
11050                    async move {
11051                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
11052                    }
11053                })
11054                    .await;
11055
11056            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
11057            this.update(&mut cx, |this, _| {
11058                this.clear_tasks();
11059                for (key, value) in rows {
11060                    this.insert_tasks(key, value);
11061                }
11062            })
11063            .ok();
11064        })
11065    }
11066    fn fetch_runnable_ranges(
11067        snapshot: &DisplaySnapshot,
11068        range: Range<Anchor>,
11069    ) -> Vec<language::RunnableRange> {
11070        snapshot.buffer_snapshot.runnable_ranges(range).collect()
11071    }
11072
11073    fn runnable_rows(
11074        project: Entity<Project>,
11075        snapshot: DisplaySnapshot,
11076        runnable_ranges: Vec<RunnableRange>,
11077        mut cx: AsyncWindowContext,
11078    ) -> Vec<((BufferId, u32), RunnableTasks)> {
11079        runnable_ranges
11080            .into_iter()
11081            .filter_map(|mut runnable| {
11082                let tasks = cx
11083                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11084                    .ok()?;
11085                if tasks.is_empty() {
11086                    return None;
11087                }
11088
11089                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11090
11091                let row = snapshot
11092                    .buffer_snapshot
11093                    .buffer_line_for_row(MultiBufferRow(point.row))?
11094                    .1
11095                    .start
11096                    .row;
11097
11098                let context_range =
11099                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11100                Some((
11101                    (runnable.buffer_id, row),
11102                    RunnableTasks {
11103                        templates: tasks,
11104                        offset: snapshot
11105                            .buffer_snapshot
11106                            .anchor_before(runnable.run_range.start),
11107                        context_range,
11108                        column: point.column,
11109                        extra_variables: runnable.extra_captures,
11110                    },
11111                ))
11112            })
11113            .collect()
11114    }
11115
11116    fn templates_with_tags(
11117        project: &Entity<Project>,
11118        runnable: &mut Runnable,
11119        cx: &mut App,
11120    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11121        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11122            let (worktree_id, file) = project
11123                .buffer_for_id(runnable.buffer, cx)
11124                .and_then(|buffer| buffer.read(cx).file())
11125                .map(|file| (file.worktree_id(cx), file.clone()))
11126                .unzip();
11127
11128            (
11129                project.task_store().read(cx).task_inventory().cloned(),
11130                worktree_id,
11131                file,
11132            )
11133        });
11134
11135        let tags = mem::take(&mut runnable.tags);
11136        let mut tags: Vec<_> = tags
11137            .into_iter()
11138            .flat_map(|tag| {
11139                let tag = tag.0.clone();
11140                inventory
11141                    .as_ref()
11142                    .into_iter()
11143                    .flat_map(|inventory| {
11144                        inventory.read(cx).list_tasks(
11145                            file.clone(),
11146                            Some(runnable.language.clone()),
11147                            worktree_id,
11148                            cx,
11149                        )
11150                    })
11151                    .filter(move |(_, template)| {
11152                        template.tags.iter().any(|source_tag| source_tag == &tag)
11153                    })
11154            })
11155            .sorted_by_key(|(kind, _)| kind.to_owned())
11156            .collect();
11157        if let Some((leading_tag_source, _)) = tags.first() {
11158            // Strongest source wins; if we have worktree tag binding, prefer that to
11159            // global and language bindings;
11160            // if we have a global binding, prefer that to language binding.
11161            let first_mismatch = tags
11162                .iter()
11163                .position(|(tag_source, _)| tag_source != leading_tag_source);
11164            if let Some(index) = first_mismatch {
11165                tags.truncate(index);
11166            }
11167        }
11168
11169        tags
11170    }
11171
11172    pub fn move_to_enclosing_bracket(
11173        &mut self,
11174        _: &MoveToEnclosingBracket,
11175        window: &mut Window,
11176        cx: &mut Context<Self>,
11177    ) {
11178        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11179            s.move_offsets_with(|snapshot, selection| {
11180                let Some(enclosing_bracket_ranges) =
11181                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11182                else {
11183                    return;
11184                };
11185
11186                let mut best_length = usize::MAX;
11187                let mut best_inside = false;
11188                let mut best_in_bracket_range = false;
11189                let mut best_destination = None;
11190                for (open, close) in enclosing_bracket_ranges {
11191                    let close = close.to_inclusive();
11192                    let length = close.end() - open.start;
11193                    let inside = selection.start >= open.end && selection.end <= *close.start();
11194                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
11195                        || close.contains(&selection.head());
11196
11197                    // If best is next to a bracket and current isn't, skip
11198                    if !in_bracket_range && best_in_bracket_range {
11199                        continue;
11200                    }
11201
11202                    // Prefer smaller lengths unless best is inside and current isn't
11203                    if length > best_length && (best_inside || !inside) {
11204                        continue;
11205                    }
11206
11207                    best_length = length;
11208                    best_inside = inside;
11209                    best_in_bracket_range = in_bracket_range;
11210                    best_destination = Some(
11211                        if close.contains(&selection.start) && close.contains(&selection.end) {
11212                            if inside {
11213                                open.end
11214                            } else {
11215                                open.start
11216                            }
11217                        } else if inside {
11218                            *close.start()
11219                        } else {
11220                            *close.end()
11221                        },
11222                    );
11223                }
11224
11225                if let Some(destination) = best_destination {
11226                    selection.collapse_to(destination, SelectionGoal::None);
11227                }
11228            })
11229        });
11230    }
11231
11232    pub fn undo_selection(
11233        &mut self,
11234        _: &UndoSelection,
11235        window: &mut Window,
11236        cx: &mut Context<Self>,
11237    ) {
11238        self.end_selection(window, cx);
11239        self.selection_history.mode = SelectionHistoryMode::Undoing;
11240        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11241            self.change_selections(None, window, cx, |s| {
11242                s.select_anchors(entry.selections.to_vec())
11243            });
11244            self.select_next_state = entry.select_next_state;
11245            self.select_prev_state = entry.select_prev_state;
11246            self.add_selections_state = entry.add_selections_state;
11247            self.request_autoscroll(Autoscroll::newest(), cx);
11248        }
11249        self.selection_history.mode = SelectionHistoryMode::Normal;
11250    }
11251
11252    pub fn redo_selection(
11253        &mut self,
11254        _: &RedoSelection,
11255        window: &mut Window,
11256        cx: &mut Context<Self>,
11257    ) {
11258        self.end_selection(window, cx);
11259        self.selection_history.mode = SelectionHistoryMode::Redoing;
11260        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11261            self.change_selections(None, window, cx, |s| {
11262                s.select_anchors(entry.selections.to_vec())
11263            });
11264            self.select_next_state = entry.select_next_state;
11265            self.select_prev_state = entry.select_prev_state;
11266            self.add_selections_state = entry.add_selections_state;
11267            self.request_autoscroll(Autoscroll::newest(), cx);
11268        }
11269        self.selection_history.mode = SelectionHistoryMode::Normal;
11270    }
11271
11272    pub fn expand_excerpts(
11273        &mut self,
11274        action: &ExpandExcerpts,
11275        _: &mut Window,
11276        cx: &mut Context<Self>,
11277    ) {
11278        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11279    }
11280
11281    pub fn expand_excerpts_down(
11282        &mut self,
11283        action: &ExpandExcerptsDown,
11284        _: &mut Window,
11285        cx: &mut Context<Self>,
11286    ) {
11287        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11288    }
11289
11290    pub fn expand_excerpts_up(
11291        &mut self,
11292        action: &ExpandExcerptsUp,
11293        _: &mut Window,
11294        cx: &mut Context<Self>,
11295    ) {
11296        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11297    }
11298
11299    pub fn expand_excerpts_for_direction(
11300        &mut self,
11301        lines: u32,
11302        direction: ExpandExcerptDirection,
11303
11304        cx: &mut Context<Self>,
11305    ) {
11306        let selections = self.selections.disjoint_anchors();
11307
11308        let lines = if lines == 0 {
11309            EditorSettings::get_global(cx).expand_excerpt_lines
11310        } else {
11311            lines
11312        };
11313
11314        self.buffer.update(cx, |buffer, cx| {
11315            let snapshot = buffer.snapshot(cx);
11316            let mut excerpt_ids = selections
11317                .iter()
11318                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11319                .collect::<Vec<_>>();
11320            excerpt_ids.sort();
11321            excerpt_ids.dedup();
11322            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11323        })
11324    }
11325
11326    pub fn expand_excerpt(
11327        &mut self,
11328        excerpt: ExcerptId,
11329        direction: ExpandExcerptDirection,
11330        cx: &mut Context<Self>,
11331    ) {
11332        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11333        self.buffer.update(cx, |buffer, cx| {
11334            buffer.expand_excerpts([excerpt], lines, direction, cx)
11335        })
11336    }
11337
11338    pub fn go_to_singleton_buffer_point(
11339        &mut self,
11340        point: Point,
11341        window: &mut Window,
11342        cx: &mut Context<Self>,
11343    ) {
11344        self.go_to_singleton_buffer_range(point..point, window, cx);
11345    }
11346
11347    pub fn go_to_singleton_buffer_range(
11348        &mut self,
11349        range: Range<Point>,
11350        window: &mut Window,
11351        cx: &mut Context<Self>,
11352    ) {
11353        let multibuffer = self.buffer().read(cx);
11354        let Some(buffer) = multibuffer.as_singleton() else {
11355            return;
11356        };
11357        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11358            return;
11359        };
11360        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11361            return;
11362        };
11363        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11364            s.select_anchor_ranges([start..end])
11365        });
11366    }
11367
11368    fn go_to_diagnostic(
11369        &mut self,
11370        _: &GoToDiagnostic,
11371        window: &mut Window,
11372        cx: &mut Context<Self>,
11373    ) {
11374        self.go_to_diagnostic_impl(Direction::Next, window, cx)
11375    }
11376
11377    fn go_to_prev_diagnostic(
11378        &mut self,
11379        _: &GoToPreviousDiagnostic,
11380        window: &mut Window,
11381        cx: &mut Context<Self>,
11382    ) {
11383        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11384    }
11385
11386    pub fn go_to_diagnostic_impl(
11387        &mut self,
11388        direction: Direction,
11389        window: &mut Window,
11390        cx: &mut Context<Self>,
11391    ) {
11392        let buffer = self.buffer.read(cx).snapshot(cx);
11393        let selection = self.selections.newest::<usize>(cx);
11394
11395        // If there is an active Diagnostic Popover jump to its diagnostic instead.
11396        if direction == Direction::Next {
11397            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11398                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11399                    return;
11400                };
11401                self.activate_diagnostics(
11402                    buffer_id,
11403                    popover.local_diagnostic.diagnostic.group_id,
11404                    window,
11405                    cx,
11406                );
11407                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11408                    let primary_range_start = active_diagnostics.primary_range.start;
11409                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11410                        let mut new_selection = s.newest_anchor().clone();
11411                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11412                        s.select_anchors(vec![new_selection.clone()]);
11413                    });
11414                    self.refresh_inline_completion(false, true, window, cx);
11415                }
11416                return;
11417            }
11418        }
11419
11420        let active_group_id = self
11421            .active_diagnostics
11422            .as_ref()
11423            .map(|active_group| active_group.group_id);
11424        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11425            active_diagnostics
11426                .primary_range
11427                .to_offset(&buffer)
11428                .to_inclusive()
11429        });
11430        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11431            if active_primary_range.contains(&selection.head()) {
11432                *active_primary_range.start()
11433            } else {
11434                selection.head()
11435            }
11436        } else {
11437            selection.head()
11438        };
11439
11440        let snapshot = self.snapshot(window, cx);
11441        let primary_diagnostics_before = buffer
11442            .diagnostics_in_range::<usize>(0..search_start)
11443            .filter(|entry| entry.diagnostic.is_primary)
11444            .filter(|entry| entry.range.start != entry.range.end)
11445            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11446            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11447            .collect::<Vec<_>>();
11448        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11449            primary_diagnostics_before
11450                .iter()
11451                .position(|entry| entry.diagnostic.group_id == active_group_id)
11452        });
11453
11454        let primary_diagnostics_after = buffer
11455            .diagnostics_in_range::<usize>(search_start..buffer.len())
11456            .filter(|entry| entry.diagnostic.is_primary)
11457            .filter(|entry| entry.range.start != entry.range.end)
11458            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11459            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11460            .collect::<Vec<_>>();
11461        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11462            primary_diagnostics_after
11463                .iter()
11464                .enumerate()
11465                .rev()
11466                .find_map(|(i, entry)| {
11467                    if entry.diagnostic.group_id == active_group_id {
11468                        Some(i)
11469                    } else {
11470                        None
11471                    }
11472                })
11473        });
11474
11475        let next_primary_diagnostic = match direction {
11476            Direction::Prev => primary_diagnostics_before
11477                .iter()
11478                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11479                .rev()
11480                .next(),
11481            Direction::Next => primary_diagnostics_after
11482                .iter()
11483                .skip(
11484                    last_same_group_diagnostic_after
11485                        .map(|index| index + 1)
11486                        .unwrap_or(0),
11487                )
11488                .next(),
11489        };
11490
11491        // Cycle around to the start of the buffer, potentially moving back to the start of
11492        // the currently active diagnostic.
11493        let cycle_around = || match direction {
11494            Direction::Prev => primary_diagnostics_after
11495                .iter()
11496                .rev()
11497                .chain(primary_diagnostics_before.iter().rev())
11498                .next(),
11499            Direction::Next => primary_diagnostics_before
11500                .iter()
11501                .chain(primary_diagnostics_after.iter())
11502                .next(),
11503        };
11504
11505        if let Some((primary_range, group_id)) = next_primary_diagnostic
11506            .or_else(cycle_around)
11507            .map(|entry| (&entry.range, entry.diagnostic.group_id))
11508        {
11509            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11510                return;
11511            };
11512            self.activate_diagnostics(buffer_id, group_id, window, cx);
11513            if self.active_diagnostics.is_some() {
11514                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11515                    s.select(vec![Selection {
11516                        id: selection.id,
11517                        start: primary_range.start,
11518                        end: primary_range.start,
11519                        reversed: false,
11520                        goal: SelectionGoal::None,
11521                    }]);
11522                });
11523                self.refresh_inline_completion(false, true, window, cx);
11524            }
11525        }
11526    }
11527
11528    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11529        let snapshot = self.snapshot(window, cx);
11530        let selection = self.selections.newest::<Point>(cx);
11531        self.go_to_hunk_after_or_before_position(
11532            &snapshot,
11533            selection.head(),
11534            Direction::Next,
11535            window,
11536            cx,
11537        );
11538    }
11539
11540    fn go_to_hunk_after_or_before_position(
11541        &mut self,
11542        snapshot: &EditorSnapshot,
11543        position: Point,
11544        direction: Direction,
11545        window: &mut Window,
11546        cx: &mut Context<Editor>,
11547    ) -> Option<MultiBufferDiffHunk> {
11548        let hunk = if direction == Direction::Next {
11549            self.hunk_after_position(snapshot, position)
11550        } else {
11551            self.hunk_before_position(snapshot, position)
11552        };
11553
11554        if let Some(hunk) = &hunk {
11555            let destination = Point::new(hunk.row_range.start.0, 0);
11556            let autoscroll = Autoscroll::center();
11557
11558            self.unfold_ranges(&[destination..destination], false, false, cx);
11559            self.change_selections(Some(autoscroll), window, cx, |s| {
11560                s.select_ranges([destination..destination]);
11561            });
11562        }
11563
11564        hunk
11565    }
11566
11567    fn hunk_after_position(
11568        &mut self,
11569        snapshot: &EditorSnapshot,
11570        position: Point,
11571    ) -> Option<MultiBufferDiffHunk> {
11572        snapshot
11573            .buffer_snapshot
11574            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11575            .find(|hunk| hunk.row_range.start.0 > position.row)
11576            .or_else(|| {
11577                snapshot
11578                    .buffer_snapshot
11579                    .diff_hunks_in_range(Point::zero()..position)
11580                    .find(|hunk| hunk.row_range.end.0 < position.row)
11581            })
11582    }
11583
11584    fn go_to_prev_hunk(
11585        &mut self,
11586        _: &GoToPreviousHunk,
11587        window: &mut Window,
11588        cx: &mut Context<Self>,
11589    ) {
11590        let snapshot = self.snapshot(window, cx);
11591        let selection = self.selections.newest::<Point>(cx);
11592        self.go_to_hunk_after_or_before_position(
11593            &snapshot,
11594            selection.head(),
11595            Direction::Prev,
11596            window,
11597            cx,
11598        );
11599    }
11600
11601    fn hunk_before_position(
11602        &mut self,
11603        snapshot: &EditorSnapshot,
11604        position: Point,
11605    ) -> Option<MultiBufferDiffHunk> {
11606        snapshot
11607            .buffer_snapshot
11608            .diff_hunk_before(position)
11609            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11610    }
11611
11612    pub fn go_to_definition(
11613        &mut self,
11614        _: &GoToDefinition,
11615        window: &mut Window,
11616        cx: &mut Context<Self>,
11617    ) -> Task<Result<Navigated>> {
11618        let definition =
11619            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11620        cx.spawn_in(window, |editor, mut cx| async move {
11621            if definition.await? == Navigated::Yes {
11622                return Ok(Navigated::Yes);
11623            }
11624            match editor.update_in(&mut cx, |editor, window, cx| {
11625                editor.find_all_references(&FindAllReferences, window, cx)
11626            })? {
11627                Some(references) => references.await,
11628                None => Ok(Navigated::No),
11629            }
11630        })
11631    }
11632
11633    pub fn go_to_declaration(
11634        &mut self,
11635        _: &GoToDeclaration,
11636        window: &mut Window,
11637        cx: &mut Context<Self>,
11638    ) -> Task<Result<Navigated>> {
11639        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11640    }
11641
11642    pub fn go_to_declaration_split(
11643        &mut self,
11644        _: &GoToDeclaration,
11645        window: &mut Window,
11646        cx: &mut Context<Self>,
11647    ) -> Task<Result<Navigated>> {
11648        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11649    }
11650
11651    pub fn go_to_implementation(
11652        &mut self,
11653        _: &GoToImplementation,
11654        window: &mut Window,
11655        cx: &mut Context<Self>,
11656    ) -> Task<Result<Navigated>> {
11657        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11658    }
11659
11660    pub fn go_to_implementation_split(
11661        &mut self,
11662        _: &GoToImplementationSplit,
11663        window: &mut Window,
11664        cx: &mut Context<Self>,
11665    ) -> Task<Result<Navigated>> {
11666        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11667    }
11668
11669    pub fn go_to_type_definition(
11670        &mut self,
11671        _: &GoToTypeDefinition,
11672        window: &mut Window,
11673        cx: &mut Context<Self>,
11674    ) -> Task<Result<Navigated>> {
11675        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11676    }
11677
11678    pub fn go_to_definition_split(
11679        &mut self,
11680        _: &GoToDefinitionSplit,
11681        window: &mut Window,
11682        cx: &mut Context<Self>,
11683    ) -> Task<Result<Navigated>> {
11684        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11685    }
11686
11687    pub fn go_to_type_definition_split(
11688        &mut self,
11689        _: &GoToTypeDefinitionSplit,
11690        window: &mut Window,
11691        cx: &mut Context<Self>,
11692    ) -> Task<Result<Navigated>> {
11693        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11694    }
11695
11696    fn go_to_definition_of_kind(
11697        &mut self,
11698        kind: GotoDefinitionKind,
11699        split: bool,
11700        window: &mut Window,
11701        cx: &mut Context<Self>,
11702    ) -> Task<Result<Navigated>> {
11703        let Some(provider) = self.semantics_provider.clone() else {
11704            return Task::ready(Ok(Navigated::No));
11705        };
11706        let head = self.selections.newest::<usize>(cx).head();
11707        let buffer = self.buffer.read(cx);
11708        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11709            text_anchor
11710        } else {
11711            return Task::ready(Ok(Navigated::No));
11712        };
11713
11714        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11715            return Task::ready(Ok(Navigated::No));
11716        };
11717
11718        cx.spawn_in(window, |editor, mut cx| async move {
11719            let definitions = definitions.await?;
11720            let navigated = editor
11721                .update_in(&mut cx, |editor, window, cx| {
11722                    editor.navigate_to_hover_links(
11723                        Some(kind),
11724                        definitions
11725                            .into_iter()
11726                            .filter(|location| {
11727                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11728                            })
11729                            .map(HoverLink::Text)
11730                            .collect::<Vec<_>>(),
11731                        split,
11732                        window,
11733                        cx,
11734                    )
11735                })?
11736                .await?;
11737            anyhow::Ok(navigated)
11738        })
11739    }
11740
11741    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11742        let selection = self.selections.newest_anchor();
11743        let head = selection.head();
11744        let tail = selection.tail();
11745
11746        let Some((buffer, start_position)) =
11747            self.buffer.read(cx).text_anchor_for_position(head, cx)
11748        else {
11749            return;
11750        };
11751
11752        let end_position = if head != tail {
11753            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11754                return;
11755            };
11756            Some(pos)
11757        } else {
11758            None
11759        };
11760
11761        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11762            let url = if let Some(end_pos) = end_position {
11763                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11764            } else {
11765                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11766            };
11767
11768            if let Some(url) = url {
11769                editor.update(&mut cx, |_, cx| {
11770                    cx.open_url(&url);
11771                })
11772            } else {
11773                Ok(())
11774            }
11775        });
11776
11777        url_finder.detach();
11778    }
11779
11780    pub fn open_selected_filename(
11781        &mut self,
11782        _: &OpenSelectedFilename,
11783        window: &mut Window,
11784        cx: &mut Context<Self>,
11785    ) {
11786        let Some(workspace) = self.workspace() else {
11787            return;
11788        };
11789
11790        let position = self.selections.newest_anchor().head();
11791
11792        let Some((buffer, buffer_position)) =
11793            self.buffer.read(cx).text_anchor_for_position(position, cx)
11794        else {
11795            return;
11796        };
11797
11798        let project = self.project.clone();
11799
11800        cx.spawn_in(window, |_, mut cx| async move {
11801            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11802
11803            if let Some((_, path)) = result {
11804                workspace
11805                    .update_in(&mut cx, |workspace, window, cx| {
11806                        workspace.open_resolved_path(path, window, cx)
11807                    })?
11808                    .await?;
11809            }
11810            anyhow::Ok(())
11811        })
11812        .detach();
11813    }
11814
11815    pub(crate) fn navigate_to_hover_links(
11816        &mut self,
11817        kind: Option<GotoDefinitionKind>,
11818        mut definitions: Vec<HoverLink>,
11819        split: bool,
11820        window: &mut Window,
11821        cx: &mut Context<Editor>,
11822    ) -> Task<Result<Navigated>> {
11823        // If there is one definition, just open it directly
11824        if definitions.len() == 1 {
11825            let definition = definitions.pop().unwrap();
11826
11827            enum TargetTaskResult {
11828                Location(Option<Location>),
11829                AlreadyNavigated,
11830            }
11831
11832            let target_task = match definition {
11833                HoverLink::Text(link) => {
11834                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11835                }
11836                HoverLink::InlayHint(lsp_location, server_id) => {
11837                    let computation =
11838                        self.compute_target_location(lsp_location, server_id, window, cx);
11839                    cx.background_spawn(async move {
11840                        let location = computation.await?;
11841                        Ok(TargetTaskResult::Location(location))
11842                    })
11843                }
11844                HoverLink::Url(url) => {
11845                    cx.open_url(&url);
11846                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11847                }
11848                HoverLink::File(path) => {
11849                    if let Some(workspace) = self.workspace() {
11850                        cx.spawn_in(window, |_, mut cx| async move {
11851                            workspace
11852                                .update_in(&mut cx, |workspace, window, cx| {
11853                                    workspace.open_resolved_path(path, window, cx)
11854                                })?
11855                                .await
11856                                .map(|_| TargetTaskResult::AlreadyNavigated)
11857                        })
11858                    } else {
11859                        Task::ready(Ok(TargetTaskResult::Location(None)))
11860                    }
11861                }
11862            };
11863            cx.spawn_in(window, |editor, mut cx| async move {
11864                let target = match target_task.await.context("target resolution task")? {
11865                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11866                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11867                    TargetTaskResult::Location(Some(target)) => target,
11868                };
11869
11870                editor.update_in(&mut cx, |editor, window, cx| {
11871                    let Some(workspace) = editor.workspace() else {
11872                        return Navigated::No;
11873                    };
11874                    let pane = workspace.read(cx).active_pane().clone();
11875
11876                    let range = target.range.to_point(target.buffer.read(cx));
11877                    let range = editor.range_for_match(&range);
11878                    let range = collapse_multiline_range(range);
11879
11880                    if !split
11881                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11882                    {
11883                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11884                    } else {
11885                        window.defer(cx, move |window, cx| {
11886                            let target_editor: Entity<Self> =
11887                                workspace.update(cx, |workspace, cx| {
11888                                    let pane = if split {
11889                                        workspace.adjacent_pane(window, cx)
11890                                    } else {
11891                                        workspace.active_pane().clone()
11892                                    };
11893
11894                                    workspace.open_project_item(
11895                                        pane,
11896                                        target.buffer.clone(),
11897                                        true,
11898                                        true,
11899                                        window,
11900                                        cx,
11901                                    )
11902                                });
11903                            target_editor.update(cx, |target_editor, cx| {
11904                                // When selecting a definition in a different buffer, disable the nav history
11905                                // to avoid creating a history entry at the previous cursor location.
11906                                pane.update(cx, |pane, _| pane.disable_history());
11907                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11908                                pane.update(cx, |pane, _| pane.enable_history());
11909                            });
11910                        });
11911                    }
11912                    Navigated::Yes
11913                })
11914            })
11915        } else if !definitions.is_empty() {
11916            cx.spawn_in(window, |editor, mut cx| async move {
11917                let (title, location_tasks, workspace) = editor
11918                    .update_in(&mut cx, |editor, window, cx| {
11919                        let tab_kind = match kind {
11920                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11921                            _ => "Definitions",
11922                        };
11923                        let title = definitions
11924                            .iter()
11925                            .find_map(|definition| match definition {
11926                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11927                                    let buffer = origin.buffer.read(cx);
11928                                    format!(
11929                                        "{} for {}",
11930                                        tab_kind,
11931                                        buffer
11932                                            .text_for_range(origin.range.clone())
11933                                            .collect::<String>()
11934                                    )
11935                                }),
11936                                HoverLink::InlayHint(_, _) => None,
11937                                HoverLink::Url(_) => None,
11938                                HoverLink::File(_) => None,
11939                            })
11940                            .unwrap_or(tab_kind.to_string());
11941                        let location_tasks = definitions
11942                            .into_iter()
11943                            .map(|definition| match definition {
11944                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11945                                HoverLink::InlayHint(lsp_location, server_id) => editor
11946                                    .compute_target_location(lsp_location, server_id, window, cx),
11947                                HoverLink::Url(_) => Task::ready(Ok(None)),
11948                                HoverLink::File(_) => Task::ready(Ok(None)),
11949                            })
11950                            .collect::<Vec<_>>();
11951                        (title, location_tasks, editor.workspace().clone())
11952                    })
11953                    .context("location tasks preparation")?;
11954
11955                let locations = future::join_all(location_tasks)
11956                    .await
11957                    .into_iter()
11958                    .filter_map(|location| location.transpose())
11959                    .collect::<Result<_>>()
11960                    .context("location tasks")?;
11961
11962                let Some(workspace) = workspace else {
11963                    return Ok(Navigated::No);
11964                };
11965                let opened = workspace
11966                    .update_in(&mut cx, |workspace, window, cx| {
11967                        Self::open_locations_in_multibuffer(
11968                            workspace,
11969                            locations,
11970                            title,
11971                            split,
11972                            MultibufferSelectionMode::First,
11973                            window,
11974                            cx,
11975                        )
11976                    })
11977                    .ok();
11978
11979                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11980            })
11981        } else {
11982            Task::ready(Ok(Navigated::No))
11983        }
11984    }
11985
11986    fn compute_target_location(
11987        &self,
11988        lsp_location: lsp::Location,
11989        server_id: LanguageServerId,
11990        window: &mut Window,
11991        cx: &mut Context<Self>,
11992    ) -> Task<anyhow::Result<Option<Location>>> {
11993        let Some(project) = self.project.clone() else {
11994            return Task::ready(Ok(None));
11995        };
11996
11997        cx.spawn_in(window, move |editor, mut cx| async move {
11998            let location_task = editor.update(&mut cx, |_, cx| {
11999                project.update(cx, |project, cx| {
12000                    let language_server_name = project
12001                        .language_server_statuses(cx)
12002                        .find(|(id, _)| server_id == *id)
12003                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
12004                    language_server_name.map(|language_server_name| {
12005                        project.open_local_buffer_via_lsp(
12006                            lsp_location.uri.clone(),
12007                            server_id,
12008                            language_server_name,
12009                            cx,
12010                        )
12011                    })
12012                })
12013            })?;
12014            let location = match location_task {
12015                Some(task) => Some({
12016                    let target_buffer_handle = task.await.context("open local buffer")?;
12017                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
12018                        let target_start = target_buffer
12019                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
12020                        let target_end = target_buffer
12021                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
12022                        target_buffer.anchor_after(target_start)
12023                            ..target_buffer.anchor_before(target_end)
12024                    })?;
12025                    Location {
12026                        buffer: target_buffer_handle,
12027                        range,
12028                    }
12029                }),
12030                None => None,
12031            };
12032            Ok(location)
12033        })
12034    }
12035
12036    pub fn find_all_references(
12037        &mut self,
12038        _: &FindAllReferences,
12039        window: &mut Window,
12040        cx: &mut Context<Self>,
12041    ) -> Option<Task<Result<Navigated>>> {
12042        let selection = self.selections.newest::<usize>(cx);
12043        let multi_buffer = self.buffer.read(cx);
12044        let head = selection.head();
12045
12046        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12047        let head_anchor = multi_buffer_snapshot.anchor_at(
12048            head,
12049            if head < selection.tail() {
12050                Bias::Right
12051            } else {
12052                Bias::Left
12053            },
12054        );
12055
12056        match self
12057            .find_all_references_task_sources
12058            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12059        {
12060            Ok(_) => {
12061                log::info!(
12062                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
12063                );
12064                return None;
12065            }
12066            Err(i) => {
12067                self.find_all_references_task_sources.insert(i, head_anchor);
12068            }
12069        }
12070
12071        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12072        let workspace = self.workspace()?;
12073        let project = workspace.read(cx).project().clone();
12074        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12075        Some(cx.spawn_in(window, |editor, mut cx| async move {
12076            let _cleanup = defer({
12077                let mut cx = cx.clone();
12078                move || {
12079                    let _ = editor.update(&mut cx, |editor, _| {
12080                        if let Ok(i) =
12081                            editor
12082                                .find_all_references_task_sources
12083                                .binary_search_by(|anchor| {
12084                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
12085                                })
12086                        {
12087                            editor.find_all_references_task_sources.remove(i);
12088                        }
12089                    });
12090                }
12091            });
12092
12093            let locations = references.await?;
12094            if locations.is_empty() {
12095                return anyhow::Ok(Navigated::No);
12096            }
12097
12098            workspace.update_in(&mut cx, |workspace, window, cx| {
12099                let title = locations
12100                    .first()
12101                    .as_ref()
12102                    .map(|location| {
12103                        let buffer = location.buffer.read(cx);
12104                        format!(
12105                            "References to `{}`",
12106                            buffer
12107                                .text_for_range(location.range.clone())
12108                                .collect::<String>()
12109                        )
12110                    })
12111                    .unwrap();
12112                Self::open_locations_in_multibuffer(
12113                    workspace,
12114                    locations,
12115                    title,
12116                    false,
12117                    MultibufferSelectionMode::First,
12118                    window,
12119                    cx,
12120                );
12121                Navigated::Yes
12122            })
12123        }))
12124    }
12125
12126    /// Opens a multibuffer with the given project locations in it
12127    pub fn open_locations_in_multibuffer(
12128        workspace: &mut Workspace,
12129        mut locations: Vec<Location>,
12130        title: String,
12131        split: bool,
12132        multibuffer_selection_mode: MultibufferSelectionMode,
12133        window: &mut Window,
12134        cx: &mut Context<Workspace>,
12135    ) {
12136        // If there are multiple definitions, open them in a multibuffer
12137        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12138        let mut locations = locations.into_iter().peekable();
12139        let mut ranges = Vec::new();
12140        let capability = workspace.project().read(cx).capability();
12141
12142        let excerpt_buffer = cx.new(|cx| {
12143            let mut multibuffer = MultiBuffer::new(capability);
12144            while let Some(location) = locations.next() {
12145                let buffer = location.buffer.read(cx);
12146                let mut ranges_for_buffer = Vec::new();
12147                let range = location.range.to_offset(buffer);
12148                ranges_for_buffer.push(range.clone());
12149
12150                while let Some(next_location) = locations.peek() {
12151                    if next_location.buffer == location.buffer {
12152                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
12153                        locations.next();
12154                    } else {
12155                        break;
12156                    }
12157                }
12158
12159                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12160                ranges.extend(multibuffer.push_excerpts_with_context_lines(
12161                    location.buffer.clone(),
12162                    ranges_for_buffer,
12163                    DEFAULT_MULTIBUFFER_CONTEXT,
12164                    cx,
12165                ))
12166            }
12167
12168            multibuffer.with_title(title)
12169        });
12170
12171        let editor = cx.new(|cx| {
12172            Editor::for_multibuffer(
12173                excerpt_buffer,
12174                Some(workspace.project().clone()),
12175                true,
12176                window,
12177                cx,
12178            )
12179        });
12180        editor.update(cx, |editor, cx| {
12181            match multibuffer_selection_mode {
12182                MultibufferSelectionMode::First => {
12183                    if let Some(first_range) = ranges.first() {
12184                        editor.change_selections(None, window, cx, |selections| {
12185                            selections.clear_disjoint();
12186                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12187                        });
12188                    }
12189                    editor.highlight_background::<Self>(
12190                        &ranges,
12191                        |theme| theme.editor_highlighted_line_background,
12192                        cx,
12193                    );
12194                }
12195                MultibufferSelectionMode::All => {
12196                    editor.change_selections(None, window, cx, |selections| {
12197                        selections.clear_disjoint();
12198                        selections.select_anchor_ranges(ranges);
12199                    });
12200                }
12201            }
12202            editor.register_buffers_with_language_servers(cx);
12203        });
12204
12205        let item = Box::new(editor);
12206        let item_id = item.item_id();
12207
12208        if split {
12209            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12210        } else {
12211            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12212                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12213                    pane.close_current_preview_item(window, cx)
12214                } else {
12215                    None
12216                }
12217            });
12218            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12219        }
12220        workspace.active_pane().update(cx, |pane, cx| {
12221            pane.set_preview_item_id(Some(item_id), cx);
12222        });
12223    }
12224
12225    pub fn rename(
12226        &mut self,
12227        _: &Rename,
12228        window: &mut Window,
12229        cx: &mut Context<Self>,
12230    ) -> Option<Task<Result<()>>> {
12231        use language::ToOffset as _;
12232
12233        let provider = self.semantics_provider.clone()?;
12234        let selection = self.selections.newest_anchor().clone();
12235        let (cursor_buffer, cursor_buffer_position) = self
12236            .buffer
12237            .read(cx)
12238            .text_anchor_for_position(selection.head(), cx)?;
12239        let (tail_buffer, cursor_buffer_position_end) = self
12240            .buffer
12241            .read(cx)
12242            .text_anchor_for_position(selection.tail(), cx)?;
12243        if tail_buffer != cursor_buffer {
12244            return None;
12245        }
12246
12247        let snapshot = cursor_buffer.read(cx).snapshot();
12248        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12249        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12250        let prepare_rename = provider
12251            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12252            .unwrap_or_else(|| Task::ready(Ok(None)));
12253        drop(snapshot);
12254
12255        Some(cx.spawn_in(window, |this, mut cx| async move {
12256            let rename_range = if let Some(range) = prepare_rename.await? {
12257                Some(range)
12258            } else {
12259                this.update(&mut cx, |this, cx| {
12260                    let buffer = this.buffer.read(cx).snapshot(cx);
12261                    let mut buffer_highlights = this
12262                        .document_highlights_for_position(selection.head(), &buffer)
12263                        .filter(|highlight| {
12264                            highlight.start.excerpt_id == selection.head().excerpt_id
12265                                && highlight.end.excerpt_id == selection.head().excerpt_id
12266                        });
12267                    buffer_highlights
12268                        .next()
12269                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12270                })?
12271            };
12272            if let Some(rename_range) = rename_range {
12273                this.update_in(&mut cx, |this, window, cx| {
12274                    let snapshot = cursor_buffer.read(cx).snapshot();
12275                    let rename_buffer_range = rename_range.to_offset(&snapshot);
12276                    let cursor_offset_in_rename_range =
12277                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12278                    let cursor_offset_in_rename_range_end =
12279                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12280
12281                    this.take_rename(false, window, cx);
12282                    let buffer = this.buffer.read(cx).read(cx);
12283                    let cursor_offset = selection.head().to_offset(&buffer);
12284                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12285                    let rename_end = rename_start + rename_buffer_range.len();
12286                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12287                    let mut old_highlight_id = None;
12288                    let old_name: Arc<str> = buffer
12289                        .chunks(rename_start..rename_end, true)
12290                        .map(|chunk| {
12291                            if old_highlight_id.is_none() {
12292                                old_highlight_id = chunk.syntax_highlight_id;
12293                            }
12294                            chunk.text
12295                        })
12296                        .collect::<String>()
12297                        .into();
12298
12299                    drop(buffer);
12300
12301                    // Position the selection in the rename editor so that it matches the current selection.
12302                    this.show_local_selections = false;
12303                    let rename_editor = cx.new(|cx| {
12304                        let mut editor = Editor::single_line(window, cx);
12305                        editor.buffer.update(cx, |buffer, cx| {
12306                            buffer.edit([(0..0, old_name.clone())], None, cx)
12307                        });
12308                        let rename_selection_range = match cursor_offset_in_rename_range
12309                            .cmp(&cursor_offset_in_rename_range_end)
12310                        {
12311                            Ordering::Equal => {
12312                                editor.select_all(&SelectAll, window, cx);
12313                                return editor;
12314                            }
12315                            Ordering::Less => {
12316                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12317                            }
12318                            Ordering::Greater => {
12319                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12320                            }
12321                        };
12322                        if rename_selection_range.end > old_name.len() {
12323                            editor.select_all(&SelectAll, window, cx);
12324                        } else {
12325                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12326                                s.select_ranges([rename_selection_range]);
12327                            });
12328                        }
12329                        editor
12330                    });
12331                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12332                        if e == &EditorEvent::Focused {
12333                            cx.emit(EditorEvent::FocusedIn)
12334                        }
12335                    })
12336                    .detach();
12337
12338                    let write_highlights =
12339                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12340                    let read_highlights =
12341                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
12342                    let ranges = write_highlights
12343                        .iter()
12344                        .flat_map(|(_, ranges)| ranges.iter())
12345                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12346                        .cloned()
12347                        .collect();
12348
12349                    this.highlight_text::<Rename>(
12350                        ranges,
12351                        HighlightStyle {
12352                            fade_out: Some(0.6),
12353                            ..Default::default()
12354                        },
12355                        cx,
12356                    );
12357                    let rename_focus_handle = rename_editor.focus_handle(cx);
12358                    window.focus(&rename_focus_handle);
12359                    let block_id = this.insert_blocks(
12360                        [BlockProperties {
12361                            style: BlockStyle::Flex,
12362                            placement: BlockPlacement::Below(range.start),
12363                            height: 1,
12364                            render: Arc::new({
12365                                let rename_editor = rename_editor.clone();
12366                                move |cx: &mut BlockContext| {
12367                                    let mut text_style = cx.editor_style.text.clone();
12368                                    if let Some(highlight_style) = old_highlight_id
12369                                        .and_then(|h| h.style(&cx.editor_style.syntax))
12370                                    {
12371                                        text_style = text_style.highlight(highlight_style);
12372                                    }
12373                                    div()
12374                                        .block_mouse_down()
12375                                        .pl(cx.anchor_x)
12376                                        .child(EditorElement::new(
12377                                            &rename_editor,
12378                                            EditorStyle {
12379                                                background: cx.theme().system().transparent,
12380                                                local_player: cx.editor_style.local_player,
12381                                                text: text_style,
12382                                                scrollbar_width: cx.editor_style.scrollbar_width,
12383                                                syntax: cx.editor_style.syntax.clone(),
12384                                                status: cx.editor_style.status.clone(),
12385                                                inlay_hints_style: HighlightStyle {
12386                                                    font_weight: Some(FontWeight::BOLD),
12387                                                    ..make_inlay_hints_style(cx.app)
12388                                                },
12389                                                inline_completion_styles: make_suggestion_styles(
12390                                                    cx.app,
12391                                                ),
12392                                                ..EditorStyle::default()
12393                                            },
12394                                        ))
12395                                        .into_any_element()
12396                                }
12397                            }),
12398                            priority: 0,
12399                        }],
12400                        Some(Autoscroll::fit()),
12401                        cx,
12402                    )[0];
12403                    this.pending_rename = Some(RenameState {
12404                        range,
12405                        old_name,
12406                        editor: rename_editor,
12407                        block_id,
12408                    });
12409                })?;
12410            }
12411
12412            Ok(())
12413        }))
12414    }
12415
12416    pub fn confirm_rename(
12417        &mut self,
12418        _: &ConfirmRename,
12419        window: &mut Window,
12420        cx: &mut Context<Self>,
12421    ) -> Option<Task<Result<()>>> {
12422        let rename = self.take_rename(false, window, cx)?;
12423        let workspace = self.workspace()?.downgrade();
12424        let (buffer, start) = self
12425            .buffer
12426            .read(cx)
12427            .text_anchor_for_position(rename.range.start, cx)?;
12428        let (end_buffer, _) = self
12429            .buffer
12430            .read(cx)
12431            .text_anchor_for_position(rename.range.end, cx)?;
12432        if buffer != end_buffer {
12433            return None;
12434        }
12435
12436        let old_name = rename.old_name;
12437        let new_name = rename.editor.read(cx).text(cx);
12438
12439        let rename = self.semantics_provider.as_ref()?.perform_rename(
12440            &buffer,
12441            start,
12442            new_name.clone(),
12443            cx,
12444        )?;
12445
12446        Some(cx.spawn_in(window, |editor, mut cx| async move {
12447            let project_transaction = rename.await?;
12448            Self::open_project_transaction(
12449                &editor,
12450                workspace,
12451                project_transaction,
12452                format!("Rename: {}{}", old_name, new_name),
12453                cx.clone(),
12454            )
12455            .await?;
12456
12457            editor.update(&mut cx, |editor, cx| {
12458                editor.refresh_document_highlights(cx);
12459            })?;
12460            Ok(())
12461        }))
12462    }
12463
12464    fn take_rename(
12465        &mut self,
12466        moving_cursor: bool,
12467        window: &mut Window,
12468        cx: &mut Context<Self>,
12469    ) -> Option<RenameState> {
12470        let rename = self.pending_rename.take()?;
12471        if rename.editor.focus_handle(cx).is_focused(window) {
12472            window.focus(&self.focus_handle);
12473        }
12474
12475        self.remove_blocks(
12476            [rename.block_id].into_iter().collect(),
12477            Some(Autoscroll::fit()),
12478            cx,
12479        );
12480        self.clear_highlights::<Rename>(cx);
12481        self.show_local_selections = true;
12482
12483        if moving_cursor {
12484            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12485                editor.selections.newest::<usize>(cx).head()
12486            });
12487
12488            // Update the selection to match the position of the selection inside
12489            // the rename editor.
12490            let snapshot = self.buffer.read(cx).read(cx);
12491            let rename_range = rename.range.to_offset(&snapshot);
12492            let cursor_in_editor = snapshot
12493                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12494                .min(rename_range.end);
12495            drop(snapshot);
12496
12497            self.change_selections(None, window, cx, |s| {
12498                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12499            });
12500        } else {
12501            self.refresh_document_highlights(cx);
12502        }
12503
12504        Some(rename)
12505    }
12506
12507    pub fn pending_rename(&self) -> Option<&RenameState> {
12508        self.pending_rename.as_ref()
12509    }
12510
12511    fn format(
12512        &mut self,
12513        _: &Format,
12514        window: &mut Window,
12515        cx: &mut Context<Self>,
12516    ) -> Option<Task<Result<()>>> {
12517        let project = match &self.project {
12518            Some(project) => project.clone(),
12519            None => return None,
12520        };
12521
12522        Some(self.perform_format(
12523            project,
12524            FormatTrigger::Manual,
12525            FormatTarget::Buffers,
12526            window,
12527            cx,
12528        ))
12529    }
12530
12531    fn format_selections(
12532        &mut self,
12533        _: &FormatSelections,
12534        window: &mut Window,
12535        cx: &mut Context<Self>,
12536    ) -> Option<Task<Result<()>>> {
12537        let project = match &self.project {
12538            Some(project) => project.clone(),
12539            None => return None,
12540        };
12541
12542        let ranges = self
12543            .selections
12544            .all_adjusted(cx)
12545            .into_iter()
12546            .map(|selection| selection.range())
12547            .collect_vec();
12548
12549        Some(self.perform_format(
12550            project,
12551            FormatTrigger::Manual,
12552            FormatTarget::Ranges(ranges),
12553            window,
12554            cx,
12555        ))
12556    }
12557
12558    fn perform_format(
12559        &mut self,
12560        project: Entity<Project>,
12561        trigger: FormatTrigger,
12562        target: FormatTarget,
12563        window: &mut Window,
12564        cx: &mut Context<Self>,
12565    ) -> Task<Result<()>> {
12566        let buffer = self.buffer.clone();
12567        let (buffers, target) = match target {
12568            FormatTarget::Buffers => {
12569                let mut buffers = buffer.read(cx).all_buffers();
12570                if trigger == FormatTrigger::Save {
12571                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
12572                }
12573                (buffers, LspFormatTarget::Buffers)
12574            }
12575            FormatTarget::Ranges(selection_ranges) => {
12576                let multi_buffer = buffer.read(cx);
12577                let snapshot = multi_buffer.read(cx);
12578                let mut buffers = HashSet::default();
12579                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12580                    BTreeMap::new();
12581                for selection_range in selection_ranges {
12582                    for (buffer, buffer_range, _) in
12583                        snapshot.range_to_buffer_ranges(selection_range)
12584                    {
12585                        let buffer_id = buffer.remote_id();
12586                        let start = buffer.anchor_before(buffer_range.start);
12587                        let end = buffer.anchor_after(buffer_range.end);
12588                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12589                        buffer_id_to_ranges
12590                            .entry(buffer_id)
12591                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12592                            .or_insert_with(|| vec![start..end]);
12593                    }
12594                }
12595                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12596            }
12597        };
12598
12599        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12600        let format = project.update(cx, |project, cx| {
12601            project.format(buffers, target, true, trigger, cx)
12602        });
12603
12604        cx.spawn_in(window, |_, mut cx| async move {
12605            let transaction = futures::select_biased! {
12606                () = timeout => {
12607                    log::warn!("timed out waiting for formatting");
12608                    None
12609                }
12610                transaction = format.log_err().fuse() => transaction,
12611            };
12612
12613            buffer
12614                .update(&mut cx, |buffer, cx| {
12615                    if let Some(transaction) = transaction {
12616                        if !buffer.is_singleton() {
12617                            buffer.push_transaction(&transaction.0, cx);
12618                        }
12619                    }
12620                    cx.notify();
12621                })
12622                .ok();
12623
12624            Ok(())
12625        })
12626    }
12627
12628    fn organize_imports(
12629        &mut self,
12630        _: &OrganizeImports,
12631        window: &mut Window,
12632        cx: &mut Context<Self>,
12633    ) -> Option<Task<Result<()>>> {
12634        let project = match &self.project {
12635            Some(project) => project.clone(),
12636            None => return None,
12637        };
12638        Some(self.perform_code_action_kind(
12639            project,
12640            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12641            window,
12642            cx,
12643        ))
12644    }
12645
12646    fn perform_code_action_kind(
12647        &mut self,
12648        project: Entity<Project>,
12649        kind: CodeActionKind,
12650        window: &mut Window,
12651        cx: &mut Context<Self>,
12652    ) -> Task<Result<()>> {
12653        let buffer = self.buffer.clone();
12654        let buffers = buffer.read(cx).all_buffers();
12655        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12656        let apply_action = project.update(cx, |project, cx| {
12657            project.apply_code_action_kind(buffers, kind, true, cx)
12658        });
12659        cx.spawn_in(window, |_, mut cx| async move {
12660            let transaction = futures::select_biased! {
12661                () = timeout => {
12662                    log::warn!("timed out waiting for executing code action");
12663                    None
12664                }
12665                transaction = apply_action.log_err().fuse() => transaction,
12666            };
12667            buffer
12668                .update(&mut cx, |buffer, cx| {
12669                    // check if we need this
12670                    if let Some(transaction) = transaction {
12671                        if !buffer.is_singleton() {
12672                            buffer.push_transaction(&transaction.0, cx);
12673                        }
12674                    }
12675                    cx.notify();
12676                })
12677                .ok();
12678            Ok(())
12679        })
12680    }
12681
12682    fn restart_language_server(
12683        &mut self,
12684        _: &RestartLanguageServer,
12685        _: &mut Window,
12686        cx: &mut Context<Self>,
12687    ) {
12688        if let Some(project) = self.project.clone() {
12689            self.buffer.update(cx, |multi_buffer, cx| {
12690                project.update(cx, |project, cx| {
12691                    project.restart_language_servers_for_buffers(
12692                        multi_buffer.all_buffers().into_iter().collect(),
12693                        cx,
12694                    );
12695                });
12696            })
12697        }
12698    }
12699
12700    fn cancel_language_server_work(
12701        workspace: &mut Workspace,
12702        _: &actions::CancelLanguageServerWork,
12703        _: &mut Window,
12704        cx: &mut Context<Workspace>,
12705    ) {
12706        let project = workspace.project();
12707        let buffers = workspace
12708            .active_item(cx)
12709            .and_then(|item| item.act_as::<Editor>(cx))
12710            .map_or(HashSet::default(), |editor| {
12711                editor.read(cx).buffer.read(cx).all_buffers()
12712            });
12713        project.update(cx, |project, cx| {
12714            project.cancel_language_server_work_for_buffers(buffers, cx);
12715        });
12716    }
12717
12718    fn show_character_palette(
12719        &mut self,
12720        _: &ShowCharacterPalette,
12721        window: &mut Window,
12722        _: &mut Context<Self>,
12723    ) {
12724        window.show_character_palette();
12725    }
12726
12727    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12728        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12729            let buffer = self.buffer.read(cx).snapshot(cx);
12730            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12731            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12732            let is_valid = buffer
12733                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12734                .any(|entry| {
12735                    entry.diagnostic.is_primary
12736                        && !entry.range.is_empty()
12737                        && entry.range.start == primary_range_start
12738                        && entry.diagnostic.message == active_diagnostics.primary_message
12739                });
12740
12741            if is_valid != active_diagnostics.is_valid {
12742                active_diagnostics.is_valid = is_valid;
12743                if is_valid {
12744                    let mut new_styles = HashMap::default();
12745                    for (block_id, diagnostic) in &active_diagnostics.blocks {
12746                        new_styles.insert(
12747                            *block_id,
12748                            diagnostic_block_renderer(diagnostic.clone(), None, true),
12749                        );
12750                    }
12751                    self.display_map.update(cx, |display_map, _cx| {
12752                        display_map.replace_blocks(new_styles);
12753                    });
12754                } else {
12755                    self.dismiss_diagnostics(cx);
12756                }
12757            }
12758        }
12759    }
12760
12761    fn activate_diagnostics(
12762        &mut self,
12763        buffer_id: BufferId,
12764        group_id: usize,
12765        window: &mut Window,
12766        cx: &mut Context<Self>,
12767    ) {
12768        self.dismiss_diagnostics(cx);
12769        let snapshot = self.snapshot(window, cx);
12770        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12771            let buffer = self.buffer.read(cx).snapshot(cx);
12772
12773            let mut primary_range = None;
12774            let mut primary_message = None;
12775            let diagnostic_group = buffer
12776                .diagnostic_group(buffer_id, group_id)
12777                .filter_map(|entry| {
12778                    let start = entry.range.start;
12779                    let end = entry.range.end;
12780                    if snapshot.is_line_folded(MultiBufferRow(start.row))
12781                        && (start.row == end.row
12782                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
12783                    {
12784                        return None;
12785                    }
12786                    if entry.diagnostic.is_primary {
12787                        primary_range = Some(entry.range.clone());
12788                        primary_message = Some(entry.diagnostic.message.clone());
12789                    }
12790                    Some(entry)
12791                })
12792                .collect::<Vec<_>>();
12793            let primary_range = primary_range?;
12794            let primary_message = primary_message?;
12795
12796            let blocks = display_map
12797                .insert_blocks(
12798                    diagnostic_group.iter().map(|entry| {
12799                        let diagnostic = entry.diagnostic.clone();
12800                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12801                        BlockProperties {
12802                            style: BlockStyle::Fixed,
12803                            placement: BlockPlacement::Below(
12804                                buffer.anchor_after(entry.range.start),
12805                            ),
12806                            height: message_height,
12807                            render: diagnostic_block_renderer(diagnostic, None, true),
12808                            priority: 0,
12809                        }
12810                    }),
12811                    cx,
12812                )
12813                .into_iter()
12814                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12815                .collect();
12816
12817            Some(ActiveDiagnosticGroup {
12818                primary_range: buffer.anchor_before(primary_range.start)
12819                    ..buffer.anchor_after(primary_range.end),
12820                primary_message,
12821                group_id,
12822                blocks,
12823                is_valid: true,
12824            })
12825        });
12826    }
12827
12828    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12829        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12830            self.display_map.update(cx, |display_map, cx| {
12831                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12832            });
12833            cx.notify();
12834        }
12835    }
12836
12837    /// Disable inline diagnostics rendering for this editor.
12838    pub fn disable_inline_diagnostics(&mut self) {
12839        self.inline_diagnostics_enabled = false;
12840        self.inline_diagnostics_update = Task::ready(());
12841        self.inline_diagnostics.clear();
12842    }
12843
12844    pub fn inline_diagnostics_enabled(&self) -> bool {
12845        self.inline_diagnostics_enabled
12846    }
12847
12848    pub fn show_inline_diagnostics(&self) -> bool {
12849        self.show_inline_diagnostics
12850    }
12851
12852    pub fn toggle_inline_diagnostics(
12853        &mut self,
12854        _: &ToggleInlineDiagnostics,
12855        window: &mut Window,
12856        cx: &mut Context<'_, Editor>,
12857    ) {
12858        self.show_inline_diagnostics = !self.show_inline_diagnostics;
12859        self.refresh_inline_diagnostics(false, window, cx);
12860    }
12861
12862    fn refresh_inline_diagnostics(
12863        &mut self,
12864        debounce: bool,
12865        window: &mut Window,
12866        cx: &mut Context<Self>,
12867    ) {
12868        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12869            self.inline_diagnostics_update = Task::ready(());
12870            self.inline_diagnostics.clear();
12871            return;
12872        }
12873
12874        let debounce_ms = ProjectSettings::get_global(cx)
12875            .diagnostics
12876            .inline
12877            .update_debounce_ms;
12878        let debounce = if debounce && debounce_ms > 0 {
12879            Some(Duration::from_millis(debounce_ms))
12880        } else {
12881            None
12882        };
12883        self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12884            if let Some(debounce) = debounce {
12885                cx.background_executor().timer(debounce).await;
12886            }
12887            let Some(snapshot) = editor
12888                .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12889                .ok()
12890            else {
12891                return;
12892            };
12893
12894            let new_inline_diagnostics = cx
12895                .background_spawn(async move {
12896                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12897                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12898                        let message = diagnostic_entry
12899                            .diagnostic
12900                            .message
12901                            .split_once('\n')
12902                            .map(|(line, _)| line)
12903                            .map(SharedString::new)
12904                            .unwrap_or_else(|| {
12905                                SharedString::from(diagnostic_entry.diagnostic.message)
12906                            });
12907                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12908                        let (Ok(i) | Err(i)) = inline_diagnostics
12909                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12910                        inline_diagnostics.insert(
12911                            i,
12912                            (
12913                                start_anchor,
12914                                InlineDiagnostic {
12915                                    message,
12916                                    group_id: diagnostic_entry.diagnostic.group_id,
12917                                    start: diagnostic_entry.range.start.to_point(&snapshot),
12918                                    is_primary: diagnostic_entry.diagnostic.is_primary,
12919                                    severity: diagnostic_entry.diagnostic.severity,
12920                                },
12921                            ),
12922                        );
12923                    }
12924                    inline_diagnostics
12925                })
12926                .await;
12927
12928            editor
12929                .update(&mut cx, |editor, cx| {
12930                    editor.inline_diagnostics = new_inline_diagnostics;
12931                    cx.notify();
12932                })
12933                .ok();
12934        });
12935    }
12936
12937    pub fn set_selections_from_remote(
12938        &mut self,
12939        selections: Vec<Selection<Anchor>>,
12940        pending_selection: Option<Selection<Anchor>>,
12941        window: &mut Window,
12942        cx: &mut Context<Self>,
12943    ) {
12944        let old_cursor_position = self.selections.newest_anchor().head();
12945        self.selections.change_with(cx, |s| {
12946            s.select_anchors(selections);
12947            if let Some(pending_selection) = pending_selection {
12948                s.set_pending(pending_selection, SelectMode::Character);
12949            } else {
12950                s.clear_pending();
12951            }
12952        });
12953        self.selections_did_change(false, &old_cursor_position, true, window, cx);
12954    }
12955
12956    fn push_to_selection_history(&mut self) {
12957        self.selection_history.push(SelectionHistoryEntry {
12958            selections: self.selections.disjoint_anchors(),
12959            select_next_state: self.select_next_state.clone(),
12960            select_prev_state: self.select_prev_state.clone(),
12961            add_selections_state: self.add_selections_state.clone(),
12962        });
12963    }
12964
12965    pub fn transact(
12966        &mut self,
12967        window: &mut Window,
12968        cx: &mut Context<Self>,
12969        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12970    ) -> Option<TransactionId> {
12971        self.start_transaction_at(Instant::now(), window, cx);
12972        update(self, window, cx);
12973        self.end_transaction_at(Instant::now(), cx)
12974    }
12975
12976    pub fn start_transaction_at(
12977        &mut self,
12978        now: Instant,
12979        window: &mut Window,
12980        cx: &mut Context<Self>,
12981    ) {
12982        self.end_selection(window, cx);
12983        if let Some(tx_id) = self
12984            .buffer
12985            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12986        {
12987            self.selection_history
12988                .insert_transaction(tx_id, self.selections.disjoint_anchors());
12989            cx.emit(EditorEvent::TransactionBegun {
12990                transaction_id: tx_id,
12991            })
12992        }
12993    }
12994
12995    pub fn end_transaction_at(
12996        &mut self,
12997        now: Instant,
12998        cx: &mut Context<Self>,
12999    ) -> Option<TransactionId> {
13000        if let Some(transaction_id) = self
13001            .buffer
13002            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
13003        {
13004            if let Some((_, end_selections)) =
13005                self.selection_history.transaction_mut(transaction_id)
13006            {
13007                *end_selections = Some(self.selections.disjoint_anchors());
13008            } else {
13009                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
13010            }
13011
13012            cx.emit(EditorEvent::Edited { transaction_id });
13013            Some(transaction_id)
13014        } else {
13015            None
13016        }
13017    }
13018
13019    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
13020        if self.selection_mark_mode {
13021            self.change_selections(None, window, cx, |s| {
13022                s.move_with(|_, sel| {
13023                    sel.collapse_to(sel.head(), SelectionGoal::None);
13024                });
13025            })
13026        }
13027        self.selection_mark_mode = true;
13028        cx.notify();
13029    }
13030
13031    pub fn swap_selection_ends(
13032        &mut self,
13033        _: &actions::SwapSelectionEnds,
13034        window: &mut Window,
13035        cx: &mut Context<Self>,
13036    ) {
13037        self.change_selections(None, window, cx, |s| {
13038            s.move_with(|_, sel| {
13039                if sel.start != sel.end {
13040                    sel.reversed = !sel.reversed
13041                }
13042            });
13043        });
13044        self.request_autoscroll(Autoscroll::newest(), cx);
13045        cx.notify();
13046    }
13047
13048    pub fn toggle_fold(
13049        &mut self,
13050        _: &actions::ToggleFold,
13051        window: &mut Window,
13052        cx: &mut Context<Self>,
13053    ) {
13054        if self.is_singleton(cx) {
13055            let selection = self.selections.newest::<Point>(cx);
13056
13057            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13058            let range = if selection.is_empty() {
13059                let point = selection.head().to_display_point(&display_map);
13060                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13061                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13062                    .to_point(&display_map);
13063                start..end
13064            } else {
13065                selection.range()
13066            };
13067            if display_map.folds_in_range(range).next().is_some() {
13068                self.unfold_lines(&Default::default(), window, cx)
13069            } else {
13070                self.fold(&Default::default(), window, cx)
13071            }
13072        } else {
13073            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13074            let buffer_ids: HashSet<_> = self
13075                .selections
13076                .disjoint_anchor_ranges()
13077                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13078                .collect();
13079
13080            let should_unfold = buffer_ids
13081                .iter()
13082                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13083
13084            for buffer_id in buffer_ids {
13085                if should_unfold {
13086                    self.unfold_buffer(buffer_id, cx);
13087                } else {
13088                    self.fold_buffer(buffer_id, cx);
13089                }
13090            }
13091        }
13092    }
13093
13094    pub fn toggle_fold_recursive(
13095        &mut self,
13096        _: &actions::ToggleFoldRecursive,
13097        window: &mut Window,
13098        cx: &mut Context<Self>,
13099    ) {
13100        let selection = self.selections.newest::<Point>(cx);
13101
13102        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13103        let range = if selection.is_empty() {
13104            let point = selection.head().to_display_point(&display_map);
13105            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13106            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13107                .to_point(&display_map);
13108            start..end
13109        } else {
13110            selection.range()
13111        };
13112        if display_map.folds_in_range(range).next().is_some() {
13113            self.unfold_recursive(&Default::default(), window, cx)
13114        } else {
13115            self.fold_recursive(&Default::default(), window, cx)
13116        }
13117    }
13118
13119    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13120        if self.is_singleton(cx) {
13121            let mut to_fold = Vec::new();
13122            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13123            let selections = self.selections.all_adjusted(cx);
13124
13125            for selection in selections {
13126                let range = selection.range().sorted();
13127                let buffer_start_row = range.start.row;
13128
13129                if range.start.row != range.end.row {
13130                    let mut found = false;
13131                    let mut row = range.start.row;
13132                    while row <= range.end.row {
13133                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13134                        {
13135                            found = true;
13136                            row = crease.range().end.row + 1;
13137                            to_fold.push(crease);
13138                        } else {
13139                            row += 1
13140                        }
13141                    }
13142                    if found {
13143                        continue;
13144                    }
13145                }
13146
13147                for row in (0..=range.start.row).rev() {
13148                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13149                        if crease.range().end.row >= buffer_start_row {
13150                            to_fold.push(crease);
13151                            if row <= range.start.row {
13152                                break;
13153                            }
13154                        }
13155                    }
13156                }
13157            }
13158
13159            self.fold_creases(to_fold, true, window, cx);
13160        } else {
13161            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13162            let buffer_ids = self
13163                .selections
13164                .disjoint_anchor_ranges()
13165                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13166                .collect::<HashSet<_>>();
13167            for buffer_id in buffer_ids {
13168                self.fold_buffer(buffer_id, cx);
13169            }
13170        }
13171    }
13172
13173    fn fold_at_level(
13174        &mut self,
13175        fold_at: &FoldAtLevel,
13176        window: &mut Window,
13177        cx: &mut Context<Self>,
13178    ) {
13179        if !self.buffer.read(cx).is_singleton() {
13180            return;
13181        }
13182
13183        let fold_at_level = fold_at.0;
13184        let snapshot = self.buffer.read(cx).snapshot(cx);
13185        let mut to_fold = Vec::new();
13186        let mut stack = vec![(0, snapshot.max_row().0, 1)];
13187
13188        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13189            while start_row < end_row {
13190                match self
13191                    .snapshot(window, cx)
13192                    .crease_for_buffer_row(MultiBufferRow(start_row))
13193                {
13194                    Some(crease) => {
13195                        let nested_start_row = crease.range().start.row + 1;
13196                        let nested_end_row = crease.range().end.row;
13197
13198                        if current_level < fold_at_level {
13199                            stack.push((nested_start_row, nested_end_row, current_level + 1));
13200                        } else if current_level == fold_at_level {
13201                            to_fold.push(crease);
13202                        }
13203
13204                        start_row = nested_end_row + 1;
13205                    }
13206                    None => start_row += 1,
13207                }
13208            }
13209        }
13210
13211        self.fold_creases(to_fold, true, window, cx);
13212    }
13213
13214    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13215        if self.buffer.read(cx).is_singleton() {
13216            let mut fold_ranges = Vec::new();
13217            let snapshot = self.buffer.read(cx).snapshot(cx);
13218
13219            for row in 0..snapshot.max_row().0 {
13220                if let Some(foldable_range) = self
13221                    .snapshot(window, cx)
13222                    .crease_for_buffer_row(MultiBufferRow(row))
13223                {
13224                    fold_ranges.push(foldable_range);
13225                }
13226            }
13227
13228            self.fold_creases(fold_ranges, true, window, cx);
13229        } else {
13230            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13231                editor
13232                    .update_in(&mut cx, |editor, _, cx| {
13233                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13234                            editor.fold_buffer(buffer_id, cx);
13235                        }
13236                    })
13237                    .ok();
13238            });
13239        }
13240    }
13241
13242    pub fn fold_function_bodies(
13243        &mut self,
13244        _: &actions::FoldFunctionBodies,
13245        window: &mut Window,
13246        cx: &mut Context<Self>,
13247    ) {
13248        let snapshot = self.buffer.read(cx).snapshot(cx);
13249
13250        let ranges = snapshot
13251            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13252            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13253            .collect::<Vec<_>>();
13254
13255        let creases = ranges
13256            .into_iter()
13257            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13258            .collect();
13259
13260        self.fold_creases(creases, true, window, cx);
13261    }
13262
13263    pub fn fold_recursive(
13264        &mut self,
13265        _: &actions::FoldRecursive,
13266        window: &mut Window,
13267        cx: &mut Context<Self>,
13268    ) {
13269        let mut to_fold = Vec::new();
13270        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13271        let selections = self.selections.all_adjusted(cx);
13272
13273        for selection in selections {
13274            let range = selection.range().sorted();
13275            let buffer_start_row = range.start.row;
13276
13277            if range.start.row != range.end.row {
13278                let mut found = false;
13279                for row in range.start.row..=range.end.row {
13280                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13281                        found = true;
13282                        to_fold.push(crease);
13283                    }
13284                }
13285                if found {
13286                    continue;
13287                }
13288            }
13289
13290            for row in (0..=range.start.row).rev() {
13291                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13292                    if crease.range().end.row >= buffer_start_row {
13293                        to_fold.push(crease);
13294                    } else {
13295                        break;
13296                    }
13297                }
13298            }
13299        }
13300
13301        self.fold_creases(to_fold, true, window, cx);
13302    }
13303
13304    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13305        let buffer_row = fold_at.buffer_row;
13306        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13307
13308        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13309            let autoscroll = self
13310                .selections
13311                .all::<Point>(cx)
13312                .iter()
13313                .any(|selection| crease.range().overlaps(&selection.range()));
13314
13315            self.fold_creases(vec![crease], autoscroll, window, cx);
13316        }
13317    }
13318
13319    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13320        if self.is_singleton(cx) {
13321            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13322            let buffer = &display_map.buffer_snapshot;
13323            let selections = self.selections.all::<Point>(cx);
13324            let ranges = selections
13325                .iter()
13326                .map(|s| {
13327                    let range = s.display_range(&display_map).sorted();
13328                    let mut start = range.start.to_point(&display_map);
13329                    let mut end = range.end.to_point(&display_map);
13330                    start.column = 0;
13331                    end.column = buffer.line_len(MultiBufferRow(end.row));
13332                    start..end
13333                })
13334                .collect::<Vec<_>>();
13335
13336            self.unfold_ranges(&ranges, true, true, cx);
13337        } else {
13338            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13339            let buffer_ids = self
13340                .selections
13341                .disjoint_anchor_ranges()
13342                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13343                .collect::<HashSet<_>>();
13344            for buffer_id in buffer_ids {
13345                self.unfold_buffer(buffer_id, cx);
13346            }
13347        }
13348    }
13349
13350    pub fn unfold_recursive(
13351        &mut self,
13352        _: &UnfoldRecursive,
13353        _window: &mut Window,
13354        cx: &mut Context<Self>,
13355    ) {
13356        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13357        let selections = self.selections.all::<Point>(cx);
13358        let ranges = selections
13359            .iter()
13360            .map(|s| {
13361                let mut range = s.display_range(&display_map).sorted();
13362                *range.start.column_mut() = 0;
13363                *range.end.column_mut() = display_map.line_len(range.end.row());
13364                let start = range.start.to_point(&display_map);
13365                let end = range.end.to_point(&display_map);
13366                start..end
13367            })
13368            .collect::<Vec<_>>();
13369
13370        self.unfold_ranges(&ranges, true, true, cx);
13371    }
13372
13373    pub fn unfold_at(
13374        &mut self,
13375        unfold_at: &UnfoldAt,
13376        _window: &mut Window,
13377        cx: &mut Context<Self>,
13378    ) {
13379        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13380
13381        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13382            ..Point::new(
13383                unfold_at.buffer_row.0,
13384                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13385            );
13386
13387        let autoscroll = self
13388            .selections
13389            .all::<Point>(cx)
13390            .iter()
13391            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13392
13393        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13394    }
13395
13396    pub fn unfold_all(
13397        &mut self,
13398        _: &actions::UnfoldAll,
13399        _window: &mut Window,
13400        cx: &mut Context<Self>,
13401    ) {
13402        if self.buffer.read(cx).is_singleton() {
13403            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13404            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13405        } else {
13406            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13407                editor
13408                    .update(&mut cx, |editor, cx| {
13409                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13410                            editor.unfold_buffer(buffer_id, cx);
13411                        }
13412                    })
13413                    .ok();
13414            });
13415        }
13416    }
13417
13418    pub fn fold_selected_ranges(
13419        &mut self,
13420        _: &FoldSelectedRanges,
13421        window: &mut Window,
13422        cx: &mut Context<Self>,
13423    ) {
13424        let selections = self.selections.all::<Point>(cx);
13425        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13426        let line_mode = self.selections.line_mode;
13427        let ranges = selections
13428            .into_iter()
13429            .map(|s| {
13430                if line_mode {
13431                    let start = Point::new(s.start.row, 0);
13432                    let end = Point::new(
13433                        s.end.row,
13434                        display_map
13435                            .buffer_snapshot
13436                            .line_len(MultiBufferRow(s.end.row)),
13437                    );
13438                    Crease::simple(start..end, display_map.fold_placeholder.clone())
13439                } else {
13440                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13441                }
13442            })
13443            .collect::<Vec<_>>();
13444        self.fold_creases(ranges, true, window, cx);
13445    }
13446
13447    pub fn fold_ranges<T: ToOffset + Clone>(
13448        &mut self,
13449        ranges: Vec<Range<T>>,
13450        auto_scroll: bool,
13451        window: &mut Window,
13452        cx: &mut Context<Self>,
13453    ) {
13454        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13455        let ranges = ranges
13456            .into_iter()
13457            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13458            .collect::<Vec<_>>();
13459        self.fold_creases(ranges, auto_scroll, window, cx);
13460    }
13461
13462    pub fn fold_creases<T: ToOffset + Clone>(
13463        &mut self,
13464        creases: Vec<Crease<T>>,
13465        auto_scroll: bool,
13466        window: &mut Window,
13467        cx: &mut Context<Self>,
13468    ) {
13469        if creases.is_empty() {
13470            return;
13471        }
13472
13473        let mut buffers_affected = HashSet::default();
13474        let multi_buffer = self.buffer().read(cx);
13475        for crease in &creases {
13476            if let Some((_, buffer, _)) =
13477                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13478            {
13479                buffers_affected.insert(buffer.read(cx).remote_id());
13480            };
13481        }
13482
13483        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13484
13485        if auto_scroll {
13486            self.request_autoscroll(Autoscroll::fit(), cx);
13487        }
13488
13489        cx.notify();
13490
13491        if let Some(active_diagnostics) = self.active_diagnostics.take() {
13492            // Clear diagnostics block when folding a range that contains it.
13493            let snapshot = self.snapshot(window, cx);
13494            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13495                drop(snapshot);
13496                self.active_diagnostics = Some(active_diagnostics);
13497                self.dismiss_diagnostics(cx);
13498            } else {
13499                self.active_diagnostics = Some(active_diagnostics);
13500            }
13501        }
13502
13503        self.scrollbar_marker_state.dirty = true;
13504    }
13505
13506    /// Removes any folds whose ranges intersect any of the given ranges.
13507    pub fn unfold_ranges<T: ToOffset + Clone>(
13508        &mut self,
13509        ranges: &[Range<T>],
13510        inclusive: bool,
13511        auto_scroll: bool,
13512        cx: &mut Context<Self>,
13513    ) {
13514        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13515            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13516        });
13517    }
13518
13519    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13520        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13521            return;
13522        }
13523        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13524        self.display_map.update(cx, |display_map, cx| {
13525            display_map.fold_buffers([buffer_id], cx)
13526        });
13527        cx.emit(EditorEvent::BufferFoldToggled {
13528            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13529            folded: true,
13530        });
13531        cx.notify();
13532    }
13533
13534    pub fn unfold_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 unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13539        self.display_map.update(cx, |display_map, cx| {
13540            display_map.unfold_buffers([buffer_id], cx);
13541        });
13542        cx.emit(EditorEvent::BufferFoldToggled {
13543            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13544            folded: false,
13545        });
13546        cx.notify();
13547    }
13548
13549    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13550        self.display_map.read(cx).is_buffer_folded(buffer)
13551    }
13552
13553    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13554        self.display_map.read(cx).folded_buffers()
13555    }
13556
13557    /// Removes any folds with the given ranges.
13558    pub fn remove_folds_with_type<T: ToOffset + Clone>(
13559        &mut self,
13560        ranges: &[Range<T>],
13561        type_id: TypeId,
13562        auto_scroll: bool,
13563        cx: &mut Context<Self>,
13564    ) {
13565        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13566            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13567        });
13568    }
13569
13570    fn remove_folds_with<T: ToOffset + Clone>(
13571        &mut self,
13572        ranges: &[Range<T>],
13573        auto_scroll: bool,
13574        cx: &mut Context<Self>,
13575        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13576    ) {
13577        if ranges.is_empty() {
13578            return;
13579        }
13580
13581        let mut buffers_affected = HashSet::default();
13582        let multi_buffer = self.buffer().read(cx);
13583        for range in ranges {
13584            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13585                buffers_affected.insert(buffer.read(cx).remote_id());
13586            };
13587        }
13588
13589        self.display_map.update(cx, update);
13590
13591        if auto_scroll {
13592            self.request_autoscroll(Autoscroll::fit(), cx);
13593        }
13594
13595        cx.notify();
13596        self.scrollbar_marker_state.dirty = true;
13597        self.active_indent_guides_state.dirty = true;
13598    }
13599
13600    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13601        self.display_map.read(cx).fold_placeholder.clone()
13602    }
13603
13604    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13605        self.buffer.update(cx, |buffer, cx| {
13606            buffer.set_all_diff_hunks_expanded(cx);
13607        });
13608    }
13609
13610    pub fn expand_all_diff_hunks(
13611        &mut self,
13612        _: &ExpandAllDiffHunks,
13613        _window: &mut Window,
13614        cx: &mut Context<Self>,
13615    ) {
13616        self.buffer.update(cx, |buffer, cx| {
13617            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13618        });
13619    }
13620
13621    pub fn toggle_selected_diff_hunks(
13622        &mut self,
13623        _: &ToggleSelectedDiffHunks,
13624        _window: &mut Window,
13625        cx: &mut Context<Self>,
13626    ) {
13627        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13628        self.toggle_diff_hunks_in_ranges(ranges, cx);
13629    }
13630
13631    pub fn diff_hunks_in_ranges<'a>(
13632        &'a self,
13633        ranges: &'a [Range<Anchor>],
13634        buffer: &'a MultiBufferSnapshot,
13635    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13636        ranges.iter().flat_map(move |range| {
13637            let end_excerpt_id = range.end.excerpt_id;
13638            let range = range.to_point(buffer);
13639            let mut peek_end = range.end;
13640            if range.end.row < buffer.max_row().0 {
13641                peek_end = Point::new(range.end.row + 1, 0);
13642            }
13643            buffer
13644                .diff_hunks_in_range(range.start..peek_end)
13645                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13646        })
13647    }
13648
13649    pub fn has_stageable_diff_hunks_in_ranges(
13650        &self,
13651        ranges: &[Range<Anchor>],
13652        snapshot: &MultiBufferSnapshot,
13653    ) -> bool {
13654        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13655        hunks.any(|hunk| hunk.status().has_secondary_hunk())
13656    }
13657
13658    pub fn toggle_staged_selected_diff_hunks(
13659        &mut self,
13660        _: &::git::ToggleStaged,
13661        window: &mut Window,
13662        cx: &mut Context<Self>,
13663    ) {
13664        let snapshot = self.buffer.read(cx).snapshot(cx);
13665        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13666        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13667        self.stage_or_unstage_diff_hunks(stage, &ranges, window, cx);
13668    }
13669
13670    pub fn stage_and_next(
13671        &mut self,
13672        _: &::git::StageAndNext,
13673        window: &mut Window,
13674        cx: &mut Context<Self>,
13675    ) {
13676        self.do_stage_or_unstage_and_next(true, window, cx);
13677    }
13678
13679    pub fn unstage_and_next(
13680        &mut self,
13681        _: &::git::UnstageAndNext,
13682        window: &mut Window,
13683        cx: &mut Context<Self>,
13684    ) {
13685        self.do_stage_or_unstage_and_next(false, window, cx);
13686    }
13687
13688    pub fn stage_or_unstage_diff_hunks(
13689        &mut self,
13690        stage: bool,
13691        ranges: &[Range<Anchor>],
13692        window: &mut Window,
13693        cx: &mut Context<Self>,
13694    ) {
13695        let snapshot = self.buffer.read(cx).snapshot(cx);
13696        let chunk_by = self
13697            .diff_hunks_in_ranges(&ranges, &snapshot)
13698            .chunk_by(|hunk| hunk.buffer_id);
13699        for (buffer_id, hunks) in &chunk_by {
13700            self.do_stage_or_unstage(stage, buffer_id, hunks, window, cx);
13701        }
13702    }
13703
13704    fn do_stage_or_unstage_and_next(
13705        &mut self,
13706        stage: bool,
13707        window: &mut Window,
13708        cx: &mut Context<Self>,
13709    ) {
13710        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13711
13712        if ranges.iter().any(|range| range.start != range.end) {
13713            self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13714            return;
13715        }
13716
13717        let snapshot = self.snapshot(window, cx);
13718        let newest_range = self.selections.newest::<Point>(cx).range();
13719
13720        let run_twice = snapshot
13721            .hunks_for_ranges([newest_range])
13722            .first()
13723            .is_some_and(|hunk| {
13724                let next_line = Point::new(hunk.row_range.end.0 + 1, 0);
13725                self.hunk_after_position(&snapshot, next_line)
13726                    .is_some_and(|other| other.row_range == hunk.row_range)
13727            });
13728
13729        if run_twice {
13730            self.go_to_next_hunk(&GoToHunk, window, cx);
13731        }
13732        self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13733        self.go_to_next_hunk(&GoToHunk, window, cx);
13734    }
13735
13736    fn do_stage_or_unstage(
13737        &self,
13738        stage: bool,
13739        buffer_id: BufferId,
13740        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13741        window: &mut Window,
13742        cx: &mut App,
13743    ) {
13744        let Some(project) = self.project.as_ref() else {
13745            return;
13746        };
13747        let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
13748            return;
13749        };
13750        let Some(diff) = self.buffer.read(cx).diff_for(buffer_id) else {
13751            return;
13752        };
13753        let buffer_snapshot = buffer.read(cx).snapshot();
13754        let file_exists = buffer_snapshot
13755            .file()
13756            .is_some_and(|file| file.disk_state().exists());
13757        let Some((repo, path)) = project
13758            .read(cx)
13759            .repository_and_path_for_buffer_id(buffer_id, cx)
13760        else {
13761            log::debug!("no git repo for buffer id");
13762            return;
13763        };
13764
13765        let new_index_text = diff.update(cx, |diff, cx| {
13766            diff.stage_or_unstage_hunks(
13767                stage,
13768                &hunks
13769                    .map(|hunk| buffer_diff::DiffHunk {
13770                        buffer_range: hunk.buffer_range,
13771                        diff_base_byte_range: hunk.diff_base_byte_range,
13772                        secondary_status: hunk.secondary_status,
13773                        range: Point::zero()..Point::zero(), // unused
13774                    })
13775                    .collect::<Vec<_>>(),
13776                &buffer_snapshot,
13777                file_exists,
13778                cx,
13779            )
13780        });
13781
13782        if file_exists {
13783            let buffer_store = project.read(cx).buffer_store().clone();
13784            buffer_store
13785                .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
13786                .detach_and_log_err(cx);
13787        }
13788
13789        let recv = repo
13790            .read(cx)
13791            .set_index_text(&path, new_index_text.map(|rope| rope.to_string()));
13792
13793        cx.background_spawn(async move { recv.await? })
13794            .detach_and_notify_err(window, cx);
13795    }
13796
13797    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13798        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13799        self.buffer
13800            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13801    }
13802
13803    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13804        self.buffer.update(cx, |buffer, cx| {
13805            let ranges = vec![Anchor::min()..Anchor::max()];
13806            if !buffer.all_diff_hunks_expanded()
13807                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13808            {
13809                buffer.collapse_diff_hunks(ranges, cx);
13810                true
13811            } else {
13812                false
13813            }
13814        })
13815    }
13816
13817    fn toggle_diff_hunks_in_ranges(
13818        &mut self,
13819        ranges: Vec<Range<Anchor>>,
13820        cx: &mut Context<'_, Editor>,
13821    ) {
13822        self.buffer.update(cx, |buffer, cx| {
13823            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13824            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13825        })
13826    }
13827
13828    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13829        self.buffer.update(cx, |buffer, cx| {
13830            let snapshot = buffer.snapshot(cx);
13831            let excerpt_id = range.end.excerpt_id;
13832            let point_range = range.to_point(&snapshot);
13833            let expand = !buffer.single_hunk_is_expanded(range, cx);
13834            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13835        })
13836    }
13837
13838    pub(crate) fn apply_all_diff_hunks(
13839        &mut self,
13840        _: &ApplyAllDiffHunks,
13841        window: &mut Window,
13842        cx: &mut Context<Self>,
13843    ) {
13844        let buffers = self.buffer.read(cx).all_buffers();
13845        for branch_buffer in buffers {
13846            branch_buffer.update(cx, |branch_buffer, cx| {
13847                branch_buffer.merge_into_base(Vec::new(), cx);
13848            });
13849        }
13850
13851        if let Some(project) = self.project.clone() {
13852            self.save(true, project, window, cx).detach_and_log_err(cx);
13853        }
13854    }
13855
13856    pub(crate) fn apply_selected_diff_hunks(
13857        &mut self,
13858        _: &ApplyDiffHunk,
13859        window: &mut Window,
13860        cx: &mut Context<Self>,
13861    ) {
13862        let snapshot = self.snapshot(window, cx);
13863        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
13864        let mut ranges_by_buffer = HashMap::default();
13865        self.transact(window, cx, |editor, _window, cx| {
13866            for hunk in hunks {
13867                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13868                    ranges_by_buffer
13869                        .entry(buffer.clone())
13870                        .or_insert_with(Vec::new)
13871                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13872                }
13873            }
13874
13875            for (buffer, ranges) in ranges_by_buffer {
13876                buffer.update(cx, |buffer, cx| {
13877                    buffer.merge_into_base(ranges, cx);
13878                });
13879            }
13880        });
13881
13882        if let Some(project) = self.project.clone() {
13883            self.save(true, project, window, cx).detach_and_log_err(cx);
13884        }
13885    }
13886
13887    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13888        if hovered != self.gutter_hovered {
13889            self.gutter_hovered = hovered;
13890            cx.notify();
13891        }
13892    }
13893
13894    pub fn insert_blocks(
13895        &mut self,
13896        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13897        autoscroll: Option<Autoscroll>,
13898        cx: &mut Context<Self>,
13899    ) -> Vec<CustomBlockId> {
13900        let blocks = self
13901            .display_map
13902            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13903        if let Some(autoscroll) = autoscroll {
13904            self.request_autoscroll(autoscroll, cx);
13905        }
13906        cx.notify();
13907        blocks
13908    }
13909
13910    pub fn resize_blocks(
13911        &mut self,
13912        heights: HashMap<CustomBlockId, u32>,
13913        autoscroll: Option<Autoscroll>,
13914        cx: &mut Context<Self>,
13915    ) {
13916        self.display_map
13917            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13918        if let Some(autoscroll) = autoscroll {
13919            self.request_autoscroll(autoscroll, cx);
13920        }
13921        cx.notify();
13922    }
13923
13924    pub fn replace_blocks(
13925        &mut self,
13926        renderers: HashMap<CustomBlockId, RenderBlock>,
13927        autoscroll: Option<Autoscroll>,
13928        cx: &mut Context<Self>,
13929    ) {
13930        self.display_map
13931            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13932        if let Some(autoscroll) = autoscroll {
13933            self.request_autoscroll(autoscroll, cx);
13934        }
13935        cx.notify();
13936    }
13937
13938    pub fn remove_blocks(
13939        &mut self,
13940        block_ids: HashSet<CustomBlockId>,
13941        autoscroll: Option<Autoscroll>,
13942        cx: &mut Context<Self>,
13943    ) {
13944        self.display_map.update(cx, |display_map, cx| {
13945            display_map.remove_blocks(block_ids, cx)
13946        });
13947        if let Some(autoscroll) = autoscroll {
13948            self.request_autoscroll(autoscroll, cx);
13949        }
13950        cx.notify();
13951    }
13952
13953    pub fn row_for_block(
13954        &self,
13955        block_id: CustomBlockId,
13956        cx: &mut Context<Self>,
13957    ) -> Option<DisplayRow> {
13958        self.display_map
13959            .update(cx, |map, cx| map.row_for_block(block_id, cx))
13960    }
13961
13962    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13963        self.focused_block = Some(focused_block);
13964    }
13965
13966    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13967        self.focused_block.take()
13968    }
13969
13970    pub fn insert_creases(
13971        &mut self,
13972        creases: impl IntoIterator<Item = Crease<Anchor>>,
13973        cx: &mut Context<Self>,
13974    ) -> Vec<CreaseId> {
13975        self.display_map
13976            .update(cx, |map, cx| map.insert_creases(creases, cx))
13977    }
13978
13979    pub fn remove_creases(
13980        &mut self,
13981        ids: impl IntoIterator<Item = CreaseId>,
13982        cx: &mut Context<Self>,
13983    ) {
13984        self.display_map
13985            .update(cx, |map, cx| map.remove_creases(ids, cx));
13986    }
13987
13988    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13989        self.display_map
13990            .update(cx, |map, cx| map.snapshot(cx))
13991            .longest_row()
13992    }
13993
13994    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13995        self.display_map
13996            .update(cx, |map, cx| map.snapshot(cx))
13997            .max_point()
13998    }
13999
14000    pub fn text(&self, cx: &App) -> String {
14001        self.buffer.read(cx).read(cx).text()
14002    }
14003
14004    pub fn is_empty(&self, cx: &App) -> bool {
14005        self.buffer.read(cx).read(cx).is_empty()
14006    }
14007
14008    pub fn text_option(&self, cx: &App) -> Option<String> {
14009        let text = self.text(cx);
14010        let text = text.trim();
14011
14012        if text.is_empty() {
14013            return None;
14014        }
14015
14016        Some(text.to_string())
14017    }
14018
14019    pub fn set_text(
14020        &mut self,
14021        text: impl Into<Arc<str>>,
14022        window: &mut Window,
14023        cx: &mut Context<Self>,
14024    ) {
14025        self.transact(window, cx, |this, _, cx| {
14026            this.buffer
14027                .read(cx)
14028                .as_singleton()
14029                .expect("you can only call set_text on editors for singleton buffers")
14030                .update(cx, |buffer, cx| buffer.set_text(text, cx));
14031        });
14032    }
14033
14034    pub fn display_text(&self, cx: &mut App) -> String {
14035        self.display_map
14036            .update(cx, |map, cx| map.snapshot(cx))
14037            .text()
14038    }
14039
14040    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
14041        let mut wrap_guides = smallvec::smallvec![];
14042
14043        if self.show_wrap_guides == Some(false) {
14044            return wrap_guides;
14045        }
14046
14047        let settings = self.buffer.read(cx).language_settings(cx);
14048        if settings.show_wrap_guides {
14049            match self.soft_wrap_mode(cx) {
14050                SoftWrap::Column(soft_wrap) => {
14051                    wrap_guides.push((soft_wrap as usize, true));
14052                }
14053                SoftWrap::Bounded(soft_wrap) => {
14054                    wrap_guides.push((soft_wrap as usize, true));
14055                }
14056                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
14057            }
14058            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14059        }
14060
14061        wrap_guides
14062    }
14063
14064    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14065        let settings = self.buffer.read(cx).language_settings(cx);
14066        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14067        match mode {
14068            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14069                SoftWrap::None
14070            }
14071            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14072            language_settings::SoftWrap::PreferredLineLength => {
14073                SoftWrap::Column(settings.preferred_line_length)
14074            }
14075            language_settings::SoftWrap::Bounded => {
14076                SoftWrap::Bounded(settings.preferred_line_length)
14077            }
14078        }
14079    }
14080
14081    pub fn set_soft_wrap_mode(
14082        &mut self,
14083        mode: language_settings::SoftWrap,
14084
14085        cx: &mut Context<Self>,
14086    ) {
14087        self.soft_wrap_mode_override = Some(mode);
14088        cx.notify();
14089    }
14090
14091    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14092        self.text_style_refinement = Some(style);
14093    }
14094
14095    /// called by the Element so we know what style we were most recently rendered with.
14096    pub(crate) fn set_style(
14097        &mut self,
14098        style: EditorStyle,
14099        window: &mut Window,
14100        cx: &mut Context<Self>,
14101    ) {
14102        let rem_size = window.rem_size();
14103        self.display_map.update(cx, |map, cx| {
14104            map.set_font(
14105                style.text.font(),
14106                style.text.font_size.to_pixels(rem_size),
14107                cx,
14108            )
14109        });
14110        self.style = Some(style);
14111    }
14112
14113    pub fn style(&self) -> Option<&EditorStyle> {
14114        self.style.as_ref()
14115    }
14116
14117    // Called by the element. This method is not designed to be called outside of the editor
14118    // element's layout code because it does not notify when rewrapping is computed synchronously.
14119    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14120        self.display_map
14121            .update(cx, |map, cx| map.set_wrap_width(width, cx))
14122    }
14123
14124    pub fn set_soft_wrap(&mut self) {
14125        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14126    }
14127
14128    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14129        if self.soft_wrap_mode_override.is_some() {
14130            self.soft_wrap_mode_override.take();
14131        } else {
14132            let soft_wrap = match self.soft_wrap_mode(cx) {
14133                SoftWrap::GitDiff => return,
14134                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14135                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14136                    language_settings::SoftWrap::None
14137                }
14138            };
14139            self.soft_wrap_mode_override = Some(soft_wrap);
14140        }
14141        cx.notify();
14142    }
14143
14144    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14145        let Some(workspace) = self.workspace() else {
14146            return;
14147        };
14148        let fs = workspace.read(cx).app_state().fs.clone();
14149        let current_show = TabBarSettings::get_global(cx).show;
14150        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14151            setting.show = Some(!current_show);
14152        });
14153    }
14154
14155    pub fn toggle_indent_guides(
14156        &mut self,
14157        _: &ToggleIndentGuides,
14158        _: &mut Window,
14159        cx: &mut Context<Self>,
14160    ) {
14161        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14162            self.buffer
14163                .read(cx)
14164                .language_settings(cx)
14165                .indent_guides
14166                .enabled
14167        });
14168        self.show_indent_guides = Some(!currently_enabled);
14169        cx.notify();
14170    }
14171
14172    fn should_show_indent_guides(&self) -> Option<bool> {
14173        self.show_indent_guides
14174    }
14175
14176    pub fn toggle_line_numbers(
14177        &mut self,
14178        _: &ToggleLineNumbers,
14179        _: &mut Window,
14180        cx: &mut Context<Self>,
14181    ) {
14182        let mut editor_settings = EditorSettings::get_global(cx).clone();
14183        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14184        EditorSettings::override_global(editor_settings, cx);
14185    }
14186
14187    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14188        self.use_relative_line_numbers
14189            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14190    }
14191
14192    pub fn toggle_relative_line_numbers(
14193        &mut self,
14194        _: &ToggleRelativeLineNumbers,
14195        _: &mut Window,
14196        cx: &mut Context<Self>,
14197    ) {
14198        let is_relative = self.should_use_relative_line_numbers(cx);
14199        self.set_relative_line_number(Some(!is_relative), cx)
14200    }
14201
14202    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14203        self.use_relative_line_numbers = is_relative;
14204        cx.notify();
14205    }
14206
14207    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14208        self.show_gutter = show_gutter;
14209        cx.notify();
14210    }
14211
14212    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14213        self.show_scrollbars = show_scrollbars;
14214        cx.notify();
14215    }
14216
14217    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14218        self.show_line_numbers = Some(show_line_numbers);
14219        cx.notify();
14220    }
14221
14222    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14223        self.show_git_diff_gutter = Some(show_git_diff_gutter);
14224        cx.notify();
14225    }
14226
14227    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14228        self.show_code_actions = Some(show_code_actions);
14229        cx.notify();
14230    }
14231
14232    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14233        self.show_runnables = Some(show_runnables);
14234        cx.notify();
14235    }
14236
14237    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14238        if self.display_map.read(cx).masked != masked {
14239            self.display_map.update(cx, |map, _| map.masked = masked);
14240        }
14241        cx.notify()
14242    }
14243
14244    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14245        self.show_wrap_guides = Some(show_wrap_guides);
14246        cx.notify();
14247    }
14248
14249    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14250        self.show_indent_guides = Some(show_indent_guides);
14251        cx.notify();
14252    }
14253
14254    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14255        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14256            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14257                if let Some(dir) = file.abs_path(cx).parent() {
14258                    return Some(dir.to_owned());
14259                }
14260            }
14261
14262            if let Some(project_path) = buffer.read(cx).project_path(cx) {
14263                return Some(project_path.path.to_path_buf());
14264            }
14265        }
14266
14267        None
14268    }
14269
14270    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14271        self.active_excerpt(cx)?
14272            .1
14273            .read(cx)
14274            .file()
14275            .and_then(|f| f.as_local())
14276    }
14277
14278    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14279        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14280            let buffer = buffer.read(cx);
14281            if let Some(project_path) = buffer.project_path(cx) {
14282                let project = self.project.as_ref()?.read(cx);
14283                project.absolute_path(&project_path, cx)
14284            } else {
14285                buffer
14286                    .file()
14287                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14288            }
14289        })
14290    }
14291
14292    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14293        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14294            let project_path = buffer.read(cx).project_path(cx)?;
14295            let project = self.project.as_ref()?.read(cx);
14296            let entry = project.entry_for_path(&project_path, cx)?;
14297            let path = entry.path.to_path_buf();
14298            Some(path)
14299        })
14300    }
14301
14302    pub fn reveal_in_finder(
14303        &mut self,
14304        _: &RevealInFileManager,
14305        _window: &mut Window,
14306        cx: &mut Context<Self>,
14307    ) {
14308        if let Some(target) = self.target_file(cx) {
14309            cx.reveal_path(&target.abs_path(cx));
14310        }
14311    }
14312
14313    pub fn copy_path(
14314        &mut self,
14315        _: &zed_actions::workspace::CopyPath,
14316        _window: &mut Window,
14317        cx: &mut Context<Self>,
14318    ) {
14319        if let Some(path) = self.target_file_abs_path(cx) {
14320            if let Some(path) = path.to_str() {
14321                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14322            }
14323        }
14324    }
14325
14326    pub fn copy_relative_path(
14327        &mut self,
14328        _: &zed_actions::workspace::CopyRelativePath,
14329        _window: &mut Window,
14330        cx: &mut Context<Self>,
14331    ) {
14332        if let Some(path) = self.target_file_path(cx) {
14333            if let Some(path) = path.to_str() {
14334                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14335            }
14336        }
14337    }
14338
14339    pub fn copy_file_name_without_extension(
14340        &mut self,
14341        _: &CopyFileNameWithoutExtension,
14342        _: &mut Window,
14343        cx: &mut Context<Self>,
14344    ) {
14345        if let Some(file) = self.target_file(cx) {
14346            if let Some(file_stem) = file.path().file_stem() {
14347                if let Some(name) = file_stem.to_str() {
14348                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14349                }
14350            }
14351        }
14352    }
14353
14354    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14355        if let Some(file) = self.target_file(cx) {
14356            if let Some(file_name) = file.path().file_name() {
14357                if let Some(name) = file_name.to_str() {
14358                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14359                }
14360            }
14361        }
14362    }
14363
14364    pub fn toggle_git_blame(
14365        &mut self,
14366        _: &ToggleGitBlame,
14367        window: &mut Window,
14368        cx: &mut Context<Self>,
14369    ) {
14370        self.show_git_blame_gutter = !self.show_git_blame_gutter;
14371
14372        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14373            self.start_git_blame(true, window, cx);
14374        }
14375
14376        cx.notify();
14377    }
14378
14379    pub fn toggle_git_blame_inline(
14380        &mut self,
14381        _: &ToggleGitBlameInline,
14382        window: &mut Window,
14383        cx: &mut Context<Self>,
14384    ) {
14385        self.toggle_git_blame_inline_internal(true, window, cx);
14386        cx.notify();
14387    }
14388
14389    pub fn git_blame_inline_enabled(&self) -> bool {
14390        self.git_blame_inline_enabled
14391    }
14392
14393    pub fn toggle_selection_menu(
14394        &mut self,
14395        _: &ToggleSelectionMenu,
14396        _: &mut Window,
14397        cx: &mut Context<Self>,
14398    ) {
14399        self.show_selection_menu = self
14400            .show_selection_menu
14401            .map(|show_selections_menu| !show_selections_menu)
14402            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14403
14404        cx.notify();
14405    }
14406
14407    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14408        self.show_selection_menu
14409            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14410    }
14411
14412    fn start_git_blame(
14413        &mut self,
14414        user_triggered: bool,
14415        window: &mut Window,
14416        cx: &mut Context<Self>,
14417    ) {
14418        if let Some(project) = self.project.as_ref() {
14419            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14420                return;
14421            };
14422
14423            if buffer.read(cx).file().is_none() {
14424                return;
14425            }
14426
14427            let focused = self.focus_handle(cx).contains_focused(window, cx);
14428
14429            let project = project.clone();
14430            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14431            self.blame_subscription =
14432                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14433            self.blame = Some(blame);
14434        }
14435    }
14436
14437    fn toggle_git_blame_inline_internal(
14438        &mut self,
14439        user_triggered: bool,
14440        window: &mut Window,
14441        cx: &mut Context<Self>,
14442    ) {
14443        if self.git_blame_inline_enabled {
14444            self.git_blame_inline_enabled = false;
14445            self.show_git_blame_inline = false;
14446            self.show_git_blame_inline_delay_task.take();
14447        } else {
14448            self.git_blame_inline_enabled = true;
14449            self.start_git_blame_inline(user_triggered, window, cx);
14450        }
14451
14452        cx.notify();
14453    }
14454
14455    fn start_git_blame_inline(
14456        &mut self,
14457        user_triggered: bool,
14458        window: &mut Window,
14459        cx: &mut Context<Self>,
14460    ) {
14461        self.start_git_blame(user_triggered, window, cx);
14462
14463        if ProjectSettings::get_global(cx)
14464            .git
14465            .inline_blame_delay()
14466            .is_some()
14467        {
14468            self.start_inline_blame_timer(window, cx);
14469        } else {
14470            self.show_git_blame_inline = true
14471        }
14472    }
14473
14474    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14475        self.blame.as_ref()
14476    }
14477
14478    pub fn show_git_blame_gutter(&self) -> bool {
14479        self.show_git_blame_gutter
14480    }
14481
14482    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14483        self.show_git_blame_gutter && self.has_blame_entries(cx)
14484    }
14485
14486    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14487        self.show_git_blame_inline
14488            && (self.focus_handle.is_focused(window)
14489                || self
14490                    .git_blame_inline_tooltip
14491                    .as_ref()
14492                    .and_then(|t| t.upgrade())
14493                    .is_some())
14494            && !self.newest_selection_head_on_empty_line(cx)
14495            && self.has_blame_entries(cx)
14496    }
14497
14498    fn has_blame_entries(&self, cx: &App) -> bool {
14499        self.blame()
14500            .map_or(false, |blame| blame.read(cx).has_generated_entries())
14501    }
14502
14503    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14504        let cursor_anchor = self.selections.newest_anchor().head();
14505
14506        let snapshot = self.buffer.read(cx).snapshot(cx);
14507        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14508
14509        snapshot.line_len(buffer_row) == 0
14510    }
14511
14512    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14513        let buffer_and_selection = maybe!({
14514            let selection = self.selections.newest::<Point>(cx);
14515            let selection_range = selection.range();
14516
14517            let multi_buffer = self.buffer().read(cx);
14518            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14519            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14520
14521            let (buffer, range, _) = if selection.reversed {
14522                buffer_ranges.first()
14523            } else {
14524                buffer_ranges.last()
14525            }?;
14526
14527            let selection = text::ToPoint::to_point(&range.start, &buffer).row
14528                ..text::ToPoint::to_point(&range.end, &buffer).row;
14529            Some((
14530                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14531                selection,
14532            ))
14533        });
14534
14535        let Some((buffer, selection)) = buffer_and_selection else {
14536            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14537        };
14538
14539        let Some(project) = self.project.as_ref() else {
14540            return Task::ready(Err(anyhow!("editor does not have project")));
14541        };
14542
14543        project.update(cx, |project, cx| {
14544            project.get_permalink_to_line(&buffer, selection, cx)
14545        })
14546    }
14547
14548    pub fn copy_permalink_to_line(
14549        &mut self,
14550        _: &CopyPermalinkToLine,
14551        window: &mut Window,
14552        cx: &mut Context<Self>,
14553    ) {
14554        let permalink_task = self.get_permalink_to_line(cx);
14555        let workspace = self.workspace();
14556
14557        cx.spawn_in(window, |_, mut cx| async move {
14558            match permalink_task.await {
14559                Ok(permalink) => {
14560                    cx.update(|_, cx| {
14561                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14562                    })
14563                    .ok();
14564                }
14565                Err(err) => {
14566                    let message = format!("Failed to copy permalink: {err}");
14567
14568                    Err::<(), anyhow::Error>(err).log_err();
14569
14570                    if let Some(workspace) = workspace {
14571                        workspace
14572                            .update_in(&mut cx, |workspace, _, cx| {
14573                                struct CopyPermalinkToLine;
14574
14575                                workspace.show_toast(
14576                                    Toast::new(
14577                                        NotificationId::unique::<CopyPermalinkToLine>(),
14578                                        message,
14579                                    ),
14580                                    cx,
14581                                )
14582                            })
14583                            .ok();
14584                    }
14585                }
14586            }
14587        })
14588        .detach();
14589    }
14590
14591    pub fn copy_file_location(
14592        &mut self,
14593        _: &CopyFileLocation,
14594        _: &mut Window,
14595        cx: &mut Context<Self>,
14596    ) {
14597        let selection = self.selections.newest::<Point>(cx).start.row + 1;
14598        if let Some(file) = self.target_file(cx) {
14599            if let Some(path) = file.path().to_str() {
14600                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14601            }
14602        }
14603    }
14604
14605    pub fn open_permalink_to_line(
14606        &mut self,
14607        _: &OpenPermalinkToLine,
14608        window: &mut Window,
14609        cx: &mut Context<Self>,
14610    ) {
14611        let permalink_task = self.get_permalink_to_line(cx);
14612        let workspace = self.workspace();
14613
14614        cx.spawn_in(window, |_, mut cx| async move {
14615            match permalink_task.await {
14616                Ok(permalink) => {
14617                    cx.update(|_, cx| {
14618                        cx.open_url(permalink.as_ref());
14619                    })
14620                    .ok();
14621                }
14622                Err(err) => {
14623                    let message = format!("Failed to open permalink: {err}");
14624
14625                    Err::<(), anyhow::Error>(err).log_err();
14626
14627                    if let Some(workspace) = workspace {
14628                        workspace
14629                            .update(&mut cx, |workspace, cx| {
14630                                struct OpenPermalinkToLine;
14631
14632                                workspace.show_toast(
14633                                    Toast::new(
14634                                        NotificationId::unique::<OpenPermalinkToLine>(),
14635                                        message,
14636                                    ),
14637                                    cx,
14638                                )
14639                            })
14640                            .ok();
14641                    }
14642                }
14643            }
14644        })
14645        .detach();
14646    }
14647
14648    pub fn insert_uuid_v4(
14649        &mut self,
14650        _: &InsertUuidV4,
14651        window: &mut Window,
14652        cx: &mut Context<Self>,
14653    ) {
14654        self.insert_uuid(UuidVersion::V4, window, cx);
14655    }
14656
14657    pub fn insert_uuid_v7(
14658        &mut self,
14659        _: &InsertUuidV7,
14660        window: &mut Window,
14661        cx: &mut Context<Self>,
14662    ) {
14663        self.insert_uuid(UuidVersion::V7, window, cx);
14664    }
14665
14666    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14667        self.transact(window, cx, |this, window, cx| {
14668            let edits = this
14669                .selections
14670                .all::<Point>(cx)
14671                .into_iter()
14672                .map(|selection| {
14673                    let uuid = match version {
14674                        UuidVersion::V4 => uuid::Uuid::new_v4(),
14675                        UuidVersion::V7 => uuid::Uuid::now_v7(),
14676                    };
14677
14678                    (selection.range(), uuid.to_string())
14679                });
14680            this.edit(edits, cx);
14681            this.refresh_inline_completion(true, false, window, cx);
14682        });
14683    }
14684
14685    pub fn open_selections_in_multibuffer(
14686        &mut self,
14687        _: &OpenSelectionsInMultibuffer,
14688        window: &mut Window,
14689        cx: &mut Context<Self>,
14690    ) {
14691        let multibuffer = self.buffer.read(cx);
14692
14693        let Some(buffer) = multibuffer.as_singleton() else {
14694            return;
14695        };
14696
14697        let Some(workspace) = self.workspace() else {
14698            return;
14699        };
14700
14701        let locations = self
14702            .selections
14703            .disjoint_anchors()
14704            .iter()
14705            .map(|range| Location {
14706                buffer: buffer.clone(),
14707                range: range.start.text_anchor..range.end.text_anchor,
14708            })
14709            .collect::<Vec<_>>();
14710
14711        let title = multibuffer.title(cx).to_string();
14712
14713        cx.spawn_in(window, |_, mut cx| async move {
14714            workspace.update_in(&mut cx, |workspace, window, cx| {
14715                Self::open_locations_in_multibuffer(
14716                    workspace,
14717                    locations,
14718                    format!("Selections for '{title}'"),
14719                    false,
14720                    MultibufferSelectionMode::All,
14721                    window,
14722                    cx,
14723                );
14724            })
14725        })
14726        .detach();
14727    }
14728
14729    /// Adds a row highlight for the given range. If a row has multiple highlights, the
14730    /// last highlight added will be used.
14731    ///
14732    /// If the range ends at the beginning of a line, then that line will not be highlighted.
14733    pub fn highlight_rows<T: 'static>(
14734        &mut self,
14735        range: Range<Anchor>,
14736        color: Hsla,
14737        should_autoscroll: bool,
14738        cx: &mut Context<Self>,
14739    ) {
14740        let snapshot = self.buffer().read(cx).snapshot(cx);
14741        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14742        let ix = row_highlights.binary_search_by(|highlight| {
14743            Ordering::Equal
14744                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14745                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14746        });
14747
14748        if let Err(mut ix) = ix {
14749            let index = post_inc(&mut self.highlight_order);
14750
14751            // If this range intersects with the preceding highlight, then merge it with
14752            // the preceding highlight. Otherwise insert a new highlight.
14753            let mut merged = false;
14754            if ix > 0 {
14755                let prev_highlight = &mut row_highlights[ix - 1];
14756                if prev_highlight
14757                    .range
14758                    .end
14759                    .cmp(&range.start, &snapshot)
14760                    .is_ge()
14761                {
14762                    ix -= 1;
14763                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14764                        prev_highlight.range.end = range.end;
14765                    }
14766                    merged = true;
14767                    prev_highlight.index = index;
14768                    prev_highlight.color = color;
14769                    prev_highlight.should_autoscroll = should_autoscroll;
14770                }
14771            }
14772
14773            if !merged {
14774                row_highlights.insert(
14775                    ix,
14776                    RowHighlight {
14777                        range: range.clone(),
14778                        index,
14779                        color,
14780                        should_autoscroll,
14781                    },
14782                );
14783            }
14784
14785            // If any of the following highlights intersect with this one, merge them.
14786            while let Some(next_highlight) = row_highlights.get(ix + 1) {
14787                let highlight = &row_highlights[ix];
14788                if next_highlight
14789                    .range
14790                    .start
14791                    .cmp(&highlight.range.end, &snapshot)
14792                    .is_le()
14793                {
14794                    if next_highlight
14795                        .range
14796                        .end
14797                        .cmp(&highlight.range.end, &snapshot)
14798                        .is_gt()
14799                    {
14800                        row_highlights[ix].range.end = next_highlight.range.end;
14801                    }
14802                    row_highlights.remove(ix + 1);
14803                } else {
14804                    break;
14805                }
14806            }
14807        }
14808    }
14809
14810    /// Remove any highlighted row ranges of the given type that intersect the
14811    /// given ranges.
14812    pub fn remove_highlighted_rows<T: 'static>(
14813        &mut self,
14814        ranges_to_remove: Vec<Range<Anchor>>,
14815        cx: &mut Context<Self>,
14816    ) {
14817        let snapshot = self.buffer().read(cx).snapshot(cx);
14818        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14819        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14820        row_highlights.retain(|highlight| {
14821            while let Some(range_to_remove) = ranges_to_remove.peek() {
14822                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14823                    Ordering::Less | Ordering::Equal => {
14824                        ranges_to_remove.next();
14825                    }
14826                    Ordering::Greater => {
14827                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14828                            Ordering::Less | Ordering::Equal => {
14829                                return false;
14830                            }
14831                            Ordering::Greater => break,
14832                        }
14833                    }
14834                }
14835            }
14836
14837            true
14838        })
14839    }
14840
14841    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14842    pub fn clear_row_highlights<T: 'static>(&mut self) {
14843        self.highlighted_rows.remove(&TypeId::of::<T>());
14844    }
14845
14846    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14847    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14848        self.highlighted_rows
14849            .get(&TypeId::of::<T>())
14850            .map_or(&[] as &[_], |vec| vec.as_slice())
14851            .iter()
14852            .map(|highlight| (highlight.range.clone(), highlight.color))
14853    }
14854
14855    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14856    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14857    /// Allows to ignore certain kinds of highlights.
14858    pub fn highlighted_display_rows(
14859        &self,
14860        window: &mut Window,
14861        cx: &mut App,
14862    ) -> BTreeMap<DisplayRow, Background> {
14863        let snapshot = self.snapshot(window, cx);
14864        let mut used_highlight_orders = HashMap::default();
14865        self.highlighted_rows
14866            .iter()
14867            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14868            .fold(
14869                BTreeMap::<DisplayRow, Background>::new(),
14870                |mut unique_rows, highlight| {
14871                    let start = highlight.range.start.to_display_point(&snapshot);
14872                    let end = highlight.range.end.to_display_point(&snapshot);
14873                    let start_row = start.row().0;
14874                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14875                        && end.column() == 0
14876                    {
14877                        end.row().0.saturating_sub(1)
14878                    } else {
14879                        end.row().0
14880                    };
14881                    for row in start_row..=end_row {
14882                        let used_index =
14883                            used_highlight_orders.entry(row).or_insert(highlight.index);
14884                        if highlight.index >= *used_index {
14885                            *used_index = highlight.index;
14886                            unique_rows.insert(DisplayRow(row), highlight.color.into());
14887                        }
14888                    }
14889                    unique_rows
14890                },
14891            )
14892    }
14893
14894    pub fn highlighted_display_row_for_autoscroll(
14895        &self,
14896        snapshot: &DisplaySnapshot,
14897    ) -> Option<DisplayRow> {
14898        self.highlighted_rows
14899            .values()
14900            .flat_map(|highlighted_rows| highlighted_rows.iter())
14901            .filter_map(|highlight| {
14902                if highlight.should_autoscroll {
14903                    Some(highlight.range.start.to_display_point(snapshot).row())
14904                } else {
14905                    None
14906                }
14907            })
14908            .min()
14909    }
14910
14911    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14912        self.highlight_background::<SearchWithinRange>(
14913            ranges,
14914            |colors| colors.editor_document_highlight_read_background,
14915            cx,
14916        )
14917    }
14918
14919    pub fn set_breadcrumb_header(&mut self, new_header: String) {
14920        self.breadcrumb_header = Some(new_header);
14921    }
14922
14923    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14924        self.clear_background_highlights::<SearchWithinRange>(cx);
14925    }
14926
14927    pub fn highlight_background<T: 'static>(
14928        &mut self,
14929        ranges: &[Range<Anchor>],
14930        color_fetcher: fn(&ThemeColors) -> Hsla,
14931        cx: &mut Context<Self>,
14932    ) {
14933        self.background_highlights
14934            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14935        self.scrollbar_marker_state.dirty = true;
14936        cx.notify();
14937    }
14938
14939    pub fn clear_background_highlights<T: 'static>(
14940        &mut self,
14941        cx: &mut Context<Self>,
14942    ) -> Option<BackgroundHighlight> {
14943        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14944        if !text_highlights.1.is_empty() {
14945            self.scrollbar_marker_state.dirty = true;
14946            cx.notify();
14947        }
14948        Some(text_highlights)
14949    }
14950
14951    pub fn highlight_gutter<T: 'static>(
14952        &mut self,
14953        ranges: &[Range<Anchor>],
14954        color_fetcher: fn(&App) -> Hsla,
14955        cx: &mut Context<Self>,
14956    ) {
14957        self.gutter_highlights
14958            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14959        cx.notify();
14960    }
14961
14962    pub fn clear_gutter_highlights<T: 'static>(
14963        &mut self,
14964        cx: &mut Context<Self>,
14965    ) -> Option<GutterHighlight> {
14966        cx.notify();
14967        self.gutter_highlights.remove(&TypeId::of::<T>())
14968    }
14969
14970    #[cfg(feature = "test-support")]
14971    pub fn all_text_background_highlights(
14972        &self,
14973        window: &mut Window,
14974        cx: &mut Context<Self>,
14975    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14976        let snapshot = self.snapshot(window, cx);
14977        let buffer = &snapshot.buffer_snapshot;
14978        let start = buffer.anchor_before(0);
14979        let end = buffer.anchor_after(buffer.len());
14980        let theme = cx.theme().colors();
14981        self.background_highlights_in_range(start..end, &snapshot, theme)
14982    }
14983
14984    #[cfg(feature = "test-support")]
14985    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14986        let snapshot = self.buffer().read(cx).snapshot(cx);
14987
14988        let highlights = self
14989            .background_highlights
14990            .get(&TypeId::of::<items::BufferSearchHighlights>());
14991
14992        if let Some((_color, ranges)) = highlights {
14993            ranges
14994                .iter()
14995                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14996                .collect_vec()
14997        } else {
14998            vec![]
14999        }
15000    }
15001
15002    fn document_highlights_for_position<'a>(
15003        &'a self,
15004        position: Anchor,
15005        buffer: &'a MultiBufferSnapshot,
15006    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
15007        let read_highlights = self
15008            .background_highlights
15009            .get(&TypeId::of::<DocumentHighlightRead>())
15010            .map(|h| &h.1);
15011        let write_highlights = self
15012            .background_highlights
15013            .get(&TypeId::of::<DocumentHighlightWrite>())
15014            .map(|h| &h.1);
15015        let left_position = position.bias_left(buffer);
15016        let right_position = position.bias_right(buffer);
15017        read_highlights
15018            .into_iter()
15019            .chain(write_highlights)
15020            .flat_map(move |ranges| {
15021                let start_ix = match ranges.binary_search_by(|probe| {
15022                    let cmp = probe.end.cmp(&left_position, buffer);
15023                    if cmp.is_ge() {
15024                        Ordering::Greater
15025                    } else {
15026                        Ordering::Less
15027                    }
15028                }) {
15029                    Ok(i) | Err(i) => i,
15030                };
15031
15032                ranges[start_ix..]
15033                    .iter()
15034                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
15035            })
15036    }
15037
15038    pub fn has_background_highlights<T: 'static>(&self) -> bool {
15039        self.background_highlights
15040            .get(&TypeId::of::<T>())
15041            .map_or(false, |(_, highlights)| !highlights.is_empty())
15042    }
15043
15044    pub fn background_highlights_in_range(
15045        &self,
15046        search_range: Range<Anchor>,
15047        display_snapshot: &DisplaySnapshot,
15048        theme: &ThemeColors,
15049    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15050        let mut results = Vec::new();
15051        for (color_fetcher, ranges) in self.background_highlights.values() {
15052            let color = color_fetcher(theme);
15053            let start_ix = match ranges.binary_search_by(|probe| {
15054                let cmp = probe
15055                    .end
15056                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15057                if cmp.is_gt() {
15058                    Ordering::Greater
15059                } else {
15060                    Ordering::Less
15061                }
15062            }) {
15063                Ok(i) | Err(i) => i,
15064            };
15065            for range in &ranges[start_ix..] {
15066                if range
15067                    .start
15068                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15069                    .is_ge()
15070                {
15071                    break;
15072                }
15073
15074                let start = range.start.to_display_point(display_snapshot);
15075                let end = range.end.to_display_point(display_snapshot);
15076                results.push((start..end, color))
15077            }
15078        }
15079        results
15080    }
15081
15082    pub fn background_highlight_row_ranges<T: 'static>(
15083        &self,
15084        search_range: Range<Anchor>,
15085        display_snapshot: &DisplaySnapshot,
15086        count: usize,
15087    ) -> Vec<RangeInclusive<DisplayPoint>> {
15088        let mut results = Vec::new();
15089        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15090            return vec![];
15091        };
15092
15093        let start_ix = match ranges.binary_search_by(|probe| {
15094            let cmp = probe
15095                .end
15096                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15097            if cmp.is_gt() {
15098                Ordering::Greater
15099            } else {
15100                Ordering::Less
15101            }
15102        }) {
15103            Ok(i) | Err(i) => i,
15104        };
15105        let mut push_region = |start: Option<Point>, end: Option<Point>| {
15106            if let (Some(start_display), Some(end_display)) = (start, end) {
15107                results.push(
15108                    start_display.to_display_point(display_snapshot)
15109                        ..=end_display.to_display_point(display_snapshot),
15110                );
15111            }
15112        };
15113        let mut start_row: Option<Point> = None;
15114        let mut end_row: Option<Point> = None;
15115        if ranges.len() > count {
15116            return Vec::new();
15117        }
15118        for range in &ranges[start_ix..] {
15119            if range
15120                .start
15121                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15122                .is_ge()
15123            {
15124                break;
15125            }
15126            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15127            if let Some(current_row) = &end_row {
15128                if end.row == current_row.row {
15129                    continue;
15130                }
15131            }
15132            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15133            if start_row.is_none() {
15134                assert_eq!(end_row, None);
15135                start_row = Some(start);
15136                end_row = Some(end);
15137                continue;
15138            }
15139            if let Some(current_end) = end_row.as_mut() {
15140                if start.row > current_end.row + 1 {
15141                    push_region(start_row, end_row);
15142                    start_row = Some(start);
15143                    end_row = Some(end);
15144                } else {
15145                    // Merge two hunks.
15146                    *current_end = end;
15147                }
15148            } else {
15149                unreachable!();
15150            }
15151        }
15152        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15153        push_region(start_row, end_row);
15154        results
15155    }
15156
15157    pub fn gutter_highlights_in_range(
15158        &self,
15159        search_range: Range<Anchor>,
15160        display_snapshot: &DisplaySnapshot,
15161        cx: &App,
15162    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15163        let mut results = Vec::new();
15164        for (color_fetcher, ranges) in self.gutter_highlights.values() {
15165            let color = color_fetcher(cx);
15166            let start_ix = match ranges.binary_search_by(|probe| {
15167                let cmp = probe
15168                    .end
15169                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15170                if cmp.is_gt() {
15171                    Ordering::Greater
15172                } else {
15173                    Ordering::Less
15174                }
15175            }) {
15176                Ok(i) | Err(i) => i,
15177            };
15178            for range in &ranges[start_ix..] {
15179                if range
15180                    .start
15181                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15182                    .is_ge()
15183                {
15184                    break;
15185                }
15186
15187                let start = range.start.to_display_point(display_snapshot);
15188                let end = range.end.to_display_point(display_snapshot);
15189                results.push((start..end, color))
15190            }
15191        }
15192        results
15193    }
15194
15195    /// Get the text ranges corresponding to the redaction query
15196    pub fn redacted_ranges(
15197        &self,
15198        search_range: Range<Anchor>,
15199        display_snapshot: &DisplaySnapshot,
15200        cx: &App,
15201    ) -> Vec<Range<DisplayPoint>> {
15202        display_snapshot
15203            .buffer_snapshot
15204            .redacted_ranges(search_range, |file| {
15205                if let Some(file) = file {
15206                    file.is_private()
15207                        && EditorSettings::get(
15208                            Some(SettingsLocation {
15209                                worktree_id: file.worktree_id(cx),
15210                                path: file.path().as_ref(),
15211                            }),
15212                            cx,
15213                        )
15214                        .redact_private_values
15215                } else {
15216                    false
15217                }
15218            })
15219            .map(|range| {
15220                range.start.to_display_point(display_snapshot)
15221                    ..range.end.to_display_point(display_snapshot)
15222            })
15223            .collect()
15224    }
15225
15226    pub fn highlight_text<T: 'static>(
15227        &mut self,
15228        ranges: Vec<Range<Anchor>>,
15229        style: HighlightStyle,
15230        cx: &mut Context<Self>,
15231    ) {
15232        self.display_map.update(cx, |map, _| {
15233            map.highlight_text(TypeId::of::<T>(), ranges, style)
15234        });
15235        cx.notify();
15236    }
15237
15238    pub(crate) fn highlight_inlays<T: 'static>(
15239        &mut self,
15240        highlights: Vec<InlayHighlight>,
15241        style: HighlightStyle,
15242        cx: &mut Context<Self>,
15243    ) {
15244        self.display_map.update(cx, |map, _| {
15245            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15246        });
15247        cx.notify();
15248    }
15249
15250    pub fn text_highlights<'a, T: 'static>(
15251        &'a self,
15252        cx: &'a App,
15253    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15254        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15255    }
15256
15257    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15258        let cleared = self
15259            .display_map
15260            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15261        if cleared {
15262            cx.notify();
15263        }
15264    }
15265
15266    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15267        (self.read_only(cx) || self.blink_manager.read(cx).visible())
15268            && self.focus_handle.is_focused(window)
15269    }
15270
15271    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15272        self.show_cursor_when_unfocused = is_enabled;
15273        cx.notify();
15274    }
15275
15276    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15277        cx.notify();
15278    }
15279
15280    fn on_buffer_event(
15281        &mut self,
15282        multibuffer: &Entity<MultiBuffer>,
15283        event: &multi_buffer::Event,
15284        window: &mut Window,
15285        cx: &mut Context<Self>,
15286    ) {
15287        match event {
15288            multi_buffer::Event::Edited {
15289                singleton_buffer_edited,
15290                edited_buffer: buffer_edited,
15291            } => {
15292                self.scrollbar_marker_state.dirty = true;
15293                self.active_indent_guides_state.dirty = true;
15294                self.refresh_active_diagnostics(cx);
15295                self.refresh_code_actions(window, cx);
15296                if self.has_active_inline_completion() {
15297                    self.update_visible_inline_completion(window, cx);
15298                }
15299                if let Some(buffer) = buffer_edited {
15300                    let buffer_id = buffer.read(cx).remote_id();
15301                    if !self.registered_buffers.contains_key(&buffer_id) {
15302                        if let Some(project) = self.project.as_ref() {
15303                            project.update(cx, |project, cx| {
15304                                self.registered_buffers.insert(
15305                                    buffer_id,
15306                                    project.register_buffer_with_language_servers(&buffer, cx),
15307                                );
15308                            })
15309                        }
15310                    }
15311                }
15312                cx.emit(EditorEvent::BufferEdited);
15313                cx.emit(SearchEvent::MatchesInvalidated);
15314                if *singleton_buffer_edited {
15315                    if let Some(project) = &self.project {
15316                        #[allow(clippy::mutable_key_type)]
15317                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15318                            multibuffer
15319                                .all_buffers()
15320                                .into_iter()
15321                                .filter_map(|buffer| {
15322                                    buffer.update(cx, |buffer, cx| {
15323                                        let language = buffer.language()?;
15324                                        let should_discard = project.update(cx, |project, cx| {
15325                                            project.is_local()
15326                                                && !project.has_language_servers_for(buffer, cx)
15327                                        });
15328                                        should_discard.not().then_some(language.clone())
15329                                    })
15330                                })
15331                                .collect::<HashSet<_>>()
15332                        });
15333                        if !languages_affected.is_empty() {
15334                            self.refresh_inlay_hints(
15335                                InlayHintRefreshReason::BufferEdited(languages_affected),
15336                                cx,
15337                            );
15338                        }
15339                    }
15340                }
15341
15342                let Some(project) = &self.project else { return };
15343                let (telemetry, is_via_ssh) = {
15344                    let project = project.read(cx);
15345                    let telemetry = project.client().telemetry().clone();
15346                    let is_via_ssh = project.is_via_ssh();
15347                    (telemetry, is_via_ssh)
15348                };
15349                refresh_linked_ranges(self, window, cx);
15350                telemetry.log_edit_event("editor", is_via_ssh);
15351            }
15352            multi_buffer::Event::ExcerptsAdded {
15353                buffer,
15354                predecessor,
15355                excerpts,
15356            } => {
15357                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15358                let buffer_id = buffer.read(cx).remote_id();
15359                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15360                    if let Some(project) = &self.project {
15361                        get_uncommitted_diff_for_buffer(
15362                            project,
15363                            [buffer.clone()],
15364                            self.buffer.clone(),
15365                            cx,
15366                        )
15367                        .detach();
15368                    }
15369                }
15370                cx.emit(EditorEvent::ExcerptsAdded {
15371                    buffer: buffer.clone(),
15372                    predecessor: *predecessor,
15373                    excerpts: excerpts.clone(),
15374                });
15375                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15376            }
15377            multi_buffer::Event::ExcerptsRemoved { ids } => {
15378                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15379                let buffer = self.buffer.read(cx);
15380                self.registered_buffers
15381                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15382                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15383            }
15384            multi_buffer::Event::ExcerptsEdited {
15385                excerpt_ids,
15386                buffer_ids,
15387            } => {
15388                self.display_map.update(cx, |map, cx| {
15389                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
15390                });
15391                cx.emit(EditorEvent::ExcerptsEdited {
15392                    ids: excerpt_ids.clone(),
15393                })
15394            }
15395            multi_buffer::Event::ExcerptsExpanded { ids } => {
15396                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15397                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15398            }
15399            multi_buffer::Event::Reparsed(buffer_id) => {
15400                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15401
15402                cx.emit(EditorEvent::Reparsed(*buffer_id));
15403            }
15404            multi_buffer::Event::DiffHunksToggled => {
15405                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15406            }
15407            multi_buffer::Event::LanguageChanged(buffer_id) => {
15408                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15409                cx.emit(EditorEvent::Reparsed(*buffer_id));
15410                cx.notify();
15411            }
15412            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15413            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15414            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15415                cx.emit(EditorEvent::TitleChanged)
15416            }
15417            // multi_buffer::Event::DiffBaseChanged => {
15418            //     self.scrollbar_marker_state.dirty = true;
15419            //     cx.emit(EditorEvent::DiffBaseChanged);
15420            //     cx.notify();
15421            // }
15422            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15423            multi_buffer::Event::DiagnosticsUpdated => {
15424                self.refresh_active_diagnostics(cx);
15425                self.refresh_inline_diagnostics(true, window, cx);
15426                self.scrollbar_marker_state.dirty = true;
15427                cx.notify();
15428            }
15429            _ => {}
15430        };
15431    }
15432
15433    fn on_display_map_changed(
15434        &mut self,
15435        _: Entity<DisplayMap>,
15436        _: &mut Window,
15437        cx: &mut Context<Self>,
15438    ) {
15439        cx.notify();
15440    }
15441
15442    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15443        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15444        self.update_edit_prediction_settings(cx);
15445        self.refresh_inline_completion(true, false, window, cx);
15446        self.refresh_inlay_hints(
15447            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15448                self.selections.newest_anchor().head(),
15449                &self.buffer.read(cx).snapshot(cx),
15450                cx,
15451            )),
15452            cx,
15453        );
15454
15455        let old_cursor_shape = self.cursor_shape;
15456
15457        {
15458            let editor_settings = EditorSettings::get_global(cx);
15459            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15460            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15461            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15462        }
15463
15464        if old_cursor_shape != self.cursor_shape {
15465            cx.emit(EditorEvent::CursorShapeChanged);
15466        }
15467
15468        let project_settings = ProjectSettings::get_global(cx);
15469        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15470
15471        if self.mode == EditorMode::Full {
15472            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15473            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15474            if self.show_inline_diagnostics != show_inline_diagnostics {
15475                self.show_inline_diagnostics = show_inline_diagnostics;
15476                self.refresh_inline_diagnostics(false, window, cx);
15477            }
15478
15479            if self.git_blame_inline_enabled != inline_blame_enabled {
15480                self.toggle_git_blame_inline_internal(false, window, cx);
15481            }
15482        }
15483
15484        cx.notify();
15485    }
15486
15487    pub fn set_searchable(&mut self, searchable: bool) {
15488        self.searchable = searchable;
15489    }
15490
15491    pub fn searchable(&self) -> bool {
15492        self.searchable
15493    }
15494
15495    fn open_proposed_changes_editor(
15496        &mut self,
15497        _: &OpenProposedChangesEditor,
15498        window: &mut Window,
15499        cx: &mut Context<Self>,
15500    ) {
15501        let Some(workspace) = self.workspace() else {
15502            cx.propagate();
15503            return;
15504        };
15505
15506        let selections = self.selections.all::<usize>(cx);
15507        let multi_buffer = self.buffer.read(cx);
15508        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15509        let mut new_selections_by_buffer = HashMap::default();
15510        for selection in selections {
15511            for (buffer, range, _) in
15512                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15513            {
15514                let mut range = range.to_point(buffer);
15515                range.start.column = 0;
15516                range.end.column = buffer.line_len(range.end.row);
15517                new_selections_by_buffer
15518                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15519                    .or_insert(Vec::new())
15520                    .push(range)
15521            }
15522        }
15523
15524        let proposed_changes_buffers = new_selections_by_buffer
15525            .into_iter()
15526            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15527            .collect::<Vec<_>>();
15528        let proposed_changes_editor = cx.new(|cx| {
15529            ProposedChangesEditor::new(
15530                "Proposed changes",
15531                proposed_changes_buffers,
15532                self.project.clone(),
15533                window,
15534                cx,
15535            )
15536        });
15537
15538        window.defer(cx, move |window, cx| {
15539            workspace.update(cx, |workspace, cx| {
15540                workspace.active_pane().update(cx, |pane, cx| {
15541                    pane.add_item(
15542                        Box::new(proposed_changes_editor),
15543                        true,
15544                        true,
15545                        None,
15546                        window,
15547                        cx,
15548                    );
15549                });
15550            });
15551        });
15552    }
15553
15554    pub fn open_excerpts_in_split(
15555        &mut self,
15556        _: &OpenExcerptsSplit,
15557        window: &mut Window,
15558        cx: &mut Context<Self>,
15559    ) {
15560        self.open_excerpts_common(None, true, window, cx)
15561    }
15562
15563    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15564        self.open_excerpts_common(None, false, window, cx)
15565    }
15566
15567    fn open_excerpts_common(
15568        &mut self,
15569        jump_data: Option<JumpData>,
15570        split: bool,
15571        window: &mut Window,
15572        cx: &mut Context<Self>,
15573    ) {
15574        let Some(workspace) = self.workspace() else {
15575            cx.propagate();
15576            return;
15577        };
15578
15579        if self.buffer.read(cx).is_singleton() {
15580            cx.propagate();
15581            return;
15582        }
15583
15584        let mut new_selections_by_buffer = HashMap::default();
15585        match &jump_data {
15586            Some(JumpData::MultiBufferPoint {
15587                excerpt_id,
15588                position,
15589                anchor,
15590                line_offset_from_top,
15591            }) => {
15592                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15593                if let Some(buffer) = multi_buffer_snapshot
15594                    .buffer_id_for_excerpt(*excerpt_id)
15595                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15596                {
15597                    let buffer_snapshot = buffer.read(cx).snapshot();
15598                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15599                        language::ToPoint::to_point(anchor, &buffer_snapshot)
15600                    } else {
15601                        buffer_snapshot.clip_point(*position, Bias::Left)
15602                    };
15603                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15604                    new_selections_by_buffer.insert(
15605                        buffer,
15606                        (
15607                            vec![jump_to_offset..jump_to_offset],
15608                            Some(*line_offset_from_top),
15609                        ),
15610                    );
15611                }
15612            }
15613            Some(JumpData::MultiBufferRow {
15614                row,
15615                line_offset_from_top,
15616            }) => {
15617                let point = MultiBufferPoint::new(row.0, 0);
15618                if let Some((buffer, buffer_point, _)) =
15619                    self.buffer.read(cx).point_to_buffer_point(point, cx)
15620                {
15621                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15622                    new_selections_by_buffer
15623                        .entry(buffer)
15624                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
15625                        .0
15626                        .push(buffer_offset..buffer_offset)
15627                }
15628            }
15629            None => {
15630                let selections = self.selections.all::<usize>(cx);
15631                let multi_buffer = self.buffer.read(cx);
15632                for selection in selections {
15633                    for (snapshot, range, _, anchor) in multi_buffer
15634                        .snapshot(cx)
15635                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15636                    {
15637                        if let Some(anchor) = anchor {
15638                            // selection is in a deleted hunk
15639                            let Some(buffer_id) = anchor.buffer_id else {
15640                                continue;
15641                            };
15642                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15643                                continue;
15644                            };
15645                            let offset = text::ToOffset::to_offset(
15646                                &anchor.text_anchor,
15647                                &buffer_handle.read(cx).snapshot(),
15648                            );
15649                            let range = offset..offset;
15650                            new_selections_by_buffer
15651                                .entry(buffer_handle)
15652                                .or_insert((Vec::new(), None))
15653                                .0
15654                                .push(range)
15655                        } else {
15656                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15657                            else {
15658                                continue;
15659                            };
15660                            new_selections_by_buffer
15661                                .entry(buffer_handle)
15662                                .or_insert((Vec::new(), None))
15663                                .0
15664                                .push(range)
15665                        }
15666                    }
15667                }
15668            }
15669        }
15670
15671        if new_selections_by_buffer.is_empty() {
15672            return;
15673        }
15674
15675        // We defer the pane interaction because we ourselves are a workspace item
15676        // and activating a new item causes the pane to call a method on us reentrantly,
15677        // which panics if we're on the stack.
15678        window.defer(cx, move |window, cx| {
15679            workspace.update(cx, |workspace, cx| {
15680                let pane = if split {
15681                    workspace.adjacent_pane(window, cx)
15682                } else {
15683                    workspace.active_pane().clone()
15684                };
15685
15686                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15687                    let editor = buffer
15688                        .read(cx)
15689                        .file()
15690                        .is_none()
15691                        .then(|| {
15692                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15693                            // so `workspace.open_project_item` will never find them, always opening a new editor.
15694                            // Instead, we try to activate the existing editor in the pane first.
15695                            let (editor, pane_item_index) =
15696                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
15697                                    let editor = item.downcast::<Editor>()?;
15698                                    let singleton_buffer =
15699                                        editor.read(cx).buffer().read(cx).as_singleton()?;
15700                                    if singleton_buffer == buffer {
15701                                        Some((editor, i))
15702                                    } else {
15703                                        None
15704                                    }
15705                                })?;
15706                            pane.update(cx, |pane, cx| {
15707                                pane.activate_item(pane_item_index, true, true, window, cx)
15708                            });
15709                            Some(editor)
15710                        })
15711                        .flatten()
15712                        .unwrap_or_else(|| {
15713                            workspace.open_project_item::<Self>(
15714                                pane.clone(),
15715                                buffer,
15716                                true,
15717                                true,
15718                                window,
15719                                cx,
15720                            )
15721                        });
15722
15723                    editor.update(cx, |editor, cx| {
15724                        let autoscroll = match scroll_offset {
15725                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15726                            None => Autoscroll::newest(),
15727                        };
15728                        let nav_history = editor.nav_history.take();
15729                        editor.change_selections(Some(autoscroll), window, cx, |s| {
15730                            s.select_ranges(ranges);
15731                        });
15732                        editor.nav_history = nav_history;
15733                    });
15734                }
15735            })
15736        });
15737    }
15738
15739    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15740        let snapshot = self.buffer.read(cx).read(cx);
15741        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15742        Some(
15743            ranges
15744                .iter()
15745                .map(move |range| {
15746                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15747                })
15748                .collect(),
15749        )
15750    }
15751
15752    fn selection_replacement_ranges(
15753        &self,
15754        range: Range<OffsetUtf16>,
15755        cx: &mut App,
15756    ) -> Vec<Range<OffsetUtf16>> {
15757        let selections = self.selections.all::<OffsetUtf16>(cx);
15758        let newest_selection = selections
15759            .iter()
15760            .max_by_key(|selection| selection.id)
15761            .unwrap();
15762        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15763        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15764        let snapshot = self.buffer.read(cx).read(cx);
15765        selections
15766            .into_iter()
15767            .map(|mut selection| {
15768                selection.start.0 =
15769                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
15770                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15771                snapshot.clip_offset_utf16(selection.start, Bias::Left)
15772                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15773            })
15774            .collect()
15775    }
15776
15777    fn report_editor_event(
15778        &self,
15779        event_type: &'static str,
15780        file_extension: Option<String>,
15781        cx: &App,
15782    ) {
15783        if cfg!(any(test, feature = "test-support")) {
15784            return;
15785        }
15786
15787        let Some(project) = &self.project else { return };
15788
15789        // If None, we are in a file without an extension
15790        let file = self
15791            .buffer
15792            .read(cx)
15793            .as_singleton()
15794            .and_then(|b| b.read(cx).file());
15795        let file_extension = file_extension.or(file
15796            .as_ref()
15797            .and_then(|file| Path::new(file.file_name(cx)).extension())
15798            .and_then(|e| e.to_str())
15799            .map(|a| a.to_string()));
15800
15801        let vim_mode = cx
15802            .global::<SettingsStore>()
15803            .raw_user_settings()
15804            .get("vim_mode")
15805            == Some(&serde_json::Value::Bool(true));
15806
15807        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15808        let copilot_enabled = edit_predictions_provider
15809            == language::language_settings::EditPredictionProvider::Copilot;
15810        let copilot_enabled_for_language = self
15811            .buffer
15812            .read(cx)
15813            .language_settings(cx)
15814            .show_edit_predictions;
15815
15816        let project = project.read(cx);
15817        telemetry::event!(
15818            event_type,
15819            file_extension,
15820            vim_mode,
15821            copilot_enabled,
15822            copilot_enabled_for_language,
15823            edit_predictions_provider,
15824            is_via_ssh = project.is_via_ssh(),
15825        );
15826    }
15827
15828    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15829    /// with each line being an array of {text, highlight} objects.
15830    fn copy_highlight_json(
15831        &mut self,
15832        _: &CopyHighlightJson,
15833        window: &mut Window,
15834        cx: &mut Context<Self>,
15835    ) {
15836        #[derive(Serialize)]
15837        struct Chunk<'a> {
15838            text: String,
15839            highlight: Option<&'a str>,
15840        }
15841
15842        let snapshot = self.buffer.read(cx).snapshot(cx);
15843        let range = self
15844            .selected_text_range(false, window, cx)
15845            .and_then(|selection| {
15846                if selection.range.is_empty() {
15847                    None
15848                } else {
15849                    Some(selection.range)
15850                }
15851            })
15852            .unwrap_or_else(|| 0..snapshot.len());
15853
15854        let chunks = snapshot.chunks(range, true);
15855        let mut lines = Vec::new();
15856        let mut line: VecDeque<Chunk> = VecDeque::new();
15857
15858        let Some(style) = self.style.as_ref() else {
15859            return;
15860        };
15861
15862        for chunk in chunks {
15863            let highlight = chunk
15864                .syntax_highlight_id
15865                .and_then(|id| id.name(&style.syntax));
15866            let mut chunk_lines = chunk.text.split('\n').peekable();
15867            while let Some(text) = chunk_lines.next() {
15868                let mut merged_with_last_token = false;
15869                if let Some(last_token) = line.back_mut() {
15870                    if last_token.highlight == highlight {
15871                        last_token.text.push_str(text);
15872                        merged_with_last_token = true;
15873                    }
15874                }
15875
15876                if !merged_with_last_token {
15877                    line.push_back(Chunk {
15878                        text: text.into(),
15879                        highlight,
15880                    });
15881                }
15882
15883                if chunk_lines.peek().is_some() {
15884                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
15885                        line.pop_front();
15886                    }
15887                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
15888                        line.pop_back();
15889                    }
15890
15891                    lines.push(mem::take(&mut line));
15892                }
15893            }
15894        }
15895
15896        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15897            return;
15898        };
15899        cx.write_to_clipboard(ClipboardItem::new_string(lines));
15900    }
15901
15902    pub fn open_context_menu(
15903        &mut self,
15904        _: &OpenContextMenu,
15905        window: &mut Window,
15906        cx: &mut Context<Self>,
15907    ) {
15908        self.request_autoscroll(Autoscroll::newest(), cx);
15909        let position = self.selections.newest_display(cx).start;
15910        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15911    }
15912
15913    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15914        &self.inlay_hint_cache
15915    }
15916
15917    pub fn replay_insert_event(
15918        &mut self,
15919        text: &str,
15920        relative_utf16_range: Option<Range<isize>>,
15921        window: &mut Window,
15922        cx: &mut Context<Self>,
15923    ) {
15924        if !self.input_enabled {
15925            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15926            return;
15927        }
15928        if let Some(relative_utf16_range) = relative_utf16_range {
15929            let selections = self.selections.all::<OffsetUtf16>(cx);
15930            self.change_selections(None, window, cx, |s| {
15931                let new_ranges = selections.into_iter().map(|range| {
15932                    let start = OffsetUtf16(
15933                        range
15934                            .head()
15935                            .0
15936                            .saturating_add_signed(relative_utf16_range.start),
15937                    );
15938                    let end = OffsetUtf16(
15939                        range
15940                            .head()
15941                            .0
15942                            .saturating_add_signed(relative_utf16_range.end),
15943                    );
15944                    start..end
15945                });
15946                s.select_ranges(new_ranges);
15947            });
15948        }
15949
15950        self.handle_input(text, window, cx);
15951    }
15952
15953    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15954        let Some(provider) = self.semantics_provider.as_ref() else {
15955            return false;
15956        };
15957
15958        let mut supports = false;
15959        self.buffer().update(cx, |this, cx| {
15960            this.for_each_buffer(|buffer| {
15961                supports |= provider.supports_inlay_hints(buffer, cx);
15962            });
15963        });
15964
15965        supports
15966    }
15967
15968    pub fn is_focused(&self, window: &Window) -> bool {
15969        self.focus_handle.is_focused(window)
15970    }
15971
15972    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15973        cx.emit(EditorEvent::Focused);
15974
15975        if let Some(descendant) = self
15976            .last_focused_descendant
15977            .take()
15978            .and_then(|descendant| descendant.upgrade())
15979        {
15980            window.focus(&descendant);
15981        } else {
15982            if let Some(blame) = self.blame.as_ref() {
15983                blame.update(cx, GitBlame::focus)
15984            }
15985
15986            self.blink_manager.update(cx, BlinkManager::enable);
15987            self.show_cursor_names(window, cx);
15988            self.buffer.update(cx, |buffer, cx| {
15989                buffer.finalize_last_transaction(cx);
15990                if self.leader_peer_id.is_none() {
15991                    buffer.set_active_selections(
15992                        &self.selections.disjoint_anchors(),
15993                        self.selections.line_mode,
15994                        self.cursor_shape,
15995                        cx,
15996                    );
15997                }
15998            });
15999        }
16000    }
16001
16002    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16003        cx.emit(EditorEvent::FocusedIn)
16004    }
16005
16006    fn handle_focus_out(
16007        &mut self,
16008        event: FocusOutEvent,
16009        _window: &mut Window,
16010        cx: &mut Context<Self>,
16011    ) {
16012        if event.blurred != self.focus_handle {
16013            self.last_focused_descendant = Some(event.blurred);
16014        }
16015        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
16016    }
16017
16018    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16019        self.blink_manager.update(cx, BlinkManager::disable);
16020        self.buffer
16021            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
16022
16023        if let Some(blame) = self.blame.as_ref() {
16024            blame.update(cx, GitBlame::blur)
16025        }
16026        if !self.hover_state.focused(window, cx) {
16027            hide_hover(self, cx);
16028        }
16029        if !self
16030            .context_menu
16031            .borrow()
16032            .as_ref()
16033            .is_some_and(|context_menu| context_menu.focused(window, cx))
16034        {
16035            self.hide_context_menu(window, cx);
16036        }
16037        self.discard_inline_completion(false, cx);
16038        cx.emit(EditorEvent::Blurred);
16039        cx.notify();
16040    }
16041
16042    pub fn register_action<A: Action>(
16043        &mut self,
16044        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
16045    ) -> Subscription {
16046        let id = self.next_editor_action_id.post_inc();
16047        let listener = Arc::new(listener);
16048        self.editor_actions.borrow_mut().insert(
16049            id,
16050            Box::new(move |window, _| {
16051                let listener = listener.clone();
16052                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
16053                    let action = action.downcast_ref().unwrap();
16054                    if phase == DispatchPhase::Bubble {
16055                        listener(action, window, cx)
16056                    }
16057                })
16058            }),
16059        );
16060
16061        let editor_actions = self.editor_actions.clone();
16062        Subscription::new(move || {
16063            editor_actions.borrow_mut().remove(&id);
16064        })
16065    }
16066
16067    pub fn file_header_size(&self) -> u32 {
16068        FILE_HEADER_HEIGHT
16069    }
16070
16071    pub fn restore(
16072        &mut self,
16073        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16074        window: &mut Window,
16075        cx: &mut Context<Self>,
16076    ) {
16077        let workspace = self.workspace();
16078        let project = self.project.as_ref();
16079        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16080            let mut tasks = Vec::new();
16081            for (buffer_id, changes) in revert_changes {
16082                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16083                    buffer.update(cx, |buffer, cx| {
16084                        buffer.edit(
16085                            changes
16086                                .into_iter()
16087                                .map(|(range, text)| (range, text.to_string())),
16088                            None,
16089                            cx,
16090                        );
16091                    });
16092
16093                    if let Some(project) =
16094                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16095                    {
16096                        project.update(cx, |project, cx| {
16097                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16098                        })
16099                    }
16100                }
16101            }
16102            tasks
16103        });
16104        cx.spawn_in(window, |_, mut cx| async move {
16105            for (buffer, task) in save_tasks {
16106                let result = task.await;
16107                if result.is_err() {
16108                    let Some(path) = buffer
16109                        .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16110                        .ok()
16111                    else {
16112                        continue;
16113                    };
16114                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16115                        let Some(task) = cx
16116                            .update_window_entity(&workspace, |workspace, window, cx| {
16117                                workspace
16118                                    .open_path_preview(path, None, false, false, false, window, cx)
16119                            })
16120                            .ok()
16121                        else {
16122                            continue;
16123                        };
16124                        task.await.log_err();
16125                    }
16126                }
16127            }
16128        })
16129        .detach();
16130        self.change_selections(None, window, cx, |selections| selections.refresh());
16131    }
16132
16133    pub fn to_pixel_point(
16134        &self,
16135        source: multi_buffer::Anchor,
16136        editor_snapshot: &EditorSnapshot,
16137        window: &mut Window,
16138    ) -> Option<gpui::Point<Pixels>> {
16139        let source_point = source.to_display_point(editor_snapshot);
16140        self.display_to_pixel_point(source_point, editor_snapshot, window)
16141    }
16142
16143    pub fn display_to_pixel_point(
16144        &self,
16145        source: DisplayPoint,
16146        editor_snapshot: &EditorSnapshot,
16147        window: &mut Window,
16148    ) -> Option<gpui::Point<Pixels>> {
16149        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16150        let text_layout_details = self.text_layout_details(window);
16151        let scroll_top = text_layout_details
16152            .scroll_anchor
16153            .scroll_position(editor_snapshot)
16154            .y;
16155
16156        if source.row().as_f32() < scroll_top.floor() {
16157            return None;
16158        }
16159        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16160        let source_y = line_height * (source.row().as_f32() - scroll_top);
16161        Some(gpui::Point::new(source_x, source_y))
16162    }
16163
16164    pub fn has_visible_completions_menu(&self) -> bool {
16165        !self.edit_prediction_preview_is_active()
16166            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16167                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16168            })
16169    }
16170
16171    pub fn register_addon<T: Addon>(&mut self, instance: T) {
16172        self.addons
16173            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16174    }
16175
16176    pub fn unregister_addon<T: Addon>(&mut self) {
16177        self.addons.remove(&std::any::TypeId::of::<T>());
16178    }
16179
16180    pub fn addon<T: Addon>(&self) -> Option<&T> {
16181        let type_id = std::any::TypeId::of::<T>();
16182        self.addons
16183            .get(&type_id)
16184            .and_then(|item| item.to_any().downcast_ref::<T>())
16185    }
16186
16187    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16188        let text_layout_details = self.text_layout_details(window);
16189        let style = &text_layout_details.editor_style;
16190        let font_id = window.text_system().resolve_font(&style.text.font());
16191        let font_size = style.text.font_size.to_pixels(window.rem_size());
16192        let line_height = style.text.line_height_in_pixels(window.rem_size());
16193        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16194
16195        gpui::Size::new(em_width, line_height)
16196    }
16197
16198    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16199        self.load_diff_task.clone()
16200    }
16201
16202    fn read_selections_from_db(
16203        &mut self,
16204        item_id: u64,
16205        workspace_id: WorkspaceId,
16206        window: &mut Window,
16207        cx: &mut Context<Editor>,
16208    ) {
16209        if !self.is_singleton(cx)
16210            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16211        {
16212            return;
16213        }
16214        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16215            return;
16216        };
16217        if selections.is_empty() {
16218            return;
16219        }
16220
16221        let snapshot = self.buffer.read(cx).snapshot(cx);
16222        self.change_selections(None, window, cx, |s| {
16223            s.select_ranges(selections.into_iter().map(|(start, end)| {
16224                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16225            }));
16226        });
16227    }
16228}
16229
16230fn insert_extra_newline_brackets(
16231    buffer: &MultiBufferSnapshot,
16232    range: Range<usize>,
16233    language: &language::LanguageScope,
16234) -> bool {
16235    let leading_whitespace_len = buffer
16236        .reversed_chars_at(range.start)
16237        .take_while(|c| c.is_whitespace() && *c != '\n')
16238        .map(|c| c.len_utf8())
16239        .sum::<usize>();
16240    let trailing_whitespace_len = buffer
16241        .chars_at(range.end)
16242        .take_while(|c| c.is_whitespace() && *c != '\n')
16243        .map(|c| c.len_utf8())
16244        .sum::<usize>();
16245    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16246
16247    language.brackets().any(|(pair, enabled)| {
16248        let pair_start = pair.start.trim_end();
16249        let pair_end = pair.end.trim_start();
16250
16251        enabled
16252            && pair.newline
16253            && buffer.contains_str_at(range.end, pair_end)
16254            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16255    })
16256}
16257
16258fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16259    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16260        [(buffer, range, _)] => (*buffer, range.clone()),
16261        _ => return false,
16262    };
16263    let pair = {
16264        let mut result: Option<BracketMatch> = None;
16265
16266        for pair in buffer
16267            .all_bracket_ranges(range.clone())
16268            .filter(move |pair| {
16269                pair.open_range.start <= range.start && pair.close_range.end >= range.end
16270            })
16271        {
16272            let len = pair.close_range.end - pair.open_range.start;
16273
16274            if let Some(existing) = &result {
16275                let existing_len = existing.close_range.end - existing.open_range.start;
16276                if len > existing_len {
16277                    continue;
16278                }
16279            }
16280
16281            result = Some(pair);
16282        }
16283
16284        result
16285    };
16286    let Some(pair) = pair else {
16287        return false;
16288    };
16289    pair.newline_only
16290        && buffer
16291            .chars_for_range(pair.open_range.end..range.start)
16292            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16293            .all(|c| c.is_whitespace() && c != '\n')
16294}
16295
16296fn get_uncommitted_diff_for_buffer(
16297    project: &Entity<Project>,
16298    buffers: impl IntoIterator<Item = Entity<Buffer>>,
16299    buffer: Entity<MultiBuffer>,
16300    cx: &mut App,
16301) -> Task<()> {
16302    let mut tasks = Vec::new();
16303    project.update(cx, |project, cx| {
16304        for buffer in buffers {
16305            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16306        }
16307    });
16308    cx.spawn(|mut cx| async move {
16309        let diffs = futures::future::join_all(tasks).await;
16310        buffer
16311            .update(&mut cx, |buffer, cx| {
16312                for diff in diffs.into_iter().flatten() {
16313                    buffer.add_diff(diff, cx);
16314                }
16315            })
16316            .ok();
16317    })
16318}
16319
16320fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16321    let tab_size = tab_size.get() as usize;
16322    let mut width = offset;
16323
16324    for ch in text.chars() {
16325        width += if ch == '\t' {
16326            tab_size - (width % tab_size)
16327        } else {
16328            1
16329        };
16330    }
16331
16332    width - offset
16333}
16334
16335#[cfg(test)]
16336mod tests {
16337    use super::*;
16338
16339    #[test]
16340    fn test_string_size_with_expanded_tabs() {
16341        let nz = |val| NonZeroU32::new(val).unwrap();
16342        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16343        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16344        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16345        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16346        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16347        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16348        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16349        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16350    }
16351}
16352
16353/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16354struct WordBreakingTokenizer<'a> {
16355    input: &'a str,
16356}
16357
16358impl<'a> WordBreakingTokenizer<'a> {
16359    fn new(input: &'a str) -> Self {
16360        Self { input }
16361    }
16362}
16363
16364fn is_char_ideographic(ch: char) -> bool {
16365    use unicode_script::Script::*;
16366    use unicode_script::UnicodeScript;
16367    matches!(ch.script(), Han | Tangut | Yi)
16368}
16369
16370fn is_grapheme_ideographic(text: &str) -> bool {
16371    text.chars().any(is_char_ideographic)
16372}
16373
16374fn is_grapheme_whitespace(text: &str) -> bool {
16375    text.chars().any(|x| x.is_whitespace())
16376}
16377
16378fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16379    text.chars().next().map_or(false, |ch| {
16380        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16381    })
16382}
16383
16384#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16385struct WordBreakToken<'a> {
16386    token: &'a str,
16387    grapheme_len: usize,
16388    is_whitespace: bool,
16389}
16390
16391impl<'a> Iterator for WordBreakingTokenizer<'a> {
16392    /// Yields a span, the count of graphemes in the token, and whether it was
16393    /// whitespace. Note that it also breaks at word boundaries.
16394    type Item = WordBreakToken<'a>;
16395
16396    fn next(&mut self) -> Option<Self::Item> {
16397        use unicode_segmentation::UnicodeSegmentation;
16398        if self.input.is_empty() {
16399            return None;
16400        }
16401
16402        let mut iter = self.input.graphemes(true).peekable();
16403        let mut offset = 0;
16404        let mut graphemes = 0;
16405        if let Some(first_grapheme) = iter.next() {
16406            let is_whitespace = is_grapheme_whitespace(first_grapheme);
16407            offset += first_grapheme.len();
16408            graphemes += 1;
16409            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16410                if let Some(grapheme) = iter.peek().copied() {
16411                    if should_stay_with_preceding_ideograph(grapheme) {
16412                        offset += grapheme.len();
16413                        graphemes += 1;
16414                    }
16415                }
16416            } else {
16417                let mut words = self.input[offset..].split_word_bound_indices().peekable();
16418                let mut next_word_bound = words.peek().copied();
16419                if next_word_bound.map_or(false, |(i, _)| i == 0) {
16420                    next_word_bound = words.next();
16421                }
16422                while let Some(grapheme) = iter.peek().copied() {
16423                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
16424                        break;
16425                    };
16426                    if is_grapheme_whitespace(grapheme) != is_whitespace {
16427                        break;
16428                    };
16429                    offset += grapheme.len();
16430                    graphemes += 1;
16431                    iter.next();
16432                }
16433            }
16434            let token = &self.input[..offset];
16435            self.input = &self.input[offset..];
16436            if is_whitespace {
16437                Some(WordBreakToken {
16438                    token: " ",
16439                    grapheme_len: 1,
16440                    is_whitespace: true,
16441                })
16442            } else {
16443                Some(WordBreakToken {
16444                    token,
16445                    grapheme_len: graphemes,
16446                    is_whitespace: false,
16447                })
16448            }
16449        } else {
16450            None
16451        }
16452    }
16453}
16454
16455#[test]
16456fn test_word_breaking_tokenizer() {
16457    let tests: &[(&str, &[(&str, usize, bool)])] = &[
16458        ("", &[]),
16459        ("  ", &[(" ", 1, true)]),
16460        ("Ʒ", &[("Ʒ", 1, false)]),
16461        ("Ǽ", &[("Ǽ", 1, false)]),
16462        ("", &[("", 1, false)]),
16463        ("⋑⋑", &[("⋑⋑", 2, false)]),
16464        (
16465            "原理,进而",
16466            &[
16467                ("", 1, false),
16468                ("理,", 2, false),
16469                ("", 1, false),
16470                ("", 1, false),
16471            ],
16472        ),
16473        (
16474            "hello world",
16475            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16476        ),
16477        (
16478            "hello, world",
16479            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16480        ),
16481        (
16482            "  hello world",
16483            &[
16484                (" ", 1, true),
16485                ("hello", 5, false),
16486                (" ", 1, true),
16487                ("world", 5, false),
16488            ],
16489        ),
16490        (
16491            "这是什么 \n 钢笔",
16492            &[
16493                ("", 1, false),
16494                ("", 1, false),
16495                ("", 1, false),
16496                ("", 1, false),
16497                (" ", 1, true),
16498                ("", 1, false),
16499                ("", 1, false),
16500            ],
16501        ),
16502        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16503    ];
16504
16505    for (input, result) in tests {
16506        assert_eq!(
16507            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16508            result
16509                .iter()
16510                .copied()
16511                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16512                    token,
16513                    grapheme_len,
16514                    is_whitespace,
16515                })
16516                .collect::<Vec<_>>()
16517        );
16518    }
16519}
16520
16521fn wrap_with_prefix(
16522    line_prefix: String,
16523    unwrapped_text: String,
16524    wrap_column: usize,
16525    tab_size: NonZeroU32,
16526) -> String {
16527    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16528    let mut wrapped_text = String::new();
16529    let mut current_line = line_prefix.clone();
16530
16531    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16532    let mut current_line_len = line_prefix_len;
16533    for WordBreakToken {
16534        token,
16535        grapheme_len,
16536        is_whitespace,
16537    } in tokenizer
16538    {
16539        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16540            wrapped_text.push_str(current_line.trim_end());
16541            wrapped_text.push('\n');
16542            current_line.truncate(line_prefix.len());
16543            current_line_len = line_prefix_len;
16544            if !is_whitespace {
16545                current_line.push_str(token);
16546                current_line_len += grapheme_len;
16547            }
16548        } else if !is_whitespace {
16549            current_line.push_str(token);
16550            current_line_len += grapheme_len;
16551        } else if current_line_len != line_prefix_len {
16552            current_line.push(' ');
16553            current_line_len += 1;
16554        }
16555    }
16556
16557    if !current_line.is_empty() {
16558        wrapped_text.push_str(&current_line);
16559    }
16560    wrapped_text
16561}
16562
16563#[test]
16564fn test_wrap_with_prefix() {
16565    assert_eq!(
16566        wrap_with_prefix(
16567            "# ".to_string(),
16568            "abcdefg".to_string(),
16569            4,
16570            NonZeroU32::new(4).unwrap()
16571        ),
16572        "# abcdefg"
16573    );
16574    assert_eq!(
16575        wrap_with_prefix(
16576            "".to_string(),
16577            "\thello world".to_string(),
16578            8,
16579            NonZeroU32::new(4).unwrap()
16580        ),
16581        "hello\nworld"
16582    );
16583    assert_eq!(
16584        wrap_with_prefix(
16585            "// ".to_string(),
16586            "xx \nyy zz aa bb cc".to_string(),
16587            12,
16588            NonZeroU32::new(4).unwrap()
16589        ),
16590        "// xx yy zz\n// aa bb cc"
16591    );
16592    assert_eq!(
16593        wrap_with_prefix(
16594            String::new(),
16595            "这是什么 \n 钢笔".to_string(),
16596            3,
16597            NonZeroU32::new(4).unwrap()
16598        ),
16599        "这是什\n么 钢\n"
16600    );
16601}
16602
16603pub trait CollaborationHub {
16604    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16605    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16606    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16607}
16608
16609impl CollaborationHub for Entity<Project> {
16610    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16611        self.read(cx).collaborators()
16612    }
16613
16614    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16615        self.read(cx).user_store().read(cx).participant_indices()
16616    }
16617
16618    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16619        let this = self.read(cx);
16620        let user_ids = this.collaborators().values().map(|c| c.user_id);
16621        this.user_store().read_with(cx, |user_store, cx| {
16622            user_store.participant_names(user_ids, cx)
16623        })
16624    }
16625}
16626
16627pub trait SemanticsProvider {
16628    fn hover(
16629        &self,
16630        buffer: &Entity<Buffer>,
16631        position: text::Anchor,
16632        cx: &mut App,
16633    ) -> Option<Task<Vec<project::Hover>>>;
16634
16635    fn inlay_hints(
16636        &self,
16637        buffer_handle: Entity<Buffer>,
16638        range: Range<text::Anchor>,
16639        cx: &mut App,
16640    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16641
16642    fn resolve_inlay_hint(
16643        &self,
16644        hint: InlayHint,
16645        buffer_handle: Entity<Buffer>,
16646        server_id: LanguageServerId,
16647        cx: &mut App,
16648    ) -> Option<Task<anyhow::Result<InlayHint>>>;
16649
16650    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16651
16652    fn document_highlights(
16653        &self,
16654        buffer: &Entity<Buffer>,
16655        position: text::Anchor,
16656        cx: &mut App,
16657    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16658
16659    fn definitions(
16660        &self,
16661        buffer: &Entity<Buffer>,
16662        position: text::Anchor,
16663        kind: GotoDefinitionKind,
16664        cx: &mut App,
16665    ) -> Option<Task<Result<Vec<LocationLink>>>>;
16666
16667    fn range_for_rename(
16668        &self,
16669        buffer: &Entity<Buffer>,
16670        position: text::Anchor,
16671        cx: &mut App,
16672    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16673
16674    fn perform_rename(
16675        &self,
16676        buffer: &Entity<Buffer>,
16677        position: text::Anchor,
16678        new_name: String,
16679        cx: &mut App,
16680    ) -> Option<Task<Result<ProjectTransaction>>>;
16681}
16682
16683pub trait CompletionProvider {
16684    fn completions(
16685        &self,
16686        buffer: &Entity<Buffer>,
16687        buffer_position: text::Anchor,
16688        trigger: CompletionContext,
16689        window: &mut Window,
16690        cx: &mut Context<Editor>,
16691    ) -> Task<Result<Vec<Completion>>>;
16692
16693    fn resolve_completions(
16694        &self,
16695        buffer: Entity<Buffer>,
16696        completion_indices: Vec<usize>,
16697        completions: Rc<RefCell<Box<[Completion]>>>,
16698        cx: &mut Context<Editor>,
16699    ) -> Task<Result<bool>>;
16700
16701    fn apply_additional_edits_for_completion(
16702        &self,
16703        _buffer: Entity<Buffer>,
16704        _completions: Rc<RefCell<Box<[Completion]>>>,
16705        _completion_index: usize,
16706        _push_to_history: bool,
16707        _cx: &mut Context<Editor>,
16708    ) -> Task<Result<Option<language::Transaction>>> {
16709        Task::ready(Ok(None))
16710    }
16711
16712    fn is_completion_trigger(
16713        &self,
16714        buffer: &Entity<Buffer>,
16715        position: language::Anchor,
16716        text: &str,
16717        trigger_in_words: bool,
16718        cx: &mut Context<Editor>,
16719    ) -> bool;
16720
16721    fn sort_completions(&self) -> bool {
16722        true
16723    }
16724}
16725
16726pub trait CodeActionProvider {
16727    fn id(&self) -> Arc<str>;
16728
16729    fn code_actions(
16730        &self,
16731        buffer: &Entity<Buffer>,
16732        range: Range<text::Anchor>,
16733        window: &mut Window,
16734        cx: &mut App,
16735    ) -> Task<Result<Vec<CodeAction>>>;
16736
16737    fn apply_code_action(
16738        &self,
16739        buffer_handle: Entity<Buffer>,
16740        action: CodeAction,
16741        excerpt_id: ExcerptId,
16742        push_to_history: bool,
16743        window: &mut Window,
16744        cx: &mut App,
16745    ) -> Task<Result<ProjectTransaction>>;
16746}
16747
16748impl CodeActionProvider for Entity<Project> {
16749    fn id(&self) -> Arc<str> {
16750        "project".into()
16751    }
16752
16753    fn code_actions(
16754        &self,
16755        buffer: &Entity<Buffer>,
16756        range: Range<text::Anchor>,
16757        _window: &mut Window,
16758        cx: &mut App,
16759    ) -> Task<Result<Vec<CodeAction>>> {
16760        self.update(cx, |project, cx| {
16761            project.code_actions(buffer, range, None, cx)
16762        })
16763    }
16764
16765    fn apply_code_action(
16766        &self,
16767        buffer_handle: Entity<Buffer>,
16768        action: CodeAction,
16769        _excerpt_id: ExcerptId,
16770        push_to_history: bool,
16771        _window: &mut Window,
16772        cx: &mut App,
16773    ) -> Task<Result<ProjectTransaction>> {
16774        self.update(cx, |project, cx| {
16775            project.apply_code_action(buffer_handle, action, push_to_history, cx)
16776        })
16777    }
16778}
16779
16780fn snippet_completions(
16781    project: &Project,
16782    buffer: &Entity<Buffer>,
16783    buffer_position: text::Anchor,
16784    cx: &mut App,
16785) -> Task<Result<Vec<Completion>>> {
16786    let language = buffer.read(cx).language_at(buffer_position);
16787    let language_name = language.as_ref().map(|language| language.lsp_id());
16788    let snippet_store = project.snippets().read(cx);
16789    let snippets = snippet_store.snippets_for(language_name, cx);
16790
16791    if snippets.is_empty() {
16792        return Task::ready(Ok(vec![]));
16793    }
16794    let snapshot = buffer.read(cx).text_snapshot();
16795    let chars: String = snapshot
16796        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16797        .collect();
16798
16799    let scope = language.map(|language| language.default_scope());
16800    let executor = cx.background_executor().clone();
16801
16802    cx.background_spawn(async move {
16803        let classifier = CharClassifier::new(scope).for_completion(true);
16804        let mut last_word = chars
16805            .chars()
16806            .take_while(|c| classifier.is_word(*c))
16807            .collect::<String>();
16808        last_word = last_word.chars().rev().collect();
16809
16810        if last_word.is_empty() {
16811            return Ok(vec![]);
16812        }
16813
16814        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16815        let to_lsp = |point: &text::Anchor| {
16816            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16817            point_to_lsp(end)
16818        };
16819        let lsp_end = to_lsp(&buffer_position);
16820
16821        let candidates = snippets
16822            .iter()
16823            .enumerate()
16824            .flat_map(|(ix, snippet)| {
16825                snippet
16826                    .prefix
16827                    .iter()
16828                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16829            })
16830            .collect::<Vec<StringMatchCandidate>>();
16831
16832        let mut matches = fuzzy::match_strings(
16833            &candidates,
16834            &last_word,
16835            last_word.chars().any(|c| c.is_uppercase()),
16836            100,
16837            &Default::default(),
16838            executor,
16839        )
16840        .await;
16841
16842        // Remove all candidates where the query's start does not match the start of any word in the candidate
16843        if let Some(query_start) = last_word.chars().next() {
16844            matches.retain(|string_match| {
16845                split_words(&string_match.string).any(|word| {
16846                    // Check that the first codepoint of the word as lowercase matches the first
16847                    // codepoint of the query as lowercase
16848                    word.chars()
16849                        .flat_map(|codepoint| codepoint.to_lowercase())
16850                        .zip(query_start.to_lowercase())
16851                        .all(|(word_cp, query_cp)| word_cp == query_cp)
16852                })
16853            });
16854        }
16855
16856        let matched_strings = matches
16857            .into_iter()
16858            .map(|m| m.string)
16859            .collect::<HashSet<_>>();
16860
16861        let result: Vec<Completion> = snippets
16862            .into_iter()
16863            .filter_map(|snippet| {
16864                let matching_prefix = snippet
16865                    .prefix
16866                    .iter()
16867                    .find(|prefix| matched_strings.contains(*prefix))?;
16868                let start = as_offset - last_word.len();
16869                let start = snapshot.anchor_before(start);
16870                let range = start..buffer_position;
16871                let lsp_start = to_lsp(&start);
16872                let lsp_range = lsp::Range {
16873                    start: lsp_start,
16874                    end: lsp_end,
16875                };
16876                Some(Completion {
16877                    old_range: range,
16878                    new_text: snippet.body.clone(),
16879                    resolved: false,
16880                    label: CodeLabel {
16881                        text: matching_prefix.clone(),
16882                        runs: vec![],
16883                        filter_range: 0..matching_prefix.len(),
16884                    },
16885                    server_id: LanguageServerId(usize::MAX),
16886                    documentation: snippet
16887                        .description
16888                        .clone()
16889                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
16890                    lsp_completion: lsp::CompletionItem {
16891                        label: snippet.prefix.first().unwrap().clone(),
16892                        kind: Some(CompletionItemKind::SNIPPET),
16893                        label_details: snippet.description.as_ref().map(|description| {
16894                            lsp::CompletionItemLabelDetails {
16895                                detail: Some(description.clone()),
16896                                description: None,
16897                            }
16898                        }),
16899                        insert_text_format: Some(InsertTextFormat::SNIPPET),
16900                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16901                            lsp::InsertReplaceEdit {
16902                                new_text: snippet.body.clone(),
16903                                insert: lsp_range,
16904                                replace: lsp_range,
16905                            },
16906                        )),
16907                        filter_text: Some(snippet.body.clone()),
16908                        sort_text: Some(char::MAX.to_string()),
16909                        ..Default::default()
16910                    },
16911                    confirm: None,
16912                })
16913            })
16914            .collect();
16915
16916        Ok(result)
16917    })
16918}
16919
16920impl CompletionProvider for Entity<Project> {
16921    fn completions(
16922        &self,
16923        buffer: &Entity<Buffer>,
16924        buffer_position: text::Anchor,
16925        options: CompletionContext,
16926        _window: &mut Window,
16927        cx: &mut Context<Editor>,
16928    ) -> Task<Result<Vec<Completion>>> {
16929        self.update(cx, |project, cx| {
16930            let snippets = snippet_completions(project, buffer, buffer_position, cx);
16931            let project_completions = project.completions(buffer, buffer_position, options, cx);
16932            cx.background_spawn(async move {
16933                let mut completions = project_completions.await?;
16934                let snippets_completions = snippets.await?;
16935                completions.extend(snippets_completions);
16936                Ok(completions)
16937            })
16938        })
16939    }
16940
16941    fn resolve_completions(
16942        &self,
16943        buffer: Entity<Buffer>,
16944        completion_indices: Vec<usize>,
16945        completions: Rc<RefCell<Box<[Completion]>>>,
16946        cx: &mut Context<Editor>,
16947    ) -> Task<Result<bool>> {
16948        self.update(cx, |project, cx| {
16949            project.lsp_store().update(cx, |lsp_store, cx| {
16950                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16951            })
16952        })
16953    }
16954
16955    fn apply_additional_edits_for_completion(
16956        &self,
16957        buffer: Entity<Buffer>,
16958        completions: Rc<RefCell<Box<[Completion]>>>,
16959        completion_index: usize,
16960        push_to_history: bool,
16961        cx: &mut Context<Editor>,
16962    ) -> Task<Result<Option<language::Transaction>>> {
16963        self.update(cx, |project, cx| {
16964            project.lsp_store().update(cx, |lsp_store, cx| {
16965                lsp_store.apply_additional_edits_for_completion(
16966                    buffer,
16967                    completions,
16968                    completion_index,
16969                    push_to_history,
16970                    cx,
16971                )
16972            })
16973        })
16974    }
16975
16976    fn is_completion_trigger(
16977        &self,
16978        buffer: &Entity<Buffer>,
16979        position: language::Anchor,
16980        text: &str,
16981        trigger_in_words: bool,
16982        cx: &mut Context<Editor>,
16983    ) -> bool {
16984        let mut chars = text.chars();
16985        let char = if let Some(char) = chars.next() {
16986            char
16987        } else {
16988            return false;
16989        };
16990        if chars.next().is_some() {
16991            return false;
16992        }
16993
16994        let buffer = buffer.read(cx);
16995        let snapshot = buffer.snapshot();
16996        if !snapshot.settings_at(position, cx).show_completions_on_input {
16997            return false;
16998        }
16999        let classifier = snapshot.char_classifier_at(position).for_completion(true);
17000        if trigger_in_words && classifier.is_word(char) {
17001            return true;
17002        }
17003
17004        buffer.completion_triggers().contains(text)
17005    }
17006}
17007
17008impl SemanticsProvider for Entity<Project> {
17009    fn hover(
17010        &self,
17011        buffer: &Entity<Buffer>,
17012        position: text::Anchor,
17013        cx: &mut App,
17014    ) -> Option<Task<Vec<project::Hover>>> {
17015        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
17016    }
17017
17018    fn document_highlights(
17019        &self,
17020        buffer: &Entity<Buffer>,
17021        position: text::Anchor,
17022        cx: &mut App,
17023    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
17024        Some(self.update(cx, |project, cx| {
17025            project.document_highlights(buffer, position, cx)
17026        }))
17027    }
17028
17029    fn definitions(
17030        &self,
17031        buffer: &Entity<Buffer>,
17032        position: text::Anchor,
17033        kind: GotoDefinitionKind,
17034        cx: &mut App,
17035    ) -> Option<Task<Result<Vec<LocationLink>>>> {
17036        Some(self.update(cx, |project, cx| match kind {
17037            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
17038            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
17039            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
17040            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
17041        }))
17042    }
17043
17044    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
17045        // TODO: make this work for remote projects
17046        self.update(cx, |this, cx| {
17047            buffer.update(cx, |buffer, cx| {
17048                this.any_language_server_supports_inlay_hints(buffer, cx)
17049            })
17050        })
17051    }
17052
17053    fn inlay_hints(
17054        &self,
17055        buffer_handle: Entity<Buffer>,
17056        range: Range<text::Anchor>,
17057        cx: &mut App,
17058    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
17059        Some(self.update(cx, |project, cx| {
17060            project.inlay_hints(buffer_handle, range, cx)
17061        }))
17062    }
17063
17064    fn resolve_inlay_hint(
17065        &self,
17066        hint: InlayHint,
17067        buffer_handle: Entity<Buffer>,
17068        server_id: LanguageServerId,
17069        cx: &mut App,
17070    ) -> Option<Task<anyhow::Result<InlayHint>>> {
17071        Some(self.update(cx, |project, cx| {
17072            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
17073        }))
17074    }
17075
17076    fn range_for_rename(
17077        &self,
17078        buffer: &Entity<Buffer>,
17079        position: text::Anchor,
17080        cx: &mut App,
17081    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17082        Some(self.update(cx, |project, cx| {
17083            let buffer = buffer.clone();
17084            let task = project.prepare_rename(buffer.clone(), position, cx);
17085            cx.spawn(|_, mut cx| async move {
17086                Ok(match task.await? {
17087                    PrepareRenameResponse::Success(range) => Some(range),
17088                    PrepareRenameResponse::InvalidPosition => None,
17089                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17090                        // Fallback on using TreeSitter info to determine identifier range
17091                        buffer.update(&mut cx, |buffer, _| {
17092                            let snapshot = buffer.snapshot();
17093                            let (range, kind) = snapshot.surrounding_word(position);
17094                            if kind != Some(CharKind::Word) {
17095                                return None;
17096                            }
17097                            Some(
17098                                snapshot.anchor_before(range.start)
17099                                    ..snapshot.anchor_after(range.end),
17100                            )
17101                        })?
17102                    }
17103                })
17104            })
17105        }))
17106    }
17107
17108    fn perform_rename(
17109        &self,
17110        buffer: &Entity<Buffer>,
17111        position: text::Anchor,
17112        new_name: String,
17113        cx: &mut App,
17114    ) -> Option<Task<Result<ProjectTransaction>>> {
17115        Some(self.update(cx, |project, cx| {
17116            project.perform_rename(buffer.clone(), position, new_name, cx)
17117        }))
17118    }
17119}
17120
17121fn inlay_hint_settings(
17122    location: Anchor,
17123    snapshot: &MultiBufferSnapshot,
17124    cx: &mut Context<Editor>,
17125) -> InlayHintSettings {
17126    let file = snapshot.file_at(location);
17127    let language = snapshot.language_at(location).map(|l| l.name());
17128    language_settings(language, file, cx).inlay_hints
17129}
17130
17131fn consume_contiguous_rows(
17132    contiguous_row_selections: &mut Vec<Selection<Point>>,
17133    selection: &Selection<Point>,
17134    display_map: &DisplaySnapshot,
17135    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17136) -> (MultiBufferRow, MultiBufferRow) {
17137    contiguous_row_selections.push(selection.clone());
17138    let start_row = MultiBufferRow(selection.start.row);
17139    let mut end_row = ending_row(selection, display_map);
17140
17141    while let Some(next_selection) = selections.peek() {
17142        if next_selection.start.row <= end_row.0 {
17143            end_row = ending_row(next_selection, display_map);
17144            contiguous_row_selections.push(selections.next().unwrap().clone());
17145        } else {
17146            break;
17147        }
17148    }
17149    (start_row, end_row)
17150}
17151
17152fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17153    if next_selection.end.column > 0 || next_selection.is_empty() {
17154        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17155    } else {
17156        MultiBufferRow(next_selection.end.row)
17157    }
17158}
17159
17160impl EditorSnapshot {
17161    pub fn remote_selections_in_range<'a>(
17162        &'a self,
17163        range: &'a Range<Anchor>,
17164        collaboration_hub: &dyn CollaborationHub,
17165        cx: &'a App,
17166    ) -> impl 'a + Iterator<Item = RemoteSelection> {
17167        let participant_names = collaboration_hub.user_names(cx);
17168        let participant_indices = collaboration_hub.user_participant_indices(cx);
17169        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17170        let collaborators_by_replica_id = collaborators_by_peer_id
17171            .iter()
17172            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17173            .collect::<HashMap<_, _>>();
17174        self.buffer_snapshot
17175            .selections_in_range(range, false)
17176            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17177                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17178                let participant_index = participant_indices.get(&collaborator.user_id).copied();
17179                let user_name = participant_names.get(&collaborator.user_id).cloned();
17180                Some(RemoteSelection {
17181                    replica_id,
17182                    selection,
17183                    cursor_shape,
17184                    line_mode,
17185                    participant_index,
17186                    peer_id: collaborator.peer_id,
17187                    user_name,
17188                })
17189            })
17190    }
17191
17192    pub fn hunks_for_ranges(
17193        &self,
17194        ranges: impl IntoIterator<Item = Range<Point>>,
17195    ) -> Vec<MultiBufferDiffHunk> {
17196        let mut hunks = Vec::new();
17197        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17198            HashMap::default();
17199        for query_range in ranges {
17200            let query_rows =
17201                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17202            for hunk in self.buffer_snapshot.diff_hunks_in_range(
17203                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17204            ) {
17205                // Include deleted hunks that are adjacent to the query range, because
17206                // otherwise they would be missed.
17207                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
17208                if hunk.status().is_deleted() {
17209                    intersects_range |= hunk.row_range.start == query_rows.end;
17210                    intersects_range |= hunk.row_range.end == query_rows.start;
17211                }
17212                if intersects_range {
17213                    if !processed_buffer_rows
17214                        .entry(hunk.buffer_id)
17215                        .or_default()
17216                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17217                    {
17218                        continue;
17219                    }
17220                    hunks.push(hunk);
17221                }
17222            }
17223        }
17224
17225        hunks
17226    }
17227
17228    fn display_diff_hunks_for_rows<'a>(
17229        &'a self,
17230        display_rows: Range<DisplayRow>,
17231        folded_buffers: &'a HashSet<BufferId>,
17232    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17233        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17234        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17235
17236        self.buffer_snapshot
17237            .diff_hunks_in_range(buffer_start..buffer_end)
17238            .filter_map(|hunk| {
17239                if folded_buffers.contains(&hunk.buffer_id) {
17240                    return None;
17241                }
17242
17243                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17244                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17245
17246                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17247                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17248
17249                let display_hunk = if hunk_display_start.column() != 0 {
17250                    DisplayDiffHunk::Folded {
17251                        display_row: hunk_display_start.row(),
17252                    }
17253                } else {
17254                    let mut end_row = hunk_display_end.row();
17255                    if hunk_display_end.column() > 0 {
17256                        end_row.0 += 1;
17257                    }
17258                    DisplayDiffHunk::Unfolded {
17259                        status: hunk.status(),
17260                        diff_base_byte_range: hunk.diff_base_byte_range,
17261                        display_row_range: hunk_display_start.row()..end_row,
17262                        multi_buffer_range: Anchor::range_in_buffer(
17263                            hunk.excerpt_id,
17264                            hunk.buffer_id,
17265                            hunk.buffer_range,
17266                        ),
17267                    }
17268                };
17269
17270                Some(display_hunk)
17271            })
17272    }
17273
17274    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17275        self.display_snapshot.buffer_snapshot.language_at(position)
17276    }
17277
17278    pub fn is_focused(&self) -> bool {
17279        self.is_focused
17280    }
17281
17282    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17283        self.placeholder_text.as_ref()
17284    }
17285
17286    pub fn scroll_position(&self) -> gpui::Point<f32> {
17287        self.scroll_anchor.scroll_position(&self.display_snapshot)
17288    }
17289
17290    fn gutter_dimensions(
17291        &self,
17292        font_id: FontId,
17293        font_size: Pixels,
17294        max_line_number_width: Pixels,
17295        cx: &App,
17296    ) -> Option<GutterDimensions> {
17297        if !self.show_gutter {
17298            return None;
17299        }
17300
17301        let descent = cx.text_system().descent(font_id, font_size);
17302        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17303        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17304
17305        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17306            matches!(
17307                ProjectSettings::get_global(cx).git.git_gutter,
17308                Some(GitGutterSetting::TrackedFiles)
17309            )
17310        });
17311        let gutter_settings = EditorSettings::get_global(cx).gutter;
17312        let show_line_numbers = self
17313            .show_line_numbers
17314            .unwrap_or(gutter_settings.line_numbers);
17315        let line_gutter_width = if show_line_numbers {
17316            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17317            let min_width_for_number_on_gutter = em_advance * 4.0;
17318            max_line_number_width.max(min_width_for_number_on_gutter)
17319        } else {
17320            0.0.into()
17321        };
17322
17323        let show_code_actions = self
17324            .show_code_actions
17325            .unwrap_or(gutter_settings.code_actions);
17326
17327        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17328
17329        let git_blame_entries_width =
17330            self.git_blame_gutter_max_author_length
17331                .map(|max_author_length| {
17332                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17333
17334                    /// The number of characters to dedicate to gaps and margins.
17335                    const SPACING_WIDTH: usize = 4;
17336
17337                    let max_char_count = max_author_length
17338                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17339                        + ::git::SHORT_SHA_LENGTH
17340                        + MAX_RELATIVE_TIMESTAMP.len()
17341                        + SPACING_WIDTH;
17342
17343                    em_advance * max_char_count
17344                });
17345
17346        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17347        left_padding += if show_code_actions || show_runnables {
17348            em_width * 3.0
17349        } else if show_git_gutter && show_line_numbers {
17350            em_width * 2.0
17351        } else if show_git_gutter || show_line_numbers {
17352            em_width
17353        } else {
17354            px(0.)
17355        };
17356
17357        let right_padding = if gutter_settings.folds && show_line_numbers {
17358            em_width * 4.0
17359        } else if gutter_settings.folds {
17360            em_width * 3.0
17361        } else if show_line_numbers {
17362            em_width
17363        } else {
17364            px(0.)
17365        };
17366
17367        Some(GutterDimensions {
17368            left_padding,
17369            right_padding,
17370            width: line_gutter_width + left_padding + right_padding,
17371            margin: -descent,
17372            git_blame_entries_width,
17373        })
17374    }
17375
17376    pub fn render_crease_toggle(
17377        &self,
17378        buffer_row: MultiBufferRow,
17379        row_contains_cursor: bool,
17380        editor: Entity<Editor>,
17381        window: &mut Window,
17382        cx: &mut App,
17383    ) -> Option<AnyElement> {
17384        let folded = self.is_line_folded(buffer_row);
17385        let mut is_foldable = false;
17386
17387        if let Some(crease) = self
17388            .crease_snapshot
17389            .query_row(buffer_row, &self.buffer_snapshot)
17390        {
17391            is_foldable = true;
17392            match crease {
17393                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17394                    if let Some(render_toggle) = render_toggle {
17395                        let toggle_callback =
17396                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17397                                if folded {
17398                                    editor.update(cx, |editor, cx| {
17399                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17400                                    });
17401                                } else {
17402                                    editor.update(cx, |editor, cx| {
17403                                        editor.unfold_at(
17404                                            &crate::UnfoldAt { buffer_row },
17405                                            window,
17406                                            cx,
17407                                        )
17408                                    });
17409                                }
17410                            });
17411                        return Some((render_toggle)(
17412                            buffer_row,
17413                            folded,
17414                            toggle_callback,
17415                            window,
17416                            cx,
17417                        ));
17418                    }
17419                }
17420            }
17421        }
17422
17423        is_foldable |= self.starts_indent(buffer_row);
17424
17425        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17426            Some(
17427                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17428                    .toggle_state(folded)
17429                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17430                        if folded {
17431                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17432                        } else {
17433                            this.fold_at(&FoldAt { buffer_row }, window, cx);
17434                        }
17435                    }))
17436                    .into_any_element(),
17437            )
17438        } else {
17439            None
17440        }
17441    }
17442
17443    pub fn render_crease_trailer(
17444        &self,
17445        buffer_row: MultiBufferRow,
17446        window: &mut Window,
17447        cx: &mut App,
17448    ) -> Option<AnyElement> {
17449        let folded = self.is_line_folded(buffer_row);
17450        if let Crease::Inline { render_trailer, .. } = self
17451            .crease_snapshot
17452            .query_row(buffer_row, &self.buffer_snapshot)?
17453        {
17454            let render_trailer = render_trailer.as_ref()?;
17455            Some(render_trailer(buffer_row, folded, window, cx))
17456        } else {
17457            None
17458        }
17459    }
17460}
17461
17462impl Deref for EditorSnapshot {
17463    type Target = DisplaySnapshot;
17464
17465    fn deref(&self) -> &Self::Target {
17466        &self.display_snapshot
17467    }
17468}
17469
17470#[derive(Clone, Debug, PartialEq, Eq)]
17471pub enum EditorEvent {
17472    InputIgnored {
17473        text: Arc<str>,
17474    },
17475    InputHandled {
17476        utf16_range_to_replace: Option<Range<isize>>,
17477        text: Arc<str>,
17478    },
17479    ExcerptsAdded {
17480        buffer: Entity<Buffer>,
17481        predecessor: ExcerptId,
17482        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17483    },
17484    ExcerptsRemoved {
17485        ids: Vec<ExcerptId>,
17486    },
17487    BufferFoldToggled {
17488        ids: Vec<ExcerptId>,
17489        folded: bool,
17490    },
17491    ExcerptsEdited {
17492        ids: Vec<ExcerptId>,
17493    },
17494    ExcerptsExpanded {
17495        ids: Vec<ExcerptId>,
17496    },
17497    BufferEdited,
17498    Edited {
17499        transaction_id: clock::Lamport,
17500    },
17501    Reparsed(BufferId),
17502    Focused,
17503    FocusedIn,
17504    Blurred,
17505    DirtyChanged,
17506    Saved,
17507    TitleChanged,
17508    DiffBaseChanged,
17509    SelectionsChanged {
17510        local: bool,
17511    },
17512    ScrollPositionChanged {
17513        local: bool,
17514        autoscroll: bool,
17515    },
17516    Closed,
17517    TransactionUndone {
17518        transaction_id: clock::Lamport,
17519    },
17520    TransactionBegun {
17521        transaction_id: clock::Lamport,
17522    },
17523    Reloaded,
17524    CursorShapeChanged,
17525}
17526
17527impl EventEmitter<EditorEvent> for Editor {}
17528
17529impl Focusable for Editor {
17530    fn focus_handle(&self, _cx: &App) -> FocusHandle {
17531        self.focus_handle.clone()
17532    }
17533}
17534
17535impl Render for Editor {
17536    fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17537        let settings = ThemeSettings::get_global(cx);
17538
17539        let mut text_style = match self.mode {
17540            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17541                color: cx.theme().colors().editor_foreground,
17542                font_family: settings.ui_font.family.clone(),
17543                font_features: settings.ui_font.features.clone(),
17544                font_fallbacks: settings.ui_font.fallbacks.clone(),
17545                font_size: rems(0.875).into(),
17546                font_weight: settings.ui_font.weight,
17547                line_height: relative(settings.buffer_line_height.value()),
17548                ..Default::default()
17549            },
17550            EditorMode::Full => TextStyle {
17551                color: cx.theme().colors().editor_foreground,
17552                font_family: settings.buffer_font.family.clone(),
17553                font_features: settings.buffer_font.features.clone(),
17554                font_fallbacks: settings.buffer_font.fallbacks.clone(),
17555                font_size: settings.buffer_font_size(cx).into(),
17556                font_weight: settings.buffer_font.weight,
17557                line_height: relative(settings.buffer_line_height.value()),
17558                ..Default::default()
17559            },
17560        };
17561        if let Some(text_style_refinement) = &self.text_style_refinement {
17562            text_style.refine(text_style_refinement)
17563        }
17564
17565        let background = match self.mode {
17566            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17567            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17568            EditorMode::Full => cx.theme().colors().editor_background,
17569        };
17570
17571        EditorElement::new(
17572            &cx.entity(),
17573            EditorStyle {
17574                background,
17575                local_player: cx.theme().players().local(),
17576                text: text_style,
17577                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17578                syntax: cx.theme().syntax().clone(),
17579                status: cx.theme().status().clone(),
17580                inlay_hints_style: make_inlay_hints_style(cx),
17581                inline_completion_styles: make_suggestion_styles(cx),
17582                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17583            },
17584        )
17585    }
17586}
17587
17588impl EntityInputHandler for Editor {
17589    fn text_for_range(
17590        &mut self,
17591        range_utf16: Range<usize>,
17592        adjusted_range: &mut Option<Range<usize>>,
17593        _: &mut Window,
17594        cx: &mut Context<Self>,
17595    ) -> Option<String> {
17596        let snapshot = self.buffer.read(cx).read(cx);
17597        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17598        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17599        if (start.0..end.0) != range_utf16 {
17600            adjusted_range.replace(start.0..end.0);
17601        }
17602        Some(snapshot.text_for_range(start..end).collect())
17603    }
17604
17605    fn selected_text_range(
17606        &mut self,
17607        ignore_disabled_input: bool,
17608        _: &mut Window,
17609        cx: &mut Context<Self>,
17610    ) -> Option<UTF16Selection> {
17611        // Prevent the IME menu from appearing when holding down an alphabetic key
17612        // while input is disabled.
17613        if !ignore_disabled_input && !self.input_enabled {
17614            return None;
17615        }
17616
17617        let selection = self.selections.newest::<OffsetUtf16>(cx);
17618        let range = selection.range();
17619
17620        Some(UTF16Selection {
17621            range: range.start.0..range.end.0,
17622            reversed: selection.reversed,
17623        })
17624    }
17625
17626    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17627        let snapshot = self.buffer.read(cx).read(cx);
17628        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17629        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17630    }
17631
17632    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17633        self.clear_highlights::<InputComposition>(cx);
17634        self.ime_transaction.take();
17635    }
17636
17637    fn replace_text_in_range(
17638        &mut self,
17639        range_utf16: Option<Range<usize>>,
17640        text: &str,
17641        window: &mut Window,
17642        cx: &mut Context<Self>,
17643    ) {
17644        if !self.input_enabled {
17645            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17646            return;
17647        }
17648
17649        self.transact(window, cx, |this, window, cx| {
17650            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17651                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17652                Some(this.selection_replacement_ranges(range_utf16, cx))
17653            } else {
17654                this.marked_text_ranges(cx)
17655            };
17656
17657            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17658                let newest_selection_id = this.selections.newest_anchor().id;
17659                this.selections
17660                    .all::<OffsetUtf16>(cx)
17661                    .iter()
17662                    .zip(ranges_to_replace.iter())
17663                    .find_map(|(selection, range)| {
17664                        if selection.id == newest_selection_id {
17665                            Some(
17666                                (range.start.0 as isize - selection.head().0 as isize)
17667                                    ..(range.end.0 as isize - selection.head().0 as isize),
17668                            )
17669                        } else {
17670                            None
17671                        }
17672                    })
17673            });
17674
17675            cx.emit(EditorEvent::InputHandled {
17676                utf16_range_to_replace: range_to_replace,
17677                text: text.into(),
17678            });
17679
17680            if let Some(new_selected_ranges) = new_selected_ranges {
17681                this.change_selections(None, window, cx, |selections| {
17682                    selections.select_ranges(new_selected_ranges)
17683                });
17684                this.backspace(&Default::default(), window, cx);
17685            }
17686
17687            this.handle_input(text, window, cx);
17688        });
17689
17690        if let Some(transaction) = self.ime_transaction {
17691            self.buffer.update(cx, |buffer, cx| {
17692                buffer.group_until_transaction(transaction, cx);
17693            });
17694        }
17695
17696        self.unmark_text(window, cx);
17697    }
17698
17699    fn replace_and_mark_text_in_range(
17700        &mut self,
17701        range_utf16: Option<Range<usize>>,
17702        text: &str,
17703        new_selected_range_utf16: Option<Range<usize>>,
17704        window: &mut Window,
17705        cx: &mut Context<Self>,
17706    ) {
17707        if !self.input_enabled {
17708            return;
17709        }
17710
17711        let transaction = self.transact(window, cx, |this, window, cx| {
17712            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17713                let snapshot = this.buffer.read(cx).read(cx);
17714                if let Some(relative_range_utf16) = range_utf16.as_ref() {
17715                    for marked_range in &mut marked_ranges {
17716                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17717                        marked_range.start.0 += relative_range_utf16.start;
17718                        marked_range.start =
17719                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17720                        marked_range.end =
17721                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17722                    }
17723                }
17724                Some(marked_ranges)
17725            } else if let Some(range_utf16) = range_utf16 {
17726                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17727                Some(this.selection_replacement_ranges(range_utf16, cx))
17728            } else {
17729                None
17730            };
17731
17732            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17733                let newest_selection_id = this.selections.newest_anchor().id;
17734                this.selections
17735                    .all::<OffsetUtf16>(cx)
17736                    .iter()
17737                    .zip(ranges_to_replace.iter())
17738                    .find_map(|(selection, range)| {
17739                        if selection.id == newest_selection_id {
17740                            Some(
17741                                (range.start.0 as isize - selection.head().0 as isize)
17742                                    ..(range.end.0 as isize - selection.head().0 as isize),
17743                            )
17744                        } else {
17745                            None
17746                        }
17747                    })
17748            });
17749
17750            cx.emit(EditorEvent::InputHandled {
17751                utf16_range_to_replace: range_to_replace,
17752                text: text.into(),
17753            });
17754
17755            if let Some(ranges) = ranges_to_replace {
17756                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17757            }
17758
17759            let marked_ranges = {
17760                let snapshot = this.buffer.read(cx).read(cx);
17761                this.selections
17762                    .disjoint_anchors()
17763                    .iter()
17764                    .map(|selection| {
17765                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17766                    })
17767                    .collect::<Vec<_>>()
17768            };
17769
17770            if text.is_empty() {
17771                this.unmark_text(window, cx);
17772            } else {
17773                this.highlight_text::<InputComposition>(
17774                    marked_ranges.clone(),
17775                    HighlightStyle {
17776                        underline: Some(UnderlineStyle {
17777                            thickness: px(1.),
17778                            color: None,
17779                            wavy: false,
17780                        }),
17781                        ..Default::default()
17782                    },
17783                    cx,
17784                );
17785            }
17786
17787            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17788            let use_autoclose = this.use_autoclose;
17789            let use_auto_surround = this.use_auto_surround;
17790            this.set_use_autoclose(false);
17791            this.set_use_auto_surround(false);
17792            this.handle_input(text, window, cx);
17793            this.set_use_autoclose(use_autoclose);
17794            this.set_use_auto_surround(use_auto_surround);
17795
17796            if let Some(new_selected_range) = new_selected_range_utf16 {
17797                let snapshot = this.buffer.read(cx).read(cx);
17798                let new_selected_ranges = marked_ranges
17799                    .into_iter()
17800                    .map(|marked_range| {
17801                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17802                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17803                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17804                        snapshot.clip_offset_utf16(new_start, Bias::Left)
17805                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17806                    })
17807                    .collect::<Vec<_>>();
17808
17809                drop(snapshot);
17810                this.change_selections(None, window, cx, |selections| {
17811                    selections.select_ranges(new_selected_ranges)
17812                });
17813            }
17814        });
17815
17816        self.ime_transaction = self.ime_transaction.or(transaction);
17817        if let Some(transaction) = self.ime_transaction {
17818            self.buffer.update(cx, |buffer, cx| {
17819                buffer.group_until_transaction(transaction, cx);
17820            });
17821        }
17822
17823        if self.text_highlights::<InputComposition>(cx).is_none() {
17824            self.ime_transaction.take();
17825        }
17826    }
17827
17828    fn bounds_for_range(
17829        &mut self,
17830        range_utf16: Range<usize>,
17831        element_bounds: gpui::Bounds<Pixels>,
17832        window: &mut Window,
17833        cx: &mut Context<Self>,
17834    ) -> Option<gpui::Bounds<Pixels>> {
17835        let text_layout_details = self.text_layout_details(window);
17836        let gpui::Size {
17837            width: em_width,
17838            height: line_height,
17839        } = self.character_size(window);
17840
17841        let snapshot = self.snapshot(window, cx);
17842        let scroll_position = snapshot.scroll_position();
17843        let scroll_left = scroll_position.x * em_width;
17844
17845        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17846        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17847            + self.gutter_dimensions.width
17848            + self.gutter_dimensions.margin;
17849        let y = line_height * (start.row().as_f32() - scroll_position.y);
17850
17851        Some(Bounds {
17852            origin: element_bounds.origin + point(x, y),
17853            size: size(em_width, line_height),
17854        })
17855    }
17856
17857    fn character_index_for_point(
17858        &mut self,
17859        point: gpui::Point<Pixels>,
17860        _window: &mut Window,
17861        _cx: &mut Context<Self>,
17862    ) -> Option<usize> {
17863        let position_map = self.last_position_map.as_ref()?;
17864        if !position_map.text_hitbox.contains(&point) {
17865            return None;
17866        }
17867        let display_point = position_map.point_for_position(point).previous_valid;
17868        let anchor = position_map
17869            .snapshot
17870            .display_point_to_anchor(display_point, Bias::Left);
17871        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17872        Some(utf16_offset.0)
17873    }
17874}
17875
17876trait SelectionExt {
17877    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17878    fn spanned_rows(
17879        &self,
17880        include_end_if_at_line_start: bool,
17881        map: &DisplaySnapshot,
17882    ) -> Range<MultiBufferRow>;
17883}
17884
17885impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17886    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17887        let start = self
17888            .start
17889            .to_point(&map.buffer_snapshot)
17890            .to_display_point(map);
17891        let end = self
17892            .end
17893            .to_point(&map.buffer_snapshot)
17894            .to_display_point(map);
17895        if self.reversed {
17896            end..start
17897        } else {
17898            start..end
17899        }
17900    }
17901
17902    fn spanned_rows(
17903        &self,
17904        include_end_if_at_line_start: bool,
17905        map: &DisplaySnapshot,
17906    ) -> Range<MultiBufferRow> {
17907        let start = self.start.to_point(&map.buffer_snapshot);
17908        let mut end = self.end.to_point(&map.buffer_snapshot);
17909        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17910            end.row -= 1;
17911        }
17912
17913        let buffer_start = map.prev_line_boundary(start).0;
17914        let buffer_end = map.next_line_boundary(end).0;
17915        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17916    }
17917}
17918
17919impl<T: InvalidationRegion> InvalidationStack<T> {
17920    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17921    where
17922        S: Clone + ToOffset,
17923    {
17924        while let Some(region) = self.last() {
17925            let all_selections_inside_invalidation_ranges =
17926                if selections.len() == region.ranges().len() {
17927                    selections
17928                        .iter()
17929                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17930                        .all(|(selection, invalidation_range)| {
17931                            let head = selection.head().to_offset(buffer);
17932                            invalidation_range.start <= head && invalidation_range.end >= head
17933                        })
17934                } else {
17935                    false
17936                };
17937
17938            if all_selections_inside_invalidation_ranges {
17939                break;
17940            } else {
17941                self.pop();
17942            }
17943        }
17944    }
17945}
17946
17947impl<T> Default for InvalidationStack<T> {
17948    fn default() -> Self {
17949        Self(Default::default())
17950    }
17951}
17952
17953impl<T> Deref for InvalidationStack<T> {
17954    type Target = Vec<T>;
17955
17956    fn deref(&self) -> &Self::Target {
17957        &self.0
17958    }
17959}
17960
17961impl<T> DerefMut for InvalidationStack<T> {
17962    fn deref_mut(&mut self) -> &mut Self::Target {
17963        &mut self.0
17964    }
17965}
17966
17967impl InvalidationRegion for SnippetState {
17968    fn ranges(&self) -> &[Range<Anchor>] {
17969        &self.ranges[self.active_index]
17970    }
17971}
17972
17973pub fn diagnostic_block_renderer(
17974    diagnostic: Diagnostic,
17975    max_message_rows: Option<u8>,
17976    allow_closing: bool,
17977) -> RenderBlock {
17978    let (text_without_backticks, code_ranges) =
17979        highlight_diagnostic_message(&diagnostic, max_message_rows);
17980
17981    Arc::new(move |cx: &mut BlockContext| {
17982        let group_id: SharedString = cx.block_id.to_string().into();
17983
17984        let mut text_style = cx.window.text_style().clone();
17985        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17986        let theme_settings = ThemeSettings::get_global(cx);
17987        text_style.font_family = theme_settings.buffer_font.family.clone();
17988        text_style.font_style = theme_settings.buffer_font.style;
17989        text_style.font_features = theme_settings.buffer_font.features.clone();
17990        text_style.font_weight = theme_settings.buffer_font.weight;
17991
17992        let multi_line_diagnostic = diagnostic.message.contains('\n');
17993
17994        let buttons = |diagnostic: &Diagnostic| {
17995            if multi_line_diagnostic {
17996                v_flex()
17997            } else {
17998                h_flex()
17999            }
18000            .when(allow_closing, |div| {
18001                div.children(diagnostic.is_primary.then(|| {
18002                    IconButton::new("close-block", IconName::XCircle)
18003                        .icon_color(Color::Muted)
18004                        .size(ButtonSize::Compact)
18005                        .style(ButtonStyle::Transparent)
18006                        .visible_on_hover(group_id.clone())
18007                        .on_click(move |_click, window, cx| {
18008                            window.dispatch_action(Box::new(Cancel), cx)
18009                        })
18010                        .tooltip(|window, cx| {
18011                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
18012                        })
18013                }))
18014            })
18015            .child(
18016                IconButton::new("copy-block", IconName::Copy)
18017                    .icon_color(Color::Muted)
18018                    .size(ButtonSize::Compact)
18019                    .style(ButtonStyle::Transparent)
18020                    .visible_on_hover(group_id.clone())
18021                    .on_click({
18022                        let message = diagnostic.message.clone();
18023                        move |_click, _, cx| {
18024                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
18025                        }
18026                    })
18027                    .tooltip(Tooltip::text("Copy diagnostic message")),
18028            )
18029        };
18030
18031        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
18032            AvailableSpace::min_size(),
18033            cx.window,
18034            cx.app,
18035        );
18036
18037        h_flex()
18038            .id(cx.block_id)
18039            .group(group_id.clone())
18040            .relative()
18041            .size_full()
18042            .block_mouse_down()
18043            .pl(cx.gutter_dimensions.width)
18044            .w(cx.max_width - cx.gutter_dimensions.full_width())
18045            .child(
18046                div()
18047                    .flex()
18048                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
18049                    .flex_shrink(),
18050            )
18051            .child(buttons(&diagnostic))
18052            .child(div().flex().flex_shrink_0().child(
18053                StyledText::new(text_without_backticks.clone()).with_default_highlights(
18054                    &text_style,
18055                    code_ranges.iter().map(|range| {
18056                        (
18057                            range.clone(),
18058                            HighlightStyle {
18059                                font_weight: Some(FontWeight::BOLD),
18060                                ..Default::default()
18061                            },
18062                        )
18063                    }),
18064                ),
18065            ))
18066            .into_any_element()
18067    })
18068}
18069
18070fn inline_completion_edit_text(
18071    current_snapshot: &BufferSnapshot,
18072    edits: &[(Range<Anchor>, String)],
18073    edit_preview: &EditPreview,
18074    include_deletions: bool,
18075    cx: &App,
18076) -> HighlightedText {
18077    let edits = edits
18078        .iter()
18079        .map(|(anchor, text)| {
18080            (
18081                anchor.start.text_anchor..anchor.end.text_anchor,
18082                text.clone(),
18083            )
18084        })
18085        .collect::<Vec<_>>();
18086
18087    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18088}
18089
18090pub fn highlight_diagnostic_message(
18091    diagnostic: &Diagnostic,
18092    mut max_message_rows: Option<u8>,
18093) -> (SharedString, Vec<Range<usize>>) {
18094    let mut text_without_backticks = String::new();
18095    let mut code_ranges = Vec::new();
18096
18097    if let Some(source) = &diagnostic.source {
18098        text_without_backticks.push_str(source);
18099        code_ranges.push(0..source.len());
18100        text_without_backticks.push_str(": ");
18101    }
18102
18103    let mut prev_offset = 0;
18104    let mut in_code_block = false;
18105    let has_row_limit = max_message_rows.is_some();
18106    let mut newline_indices = diagnostic
18107        .message
18108        .match_indices('\n')
18109        .filter(|_| has_row_limit)
18110        .map(|(ix, _)| ix)
18111        .fuse()
18112        .peekable();
18113
18114    for (quote_ix, _) in diagnostic
18115        .message
18116        .match_indices('`')
18117        .chain([(diagnostic.message.len(), "")])
18118    {
18119        let mut first_newline_ix = None;
18120        let mut last_newline_ix = None;
18121        while let Some(newline_ix) = newline_indices.peek() {
18122            if *newline_ix < quote_ix {
18123                if first_newline_ix.is_none() {
18124                    first_newline_ix = Some(*newline_ix);
18125                }
18126                last_newline_ix = Some(*newline_ix);
18127
18128                if let Some(rows_left) = &mut max_message_rows {
18129                    if *rows_left == 0 {
18130                        break;
18131                    } else {
18132                        *rows_left -= 1;
18133                    }
18134                }
18135                let _ = newline_indices.next();
18136            } else {
18137                break;
18138            }
18139        }
18140        let prev_len = text_without_backticks.len();
18141        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18142        text_without_backticks.push_str(new_text);
18143        if in_code_block {
18144            code_ranges.push(prev_len..text_without_backticks.len());
18145        }
18146        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18147        in_code_block = !in_code_block;
18148        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18149            text_without_backticks.push_str("...");
18150            break;
18151        }
18152    }
18153
18154    (text_without_backticks.into(), code_ranges)
18155}
18156
18157fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18158    match severity {
18159        DiagnosticSeverity::ERROR => colors.error,
18160        DiagnosticSeverity::WARNING => colors.warning,
18161        DiagnosticSeverity::INFORMATION => colors.info,
18162        DiagnosticSeverity::HINT => colors.info,
18163        _ => colors.ignored,
18164    }
18165}
18166
18167pub fn styled_runs_for_code_label<'a>(
18168    label: &'a CodeLabel,
18169    syntax_theme: &'a theme::SyntaxTheme,
18170) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18171    let fade_out = HighlightStyle {
18172        fade_out: Some(0.35),
18173        ..Default::default()
18174    };
18175
18176    let mut prev_end = label.filter_range.end;
18177    label
18178        .runs
18179        .iter()
18180        .enumerate()
18181        .flat_map(move |(ix, (range, highlight_id))| {
18182            let style = if let Some(style) = highlight_id.style(syntax_theme) {
18183                style
18184            } else {
18185                return Default::default();
18186            };
18187            let mut muted_style = style;
18188            muted_style.highlight(fade_out);
18189
18190            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18191            if range.start >= label.filter_range.end {
18192                if range.start > prev_end {
18193                    runs.push((prev_end..range.start, fade_out));
18194                }
18195                runs.push((range.clone(), muted_style));
18196            } else if range.end <= label.filter_range.end {
18197                runs.push((range.clone(), style));
18198            } else {
18199                runs.push((range.start..label.filter_range.end, style));
18200                runs.push((label.filter_range.end..range.end, muted_style));
18201            }
18202            prev_end = cmp::max(prev_end, range.end);
18203
18204            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18205                runs.push((prev_end..label.text.len(), fade_out));
18206            }
18207
18208            runs
18209        })
18210}
18211
18212pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18213    let mut prev_index = 0;
18214    let mut prev_codepoint: Option<char> = None;
18215    text.char_indices()
18216        .chain([(text.len(), '\0')])
18217        .filter_map(move |(index, codepoint)| {
18218            let prev_codepoint = prev_codepoint.replace(codepoint)?;
18219            let is_boundary = index == text.len()
18220                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18221                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18222            if is_boundary {
18223                let chunk = &text[prev_index..index];
18224                prev_index = index;
18225                Some(chunk)
18226            } else {
18227                None
18228            }
18229        })
18230}
18231
18232pub trait RangeToAnchorExt: Sized {
18233    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18234
18235    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18236        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18237        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18238    }
18239}
18240
18241impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18242    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18243        let start_offset = self.start.to_offset(snapshot);
18244        let end_offset = self.end.to_offset(snapshot);
18245        if start_offset == end_offset {
18246            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18247        } else {
18248            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18249        }
18250    }
18251}
18252
18253pub trait RowExt {
18254    fn as_f32(&self) -> f32;
18255
18256    fn next_row(&self) -> Self;
18257
18258    fn previous_row(&self) -> Self;
18259
18260    fn minus(&self, other: Self) -> u32;
18261}
18262
18263impl RowExt for DisplayRow {
18264    fn as_f32(&self) -> f32 {
18265        self.0 as f32
18266    }
18267
18268    fn next_row(&self) -> Self {
18269        Self(self.0 + 1)
18270    }
18271
18272    fn previous_row(&self) -> Self {
18273        Self(self.0.saturating_sub(1))
18274    }
18275
18276    fn minus(&self, other: Self) -> u32 {
18277        self.0 - other.0
18278    }
18279}
18280
18281impl RowExt for MultiBufferRow {
18282    fn as_f32(&self) -> f32 {
18283        self.0 as f32
18284    }
18285
18286    fn next_row(&self) -> Self {
18287        Self(self.0 + 1)
18288    }
18289
18290    fn previous_row(&self) -> Self {
18291        Self(self.0.saturating_sub(1))
18292    }
18293
18294    fn minus(&self, other: Self) -> u32 {
18295        self.0 - other.0
18296    }
18297}
18298
18299trait RowRangeExt {
18300    type Row;
18301
18302    fn len(&self) -> usize;
18303
18304    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18305}
18306
18307impl RowRangeExt for Range<MultiBufferRow> {
18308    type Row = MultiBufferRow;
18309
18310    fn len(&self) -> usize {
18311        (self.end.0 - self.start.0) as usize
18312    }
18313
18314    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18315        (self.start.0..self.end.0).map(MultiBufferRow)
18316    }
18317}
18318
18319impl RowRangeExt for Range<DisplayRow> {
18320    type Row = DisplayRow;
18321
18322    fn len(&self) -> usize {
18323        (self.end.0 - self.start.0) as usize
18324    }
18325
18326    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18327        (self.start.0..self.end.0).map(DisplayRow)
18328    }
18329}
18330
18331/// If select range has more than one line, we
18332/// just point the cursor to range.start.
18333fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18334    if range.start.row == range.end.row {
18335        range
18336    } else {
18337        range.start..range.start
18338    }
18339}
18340pub struct KillRing(ClipboardItem);
18341impl Global for KillRing {}
18342
18343const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18344
18345fn all_edits_insertions_or_deletions(
18346    edits: &Vec<(Range<Anchor>, String)>,
18347    snapshot: &MultiBufferSnapshot,
18348) -> bool {
18349    let mut all_insertions = true;
18350    let mut all_deletions = true;
18351
18352    for (range, new_text) in edits.iter() {
18353        let range_is_empty = range.to_offset(&snapshot).is_empty();
18354        let text_is_empty = new_text.is_empty();
18355
18356        if range_is_empty != text_is_empty {
18357            if range_is_empty {
18358                all_deletions = false;
18359            } else {
18360                all_insertions = false;
18361            }
18362        } else {
18363            return false;
18364        }
18365
18366        if !all_insertions && !all_deletions {
18367            return false;
18368        }
18369    }
18370    all_insertions || all_deletions
18371}
18372
18373struct MissingEditPredictionKeybindingTooltip;
18374
18375impl Render for MissingEditPredictionKeybindingTooltip {
18376    fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18377        ui::tooltip_container(window, cx, |container, _, cx| {
18378            container
18379                .flex_shrink_0()
18380                .max_w_80()
18381                .min_h(rems_from_px(124.))
18382                .justify_between()
18383                .child(
18384                    v_flex()
18385                        .flex_1()
18386                        .text_ui_sm(cx)
18387                        .child(Label::new("Conflict with Accept Keybinding"))
18388                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
18389                )
18390                .child(
18391                    h_flex()
18392                        .pb_1()
18393                        .gap_1()
18394                        .items_end()
18395                        .w_full()
18396                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
18397                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
18398                        }))
18399                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
18400                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
18401                        })),
18402                )
18403        })
18404    }
18405}