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    ) {
11548        let row = if direction == Direction::Next {
11549            self.hunk_after_position(snapshot, position)
11550                .map(|hunk| hunk.row_range.start)
11551        } else {
11552            self.hunk_before_position(snapshot, position)
11553        };
11554
11555        if let Some(row) = row {
11556            let destination = Point::new(row.0, 0);
11557            let autoscroll = Autoscroll::center();
11558
11559            self.unfold_ranges(&[destination..destination], false, false, cx);
11560            self.change_selections(Some(autoscroll), window, cx, |s| {
11561                s.select_ranges([destination..destination]);
11562            });
11563        }
11564    }
11565
11566    fn hunk_after_position(
11567        &mut self,
11568        snapshot: &EditorSnapshot,
11569        position: Point,
11570    ) -> Option<MultiBufferDiffHunk> {
11571        snapshot
11572            .buffer_snapshot
11573            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11574            .find(|hunk| hunk.row_range.start.0 > position.row)
11575            .or_else(|| {
11576                snapshot
11577                    .buffer_snapshot
11578                    .diff_hunks_in_range(Point::zero()..position)
11579                    .find(|hunk| hunk.row_range.end.0 < position.row)
11580            })
11581    }
11582
11583    fn go_to_prev_hunk(
11584        &mut self,
11585        _: &GoToPreviousHunk,
11586        window: &mut Window,
11587        cx: &mut Context<Self>,
11588    ) {
11589        let snapshot = self.snapshot(window, cx);
11590        let selection = self.selections.newest::<Point>(cx);
11591        self.go_to_hunk_after_or_before_position(
11592            &snapshot,
11593            selection.head(),
11594            Direction::Prev,
11595            window,
11596            cx,
11597        );
11598    }
11599
11600    fn hunk_before_position(
11601        &mut self,
11602        snapshot: &EditorSnapshot,
11603        position: Point,
11604    ) -> Option<MultiBufferRow> {
11605        snapshot
11606            .buffer_snapshot
11607            .diff_hunk_before(position)
11608            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11609    }
11610
11611    pub fn go_to_definition(
11612        &mut self,
11613        _: &GoToDefinition,
11614        window: &mut Window,
11615        cx: &mut Context<Self>,
11616    ) -> Task<Result<Navigated>> {
11617        let definition =
11618            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11619        cx.spawn_in(window, |editor, mut cx| async move {
11620            if definition.await? == Navigated::Yes {
11621                return Ok(Navigated::Yes);
11622            }
11623            match editor.update_in(&mut cx, |editor, window, cx| {
11624                editor.find_all_references(&FindAllReferences, window, cx)
11625            })? {
11626                Some(references) => references.await,
11627                None => Ok(Navigated::No),
11628            }
11629        })
11630    }
11631
11632    pub fn go_to_declaration(
11633        &mut self,
11634        _: &GoToDeclaration,
11635        window: &mut Window,
11636        cx: &mut Context<Self>,
11637    ) -> Task<Result<Navigated>> {
11638        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11639    }
11640
11641    pub fn go_to_declaration_split(
11642        &mut self,
11643        _: &GoToDeclaration,
11644        window: &mut Window,
11645        cx: &mut Context<Self>,
11646    ) -> Task<Result<Navigated>> {
11647        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11648    }
11649
11650    pub fn go_to_implementation(
11651        &mut self,
11652        _: &GoToImplementation,
11653        window: &mut Window,
11654        cx: &mut Context<Self>,
11655    ) -> Task<Result<Navigated>> {
11656        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11657    }
11658
11659    pub fn go_to_implementation_split(
11660        &mut self,
11661        _: &GoToImplementationSplit,
11662        window: &mut Window,
11663        cx: &mut Context<Self>,
11664    ) -> Task<Result<Navigated>> {
11665        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11666    }
11667
11668    pub fn go_to_type_definition(
11669        &mut self,
11670        _: &GoToTypeDefinition,
11671        window: &mut Window,
11672        cx: &mut Context<Self>,
11673    ) -> Task<Result<Navigated>> {
11674        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11675    }
11676
11677    pub fn go_to_definition_split(
11678        &mut self,
11679        _: &GoToDefinitionSplit,
11680        window: &mut Window,
11681        cx: &mut Context<Self>,
11682    ) -> Task<Result<Navigated>> {
11683        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11684    }
11685
11686    pub fn go_to_type_definition_split(
11687        &mut self,
11688        _: &GoToTypeDefinitionSplit,
11689        window: &mut Window,
11690        cx: &mut Context<Self>,
11691    ) -> Task<Result<Navigated>> {
11692        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11693    }
11694
11695    fn go_to_definition_of_kind(
11696        &mut self,
11697        kind: GotoDefinitionKind,
11698        split: bool,
11699        window: &mut Window,
11700        cx: &mut Context<Self>,
11701    ) -> Task<Result<Navigated>> {
11702        let Some(provider) = self.semantics_provider.clone() else {
11703            return Task::ready(Ok(Navigated::No));
11704        };
11705        let head = self.selections.newest::<usize>(cx).head();
11706        let buffer = self.buffer.read(cx);
11707        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11708            text_anchor
11709        } else {
11710            return Task::ready(Ok(Navigated::No));
11711        };
11712
11713        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11714            return Task::ready(Ok(Navigated::No));
11715        };
11716
11717        cx.spawn_in(window, |editor, mut cx| async move {
11718            let definitions = definitions.await?;
11719            let navigated = editor
11720                .update_in(&mut cx, |editor, window, cx| {
11721                    editor.navigate_to_hover_links(
11722                        Some(kind),
11723                        definitions
11724                            .into_iter()
11725                            .filter(|location| {
11726                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11727                            })
11728                            .map(HoverLink::Text)
11729                            .collect::<Vec<_>>(),
11730                        split,
11731                        window,
11732                        cx,
11733                    )
11734                })?
11735                .await?;
11736            anyhow::Ok(navigated)
11737        })
11738    }
11739
11740    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11741        let selection = self.selections.newest_anchor();
11742        let head = selection.head();
11743        let tail = selection.tail();
11744
11745        let Some((buffer, start_position)) =
11746            self.buffer.read(cx).text_anchor_for_position(head, cx)
11747        else {
11748            return;
11749        };
11750
11751        let end_position = if head != tail {
11752            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11753                return;
11754            };
11755            Some(pos)
11756        } else {
11757            None
11758        };
11759
11760        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11761            let url = if let Some(end_pos) = end_position {
11762                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11763            } else {
11764                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11765            };
11766
11767            if let Some(url) = url {
11768                editor.update(&mut cx, |_, cx| {
11769                    cx.open_url(&url);
11770                })
11771            } else {
11772                Ok(())
11773            }
11774        });
11775
11776        url_finder.detach();
11777    }
11778
11779    pub fn open_selected_filename(
11780        &mut self,
11781        _: &OpenSelectedFilename,
11782        window: &mut Window,
11783        cx: &mut Context<Self>,
11784    ) {
11785        let Some(workspace) = self.workspace() else {
11786            return;
11787        };
11788
11789        let position = self.selections.newest_anchor().head();
11790
11791        let Some((buffer, buffer_position)) =
11792            self.buffer.read(cx).text_anchor_for_position(position, cx)
11793        else {
11794            return;
11795        };
11796
11797        let project = self.project.clone();
11798
11799        cx.spawn_in(window, |_, mut cx| async move {
11800            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11801
11802            if let Some((_, path)) = result {
11803                workspace
11804                    .update_in(&mut cx, |workspace, window, cx| {
11805                        workspace.open_resolved_path(path, window, cx)
11806                    })?
11807                    .await?;
11808            }
11809            anyhow::Ok(())
11810        })
11811        .detach();
11812    }
11813
11814    pub(crate) fn navigate_to_hover_links(
11815        &mut self,
11816        kind: Option<GotoDefinitionKind>,
11817        mut definitions: Vec<HoverLink>,
11818        split: bool,
11819        window: &mut Window,
11820        cx: &mut Context<Editor>,
11821    ) -> Task<Result<Navigated>> {
11822        // If there is one definition, just open it directly
11823        if definitions.len() == 1 {
11824            let definition = definitions.pop().unwrap();
11825
11826            enum TargetTaskResult {
11827                Location(Option<Location>),
11828                AlreadyNavigated,
11829            }
11830
11831            let target_task = match definition {
11832                HoverLink::Text(link) => {
11833                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11834                }
11835                HoverLink::InlayHint(lsp_location, server_id) => {
11836                    let computation =
11837                        self.compute_target_location(lsp_location, server_id, window, cx);
11838                    cx.background_spawn(async move {
11839                        let location = computation.await?;
11840                        Ok(TargetTaskResult::Location(location))
11841                    })
11842                }
11843                HoverLink::Url(url) => {
11844                    cx.open_url(&url);
11845                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11846                }
11847                HoverLink::File(path) => {
11848                    if let Some(workspace) = self.workspace() {
11849                        cx.spawn_in(window, |_, mut cx| async move {
11850                            workspace
11851                                .update_in(&mut cx, |workspace, window, cx| {
11852                                    workspace.open_resolved_path(path, window, cx)
11853                                })?
11854                                .await
11855                                .map(|_| TargetTaskResult::AlreadyNavigated)
11856                        })
11857                    } else {
11858                        Task::ready(Ok(TargetTaskResult::Location(None)))
11859                    }
11860                }
11861            };
11862            cx.spawn_in(window, |editor, mut cx| async move {
11863                let target = match target_task.await.context("target resolution task")? {
11864                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11865                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11866                    TargetTaskResult::Location(Some(target)) => target,
11867                };
11868
11869                editor.update_in(&mut cx, |editor, window, cx| {
11870                    let Some(workspace) = editor.workspace() else {
11871                        return Navigated::No;
11872                    };
11873                    let pane = workspace.read(cx).active_pane().clone();
11874
11875                    let range = target.range.to_point(target.buffer.read(cx));
11876                    let range = editor.range_for_match(&range);
11877                    let range = collapse_multiline_range(range);
11878
11879                    if !split
11880                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11881                    {
11882                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11883                    } else {
11884                        window.defer(cx, move |window, cx| {
11885                            let target_editor: Entity<Self> =
11886                                workspace.update(cx, |workspace, cx| {
11887                                    let pane = if split {
11888                                        workspace.adjacent_pane(window, cx)
11889                                    } else {
11890                                        workspace.active_pane().clone()
11891                                    };
11892
11893                                    workspace.open_project_item(
11894                                        pane,
11895                                        target.buffer.clone(),
11896                                        true,
11897                                        true,
11898                                        window,
11899                                        cx,
11900                                    )
11901                                });
11902                            target_editor.update(cx, |target_editor, cx| {
11903                                // When selecting a definition in a different buffer, disable the nav history
11904                                // to avoid creating a history entry at the previous cursor location.
11905                                pane.update(cx, |pane, _| pane.disable_history());
11906                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11907                                pane.update(cx, |pane, _| pane.enable_history());
11908                            });
11909                        });
11910                    }
11911                    Navigated::Yes
11912                })
11913            })
11914        } else if !definitions.is_empty() {
11915            cx.spawn_in(window, |editor, mut cx| async move {
11916                let (title, location_tasks, workspace) = editor
11917                    .update_in(&mut cx, |editor, window, cx| {
11918                        let tab_kind = match kind {
11919                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11920                            _ => "Definitions",
11921                        };
11922                        let title = definitions
11923                            .iter()
11924                            .find_map(|definition| match definition {
11925                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11926                                    let buffer = origin.buffer.read(cx);
11927                                    format!(
11928                                        "{} for {}",
11929                                        tab_kind,
11930                                        buffer
11931                                            .text_for_range(origin.range.clone())
11932                                            .collect::<String>()
11933                                    )
11934                                }),
11935                                HoverLink::InlayHint(_, _) => None,
11936                                HoverLink::Url(_) => None,
11937                                HoverLink::File(_) => None,
11938                            })
11939                            .unwrap_or(tab_kind.to_string());
11940                        let location_tasks = definitions
11941                            .into_iter()
11942                            .map(|definition| match definition {
11943                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11944                                HoverLink::InlayHint(lsp_location, server_id) => editor
11945                                    .compute_target_location(lsp_location, server_id, window, cx),
11946                                HoverLink::Url(_) => Task::ready(Ok(None)),
11947                                HoverLink::File(_) => Task::ready(Ok(None)),
11948                            })
11949                            .collect::<Vec<_>>();
11950                        (title, location_tasks, editor.workspace().clone())
11951                    })
11952                    .context("location tasks preparation")?;
11953
11954                let locations = future::join_all(location_tasks)
11955                    .await
11956                    .into_iter()
11957                    .filter_map(|location| location.transpose())
11958                    .collect::<Result<_>>()
11959                    .context("location tasks")?;
11960
11961                let Some(workspace) = workspace else {
11962                    return Ok(Navigated::No);
11963                };
11964                let opened = workspace
11965                    .update_in(&mut cx, |workspace, window, cx| {
11966                        Self::open_locations_in_multibuffer(
11967                            workspace,
11968                            locations,
11969                            title,
11970                            split,
11971                            MultibufferSelectionMode::First,
11972                            window,
11973                            cx,
11974                        )
11975                    })
11976                    .ok();
11977
11978                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11979            })
11980        } else {
11981            Task::ready(Ok(Navigated::No))
11982        }
11983    }
11984
11985    fn compute_target_location(
11986        &self,
11987        lsp_location: lsp::Location,
11988        server_id: LanguageServerId,
11989        window: &mut Window,
11990        cx: &mut Context<Self>,
11991    ) -> Task<anyhow::Result<Option<Location>>> {
11992        let Some(project) = self.project.clone() else {
11993            return Task::ready(Ok(None));
11994        };
11995
11996        cx.spawn_in(window, move |editor, mut cx| async move {
11997            let location_task = editor.update(&mut cx, |_, cx| {
11998                project.update(cx, |project, cx| {
11999                    let language_server_name = project
12000                        .language_server_statuses(cx)
12001                        .find(|(id, _)| server_id == *id)
12002                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
12003                    language_server_name.map(|language_server_name| {
12004                        project.open_local_buffer_via_lsp(
12005                            lsp_location.uri.clone(),
12006                            server_id,
12007                            language_server_name,
12008                            cx,
12009                        )
12010                    })
12011                })
12012            })?;
12013            let location = match location_task {
12014                Some(task) => Some({
12015                    let target_buffer_handle = task.await.context("open local buffer")?;
12016                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
12017                        let target_start = target_buffer
12018                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
12019                        let target_end = target_buffer
12020                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
12021                        target_buffer.anchor_after(target_start)
12022                            ..target_buffer.anchor_before(target_end)
12023                    })?;
12024                    Location {
12025                        buffer: target_buffer_handle,
12026                        range,
12027                    }
12028                }),
12029                None => None,
12030            };
12031            Ok(location)
12032        })
12033    }
12034
12035    pub fn find_all_references(
12036        &mut self,
12037        _: &FindAllReferences,
12038        window: &mut Window,
12039        cx: &mut Context<Self>,
12040    ) -> Option<Task<Result<Navigated>>> {
12041        let selection = self.selections.newest::<usize>(cx);
12042        let multi_buffer = self.buffer.read(cx);
12043        let head = selection.head();
12044
12045        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12046        let head_anchor = multi_buffer_snapshot.anchor_at(
12047            head,
12048            if head < selection.tail() {
12049                Bias::Right
12050            } else {
12051                Bias::Left
12052            },
12053        );
12054
12055        match self
12056            .find_all_references_task_sources
12057            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12058        {
12059            Ok(_) => {
12060                log::info!(
12061                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
12062                );
12063                return None;
12064            }
12065            Err(i) => {
12066                self.find_all_references_task_sources.insert(i, head_anchor);
12067            }
12068        }
12069
12070        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12071        let workspace = self.workspace()?;
12072        let project = workspace.read(cx).project().clone();
12073        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12074        Some(cx.spawn_in(window, |editor, mut cx| async move {
12075            let _cleanup = defer({
12076                let mut cx = cx.clone();
12077                move || {
12078                    let _ = editor.update(&mut cx, |editor, _| {
12079                        if let Ok(i) =
12080                            editor
12081                                .find_all_references_task_sources
12082                                .binary_search_by(|anchor| {
12083                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
12084                                })
12085                        {
12086                            editor.find_all_references_task_sources.remove(i);
12087                        }
12088                    });
12089                }
12090            });
12091
12092            let locations = references.await?;
12093            if locations.is_empty() {
12094                return anyhow::Ok(Navigated::No);
12095            }
12096
12097            workspace.update_in(&mut cx, |workspace, window, cx| {
12098                let title = locations
12099                    .first()
12100                    .as_ref()
12101                    .map(|location| {
12102                        let buffer = location.buffer.read(cx);
12103                        format!(
12104                            "References to `{}`",
12105                            buffer
12106                                .text_for_range(location.range.clone())
12107                                .collect::<String>()
12108                        )
12109                    })
12110                    .unwrap();
12111                Self::open_locations_in_multibuffer(
12112                    workspace,
12113                    locations,
12114                    title,
12115                    false,
12116                    MultibufferSelectionMode::First,
12117                    window,
12118                    cx,
12119                );
12120                Navigated::Yes
12121            })
12122        }))
12123    }
12124
12125    /// Opens a multibuffer with the given project locations in it
12126    pub fn open_locations_in_multibuffer(
12127        workspace: &mut Workspace,
12128        mut locations: Vec<Location>,
12129        title: String,
12130        split: bool,
12131        multibuffer_selection_mode: MultibufferSelectionMode,
12132        window: &mut Window,
12133        cx: &mut Context<Workspace>,
12134    ) {
12135        // If there are multiple definitions, open them in a multibuffer
12136        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12137        let mut locations = locations.into_iter().peekable();
12138        let mut ranges = Vec::new();
12139        let capability = workspace.project().read(cx).capability();
12140
12141        let excerpt_buffer = cx.new(|cx| {
12142            let mut multibuffer = MultiBuffer::new(capability);
12143            while let Some(location) = locations.next() {
12144                let buffer = location.buffer.read(cx);
12145                let mut ranges_for_buffer = Vec::new();
12146                let range = location.range.to_offset(buffer);
12147                ranges_for_buffer.push(range.clone());
12148
12149                while let Some(next_location) = locations.peek() {
12150                    if next_location.buffer == location.buffer {
12151                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
12152                        locations.next();
12153                    } else {
12154                        break;
12155                    }
12156                }
12157
12158                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12159                ranges.extend(multibuffer.push_excerpts_with_context_lines(
12160                    location.buffer.clone(),
12161                    ranges_for_buffer,
12162                    DEFAULT_MULTIBUFFER_CONTEXT,
12163                    cx,
12164                ))
12165            }
12166
12167            multibuffer.with_title(title)
12168        });
12169
12170        let editor = cx.new(|cx| {
12171            Editor::for_multibuffer(
12172                excerpt_buffer,
12173                Some(workspace.project().clone()),
12174                true,
12175                window,
12176                cx,
12177            )
12178        });
12179        editor.update(cx, |editor, cx| {
12180            match multibuffer_selection_mode {
12181                MultibufferSelectionMode::First => {
12182                    if let Some(first_range) = ranges.first() {
12183                        editor.change_selections(None, window, cx, |selections| {
12184                            selections.clear_disjoint();
12185                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12186                        });
12187                    }
12188                    editor.highlight_background::<Self>(
12189                        &ranges,
12190                        |theme| theme.editor_highlighted_line_background,
12191                        cx,
12192                    );
12193                }
12194                MultibufferSelectionMode::All => {
12195                    editor.change_selections(None, window, cx, |selections| {
12196                        selections.clear_disjoint();
12197                        selections.select_anchor_ranges(ranges);
12198                    });
12199                }
12200            }
12201            editor.register_buffers_with_language_servers(cx);
12202        });
12203
12204        let item = Box::new(editor);
12205        let item_id = item.item_id();
12206
12207        if split {
12208            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12209        } else {
12210            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12211                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12212                    pane.close_current_preview_item(window, cx)
12213                } else {
12214                    None
12215                }
12216            });
12217            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12218        }
12219        workspace.active_pane().update(cx, |pane, cx| {
12220            pane.set_preview_item_id(Some(item_id), cx);
12221        });
12222    }
12223
12224    pub fn rename(
12225        &mut self,
12226        _: &Rename,
12227        window: &mut Window,
12228        cx: &mut Context<Self>,
12229    ) -> Option<Task<Result<()>>> {
12230        use language::ToOffset as _;
12231
12232        let provider = self.semantics_provider.clone()?;
12233        let selection = self.selections.newest_anchor().clone();
12234        let (cursor_buffer, cursor_buffer_position) = self
12235            .buffer
12236            .read(cx)
12237            .text_anchor_for_position(selection.head(), cx)?;
12238        let (tail_buffer, cursor_buffer_position_end) = self
12239            .buffer
12240            .read(cx)
12241            .text_anchor_for_position(selection.tail(), cx)?;
12242        if tail_buffer != cursor_buffer {
12243            return None;
12244        }
12245
12246        let snapshot = cursor_buffer.read(cx).snapshot();
12247        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12248        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12249        let prepare_rename = provider
12250            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12251            .unwrap_or_else(|| Task::ready(Ok(None)));
12252        drop(snapshot);
12253
12254        Some(cx.spawn_in(window, |this, mut cx| async move {
12255            let rename_range = if let Some(range) = prepare_rename.await? {
12256                Some(range)
12257            } else {
12258                this.update(&mut cx, |this, cx| {
12259                    let buffer = this.buffer.read(cx).snapshot(cx);
12260                    let mut buffer_highlights = this
12261                        .document_highlights_for_position(selection.head(), &buffer)
12262                        .filter(|highlight| {
12263                            highlight.start.excerpt_id == selection.head().excerpt_id
12264                                && highlight.end.excerpt_id == selection.head().excerpt_id
12265                        });
12266                    buffer_highlights
12267                        .next()
12268                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12269                })?
12270            };
12271            if let Some(rename_range) = rename_range {
12272                this.update_in(&mut cx, |this, window, cx| {
12273                    let snapshot = cursor_buffer.read(cx).snapshot();
12274                    let rename_buffer_range = rename_range.to_offset(&snapshot);
12275                    let cursor_offset_in_rename_range =
12276                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12277                    let cursor_offset_in_rename_range_end =
12278                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12279
12280                    this.take_rename(false, window, cx);
12281                    let buffer = this.buffer.read(cx).read(cx);
12282                    let cursor_offset = selection.head().to_offset(&buffer);
12283                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12284                    let rename_end = rename_start + rename_buffer_range.len();
12285                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12286                    let mut old_highlight_id = None;
12287                    let old_name: Arc<str> = buffer
12288                        .chunks(rename_start..rename_end, true)
12289                        .map(|chunk| {
12290                            if old_highlight_id.is_none() {
12291                                old_highlight_id = chunk.syntax_highlight_id;
12292                            }
12293                            chunk.text
12294                        })
12295                        .collect::<String>()
12296                        .into();
12297
12298                    drop(buffer);
12299
12300                    // Position the selection in the rename editor so that it matches the current selection.
12301                    this.show_local_selections = false;
12302                    let rename_editor = cx.new(|cx| {
12303                        let mut editor = Editor::single_line(window, cx);
12304                        editor.buffer.update(cx, |buffer, cx| {
12305                            buffer.edit([(0..0, old_name.clone())], None, cx)
12306                        });
12307                        let rename_selection_range = match cursor_offset_in_rename_range
12308                            .cmp(&cursor_offset_in_rename_range_end)
12309                        {
12310                            Ordering::Equal => {
12311                                editor.select_all(&SelectAll, window, cx);
12312                                return editor;
12313                            }
12314                            Ordering::Less => {
12315                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12316                            }
12317                            Ordering::Greater => {
12318                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12319                            }
12320                        };
12321                        if rename_selection_range.end > old_name.len() {
12322                            editor.select_all(&SelectAll, window, cx);
12323                        } else {
12324                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12325                                s.select_ranges([rename_selection_range]);
12326                            });
12327                        }
12328                        editor
12329                    });
12330                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12331                        if e == &EditorEvent::Focused {
12332                            cx.emit(EditorEvent::FocusedIn)
12333                        }
12334                    })
12335                    .detach();
12336
12337                    let write_highlights =
12338                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12339                    let read_highlights =
12340                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
12341                    let ranges = write_highlights
12342                        .iter()
12343                        .flat_map(|(_, ranges)| ranges.iter())
12344                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12345                        .cloned()
12346                        .collect();
12347
12348                    this.highlight_text::<Rename>(
12349                        ranges,
12350                        HighlightStyle {
12351                            fade_out: Some(0.6),
12352                            ..Default::default()
12353                        },
12354                        cx,
12355                    );
12356                    let rename_focus_handle = rename_editor.focus_handle(cx);
12357                    window.focus(&rename_focus_handle);
12358                    let block_id = this.insert_blocks(
12359                        [BlockProperties {
12360                            style: BlockStyle::Flex,
12361                            placement: BlockPlacement::Below(range.start),
12362                            height: 1,
12363                            render: Arc::new({
12364                                let rename_editor = rename_editor.clone();
12365                                move |cx: &mut BlockContext| {
12366                                    let mut text_style = cx.editor_style.text.clone();
12367                                    if let Some(highlight_style) = old_highlight_id
12368                                        .and_then(|h| h.style(&cx.editor_style.syntax))
12369                                    {
12370                                        text_style = text_style.highlight(highlight_style);
12371                                    }
12372                                    div()
12373                                        .block_mouse_down()
12374                                        .pl(cx.anchor_x)
12375                                        .child(EditorElement::new(
12376                                            &rename_editor,
12377                                            EditorStyle {
12378                                                background: cx.theme().system().transparent,
12379                                                local_player: cx.editor_style.local_player,
12380                                                text: text_style,
12381                                                scrollbar_width: cx.editor_style.scrollbar_width,
12382                                                syntax: cx.editor_style.syntax.clone(),
12383                                                status: cx.editor_style.status.clone(),
12384                                                inlay_hints_style: HighlightStyle {
12385                                                    font_weight: Some(FontWeight::BOLD),
12386                                                    ..make_inlay_hints_style(cx.app)
12387                                                },
12388                                                inline_completion_styles: make_suggestion_styles(
12389                                                    cx.app,
12390                                                ),
12391                                                ..EditorStyle::default()
12392                                            },
12393                                        ))
12394                                        .into_any_element()
12395                                }
12396                            }),
12397                            priority: 0,
12398                        }],
12399                        Some(Autoscroll::fit()),
12400                        cx,
12401                    )[0];
12402                    this.pending_rename = Some(RenameState {
12403                        range,
12404                        old_name,
12405                        editor: rename_editor,
12406                        block_id,
12407                    });
12408                })?;
12409            }
12410
12411            Ok(())
12412        }))
12413    }
12414
12415    pub fn confirm_rename(
12416        &mut self,
12417        _: &ConfirmRename,
12418        window: &mut Window,
12419        cx: &mut Context<Self>,
12420    ) -> Option<Task<Result<()>>> {
12421        let rename = self.take_rename(false, window, cx)?;
12422        let workspace = self.workspace()?.downgrade();
12423        let (buffer, start) = self
12424            .buffer
12425            .read(cx)
12426            .text_anchor_for_position(rename.range.start, cx)?;
12427        let (end_buffer, _) = self
12428            .buffer
12429            .read(cx)
12430            .text_anchor_for_position(rename.range.end, cx)?;
12431        if buffer != end_buffer {
12432            return None;
12433        }
12434
12435        let old_name = rename.old_name;
12436        let new_name = rename.editor.read(cx).text(cx);
12437
12438        let rename = self.semantics_provider.as_ref()?.perform_rename(
12439            &buffer,
12440            start,
12441            new_name.clone(),
12442            cx,
12443        )?;
12444
12445        Some(cx.spawn_in(window, |editor, mut cx| async move {
12446            let project_transaction = rename.await?;
12447            Self::open_project_transaction(
12448                &editor,
12449                workspace,
12450                project_transaction,
12451                format!("Rename: {}{}", old_name, new_name),
12452                cx.clone(),
12453            )
12454            .await?;
12455
12456            editor.update(&mut cx, |editor, cx| {
12457                editor.refresh_document_highlights(cx);
12458            })?;
12459            Ok(())
12460        }))
12461    }
12462
12463    fn take_rename(
12464        &mut self,
12465        moving_cursor: bool,
12466        window: &mut Window,
12467        cx: &mut Context<Self>,
12468    ) -> Option<RenameState> {
12469        let rename = self.pending_rename.take()?;
12470        if rename.editor.focus_handle(cx).is_focused(window) {
12471            window.focus(&self.focus_handle);
12472        }
12473
12474        self.remove_blocks(
12475            [rename.block_id].into_iter().collect(),
12476            Some(Autoscroll::fit()),
12477            cx,
12478        );
12479        self.clear_highlights::<Rename>(cx);
12480        self.show_local_selections = true;
12481
12482        if moving_cursor {
12483            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12484                editor.selections.newest::<usize>(cx).head()
12485            });
12486
12487            // Update the selection to match the position of the selection inside
12488            // the rename editor.
12489            let snapshot = self.buffer.read(cx).read(cx);
12490            let rename_range = rename.range.to_offset(&snapshot);
12491            let cursor_in_editor = snapshot
12492                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12493                .min(rename_range.end);
12494            drop(snapshot);
12495
12496            self.change_selections(None, window, cx, |s| {
12497                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12498            });
12499        } else {
12500            self.refresh_document_highlights(cx);
12501        }
12502
12503        Some(rename)
12504    }
12505
12506    pub fn pending_rename(&self) -> Option<&RenameState> {
12507        self.pending_rename.as_ref()
12508    }
12509
12510    fn format(
12511        &mut self,
12512        _: &Format,
12513        window: &mut Window,
12514        cx: &mut Context<Self>,
12515    ) -> Option<Task<Result<()>>> {
12516        let project = match &self.project {
12517            Some(project) => project.clone(),
12518            None => return None,
12519        };
12520
12521        Some(self.perform_format(
12522            project,
12523            FormatTrigger::Manual,
12524            FormatTarget::Buffers,
12525            window,
12526            cx,
12527        ))
12528    }
12529
12530    fn format_selections(
12531        &mut self,
12532        _: &FormatSelections,
12533        window: &mut Window,
12534        cx: &mut Context<Self>,
12535    ) -> Option<Task<Result<()>>> {
12536        let project = match &self.project {
12537            Some(project) => project.clone(),
12538            None => return None,
12539        };
12540
12541        let ranges = self
12542            .selections
12543            .all_adjusted(cx)
12544            .into_iter()
12545            .map(|selection| selection.range())
12546            .collect_vec();
12547
12548        Some(self.perform_format(
12549            project,
12550            FormatTrigger::Manual,
12551            FormatTarget::Ranges(ranges),
12552            window,
12553            cx,
12554        ))
12555    }
12556
12557    fn perform_format(
12558        &mut self,
12559        project: Entity<Project>,
12560        trigger: FormatTrigger,
12561        target: FormatTarget,
12562        window: &mut Window,
12563        cx: &mut Context<Self>,
12564    ) -> Task<Result<()>> {
12565        let buffer = self.buffer.clone();
12566        let (buffers, target) = match target {
12567            FormatTarget::Buffers => {
12568                let mut buffers = buffer.read(cx).all_buffers();
12569                if trigger == FormatTrigger::Save {
12570                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
12571                }
12572                (buffers, LspFormatTarget::Buffers)
12573            }
12574            FormatTarget::Ranges(selection_ranges) => {
12575                let multi_buffer = buffer.read(cx);
12576                let snapshot = multi_buffer.read(cx);
12577                let mut buffers = HashSet::default();
12578                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12579                    BTreeMap::new();
12580                for selection_range in selection_ranges {
12581                    for (buffer, buffer_range, _) in
12582                        snapshot.range_to_buffer_ranges(selection_range)
12583                    {
12584                        let buffer_id = buffer.remote_id();
12585                        let start = buffer.anchor_before(buffer_range.start);
12586                        let end = buffer.anchor_after(buffer_range.end);
12587                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12588                        buffer_id_to_ranges
12589                            .entry(buffer_id)
12590                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12591                            .or_insert_with(|| vec![start..end]);
12592                    }
12593                }
12594                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12595            }
12596        };
12597
12598        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12599        let format = project.update(cx, |project, cx| {
12600            project.format(buffers, target, true, trigger, cx)
12601        });
12602
12603        cx.spawn_in(window, |_, mut cx| async move {
12604            let transaction = futures::select_biased! {
12605                () = timeout => {
12606                    log::warn!("timed out waiting for formatting");
12607                    None
12608                }
12609                transaction = format.log_err().fuse() => transaction,
12610            };
12611
12612            buffer
12613                .update(&mut cx, |buffer, cx| {
12614                    if let Some(transaction) = transaction {
12615                        if !buffer.is_singleton() {
12616                            buffer.push_transaction(&transaction.0, cx);
12617                        }
12618                    }
12619                    cx.notify();
12620                })
12621                .ok();
12622
12623            Ok(())
12624        })
12625    }
12626
12627    fn organize_imports(
12628        &mut self,
12629        _: &OrganizeImports,
12630        window: &mut Window,
12631        cx: &mut Context<Self>,
12632    ) -> Option<Task<Result<()>>> {
12633        let project = match &self.project {
12634            Some(project) => project.clone(),
12635            None => return None,
12636        };
12637        Some(self.perform_code_action_kind(
12638            project,
12639            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12640            window,
12641            cx,
12642        ))
12643    }
12644
12645    fn perform_code_action_kind(
12646        &mut self,
12647        project: Entity<Project>,
12648        kind: CodeActionKind,
12649        window: &mut Window,
12650        cx: &mut Context<Self>,
12651    ) -> Task<Result<()>> {
12652        let buffer = self.buffer.clone();
12653        let buffers = buffer.read(cx).all_buffers();
12654        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12655        let apply_action = project.update(cx, |project, cx| {
12656            project.apply_code_action_kind(buffers, kind, true, cx)
12657        });
12658        cx.spawn_in(window, |_, mut cx| async move {
12659            let transaction = futures::select_biased! {
12660                () = timeout => {
12661                    log::warn!("timed out waiting for executing code action");
12662                    None
12663                }
12664                transaction = apply_action.log_err().fuse() => transaction,
12665            };
12666            buffer
12667                .update(&mut cx, |buffer, cx| {
12668                    // check if we need this
12669                    if let Some(transaction) = transaction {
12670                        if !buffer.is_singleton() {
12671                            buffer.push_transaction(&transaction.0, cx);
12672                        }
12673                    }
12674                    cx.notify();
12675                })
12676                .ok();
12677            Ok(())
12678        })
12679    }
12680
12681    fn restart_language_server(
12682        &mut self,
12683        _: &RestartLanguageServer,
12684        _: &mut Window,
12685        cx: &mut Context<Self>,
12686    ) {
12687        if let Some(project) = self.project.clone() {
12688            self.buffer.update(cx, |multi_buffer, cx| {
12689                project.update(cx, |project, cx| {
12690                    project.restart_language_servers_for_buffers(
12691                        multi_buffer.all_buffers().into_iter().collect(),
12692                        cx,
12693                    );
12694                });
12695            })
12696        }
12697    }
12698
12699    fn cancel_language_server_work(
12700        workspace: &mut Workspace,
12701        _: &actions::CancelLanguageServerWork,
12702        _: &mut Window,
12703        cx: &mut Context<Workspace>,
12704    ) {
12705        let project = workspace.project();
12706        let buffers = workspace
12707            .active_item(cx)
12708            .and_then(|item| item.act_as::<Editor>(cx))
12709            .map_or(HashSet::default(), |editor| {
12710                editor.read(cx).buffer.read(cx).all_buffers()
12711            });
12712        project.update(cx, |project, cx| {
12713            project.cancel_language_server_work_for_buffers(buffers, cx);
12714        });
12715    }
12716
12717    fn show_character_palette(
12718        &mut self,
12719        _: &ShowCharacterPalette,
12720        window: &mut Window,
12721        _: &mut Context<Self>,
12722    ) {
12723        window.show_character_palette();
12724    }
12725
12726    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12727        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12728            let buffer = self.buffer.read(cx).snapshot(cx);
12729            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12730            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12731            let is_valid = buffer
12732                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12733                .any(|entry| {
12734                    entry.diagnostic.is_primary
12735                        && !entry.range.is_empty()
12736                        && entry.range.start == primary_range_start
12737                        && entry.diagnostic.message == active_diagnostics.primary_message
12738                });
12739
12740            if is_valid != active_diagnostics.is_valid {
12741                active_diagnostics.is_valid = is_valid;
12742                if is_valid {
12743                    let mut new_styles = HashMap::default();
12744                    for (block_id, diagnostic) in &active_diagnostics.blocks {
12745                        new_styles.insert(
12746                            *block_id,
12747                            diagnostic_block_renderer(diagnostic.clone(), None, true),
12748                        );
12749                    }
12750                    self.display_map.update(cx, |display_map, _cx| {
12751                        display_map.replace_blocks(new_styles);
12752                    });
12753                } else {
12754                    self.dismiss_diagnostics(cx);
12755                }
12756            }
12757        }
12758    }
12759
12760    fn activate_diagnostics(
12761        &mut self,
12762        buffer_id: BufferId,
12763        group_id: usize,
12764        window: &mut Window,
12765        cx: &mut Context<Self>,
12766    ) {
12767        self.dismiss_diagnostics(cx);
12768        let snapshot = self.snapshot(window, cx);
12769        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12770            let buffer = self.buffer.read(cx).snapshot(cx);
12771
12772            let mut primary_range = None;
12773            let mut primary_message = None;
12774            let diagnostic_group = buffer
12775                .diagnostic_group(buffer_id, group_id)
12776                .filter_map(|entry| {
12777                    let start = entry.range.start;
12778                    let end = entry.range.end;
12779                    if snapshot.is_line_folded(MultiBufferRow(start.row))
12780                        && (start.row == end.row
12781                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
12782                    {
12783                        return None;
12784                    }
12785                    if entry.diagnostic.is_primary {
12786                        primary_range = Some(entry.range.clone());
12787                        primary_message = Some(entry.diagnostic.message.clone());
12788                    }
12789                    Some(entry)
12790                })
12791                .collect::<Vec<_>>();
12792            let primary_range = primary_range?;
12793            let primary_message = primary_message?;
12794
12795            let blocks = display_map
12796                .insert_blocks(
12797                    diagnostic_group.iter().map(|entry| {
12798                        let diagnostic = entry.diagnostic.clone();
12799                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12800                        BlockProperties {
12801                            style: BlockStyle::Fixed,
12802                            placement: BlockPlacement::Below(
12803                                buffer.anchor_after(entry.range.start),
12804                            ),
12805                            height: message_height,
12806                            render: diagnostic_block_renderer(diagnostic, None, true),
12807                            priority: 0,
12808                        }
12809                    }),
12810                    cx,
12811                )
12812                .into_iter()
12813                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12814                .collect();
12815
12816            Some(ActiveDiagnosticGroup {
12817                primary_range: buffer.anchor_before(primary_range.start)
12818                    ..buffer.anchor_after(primary_range.end),
12819                primary_message,
12820                group_id,
12821                blocks,
12822                is_valid: true,
12823            })
12824        });
12825    }
12826
12827    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12828        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12829            self.display_map.update(cx, |display_map, cx| {
12830                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12831            });
12832            cx.notify();
12833        }
12834    }
12835
12836    /// Disable inline diagnostics rendering for this editor.
12837    pub fn disable_inline_diagnostics(&mut self) {
12838        self.inline_diagnostics_enabled = false;
12839        self.inline_diagnostics_update = Task::ready(());
12840        self.inline_diagnostics.clear();
12841    }
12842
12843    pub fn inline_diagnostics_enabled(&self) -> bool {
12844        self.inline_diagnostics_enabled
12845    }
12846
12847    pub fn show_inline_diagnostics(&self) -> bool {
12848        self.show_inline_diagnostics
12849    }
12850
12851    pub fn toggle_inline_diagnostics(
12852        &mut self,
12853        _: &ToggleInlineDiagnostics,
12854        window: &mut Window,
12855        cx: &mut Context<'_, Editor>,
12856    ) {
12857        self.show_inline_diagnostics = !self.show_inline_diagnostics;
12858        self.refresh_inline_diagnostics(false, window, cx);
12859    }
12860
12861    fn refresh_inline_diagnostics(
12862        &mut self,
12863        debounce: bool,
12864        window: &mut Window,
12865        cx: &mut Context<Self>,
12866    ) {
12867        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12868            self.inline_diagnostics_update = Task::ready(());
12869            self.inline_diagnostics.clear();
12870            return;
12871        }
12872
12873        let debounce_ms = ProjectSettings::get_global(cx)
12874            .diagnostics
12875            .inline
12876            .update_debounce_ms;
12877        let debounce = if debounce && debounce_ms > 0 {
12878            Some(Duration::from_millis(debounce_ms))
12879        } else {
12880            None
12881        };
12882        self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12883            if let Some(debounce) = debounce {
12884                cx.background_executor().timer(debounce).await;
12885            }
12886            let Some(snapshot) = editor
12887                .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12888                .ok()
12889            else {
12890                return;
12891            };
12892
12893            let new_inline_diagnostics = cx
12894                .background_spawn(async move {
12895                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12896                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12897                        let message = diagnostic_entry
12898                            .diagnostic
12899                            .message
12900                            .split_once('\n')
12901                            .map(|(line, _)| line)
12902                            .map(SharedString::new)
12903                            .unwrap_or_else(|| {
12904                                SharedString::from(diagnostic_entry.diagnostic.message)
12905                            });
12906                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12907                        let (Ok(i) | Err(i)) = inline_diagnostics
12908                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12909                        inline_diagnostics.insert(
12910                            i,
12911                            (
12912                                start_anchor,
12913                                InlineDiagnostic {
12914                                    message,
12915                                    group_id: diagnostic_entry.diagnostic.group_id,
12916                                    start: diagnostic_entry.range.start.to_point(&snapshot),
12917                                    is_primary: diagnostic_entry.diagnostic.is_primary,
12918                                    severity: diagnostic_entry.diagnostic.severity,
12919                                },
12920                            ),
12921                        );
12922                    }
12923                    inline_diagnostics
12924                })
12925                .await;
12926
12927            editor
12928                .update(&mut cx, |editor, cx| {
12929                    editor.inline_diagnostics = new_inline_diagnostics;
12930                    cx.notify();
12931                })
12932                .ok();
12933        });
12934    }
12935
12936    pub fn set_selections_from_remote(
12937        &mut self,
12938        selections: Vec<Selection<Anchor>>,
12939        pending_selection: Option<Selection<Anchor>>,
12940        window: &mut Window,
12941        cx: &mut Context<Self>,
12942    ) {
12943        let old_cursor_position = self.selections.newest_anchor().head();
12944        self.selections.change_with(cx, |s| {
12945            s.select_anchors(selections);
12946            if let Some(pending_selection) = pending_selection {
12947                s.set_pending(pending_selection, SelectMode::Character);
12948            } else {
12949                s.clear_pending();
12950            }
12951        });
12952        self.selections_did_change(false, &old_cursor_position, true, window, cx);
12953    }
12954
12955    fn push_to_selection_history(&mut self) {
12956        self.selection_history.push(SelectionHistoryEntry {
12957            selections: self.selections.disjoint_anchors(),
12958            select_next_state: self.select_next_state.clone(),
12959            select_prev_state: self.select_prev_state.clone(),
12960            add_selections_state: self.add_selections_state.clone(),
12961        });
12962    }
12963
12964    pub fn transact(
12965        &mut self,
12966        window: &mut Window,
12967        cx: &mut Context<Self>,
12968        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12969    ) -> Option<TransactionId> {
12970        self.start_transaction_at(Instant::now(), window, cx);
12971        update(self, window, cx);
12972        self.end_transaction_at(Instant::now(), cx)
12973    }
12974
12975    pub fn start_transaction_at(
12976        &mut self,
12977        now: Instant,
12978        window: &mut Window,
12979        cx: &mut Context<Self>,
12980    ) {
12981        self.end_selection(window, cx);
12982        if let Some(tx_id) = self
12983            .buffer
12984            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12985        {
12986            self.selection_history
12987                .insert_transaction(tx_id, self.selections.disjoint_anchors());
12988            cx.emit(EditorEvent::TransactionBegun {
12989                transaction_id: tx_id,
12990            })
12991        }
12992    }
12993
12994    pub fn end_transaction_at(
12995        &mut self,
12996        now: Instant,
12997        cx: &mut Context<Self>,
12998    ) -> Option<TransactionId> {
12999        if let Some(transaction_id) = self
13000            .buffer
13001            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
13002        {
13003            if let Some((_, end_selections)) =
13004                self.selection_history.transaction_mut(transaction_id)
13005            {
13006                *end_selections = Some(self.selections.disjoint_anchors());
13007            } else {
13008                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
13009            }
13010
13011            cx.emit(EditorEvent::Edited { transaction_id });
13012            Some(transaction_id)
13013        } else {
13014            None
13015        }
13016    }
13017
13018    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
13019        if self.selection_mark_mode {
13020            self.change_selections(None, window, cx, |s| {
13021                s.move_with(|_, sel| {
13022                    sel.collapse_to(sel.head(), SelectionGoal::None);
13023                });
13024            })
13025        }
13026        self.selection_mark_mode = true;
13027        cx.notify();
13028    }
13029
13030    pub fn swap_selection_ends(
13031        &mut self,
13032        _: &actions::SwapSelectionEnds,
13033        window: &mut Window,
13034        cx: &mut Context<Self>,
13035    ) {
13036        self.change_selections(None, window, cx, |s| {
13037            s.move_with(|_, sel| {
13038                if sel.start != sel.end {
13039                    sel.reversed = !sel.reversed
13040                }
13041            });
13042        });
13043        self.request_autoscroll(Autoscroll::newest(), cx);
13044        cx.notify();
13045    }
13046
13047    pub fn toggle_fold(
13048        &mut self,
13049        _: &actions::ToggleFold,
13050        window: &mut Window,
13051        cx: &mut Context<Self>,
13052    ) {
13053        if self.is_singleton(cx) {
13054            let selection = self.selections.newest::<Point>(cx);
13055
13056            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13057            let range = if selection.is_empty() {
13058                let point = selection.head().to_display_point(&display_map);
13059                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13060                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13061                    .to_point(&display_map);
13062                start..end
13063            } else {
13064                selection.range()
13065            };
13066            if display_map.folds_in_range(range).next().is_some() {
13067                self.unfold_lines(&Default::default(), window, cx)
13068            } else {
13069                self.fold(&Default::default(), window, cx)
13070            }
13071        } else {
13072            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13073            let buffer_ids: HashSet<_> = self
13074                .selections
13075                .disjoint_anchor_ranges()
13076                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13077                .collect();
13078
13079            let should_unfold = buffer_ids
13080                .iter()
13081                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13082
13083            for buffer_id in buffer_ids {
13084                if should_unfold {
13085                    self.unfold_buffer(buffer_id, cx);
13086                } else {
13087                    self.fold_buffer(buffer_id, cx);
13088                }
13089            }
13090        }
13091    }
13092
13093    pub fn toggle_fold_recursive(
13094        &mut self,
13095        _: &actions::ToggleFoldRecursive,
13096        window: &mut Window,
13097        cx: &mut Context<Self>,
13098    ) {
13099        let selection = self.selections.newest::<Point>(cx);
13100
13101        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13102        let range = if selection.is_empty() {
13103            let point = selection.head().to_display_point(&display_map);
13104            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13105            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13106                .to_point(&display_map);
13107            start..end
13108        } else {
13109            selection.range()
13110        };
13111        if display_map.folds_in_range(range).next().is_some() {
13112            self.unfold_recursive(&Default::default(), window, cx)
13113        } else {
13114            self.fold_recursive(&Default::default(), window, cx)
13115        }
13116    }
13117
13118    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13119        if self.is_singleton(cx) {
13120            let mut to_fold = Vec::new();
13121            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13122            let selections = self.selections.all_adjusted(cx);
13123
13124            for selection in selections {
13125                let range = selection.range().sorted();
13126                let buffer_start_row = range.start.row;
13127
13128                if range.start.row != range.end.row {
13129                    let mut found = false;
13130                    let mut row = range.start.row;
13131                    while row <= range.end.row {
13132                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13133                        {
13134                            found = true;
13135                            row = crease.range().end.row + 1;
13136                            to_fold.push(crease);
13137                        } else {
13138                            row += 1
13139                        }
13140                    }
13141                    if found {
13142                        continue;
13143                    }
13144                }
13145
13146                for row in (0..=range.start.row).rev() {
13147                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13148                        if crease.range().end.row >= buffer_start_row {
13149                            to_fold.push(crease);
13150                            if row <= range.start.row {
13151                                break;
13152                            }
13153                        }
13154                    }
13155                }
13156            }
13157
13158            self.fold_creases(to_fold, true, window, cx);
13159        } else {
13160            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13161            let buffer_ids = self
13162                .selections
13163                .disjoint_anchor_ranges()
13164                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13165                .collect::<HashSet<_>>();
13166            for buffer_id in buffer_ids {
13167                self.fold_buffer(buffer_id, cx);
13168            }
13169        }
13170    }
13171
13172    fn fold_at_level(
13173        &mut self,
13174        fold_at: &FoldAtLevel,
13175        window: &mut Window,
13176        cx: &mut Context<Self>,
13177    ) {
13178        if !self.buffer.read(cx).is_singleton() {
13179            return;
13180        }
13181
13182        let fold_at_level = fold_at.0;
13183        let snapshot = self.buffer.read(cx).snapshot(cx);
13184        let mut to_fold = Vec::new();
13185        let mut stack = vec![(0, snapshot.max_row().0, 1)];
13186
13187        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13188            while start_row < end_row {
13189                match self
13190                    .snapshot(window, cx)
13191                    .crease_for_buffer_row(MultiBufferRow(start_row))
13192                {
13193                    Some(crease) => {
13194                        let nested_start_row = crease.range().start.row + 1;
13195                        let nested_end_row = crease.range().end.row;
13196
13197                        if current_level < fold_at_level {
13198                            stack.push((nested_start_row, nested_end_row, current_level + 1));
13199                        } else if current_level == fold_at_level {
13200                            to_fold.push(crease);
13201                        }
13202
13203                        start_row = nested_end_row + 1;
13204                    }
13205                    None => start_row += 1,
13206                }
13207            }
13208        }
13209
13210        self.fold_creases(to_fold, true, window, cx);
13211    }
13212
13213    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13214        if self.buffer.read(cx).is_singleton() {
13215            let mut fold_ranges = Vec::new();
13216            let snapshot = self.buffer.read(cx).snapshot(cx);
13217
13218            for row in 0..snapshot.max_row().0 {
13219                if let Some(foldable_range) = self
13220                    .snapshot(window, cx)
13221                    .crease_for_buffer_row(MultiBufferRow(row))
13222                {
13223                    fold_ranges.push(foldable_range);
13224                }
13225            }
13226
13227            self.fold_creases(fold_ranges, true, window, cx);
13228        } else {
13229            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13230                editor
13231                    .update_in(&mut cx, |editor, _, cx| {
13232                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13233                            editor.fold_buffer(buffer_id, cx);
13234                        }
13235                    })
13236                    .ok();
13237            });
13238        }
13239    }
13240
13241    pub fn fold_function_bodies(
13242        &mut self,
13243        _: &actions::FoldFunctionBodies,
13244        window: &mut Window,
13245        cx: &mut Context<Self>,
13246    ) {
13247        let snapshot = self.buffer.read(cx).snapshot(cx);
13248
13249        let ranges = snapshot
13250            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13251            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13252            .collect::<Vec<_>>();
13253
13254        let creases = ranges
13255            .into_iter()
13256            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13257            .collect();
13258
13259        self.fold_creases(creases, true, window, cx);
13260    }
13261
13262    pub fn fold_recursive(
13263        &mut self,
13264        _: &actions::FoldRecursive,
13265        window: &mut Window,
13266        cx: &mut Context<Self>,
13267    ) {
13268        let mut to_fold = Vec::new();
13269        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13270        let selections = self.selections.all_adjusted(cx);
13271
13272        for selection in selections {
13273            let range = selection.range().sorted();
13274            let buffer_start_row = range.start.row;
13275
13276            if range.start.row != range.end.row {
13277                let mut found = false;
13278                for row in range.start.row..=range.end.row {
13279                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13280                        found = true;
13281                        to_fold.push(crease);
13282                    }
13283                }
13284                if found {
13285                    continue;
13286                }
13287            }
13288
13289            for row in (0..=range.start.row).rev() {
13290                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13291                    if crease.range().end.row >= buffer_start_row {
13292                        to_fold.push(crease);
13293                    } else {
13294                        break;
13295                    }
13296                }
13297            }
13298        }
13299
13300        self.fold_creases(to_fold, true, window, cx);
13301    }
13302
13303    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13304        let buffer_row = fold_at.buffer_row;
13305        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13306
13307        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13308            let autoscroll = self
13309                .selections
13310                .all::<Point>(cx)
13311                .iter()
13312                .any(|selection| crease.range().overlaps(&selection.range()));
13313
13314            self.fold_creases(vec![crease], autoscroll, window, cx);
13315        }
13316    }
13317
13318    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13319        if self.is_singleton(cx) {
13320            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13321            let buffer = &display_map.buffer_snapshot;
13322            let selections = self.selections.all::<Point>(cx);
13323            let ranges = selections
13324                .iter()
13325                .map(|s| {
13326                    let range = s.display_range(&display_map).sorted();
13327                    let mut start = range.start.to_point(&display_map);
13328                    let mut end = range.end.to_point(&display_map);
13329                    start.column = 0;
13330                    end.column = buffer.line_len(MultiBufferRow(end.row));
13331                    start..end
13332                })
13333                .collect::<Vec<_>>();
13334
13335            self.unfold_ranges(&ranges, true, true, cx);
13336        } else {
13337            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13338            let buffer_ids = self
13339                .selections
13340                .disjoint_anchor_ranges()
13341                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13342                .collect::<HashSet<_>>();
13343            for buffer_id in buffer_ids {
13344                self.unfold_buffer(buffer_id, cx);
13345            }
13346        }
13347    }
13348
13349    pub fn unfold_recursive(
13350        &mut self,
13351        _: &UnfoldRecursive,
13352        _window: &mut Window,
13353        cx: &mut Context<Self>,
13354    ) {
13355        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13356        let selections = self.selections.all::<Point>(cx);
13357        let ranges = selections
13358            .iter()
13359            .map(|s| {
13360                let mut range = s.display_range(&display_map).sorted();
13361                *range.start.column_mut() = 0;
13362                *range.end.column_mut() = display_map.line_len(range.end.row());
13363                let start = range.start.to_point(&display_map);
13364                let end = range.end.to_point(&display_map);
13365                start..end
13366            })
13367            .collect::<Vec<_>>();
13368
13369        self.unfold_ranges(&ranges, true, true, cx);
13370    }
13371
13372    pub fn unfold_at(
13373        &mut self,
13374        unfold_at: &UnfoldAt,
13375        _window: &mut Window,
13376        cx: &mut Context<Self>,
13377    ) {
13378        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13379
13380        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13381            ..Point::new(
13382                unfold_at.buffer_row.0,
13383                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13384            );
13385
13386        let autoscroll = self
13387            .selections
13388            .all::<Point>(cx)
13389            .iter()
13390            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13391
13392        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13393    }
13394
13395    pub fn unfold_all(
13396        &mut self,
13397        _: &actions::UnfoldAll,
13398        _window: &mut Window,
13399        cx: &mut Context<Self>,
13400    ) {
13401        if self.buffer.read(cx).is_singleton() {
13402            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13403            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13404        } else {
13405            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13406                editor
13407                    .update(&mut cx, |editor, cx| {
13408                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13409                            editor.unfold_buffer(buffer_id, cx);
13410                        }
13411                    })
13412                    .ok();
13413            });
13414        }
13415    }
13416
13417    pub fn fold_selected_ranges(
13418        &mut self,
13419        _: &FoldSelectedRanges,
13420        window: &mut Window,
13421        cx: &mut Context<Self>,
13422    ) {
13423        let selections = self.selections.all::<Point>(cx);
13424        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13425        let line_mode = self.selections.line_mode;
13426        let ranges = selections
13427            .into_iter()
13428            .map(|s| {
13429                if line_mode {
13430                    let start = Point::new(s.start.row, 0);
13431                    let end = Point::new(
13432                        s.end.row,
13433                        display_map
13434                            .buffer_snapshot
13435                            .line_len(MultiBufferRow(s.end.row)),
13436                    );
13437                    Crease::simple(start..end, display_map.fold_placeholder.clone())
13438                } else {
13439                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13440                }
13441            })
13442            .collect::<Vec<_>>();
13443        self.fold_creases(ranges, true, window, cx);
13444    }
13445
13446    pub fn fold_ranges<T: ToOffset + Clone>(
13447        &mut self,
13448        ranges: Vec<Range<T>>,
13449        auto_scroll: bool,
13450        window: &mut Window,
13451        cx: &mut Context<Self>,
13452    ) {
13453        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13454        let ranges = ranges
13455            .into_iter()
13456            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13457            .collect::<Vec<_>>();
13458        self.fold_creases(ranges, auto_scroll, window, cx);
13459    }
13460
13461    pub fn fold_creases<T: ToOffset + Clone>(
13462        &mut self,
13463        creases: Vec<Crease<T>>,
13464        auto_scroll: bool,
13465        window: &mut Window,
13466        cx: &mut Context<Self>,
13467    ) {
13468        if creases.is_empty() {
13469            return;
13470        }
13471
13472        let mut buffers_affected = HashSet::default();
13473        let multi_buffer = self.buffer().read(cx);
13474        for crease in &creases {
13475            if let Some((_, buffer, _)) =
13476                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13477            {
13478                buffers_affected.insert(buffer.read(cx).remote_id());
13479            };
13480        }
13481
13482        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13483
13484        if auto_scroll {
13485            self.request_autoscroll(Autoscroll::fit(), cx);
13486        }
13487
13488        cx.notify();
13489
13490        if let Some(active_diagnostics) = self.active_diagnostics.take() {
13491            // Clear diagnostics block when folding a range that contains it.
13492            let snapshot = self.snapshot(window, cx);
13493            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13494                drop(snapshot);
13495                self.active_diagnostics = Some(active_diagnostics);
13496                self.dismiss_diagnostics(cx);
13497            } else {
13498                self.active_diagnostics = Some(active_diagnostics);
13499            }
13500        }
13501
13502        self.scrollbar_marker_state.dirty = true;
13503    }
13504
13505    /// Removes any folds whose ranges intersect any of the given ranges.
13506    pub fn unfold_ranges<T: ToOffset + Clone>(
13507        &mut self,
13508        ranges: &[Range<T>],
13509        inclusive: bool,
13510        auto_scroll: bool,
13511        cx: &mut Context<Self>,
13512    ) {
13513        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13514            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13515        });
13516    }
13517
13518    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13519        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13520            return;
13521        }
13522        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13523        self.display_map.update(cx, |display_map, cx| {
13524            display_map.fold_buffers([buffer_id], cx)
13525        });
13526        cx.emit(EditorEvent::BufferFoldToggled {
13527            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13528            folded: true,
13529        });
13530        cx.notify();
13531    }
13532
13533    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13534        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13535            return;
13536        }
13537        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13538        self.display_map.update(cx, |display_map, cx| {
13539            display_map.unfold_buffers([buffer_id], cx);
13540        });
13541        cx.emit(EditorEvent::BufferFoldToggled {
13542            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13543            folded: false,
13544        });
13545        cx.notify();
13546    }
13547
13548    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13549        self.display_map.read(cx).is_buffer_folded(buffer)
13550    }
13551
13552    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13553        self.display_map.read(cx).folded_buffers()
13554    }
13555
13556    /// Removes any folds with the given ranges.
13557    pub fn remove_folds_with_type<T: ToOffset + Clone>(
13558        &mut self,
13559        ranges: &[Range<T>],
13560        type_id: TypeId,
13561        auto_scroll: bool,
13562        cx: &mut Context<Self>,
13563    ) {
13564        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13565            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13566        });
13567    }
13568
13569    fn remove_folds_with<T: ToOffset + Clone>(
13570        &mut self,
13571        ranges: &[Range<T>],
13572        auto_scroll: bool,
13573        cx: &mut Context<Self>,
13574        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13575    ) {
13576        if ranges.is_empty() {
13577            return;
13578        }
13579
13580        let mut buffers_affected = HashSet::default();
13581        let multi_buffer = self.buffer().read(cx);
13582        for range in ranges {
13583            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13584                buffers_affected.insert(buffer.read(cx).remote_id());
13585            };
13586        }
13587
13588        self.display_map.update(cx, update);
13589
13590        if auto_scroll {
13591            self.request_autoscroll(Autoscroll::fit(), cx);
13592        }
13593
13594        cx.notify();
13595        self.scrollbar_marker_state.dirty = true;
13596        self.active_indent_guides_state.dirty = true;
13597    }
13598
13599    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13600        self.display_map.read(cx).fold_placeholder.clone()
13601    }
13602
13603    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13604        self.buffer.update(cx, |buffer, cx| {
13605            buffer.set_all_diff_hunks_expanded(cx);
13606        });
13607    }
13608
13609    pub fn expand_all_diff_hunks(
13610        &mut self,
13611        _: &ExpandAllDiffHunks,
13612        _window: &mut Window,
13613        cx: &mut Context<Self>,
13614    ) {
13615        self.buffer.update(cx, |buffer, cx| {
13616            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13617        });
13618    }
13619
13620    pub fn toggle_selected_diff_hunks(
13621        &mut self,
13622        _: &ToggleSelectedDiffHunks,
13623        _window: &mut Window,
13624        cx: &mut Context<Self>,
13625    ) {
13626        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13627        self.toggle_diff_hunks_in_ranges(ranges, cx);
13628    }
13629
13630    pub fn diff_hunks_in_ranges<'a>(
13631        &'a self,
13632        ranges: &'a [Range<Anchor>],
13633        buffer: &'a MultiBufferSnapshot,
13634    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13635        ranges.iter().flat_map(move |range| {
13636            let end_excerpt_id = range.end.excerpt_id;
13637            let range = range.to_point(buffer);
13638            let mut peek_end = range.end;
13639            if range.end.row < buffer.max_row().0 {
13640                peek_end = Point::new(range.end.row + 1, 0);
13641            }
13642            buffer
13643                .diff_hunks_in_range(range.start..peek_end)
13644                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13645        })
13646    }
13647
13648    pub fn has_stageable_diff_hunks_in_ranges(
13649        &self,
13650        ranges: &[Range<Anchor>],
13651        snapshot: &MultiBufferSnapshot,
13652    ) -> bool {
13653        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13654        hunks.any(|hunk| hunk.status().has_secondary_hunk())
13655    }
13656
13657    pub fn toggle_staged_selected_diff_hunks(
13658        &mut self,
13659        _: &::git::ToggleStaged,
13660        window: &mut Window,
13661        cx: &mut Context<Self>,
13662    ) {
13663        let snapshot = self.buffer.read(cx).snapshot(cx);
13664        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13665        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13666        self.stage_or_unstage_diff_hunks(stage, &ranges, window, cx);
13667    }
13668
13669    pub fn stage_and_next(
13670        &mut self,
13671        _: &::git::StageAndNext,
13672        window: &mut Window,
13673        cx: &mut Context<Self>,
13674    ) {
13675        self.do_stage_or_unstage_and_next(true, window, cx);
13676    }
13677
13678    pub fn unstage_and_next(
13679        &mut self,
13680        _: &::git::UnstageAndNext,
13681        window: &mut Window,
13682        cx: &mut Context<Self>,
13683    ) {
13684        self.do_stage_or_unstage_and_next(false, window, cx);
13685    }
13686
13687    pub fn stage_or_unstage_diff_hunks(
13688        &mut self,
13689        stage: bool,
13690        ranges: &[Range<Anchor>],
13691        window: &mut Window,
13692        cx: &mut Context<Self>,
13693    ) {
13694        let snapshot = self.buffer.read(cx).snapshot(cx);
13695        let chunk_by = self
13696            .diff_hunks_in_ranges(&ranges, &snapshot)
13697            .chunk_by(|hunk| hunk.buffer_id);
13698        for (buffer_id, hunks) in &chunk_by {
13699            self.do_stage_or_unstage(stage, buffer_id, hunks, window, cx);
13700        }
13701    }
13702
13703    fn do_stage_or_unstage_and_next(
13704        &mut self,
13705        stage: bool,
13706        window: &mut Window,
13707        cx: &mut Context<Self>,
13708    ) {
13709        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13710
13711        if ranges.iter().any(|range| range.start != range.end) {
13712            self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13713            return;
13714        }
13715
13716        let snapshot = self.snapshot(window, cx);
13717        let newest_range = self.selections.newest::<Point>(cx).range();
13718
13719        let run_twice = snapshot
13720            .hunks_for_ranges([newest_range])
13721            .first()
13722            .is_some_and(|hunk| {
13723                let next_line = Point::new(hunk.row_range.end.0 + 1, 0);
13724                self.hunk_after_position(&snapshot, next_line)
13725                    .is_some_and(|other| other.row_range == hunk.row_range)
13726            });
13727
13728        if run_twice {
13729            self.go_to_next_hunk(&GoToHunk, window, cx);
13730        }
13731        self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13732        self.go_to_next_hunk(&GoToHunk, window, cx);
13733    }
13734
13735    fn do_stage_or_unstage(
13736        &self,
13737        stage: bool,
13738        buffer_id: BufferId,
13739        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13740        window: &mut Window,
13741        cx: &mut App,
13742    ) {
13743        let Some(project) = self.project.as_ref() else {
13744            return;
13745        };
13746        let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
13747            return;
13748        };
13749        let Some(diff) = self.buffer.read(cx).diff_for(buffer_id) else {
13750            return;
13751        };
13752        let buffer_snapshot = buffer.read(cx).snapshot();
13753        let file_exists = buffer_snapshot
13754            .file()
13755            .is_some_and(|file| file.disk_state().exists());
13756        let Some((repo, path)) = project
13757            .read(cx)
13758            .repository_and_path_for_buffer_id(buffer_id, cx)
13759        else {
13760            log::debug!("no git repo for buffer id");
13761            return;
13762        };
13763
13764        let new_index_text = diff.update(cx, |diff, cx| {
13765            diff.stage_or_unstage_hunks(
13766                stage,
13767                &hunks
13768                    .map(|hunk| buffer_diff::DiffHunk {
13769                        buffer_range: hunk.buffer_range,
13770                        diff_base_byte_range: hunk.diff_base_byte_range,
13771                        secondary_status: hunk.secondary_status,
13772                        range: Point::zero()..Point::zero(), // unused
13773                    })
13774                    .collect::<Vec<_>>(),
13775                &buffer_snapshot,
13776                file_exists,
13777                cx,
13778            )
13779        });
13780
13781        if file_exists {
13782            let buffer_store = project.read(cx).buffer_store().clone();
13783            buffer_store
13784                .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
13785                .detach_and_log_err(cx);
13786        }
13787
13788        let recv = repo
13789            .read(cx)
13790            .set_index_text(&path, new_index_text.map(|rope| rope.to_string()));
13791
13792        cx.background_spawn(async move { recv.await? })
13793            .detach_and_notify_err(window, cx);
13794    }
13795
13796    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13797        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13798        self.buffer
13799            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13800    }
13801
13802    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13803        self.buffer.update(cx, |buffer, cx| {
13804            let ranges = vec![Anchor::min()..Anchor::max()];
13805            if !buffer.all_diff_hunks_expanded()
13806                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13807            {
13808                buffer.collapse_diff_hunks(ranges, cx);
13809                true
13810            } else {
13811                false
13812            }
13813        })
13814    }
13815
13816    fn toggle_diff_hunks_in_ranges(
13817        &mut self,
13818        ranges: Vec<Range<Anchor>>,
13819        cx: &mut Context<'_, Editor>,
13820    ) {
13821        self.buffer.update(cx, |buffer, cx| {
13822            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13823            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13824        })
13825    }
13826
13827    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13828        self.buffer.update(cx, |buffer, cx| {
13829            let snapshot = buffer.snapshot(cx);
13830            let excerpt_id = range.end.excerpt_id;
13831            let point_range = range.to_point(&snapshot);
13832            let expand = !buffer.single_hunk_is_expanded(range, cx);
13833            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13834        })
13835    }
13836
13837    pub(crate) fn apply_all_diff_hunks(
13838        &mut self,
13839        _: &ApplyAllDiffHunks,
13840        window: &mut Window,
13841        cx: &mut Context<Self>,
13842    ) {
13843        let buffers = self.buffer.read(cx).all_buffers();
13844        for branch_buffer in buffers {
13845            branch_buffer.update(cx, |branch_buffer, cx| {
13846                branch_buffer.merge_into_base(Vec::new(), cx);
13847            });
13848        }
13849
13850        if let Some(project) = self.project.clone() {
13851            self.save(true, project, window, cx).detach_and_log_err(cx);
13852        }
13853    }
13854
13855    pub(crate) fn apply_selected_diff_hunks(
13856        &mut self,
13857        _: &ApplyDiffHunk,
13858        window: &mut Window,
13859        cx: &mut Context<Self>,
13860    ) {
13861        let snapshot = self.snapshot(window, cx);
13862        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
13863        let mut ranges_by_buffer = HashMap::default();
13864        self.transact(window, cx, |editor, _window, cx| {
13865            for hunk in hunks {
13866                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13867                    ranges_by_buffer
13868                        .entry(buffer.clone())
13869                        .or_insert_with(Vec::new)
13870                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13871                }
13872            }
13873
13874            for (buffer, ranges) in ranges_by_buffer {
13875                buffer.update(cx, |buffer, cx| {
13876                    buffer.merge_into_base(ranges, cx);
13877                });
13878            }
13879        });
13880
13881        if let Some(project) = self.project.clone() {
13882            self.save(true, project, window, cx).detach_and_log_err(cx);
13883        }
13884    }
13885
13886    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13887        if hovered != self.gutter_hovered {
13888            self.gutter_hovered = hovered;
13889            cx.notify();
13890        }
13891    }
13892
13893    pub fn insert_blocks(
13894        &mut self,
13895        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13896        autoscroll: Option<Autoscroll>,
13897        cx: &mut Context<Self>,
13898    ) -> Vec<CustomBlockId> {
13899        let blocks = self
13900            .display_map
13901            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13902        if let Some(autoscroll) = autoscroll {
13903            self.request_autoscroll(autoscroll, cx);
13904        }
13905        cx.notify();
13906        blocks
13907    }
13908
13909    pub fn resize_blocks(
13910        &mut self,
13911        heights: HashMap<CustomBlockId, u32>,
13912        autoscroll: Option<Autoscroll>,
13913        cx: &mut Context<Self>,
13914    ) {
13915        self.display_map
13916            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13917        if let Some(autoscroll) = autoscroll {
13918            self.request_autoscroll(autoscroll, cx);
13919        }
13920        cx.notify();
13921    }
13922
13923    pub fn replace_blocks(
13924        &mut self,
13925        renderers: HashMap<CustomBlockId, RenderBlock>,
13926        autoscroll: Option<Autoscroll>,
13927        cx: &mut Context<Self>,
13928    ) {
13929        self.display_map
13930            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13931        if let Some(autoscroll) = autoscroll {
13932            self.request_autoscroll(autoscroll, cx);
13933        }
13934        cx.notify();
13935    }
13936
13937    pub fn remove_blocks(
13938        &mut self,
13939        block_ids: HashSet<CustomBlockId>,
13940        autoscroll: Option<Autoscroll>,
13941        cx: &mut Context<Self>,
13942    ) {
13943        self.display_map.update(cx, |display_map, cx| {
13944            display_map.remove_blocks(block_ids, cx)
13945        });
13946        if let Some(autoscroll) = autoscroll {
13947            self.request_autoscroll(autoscroll, cx);
13948        }
13949        cx.notify();
13950    }
13951
13952    pub fn row_for_block(
13953        &self,
13954        block_id: CustomBlockId,
13955        cx: &mut Context<Self>,
13956    ) -> Option<DisplayRow> {
13957        self.display_map
13958            .update(cx, |map, cx| map.row_for_block(block_id, cx))
13959    }
13960
13961    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13962        self.focused_block = Some(focused_block);
13963    }
13964
13965    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13966        self.focused_block.take()
13967    }
13968
13969    pub fn insert_creases(
13970        &mut self,
13971        creases: impl IntoIterator<Item = Crease<Anchor>>,
13972        cx: &mut Context<Self>,
13973    ) -> Vec<CreaseId> {
13974        self.display_map
13975            .update(cx, |map, cx| map.insert_creases(creases, cx))
13976    }
13977
13978    pub fn remove_creases(
13979        &mut self,
13980        ids: impl IntoIterator<Item = CreaseId>,
13981        cx: &mut Context<Self>,
13982    ) {
13983        self.display_map
13984            .update(cx, |map, cx| map.remove_creases(ids, cx));
13985    }
13986
13987    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13988        self.display_map
13989            .update(cx, |map, cx| map.snapshot(cx))
13990            .longest_row()
13991    }
13992
13993    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13994        self.display_map
13995            .update(cx, |map, cx| map.snapshot(cx))
13996            .max_point()
13997    }
13998
13999    pub fn text(&self, cx: &App) -> String {
14000        self.buffer.read(cx).read(cx).text()
14001    }
14002
14003    pub fn is_empty(&self, cx: &App) -> bool {
14004        self.buffer.read(cx).read(cx).is_empty()
14005    }
14006
14007    pub fn text_option(&self, cx: &App) -> Option<String> {
14008        let text = self.text(cx);
14009        let text = text.trim();
14010
14011        if text.is_empty() {
14012            return None;
14013        }
14014
14015        Some(text.to_string())
14016    }
14017
14018    pub fn set_text(
14019        &mut self,
14020        text: impl Into<Arc<str>>,
14021        window: &mut Window,
14022        cx: &mut Context<Self>,
14023    ) {
14024        self.transact(window, cx, |this, _, cx| {
14025            this.buffer
14026                .read(cx)
14027                .as_singleton()
14028                .expect("you can only call set_text on editors for singleton buffers")
14029                .update(cx, |buffer, cx| buffer.set_text(text, cx));
14030        });
14031    }
14032
14033    pub fn display_text(&self, cx: &mut App) -> String {
14034        self.display_map
14035            .update(cx, |map, cx| map.snapshot(cx))
14036            .text()
14037    }
14038
14039    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
14040        let mut wrap_guides = smallvec::smallvec![];
14041
14042        if self.show_wrap_guides == Some(false) {
14043            return wrap_guides;
14044        }
14045
14046        let settings = self.buffer.read(cx).language_settings(cx);
14047        if settings.show_wrap_guides {
14048            match self.soft_wrap_mode(cx) {
14049                SoftWrap::Column(soft_wrap) => {
14050                    wrap_guides.push((soft_wrap as usize, true));
14051                }
14052                SoftWrap::Bounded(soft_wrap) => {
14053                    wrap_guides.push((soft_wrap as usize, true));
14054                }
14055                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
14056            }
14057            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14058        }
14059
14060        wrap_guides
14061    }
14062
14063    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14064        let settings = self.buffer.read(cx).language_settings(cx);
14065        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14066        match mode {
14067            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14068                SoftWrap::None
14069            }
14070            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14071            language_settings::SoftWrap::PreferredLineLength => {
14072                SoftWrap::Column(settings.preferred_line_length)
14073            }
14074            language_settings::SoftWrap::Bounded => {
14075                SoftWrap::Bounded(settings.preferred_line_length)
14076            }
14077        }
14078    }
14079
14080    pub fn set_soft_wrap_mode(
14081        &mut self,
14082        mode: language_settings::SoftWrap,
14083
14084        cx: &mut Context<Self>,
14085    ) {
14086        self.soft_wrap_mode_override = Some(mode);
14087        cx.notify();
14088    }
14089
14090    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14091        self.text_style_refinement = Some(style);
14092    }
14093
14094    /// called by the Element so we know what style we were most recently rendered with.
14095    pub(crate) fn set_style(
14096        &mut self,
14097        style: EditorStyle,
14098        window: &mut Window,
14099        cx: &mut Context<Self>,
14100    ) {
14101        let rem_size = window.rem_size();
14102        self.display_map.update(cx, |map, cx| {
14103            map.set_font(
14104                style.text.font(),
14105                style.text.font_size.to_pixels(rem_size),
14106                cx,
14107            )
14108        });
14109        self.style = Some(style);
14110    }
14111
14112    pub fn style(&self) -> Option<&EditorStyle> {
14113        self.style.as_ref()
14114    }
14115
14116    // Called by the element. This method is not designed to be called outside of the editor
14117    // element's layout code because it does not notify when rewrapping is computed synchronously.
14118    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14119        self.display_map
14120            .update(cx, |map, cx| map.set_wrap_width(width, cx))
14121    }
14122
14123    pub fn set_soft_wrap(&mut self) {
14124        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14125    }
14126
14127    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14128        if self.soft_wrap_mode_override.is_some() {
14129            self.soft_wrap_mode_override.take();
14130        } else {
14131            let soft_wrap = match self.soft_wrap_mode(cx) {
14132                SoftWrap::GitDiff => return,
14133                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14134                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14135                    language_settings::SoftWrap::None
14136                }
14137            };
14138            self.soft_wrap_mode_override = Some(soft_wrap);
14139        }
14140        cx.notify();
14141    }
14142
14143    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14144        let Some(workspace) = self.workspace() else {
14145            return;
14146        };
14147        let fs = workspace.read(cx).app_state().fs.clone();
14148        let current_show = TabBarSettings::get_global(cx).show;
14149        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14150            setting.show = Some(!current_show);
14151        });
14152    }
14153
14154    pub fn toggle_indent_guides(
14155        &mut self,
14156        _: &ToggleIndentGuides,
14157        _: &mut Window,
14158        cx: &mut Context<Self>,
14159    ) {
14160        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14161            self.buffer
14162                .read(cx)
14163                .language_settings(cx)
14164                .indent_guides
14165                .enabled
14166        });
14167        self.show_indent_guides = Some(!currently_enabled);
14168        cx.notify();
14169    }
14170
14171    fn should_show_indent_guides(&self) -> Option<bool> {
14172        self.show_indent_guides
14173    }
14174
14175    pub fn toggle_line_numbers(
14176        &mut self,
14177        _: &ToggleLineNumbers,
14178        _: &mut Window,
14179        cx: &mut Context<Self>,
14180    ) {
14181        let mut editor_settings = EditorSettings::get_global(cx).clone();
14182        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14183        EditorSettings::override_global(editor_settings, cx);
14184    }
14185
14186    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14187        self.use_relative_line_numbers
14188            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14189    }
14190
14191    pub fn toggle_relative_line_numbers(
14192        &mut self,
14193        _: &ToggleRelativeLineNumbers,
14194        _: &mut Window,
14195        cx: &mut Context<Self>,
14196    ) {
14197        let is_relative = self.should_use_relative_line_numbers(cx);
14198        self.set_relative_line_number(Some(!is_relative), cx)
14199    }
14200
14201    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14202        self.use_relative_line_numbers = is_relative;
14203        cx.notify();
14204    }
14205
14206    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14207        self.show_gutter = show_gutter;
14208        cx.notify();
14209    }
14210
14211    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14212        self.show_scrollbars = show_scrollbars;
14213        cx.notify();
14214    }
14215
14216    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14217        self.show_line_numbers = Some(show_line_numbers);
14218        cx.notify();
14219    }
14220
14221    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14222        self.show_git_diff_gutter = Some(show_git_diff_gutter);
14223        cx.notify();
14224    }
14225
14226    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14227        self.show_code_actions = Some(show_code_actions);
14228        cx.notify();
14229    }
14230
14231    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14232        self.show_runnables = Some(show_runnables);
14233        cx.notify();
14234    }
14235
14236    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14237        if self.display_map.read(cx).masked != masked {
14238            self.display_map.update(cx, |map, _| map.masked = masked);
14239        }
14240        cx.notify()
14241    }
14242
14243    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14244        self.show_wrap_guides = Some(show_wrap_guides);
14245        cx.notify();
14246    }
14247
14248    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14249        self.show_indent_guides = Some(show_indent_guides);
14250        cx.notify();
14251    }
14252
14253    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14254        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14255            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14256                if let Some(dir) = file.abs_path(cx).parent() {
14257                    return Some(dir.to_owned());
14258                }
14259            }
14260
14261            if let Some(project_path) = buffer.read(cx).project_path(cx) {
14262                return Some(project_path.path.to_path_buf());
14263            }
14264        }
14265
14266        None
14267    }
14268
14269    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14270        self.active_excerpt(cx)?
14271            .1
14272            .read(cx)
14273            .file()
14274            .and_then(|f| f.as_local())
14275    }
14276
14277    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14278        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14279            let buffer = buffer.read(cx);
14280            if let Some(project_path) = buffer.project_path(cx) {
14281                let project = self.project.as_ref()?.read(cx);
14282                project.absolute_path(&project_path, cx)
14283            } else {
14284                buffer
14285                    .file()
14286                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14287            }
14288        })
14289    }
14290
14291    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14292        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14293            let project_path = buffer.read(cx).project_path(cx)?;
14294            let project = self.project.as_ref()?.read(cx);
14295            let entry = project.entry_for_path(&project_path, cx)?;
14296            let path = entry.path.to_path_buf();
14297            Some(path)
14298        })
14299    }
14300
14301    pub fn reveal_in_finder(
14302        &mut self,
14303        _: &RevealInFileManager,
14304        _window: &mut Window,
14305        cx: &mut Context<Self>,
14306    ) {
14307        if let Some(target) = self.target_file(cx) {
14308            cx.reveal_path(&target.abs_path(cx));
14309        }
14310    }
14311
14312    pub fn copy_path(
14313        &mut self,
14314        _: &zed_actions::workspace::CopyPath,
14315        _window: &mut Window,
14316        cx: &mut Context<Self>,
14317    ) {
14318        if let Some(path) = self.target_file_abs_path(cx) {
14319            if let Some(path) = path.to_str() {
14320                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14321            }
14322        }
14323    }
14324
14325    pub fn copy_relative_path(
14326        &mut self,
14327        _: &zed_actions::workspace::CopyRelativePath,
14328        _window: &mut Window,
14329        cx: &mut Context<Self>,
14330    ) {
14331        if let Some(path) = self.target_file_path(cx) {
14332            if let Some(path) = path.to_str() {
14333                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14334            }
14335        }
14336    }
14337
14338    pub fn copy_file_name_without_extension(
14339        &mut self,
14340        _: &CopyFileNameWithoutExtension,
14341        _: &mut Window,
14342        cx: &mut Context<Self>,
14343    ) {
14344        if let Some(file) = self.target_file(cx) {
14345            if let Some(file_stem) = file.path().file_stem() {
14346                if let Some(name) = file_stem.to_str() {
14347                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14348                }
14349            }
14350        }
14351    }
14352
14353    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14354        if let Some(file) = self.target_file(cx) {
14355            if let Some(file_name) = file.path().file_name() {
14356                if let Some(name) = file_name.to_str() {
14357                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14358                }
14359            }
14360        }
14361    }
14362
14363    pub fn toggle_git_blame(
14364        &mut self,
14365        _: &ToggleGitBlame,
14366        window: &mut Window,
14367        cx: &mut Context<Self>,
14368    ) {
14369        self.show_git_blame_gutter = !self.show_git_blame_gutter;
14370
14371        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14372            self.start_git_blame(true, window, cx);
14373        }
14374
14375        cx.notify();
14376    }
14377
14378    pub fn toggle_git_blame_inline(
14379        &mut self,
14380        _: &ToggleGitBlameInline,
14381        window: &mut Window,
14382        cx: &mut Context<Self>,
14383    ) {
14384        self.toggle_git_blame_inline_internal(true, window, cx);
14385        cx.notify();
14386    }
14387
14388    pub fn git_blame_inline_enabled(&self) -> bool {
14389        self.git_blame_inline_enabled
14390    }
14391
14392    pub fn toggle_selection_menu(
14393        &mut self,
14394        _: &ToggleSelectionMenu,
14395        _: &mut Window,
14396        cx: &mut Context<Self>,
14397    ) {
14398        self.show_selection_menu = self
14399            .show_selection_menu
14400            .map(|show_selections_menu| !show_selections_menu)
14401            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14402
14403        cx.notify();
14404    }
14405
14406    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14407        self.show_selection_menu
14408            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14409    }
14410
14411    fn start_git_blame(
14412        &mut self,
14413        user_triggered: bool,
14414        window: &mut Window,
14415        cx: &mut Context<Self>,
14416    ) {
14417        if let Some(project) = self.project.as_ref() {
14418            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14419                return;
14420            };
14421
14422            if buffer.read(cx).file().is_none() {
14423                return;
14424            }
14425
14426            let focused = self.focus_handle(cx).contains_focused(window, cx);
14427
14428            let project = project.clone();
14429            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14430            self.blame_subscription =
14431                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14432            self.blame = Some(blame);
14433        }
14434    }
14435
14436    fn toggle_git_blame_inline_internal(
14437        &mut self,
14438        user_triggered: bool,
14439        window: &mut Window,
14440        cx: &mut Context<Self>,
14441    ) {
14442        if self.git_blame_inline_enabled {
14443            self.git_blame_inline_enabled = false;
14444            self.show_git_blame_inline = false;
14445            self.show_git_blame_inline_delay_task.take();
14446        } else {
14447            self.git_blame_inline_enabled = true;
14448            self.start_git_blame_inline(user_triggered, window, cx);
14449        }
14450
14451        cx.notify();
14452    }
14453
14454    fn start_git_blame_inline(
14455        &mut self,
14456        user_triggered: bool,
14457        window: &mut Window,
14458        cx: &mut Context<Self>,
14459    ) {
14460        self.start_git_blame(user_triggered, window, cx);
14461
14462        if ProjectSettings::get_global(cx)
14463            .git
14464            .inline_blame_delay()
14465            .is_some()
14466        {
14467            self.start_inline_blame_timer(window, cx);
14468        } else {
14469            self.show_git_blame_inline = true
14470        }
14471    }
14472
14473    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14474        self.blame.as_ref()
14475    }
14476
14477    pub fn show_git_blame_gutter(&self) -> bool {
14478        self.show_git_blame_gutter
14479    }
14480
14481    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14482        self.show_git_blame_gutter && self.has_blame_entries(cx)
14483    }
14484
14485    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14486        self.show_git_blame_inline
14487            && (self.focus_handle.is_focused(window)
14488                || self
14489                    .git_blame_inline_tooltip
14490                    .as_ref()
14491                    .and_then(|t| t.upgrade())
14492                    .is_some())
14493            && !self.newest_selection_head_on_empty_line(cx)
14494            && self.has_blame_entries(cx)
14495    }
14496
14497    fn has_blame_entries(&self, cx: &App) -> bool {
14498        self.blame()
14499            .map_or(false, |blame| blame.read(cx).has_generated_entries())
14500    }
14501
14502    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14503        let cursor_anchor = self.selections.newest_anchor().head();
14504
14505        let snapshot = self.buffer.read(cx).snapshot(cx);
14506        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14507
14508        snapshot.line_len(buffer_row) == 0
14509    }
14510
14511    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14512        let buffer_and_selection = maybe!({
14513            let selection = self.selections.newest::<Point>(cx);
14514            let selection_range = selection.range();
14515
14516            let multi_buffer = self.buffer().read(cx);
14517            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14518            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14519
14520            let (buffer, range, _) = if selection.reversed {
14521                buffer_ranges.first()
14522            } else {
14523                buffer_ranges.last()
14524            }?;
14525
14526            let selection = text::ToPoint::to_point(&range.start, &buffer).row
14527                ..text::ToPoint::to_point(&range.end, &buffer).row;
14528            Some((
14529                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14530                selection,
14531            ))
14532        });
14533
14534        let Some((buffer, selection)) = buffer_and_selection else {
14535            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14536        };
14537
14538        let Some(project) = self.project.as_ref() else {
14539            return Task::ready(Err(anyhow!("editor does not have project")));
14540        };
14541
14542        project.update(cx, |project, cx| {
14543            project.get_permalink_to_line(&buffer, selection, cx)
14544        })
14545    }
14546
14547    pub fn copy_permalink_to_line(
14548        &mut self,
14549        _: &CopyPermalinkToLine,
14550        window: &mut Window,
14551        cx: &mut Context<Self>,
14552    ) {
14553        let permalink_task = self.get_permalink_to_line(cx);
14554        let workspace = self.workspace();
14555
14556        cx.spawn_in(window, |_, mut cx| async move {
14557            match permalink_task.await {
14558                Ok(permalink) => {
14559                    cx.update(|_, cx| {
14560                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14561                    })
14562                    .ok();
14563                }
14564                Err(err) => {
14565                    let message = format!("Failed to copy permalink: {err}");
14566
14567                    Err::<(), anyhow::Error>(err).log_err();
14568
14569                    if let Some(workspace) = workspace {
14570                        workspace
14571                            .update_in(&mut cx, |workspace, _, cx| {
14572                                struct CopyPermalinkToLine;
14573
14574                                workspace.show_toast(
14575                                    Toast::new(
14576                                        NotificationId::unique::<CopyPermalinkToLine>(),
14577                                        message,
14578                                    ),
14579                                    cx,
14580                                )
14581                            })
14582                            .ok();
14583                    }
14584                }
14585            }
14586        })
14587        .detach();
14588    }
14589
14590    pub fn copy_file_location(
14591        &mut self,
14592        _: &CopyFileLocation,
14593        _: &mut Window,
14594        cx: &mut Context<Self>,
14595    ) {
14596        let selection = self.selections.newest::<Point>(cx).start.row + 1;
14597        if let Some(file) = self.target_file(cx) {
14598            if let Some(path) = file.path().to_str() {
14599                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14600            }
14601        }
14602    }
14603
14604    pub fn open_permalink_to_line(
14605        &mut self,
14606        _: &OpenPermalinkToLine,
14607        window: &mut Window,
14608        cx: &mut Context<Self>,
14609    ) {
14610        let permalink_task = self.get_permalink_to_line(cx);
14611        let workspace = self.workspace();
14612
14613        cx.spawn_in(window, |_, mut cx| async move {
14614            match permalink_task.await {
14615                Ok(permalink) => {
14616                    cx.update(|_, cx| {
14617                        cx.open_url(permalink.as_ref());
14618                    })
14619                    .ok();
14620                }
14621                Err(err) => {
14622                    let message = format!("Failed to open permalink: {err}");
14623
14624                    Err::<(), anyhow::Error>(err).log_err();
14625
14626                    if let Some(workspace) = workspace {
14627                        workspace
14628                            .update(&mut cx, |workspace, cx| {
14629                                struct OpenPermalinkToLine;
14630
14631                                workspace.show_toast(
14632                                    Toast::new(
14633                                        NotificationId::unique::<OpenPermalinkToLine>(),
14634                                        message,
14635                                    ),
14636                                    cx,
14637                                )
14638                            })
14639                            .ok();
14640                    }
14641                }
14642            }
14643        })
14644        .detach();
14645    }
14646
14647    pub fn insert_uuid_v4(
14648        &mut self,
14649        _: &InsertUuidV4,
14650        window: &mut Window,
14651        cx: &mut Context<Self>,
14652    ) {
14653        self.insert_uuid(UuidVersion::V4, window, cx);
14654    }
14655
14656    pub fn insert_uuid_v7(
14657        &mut self,
14658        _: &InsertUuidV7,
14659        window: &mut Window,
14660        cx: &mut Context<Self>,
14661    ) {
14662        self.insert_uuid(UuidVersion::V7, window, cx);
14663    }
14664
14665    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14666        self.transact(window, cx, |this, window, cx| {
14667            let edits = this
14668                .selections
14669                .all::<Point>(cx)
14670                .into_iter()
14671                .map(|selection| {
14672                    let uuid = match version {
14673                        UuidVersion::V4 => uuid::Uuid::new_v4(),
14674                        UuidVersion::V7 => uuid::Uuid::now_v7(),
14675                    };
14676
14677                    (selection.range(), uuid.to_string())
14678                });
14679            this.edit(edits, cx);
14680            this.refresh_inline_completion(true, false, window, cx);
14681        });
14682    }
14683
14684    pub fn open_selections_in_multibuffer(
14685        &mut self,
14686        _: &OpenSelectionsInMultibuffer,
14687        window: &mut Window,
14688        cx: &mut Context<Self>,
14689    ) {
14690        let multibuffer = self.buffer.read(cx);
14691
14692        let Some(buffer) = multibuffer.as_singleton() else {
14693            return;
14694        };
14695
14696        let Some(workspace) = self.workspace() else {
14697            return;
14698        };
14699
14700        let locations = self
14701            .selections
14702            .disjoint_anchors()
14703            .iter()
14704            .map(|range| Location {
14705                buffer: buffer.clone(),
14706                range: range.start.text_anchor..range.end.text_anchor,
14707            })
14708            .collect::<Vec<_>>();
14709
14710        let title = multibuffer.title(cx).to_string();
14711
14712        cx.spawn_in(window, |_, mut cx| async move {
14713            workspace.update_in(&mut cx, |workspace, window, cx| {
14714                Self::open_locations_in_multibuffer(
14715                    workspace,
14716                    locations,
14717                    format!("Selections for '{title}'"),
14718                    false,
14719                    MultibufferSelectionMode::All,
14720                    window,
14721                    cx,
14722                );
14723            })
14724        })
14725        .detach();
14726    }
14727
14728    /// Adds a row highlight for the given range. If a row has multiple highlights, the
14729    /// last highlight added will be used.
14730    ///
14731    /// If the range ends at the beginning of a line, then that line will not be highlighted.
14732    pub fn highlight_rows<T: 'static>(
14733        &mut self,
14734        range: Range<Anchor>,
14735        color: Hsla,
14736        should_autoscroll: bool,
14737        cx: &mut Context<Self>,
14738    ) {
14739        let snapshot = self.buffer().read(cx).snapshot(cx);
14740        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14741        let ix = row_highlights.binary_search_by(|highlight| {
14742            Ordering::Equal
14743                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14744                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14745        });
14746
14747        if let Err(mut ix) = ix {
14748            let index = post_inc(&mut self.highlight_order);
14749
14750            // If this range intersects with the preceding highlight, then merge it with
14751            // the preceding highlight. Otherwise insert a new highlight.
14752            let mut merged = false;
14753            if ix > 0 {
14754                let prev_highlight = &mut row_highlights[ix - 1];
14755                if prev_highlight
14756                    .range
14757                    .end
14758                    .cmp(&range.start, &snapshot)
14759                    .is_ge()
14760                {
14761                    ix -= 1;
14762                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14763                        prev_highlight.range.end = range.end;
14764                    }
14765                    merged = true;
14766                    prev_highlight.index = index;
14767                    prev_highlight.color = color;
14768                    prev_highlight.should_autoscroll = should_autoscroll;
14769                }
14770            }
14771
14772            if !merged {
14773                row_highlights.insert(
14774                    ix,
14775                    RowHighlight {
14776                        range: range.clone(),
14777                        index,
14778                        color,
14779                        should_autoscroll,
14780                    },
14781                );
14782            }
14783
14784            // If any of the following highlights intersect with this one, merge them.
14785            while let Some(next_highlight) = row_highlights.get(ix + 1) {
14786                let highlight = &row_highlights[ix];
14787                if next_highlight
14788                    .range
14789                    .start
14790                    .cmp(&highlight.range.end, &snapshot)
14791                    .is_le()
14792                {
14793                    if next_highlight
14794                        .range
14795                        .end
14796                        .cmp(&highlight.range.end, &snapshot)
14797                        .is_gt()
14798                    {
14799                        row_highlights[ix].range.end = next_highlight.range.end;
14800                    }
14801                    row_highlights.remove(ix + 1);
14802                } else {
14803                    break;
14804                }
14805            }
14806        }
14807    }
14808
14809    /// Remove any highlighted row ranges of the given type that intersect the
14810    /// given ranges.
14811    pub fn remove_highlighted_rows<T: 'static>(
14812        &mut self,
14813        ranges_to_remove: Vec<Range<Anchor>>,
14814        cx: &mut Context<Self>,
14815    ) {
14816        let snapshot = self.buffer().read(cx).snapshot(cx);
14817        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14818        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14819        row_highlights.retain(|highlight| {
14820            while let Some(range_to_remove) = ranges_to_remove.peek() {
14821                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14822                    Ordering::Less | Ordering::Equal => {
14823                        ranges_to_remove.next();
14824                    }
14825                    Ordering::Greater => {
14826                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14827                            Ordering::Less | Ordering::Equal => {
14828                                return false;
14829                            }
14830                            Ordering::Greater => break,
14831                        }
14832                    }
14833                }
14834            }
14835
14836            true
14837        })
14838    }
14839
14840    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14841    pub fn clear_row_highlights<T: 'static>(&mut self) {
14842        self.highlighted_rows.remove(&TypeId::of::<T>());
14843    }
14844
14845    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14846    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14847        self.highlighted_rows
14848            .get(&TypeId::of::<T>())
14849            .map_or(&[] as &[_], |vec| vec.as_slice())
14850            .iter()
14851            .map(|highlight| (highlight.range.clone(), highlight.color))
14852    }
14853
14854    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14855    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14856    /// Allows to ignore certain kinds of highlights.
14857    pub fn highlighted_display_rows(
14858        &self,
14859        window: &mut Window,
14860        cx: &mut App,
14861    ) -> BTreeMap<DisplayRow, Background> {
14862        let snapshot = self.snapshot(window, cx);
14863        let mut used_highlight_orders = HashMap::default();
14864        self.highlighted_rows
14865            .iter()
14866            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14867            .fold(
14868                BTreeMap::<DisplayRow, Background>::new(),
14869                |mut unique_rows, highlight| {
14870                    let start = highlight.range.start.to_display_point(&snapshot);
14871                    let end = highlight.range.end.to_display_point(&snapshot);
14872                    let start_row = start.row().0;
14873                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14874                        && end.column() == 0
14875                    {
14876                        end.row().0.saturating_sub(1)
14877                    } else {
14878                        end.row().0
14879                    };
14880                    for row in start_row..=end_row {
14881                        let used_index =
14882                            used_highlight_orders.entry(row).or_insert(highlight.index);
14883                        if highlight.index >= *used_index {
14884                            *used_index = highlight.index;
14885                            unique_rows.insert(DisplayRow(row), highlight.color.into());
14886                        }
14887                    }
14888                    unique_rows
14889                },
14890            )
14891    }
14892
14893    pub fn highlighted_display_row_for_autoscroll(
14894        &self,
14895        snapshot: &DisplaySnapshot,
14896    ) -> Option<DisplayRow> {
14897        self.highlighted_rows
14898            .values()
14899            .flat_map(|highlighted_rows| highlighted_rows.iter())
14900            .filter_map(|highlight| {
14901                if highlight.should_autoscroll {
14902                    Some(highlight.range.start.to_display_point(snapshot).row())
14903                } else {
14904                    None
14905                }
14906            })
14907            .min()
14908    }
14909
14910    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14911        self.highlight_background::<SearchWithinRange>(
14912            ranges,
14913            |colors| colors.editor_document_highlight_read_background,
14914            cx,
14915        )
14916    }
14917
14918    pub fn set_breadcrumb_header(&mut self, new_header: String) {
14919        self.breadcrumb_header = Some(new_header);
14920    }
14921
14922    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14923        self.clear_background_highlights::<SearchWithinRange>(cx);
14924    }
14925
14926    pub fn highlight_background<T: 'static>(
14927        &mut self,
14928        ranges: &[Range<Anchor>],
14929        color_fetcher: fn(&ThemeColors) -> Hsla,
14930        cx: &mut Context<Self>,
14931    ) {
14932        self.background_highlights
14933            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14934        self.scrollbar_marker_state.dirty = true;
14935        cx.notify();
14936    }
14937
14938    pub fn clear_background_highlights<T: 'static>(
14939        &mut self,
14940        cx: &mut Context<Self>,
14941    ) -> Option<BackgroundHighlight> {
14942        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14943        if !text_highlights.1.is_empty() {
14944            self.scrollbar_marker_state.dirty = true;
14945            cx.notify();
14946        }
14947        Some(text_highlights)
14948    }
14949
14950    pub fn highlight_gutter<T: 'static>(
14951        &mut self,
14952        ranges: &[Range<Anchor>],
14953        color_fetcher: fn(&App) -> Hsla,
14954        cx: &mut Context<Self>,
14955    ) {
14956        self.gutter_highlights
14957            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14958        cx.notify();
14959    }
14960
14961    pub fn clear_gutter_highlights<T: 'static>(
14962        &mut self,
14963        cx: &mut Context<Self>,
14964    ) -> Option<GutterHighlight> {
14965        cx.notify();
14966        self.gutter_highlights.remove(&TypeId::of::<T>())
14967    }
14968
14969    #[cfg(feature = "test-support")]
14970    pub fn all_text_background_highlights(
14971        &self,
14972        window: &mut Window,
14973        cx: &mut Context<Self>,
14974    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14975        let snapshot = self.snapshot(window, cx);
14976        let buffer = &snapshot.buffer_snapshot;
14977        let start = buffer.anchor_before(0);
14978        let end = buffer.anchor_after(buffer.len());
14979        let theme = cx.theme().colors();
14980        self.background_highlights_in_range(start..end, &snapshot, theme)
14981    }
14982
14983    #[cfg(feature = "test-support")]
14984    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14985        let snapshot = self.buffer().read(cx).snapshot(cx);
14986
14987        let highlights = self
14988            .background_highlights
14989            .get(&TypeId::of::<items::BufferSearchHighlights>());
14990
14991        if let Some((_color, ranges)) = highlights {
14992            ranges
14993                .iter()
14994                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14995                .collect_vec()
14996        } else {
14997            vec![]
14998        }
14999    }
15000
15001    fn document_highlights_for_position<'a>(
15002        &'a self,
15003        position: Anchor,
15004        buffer: &'a MultiBufferSnapshot,
15005    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
15006        let read_highlights = self
15007            .background_highlights
15008            .get(&TypeId::of::<DocumentHighlightRead>())
15009            .map(|h| &h.1);
15010        let write_highlights = self
15011            .background_highlights
15012            .get(&TypeId::of::<DocumentHighlightWrite>())
15013            .map(|h| &h.1);
15014        let left_position = position.bias_left(buffer);
15015        let right_position = position.bias_right(buffer);
15016        read_highlights
15017            .into_iter()
15018            .chain(write_highlights)
15019            .flat_map(move |ranges| {
15020                let start_ix = match ranges.binary_search_by(|probe| {
15021                    let cmp = probe.end.cmp(&left_position, buffer);
15022                    if cmp.is_ge() {
15023                        Ordering::Greater
15024                    } else {
15025                        Ordering::Less
15026                    }
15027                }) {
15028                    Ok(i) | Err(i) => i,
15029                };
15030
15031                ranges[start_ix..]
15032                    .iter()
15033                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
15034            })
15035    }
15036
15037    pub fn has_background_highlights<T: 'static>(&self) -> bool {
15038        self.background_highlights
15039            .get(&TypeId::of::<T>())
15040            .map_or(false, |(_, highlights)| !highlights.is_empty())
15041    }
15042
15043    pub fn background_highlights_in_range(
15044        &self,
15045        search_range: Range<Anchor>,
15046        display_snapshot: &DisplaySnapshot,
15047        theme: &ThemeColors,
15048    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15049        let mut results = Vec::new();
15050        for (color_fetcher, ranges) in self.background_highlights.values() {
15051            let color = color_fetcher(theme);
15052            let start_ix = match ranges.binary_search_by(|probe| {
15053                let cmp = probe
15054                    .end
15055                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15056                if cmp.is_gt() {
15057                    Ordering::Greater
15058                } else {
15059                    Ordering::Less
15060                }
15061            }) {
15062                Ok(i) | Err(i) => i,
15063            };
15064            for range in &ranges[start_ix..] {
15065                if range
15066                    .start
15067                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15068                    .is_ge()
15069                {
15070                    break;
15071                }
15072
15073                let start = range.start.to_display_point(display_snapshot);
15074                let end = range.end.to_display_point(display_snapshot);
15075                results.push((start..end, color))
15076            }
15077        }
15078        results
15079    }
15080
15081    pub fn background_highlight_row_ranges<T: 'static>(
15082        &self,
15083        search_range: Range<Anchor>,
15084        display_snapshot: &DisplaySnapshot,
15085        count: usize,
15086    ) -> Vec<RangeInclusive<DisplayPoint>> {
15087        let mut results = Vec::new();
15088        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15089            return vec![];
15090        };
15091
15092        let start_ix = match ranges.binary_search_by(|probe| {
15093            let cmp = probe
15094                .end
15095                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15096            if cmp.is_gt() {
15097                Ordering::Greater
15098            } else {
15099                Ordering::Less
15100            }
15101        }) {
15102            Ok(i) | Err(i) => i,
15103        };
15104        let mut push_region = |start: Option<Point>, end: Option<Point>| {
15105            if let (Some(start_display), Some(end_display)) = (start, end) {
15106                results.push(
15107                    start_display.to_display_point(display_snapshot)
15108                        ..=end_display.to_display_point(display_snapshot),
15109                );
15110            }
15111        };
15112        let mut start_row: Option<Point> = None;
15113        let mut end_row: Option<Point> = None;
15114        if ranges.len() > count {
15115            return Vec::new();
15116        }
15117        for range in &ranges[start_ix..] {
15118            if range
15119                .start
15120                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15121                .is_ge()
15122            {
15123                break;
15124            }
15125            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15126            if let Some(current_row) = &end_row {
15127                if end.row == current_row.row {
15128                    continue;
15129                }
15130            }
15131            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15132            if start_row.is_none() {
15133                assert_eq!(end_row, None);
15134                start_row = Some(start);
15135                end_row = Some(end);
15136                continue;
15137            }
15138            if let Some(current_end) = end_row.as_mut() {
15139                if start.row > current_end.row + 1 {
15140                    push_region(start_row, end_row);
15141                    start_row = Some(start);
15142                    end_row = Some(end);
15143                } else {
15144                    // Merge two hunks.
15145                    *current_end = end;
15146                }
15147            } else {
15148                unreachable!();
15149            }
15150        }
15151        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15152        push_region(start_row, end_row);
15153        results
15154    }
15155
15156    pub fn gutter_highlights_in_range(
15157        &self,
15158        search_range: Range<Anchor>,
15159        display_snapshot: &DisplaySnapshot,
15160        cx: &App,
15161    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15162        let mut results = Vec::new();
15163        for (color_fetcher, ranges) in self.gutter_highlights.values() {
15164            let color = color_fetcher(cx);
15165            let start_ix = match ranges.binary_search_by(|probe| {
15166                let cmp = probe
15167                    .end
15168                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15169                if cmp.is_gt() {
15170                    Ordering::Greater
15171                } else {
15172                    Ordering::Less
15173                }
15174            }) {
15175                Ok(i) | Err(i) => i,
15176            };
15177            for range in &ranges[start_ix..] {
15178                if range
15179                    .start
15180                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15181                    .is_ge()
15182                {
15183                    break;
15184                }
15185
15186                let start = range.start.to_display_point(display_snapshot);
15187                let end = range.end.to_display_point(display_snapshot);
15188                results.push((start..end, color))
15189            }
15190        }
15191        results
15192    }
15193
15194    /// Get the text ranges corresponding to the redaction query
15195    pub fn redacted_ranges(
15196        &self,
15197        search_range: Range<Anchor>,
15198        display_snapshot: &DisplaySnapshot,
15199        cx: &App,
15200    ) -> Vec<Range<DisplayPoint>> {
15201        display_snapshot
15202            .buffer_snapshot
15203            .redacted_ranges(search_range, |file| {
15204                if let Some(file) = file {
15205                    file.is_private()
15206                        && EditorSettings::get(
15207                            Some(SettingsLocation {
15208                                worktree_id: file.worktree_id(cx),
15209                                path: file.path().as_ref(),
15210                            }),
15211                            cx,
15212                        )
15213                        .redact_private_values
15214                } else {
15215                    false
15216                }
15217            })
15218            .map(|range| {
15219                range.start.to_display_point(display_snapshot)
15220                    ..range.end.to_display_point(display_snapshot)
15221            })
15222            .collect()
15223    }
15224
15225    pub fn highlight_text<T: 'static>(
15226        &mut self,
15227        ranges: Vec<Range<Anchor>>,
15228        style: HighlightStyle,
15229        cx: &mut Context<Self>,
15230    ) {
15231        self.display_map.update(cx, |map, _| {
15232            map.highlight_text(TypeId::of::<T>(), ranges, style)
15233        });
15234        cx.notify();
15235    }
15236
15237    pub(crate) fn highlight_inlays<T: 'static>(
15238        &mut self,
15239        highlights: Vec<InlayHighlight>,
15240        style: HighlightStyle,
15241        cx: &mut Context<Self>,
15242    ) {
15243        self.display_map.update(cx, |map, _| {
15244            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15245        });
15246        cx.notify();
15247    }
15248
15249    pub fn text_highlights<'a, T: 'static>(
15250        &'a self,
15251        cx: &'a App,
15252    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15253        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15254    }
15255
15256    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15257        let cleared = self
15258            .display_map
15259            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15260        if cleared {
15261            cx.notify();
15262        }
15263    }
15264
15265    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15266        (self.read_only(cx) || self.blink_manager.read(cx).visible())
15267            && self.focus_handle.is_focused(window)
15268    }
15269
15270    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15271        self.show_cursor_when_unfocused = is_enabled;
15272        cx.notify();
15273    }
15274
15275    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15276        cx.notify();
15277    }
15278
15279    fn on_buffer_event(
15280        &mut self,
15281        multibuffer: &Entity<MultiBuffer>,
15282        event: &multi_buffer::Event,
15283        window: &mut Window,
15284        cx: &mut Context<Self>,
15285    ) {
15286        match event {
15287            multi_buffer::Event::Edited {
15288                singleton_buffer_edited,
15289                edited_buffer: buffer_edited,
15290            } => {
15291                self.scrollbar_marker_state.dirty = true;
15292                self.active_indent_guides_state.dirty = true;
15293                self.refresh_active_diagnostics(cx);
15294                self.refresh_code_actions(window, cx);
15295                if self.has_active_inline_completion() {
15296                    self.update_visible_inline_completion(window, cx);
15297                }
15298                if let Some(buffer) = buffer_edited {
15299                    let buffer_id = buffer.read(cx).remote_id();
15300                    if !self.registered_buffers.contains_key(&buffer_id) {
15301                        if let Some(project) = self.project.as_ref() {
15302                            project.update(cx, |project, cx| {
15303                                self.registered_buffers.insert(
15304                                    buffer_id,
15305                                    project.register_buffer_with_language_servers(&buffer, cx),
15306                                );
15307                            })
15308                        }
15309                    }
15310                }
15311                cx.emit(EditorEvent::BufferEdited);
15312                cx.emit(SearchEvent::MatchesInvalidated);
15313                if *singleton_buffer_edited {
15314                    if let Some(project) = &self.project {
15315                        #[allow(clippy::mutable_key_type)]
15316                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15317                            multibuffer
15318                                .all_buffers()
15319                                .into_iter()
15320                                .filter_map(|buffer| {
15321                                    buffer.update(cx, |buffer, cx| {
15322                                        let language = buffer.language()?;
15323                                        let should_discard = project.update(cx, |project, cx| {
15324                                            project.is_local()
15325                                                && !project.has_language_servers_for(buffer, cx)
15326                                        });
15327                                        should_discard.not().then_some(language.clone())
15328                                    })
15329                                })
15330                                .collect::<HashSet<_>>()
15331                        });
15332                        if !languages_affected.is_empty() {
15333                            self.refresh_inlay_hints(
15334                                InlayHintRefreshReason::BufferEdited(languages_affected),
15335                                cx,
15336                            );
15337                        }
15338                    }
15339                }
15340
15341                let Some(project) = &self.project else { return };
15342                let (telemetry, is_via_ssh) = {
15343                    let project = project.read(cx);
15344                    let telemetry = project.client().telemetry().clone();
15345                    let is_via_ssh = project.is_via_ssh();
15346                    (telemetry, is_via_ssh)
15347                };
15348                refresh_linked_ranges(self, window, cx);
15349                telemetry.log_edit_event("editor", is_via_ssh);
15350            }
15351            multi_buffer::Event::ExcerptsAdded {
15352                buffer,
15353                predecessor,
15354                excerpts,
15355            } => {
15356                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15357                let buffer_id = buffer.read(cx).remote_id();
15358                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15359                    if let Some(project) = &self.project {
15360                        get_uncommitted_diff_for_buffer(
15361                            project,
15362                            [buffer.clone()],
15363                            self.buffer.clone(),
15364                            cx,
15365                        )
15366                        .detach();
15367                    }
15368                }
15369                cx.emit(EditorEvent::ExcerptsAdded {
15370                    buffer: buffer.clone(),
15371                    predecessor: *predecessor,
15372                    excerpts: excerpts.clone(),
15373                });
15374                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15375            }
15376            multi_buffer::Event::ExcerptsRemoved { ids } => {
15377                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15378                let buffer = self.buffer.read(cx);
15379                self.registered_buffers
15380                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15381                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15382            }
15383            multi_buffer::Event::ExcerptsEdited {
15384                excerpt_ids,
15385                buffer_ids,
15386            } => {
15387                self.display_map.update(cx, |map, cx| {
15388                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
15389                });
15390                cx.emit(EditorEvent::ExcerptsEdited {
15391                    ids: excerpt_ids.clone(),
15392                })
15393            }
15394            multi_buffer::Event::ExcerptsExpanded { ids } => {
15395                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15396                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15397            }
15398            multi_buffer::Event::Reparsed(buffer_id) => {
15399                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15400
15401                cx.emit(EditorEvent::Reparsed(*buffer_id));
15402            }
15403            multi_buffer::Event::DiffHunksToggled => {
15404                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15405            }
15406            multi_buffer::Event::LanguageChanged(buffer_id) => {
15407                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15408                cx.emit(EditorEvent::Reparsed(*buffer_id));
15409                cx.notify();
15410            }
15411            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15412            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15413            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15414                cx.emit(EditorEvent::TitleChanged)
15415            }
15416            // multi_buffer::Event::DiffBaseChanged => {
15417            //     self.scrollbar_marker_state.dirty = true;
15418            //     cx.emit(EditorEvent::DiffBaseChanged);
15419            //     cx.notify();
15420            // }
15421            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15422            multi_buffer::Event::DiagnosticsUpdated => {
15423                self.refresh_active_diagnostics(cx);
15424                self.refresh_inline_diagnostics(true, window, cx);
15425                self.scrollbar_marker_state.dirty = true;
15426                cx.notify();
15427            }
15428            _ => {}
15429        };
15430    }
15431
15432    fn on_display_map_changed(
15433        &mut self,
15434        _: Entity<DisplayMap>,
15435        _: &mut Window,
15436        cx: &mut Context<Self>,
15437    ) {
15438        cx.notify();
15439    }
15440
15441    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15442        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15443        self.update_edit_prediction_settings(cx);
15444        self.refresh_inline_completion(true, false, window, cx);
15445        self.refresh_inlay_hints(
15446            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15447                self.selections.newest_anchor().head(),
15448                &self.buffer.read(cx).snapshot(cx),
15449                cx,
15450            )),
15451            cx,
15452        );
15453
15454        let old_cursor_shape = self.cursor_shape;
15455
15456        {
15457            let editor_settings = EditorSettings::get_global(cx);
15458            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15459            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15460            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15461        }
15462
15463        if old_cursor_shape != self.cursor_shape {
15464            cx.emit(EditorEvent::CursorShapeChanged);
15465        }
15466
15467        let project_settings = ProjectSettings::get_global(cx);
15468        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15469
15470        if self.mode == EditorMode::Full {
15471            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15472            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15473            if self.show_inline_diagnostics != show_inline_diagnostics {
15474                self.show_inline_diagnostics = show_inline_diagnostics;
15475                self.refresh_inline_diagnostics(false, window, cx);
15476            }
15477
15478            if self.git_blame_inline_enabled != inline_blame_enabled {
15479                self.toggle_git_blame_inline_internal(false, window, cx);
15480            }
15481        }
15482
15483        cx.notify();
15484    }
15485
15486    pub fn set_searchable(&mut self, searchable: bool) {
15487        self.searchable = searchable;
15488    }
15489
15490    pub fn searchable(&self) -> bool {
15491        self.searchable
15492    }
15493
15494    fn open_proposed_changes_editor(
15495        &mut self,
15496        _: &OpenProposedChangesEditor,
15497        window: &mut Window,
15498        cx: &mut Context<Self>,
15499    ) {
15500        let Some(workspace) = self.workspace() else {
15501            cx.propagate();
15502            return;
15503        };
15504
15505        let selections = self.selections.all::<usize>(cx);
15506        let multi_buffer = self.buffer.read(cx);
15507        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15508        let mut new_selections_by_buffer = HashMap::default();
15509        for selection in selections {
15510            for (buffer, range, _) in
15511                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15512            {
15513                let mut range = range.to_point(buffer);
15514                range.start.column = 0;
15515                range.end.column = buffer.line_len(range.end.row);
15516                new_selections_by_buffer
15517                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15518                    .or_insert(Vec::new())
15519                    .push(range)
15520            }
15521        }
15522
15523        let proposed_changes_buffers = new_selections_by_buffer
15524            .into_iter()
15525            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15526            .collect::<Vec<_>>();
15527        let proposed_changes_editor = cx.new(|cx| {
15528            ProposedChangesEditor::new(
15529                "Proposed changes",
15530                proposed_changes_buffers,
15531                self.project.clone(),
15532                window,
15533                cx,
15534            )
15535        });
15536
15537        window.defer(cx, move |window, cx| {
15538            workspace.update(cx, |workspace, cx| {
15539                workspace.active_pane().update(cx, |pane, cx| {
15540                    pane.add_item(
15541                        Box::new(proposed_changes_editor),
15542                        true,
15543                        true,
15544                        None,
15545                        window,
15546                        cx,
15547                    );
15548                });
15549            });
15550        });
15551    }
15552
15553    pub fn open_excerpts_in_split(
15554        &mut self,
15555        _: &OpenExcerptsSplit,
15556        window: &mut Window,
15557        cx: &mut Context<Self>,
15558    ) {
15559        self.open_excerpts_common(None, true, window, cx)
15560    }
15561
15562    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15563        self.open_excerpts_common(None, false, window, cx)
15564    }
15565
15566    fn open_excerpts_common(
15567        &mut self,
15568        jump_data: Option<JumpData>,
15569        split: bool,
15570        window: &mut Window,
15571        cx: &mut Context<Self>,
15572    ) {
15573        let Some(workspace) = self.workspace() else {
15574            cx.propagate();
15575            return;
15576        };
15577
15578        if self.buffer.read(cx).is_singleton() {
15579            cx.propagate();
15580            return;
15581        }
15582
15583        let mut new_selections_by_buffer = HashMap::default();
15584        match &jump_data {
15585            Some(JumpData::MultiBufferPoint {
15586                excerpt_id,
15587                position,
15588                anchor,
15589                line_offset_from_top,
15590            }) => {
15591                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15592                if let Some(buffer) = multi_buffer_snapshot
15593                    .buffer_id_for_excerpt(*excerpt_id)
15594                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15595                {
15596                    let buffer_snapshot = buffer.read(cx).snapshot();
15597                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15598                        language::ToPoint::to_point(anchor, &buffer_snapshot)
15599                    } else {
15600                        buffer_snapshot.clip_point(*position, Bias::Left)
15601                    };
15602                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15603                    new_selections_by_buffer.insert(
15604                        buffer,
15605                        (
15606                            vec![jump_to_offset..jump_to_offset],
15607                            Some(*line_offset_from_top),
15608                        ),
15609                    );
15610                }
15611            }
15612            Some(JumpData::MultiBufferRow {
15613                row,
15614                line_offset_from_top,
15615            }) => {
15616                let point = MultiBufferPoint::new(row.0, 0);
15617                if let Some((buffer, buffer_point, _)) =
15618                    self.buffer.read(cx).point_to_buffer_point(point, cx)
15619                {
15620                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15621                    new_selections_by_buffer
15622                        .entry(buffer)
15623                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
15624                        .0
15625                        .push(buffer_offset..buffer_offset)
15626                }
15627            }
15628            None => {
15629                let selections = self.selections.all::<usize>(cx);
15630                let multi_buffer = self.buffer.read(cx);
15631                for selection in selections {
15632                    for (snapshot, range, _, anchor) in multi_buffer
15633                        .snapshot(cx)
15634                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15635                    {
15636                        if let Some(anchor) = anchor {
15637                            // selection is in a deleted hunk
15638                            let Some(buffer_id) = anchor.buffer_id else {
15639                                continue;
15640                            };
15641                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15642                                continue;
15643                            };
15644                            let offset = text::ToOffset::to_offset(
15645                                &anchor.text_anchor,
15646                                &buffer_handle.read(cx).snapshot(),
15647                            );
15648                            let range = offset..offset;
15649                            new_selections_by_buffer
15650                                .entry(buffer_handle)
15651                                .or_insert((Vec::new(), None))
15652                                .0
15653                                .push(range)
15654                        } else {
15655                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15656                            else {
15657                                continue;
15658                            };
15659                            new_selections_by_buffer
15660                                .entry(buffer_handle)
15661                                .or_insert((Vec::new(), None))
15662                                .0
15663                                .push(range)
15664                        }
15665                    }
15666                }
15667            }
15668        }
15669
15670        if new_selections_by_buffer.is_empty() {
15671            return;
15672        }
15673
15674        // We defer the pane interaction because we ourselves are a workspace item
15675        // and activating a new item causes the pane to call a method on us reentrantly,
15676        // which panics if we're on the stack.
15677        window.defer(cx, move |window, cx| {
15678            workspace.update(cx, |workspace, cx| {
15679                let pane = if split {
15680                    workspace.adjacent_pane(window, cx)
15681                } else {
15682                    workspace.active_pane().clone()
15683                };
15684
15685                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15686                    let editor = buffer
15687                        .read(cx)
15688                        .file()
15689                        .is_none()
15690                        .then(|| {
15691                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15692                            // so `workspace.open_project_item` will never find them, always opening a new editor.
15693                            // Instead, we try to activate the existing editor in the pane first.
15694                            let (editor, pane_item_index) =
15695                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
15696                                    let editor = item.downcast::<Editor>()?;
15697                                    let singleton_buffer =
15698                                        editor.read(cx).buffer().read(cx).as_singleton()?;
15699                                    if singleton_buffer == buffer {
15700                                        Some((editor, i))
15701                                    } else {
15702                                        None
15703                                    }
15704                                })?;
15705                            pane.update(cx, |pane, cx| {
15706                                pane.activate_item(pane_item_index, true, true, window, cx)
15707                            });
15708                            Some(editor)
15709                        })
15710                        .flatten()
15711                        .unwrap_or_else(|| {
15712                            workspace.open_project_item::<Self>(
15713                                pane.clone(),
15714                                buffer,
15715                                true,
15716                                true,
15717                                window,
15718                                cx,
15719                            )
15720                        });
15721
15722                    editor.update(cx, |editor, cx| {
15723                        let autoscroll = match scroll_offset {
15724                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15725                            None => Autoscroll::newest(),
15726                        };
15727                        let nav_history = editor.nav_history.take();
15728                        editor.change_selections(Some(autoscroll), window, cx, |s| {
15729                            s.select_ranges(ranges);
15730                        });
15731                        editor.nav_history = nav_history;
15732                    });
15733                }
15734            })
15735        });
15736    }
15737
15738    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15739        let snapshot = self.buffer.read(cx).read(cx);
15740        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15741        Some(
15742            ranges
15743                .iter()
15744                .map(move |range| {
15745                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15746                })
15747                .collect(),
15748        )
15749    }
15750
15751    fn selection_replacement_ranges(
15752        &self,
15753        range: Range<OffsetUtf16>,
15754        cx: &mut App,
15755    ) -> Vec<Range<OffsetUtf16>> {
15756        let selections = self.selections.all::<OffsetUtf16>(cx);
15757        let newest_selection = selections
15758            .iter()
15759            .max_by_key(|selection| selection.id)
15760            .unwrap();
15761        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15762        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15763        let snapshot = self.buffer.read(cx).read(cx);
15764        selections
15765            .into_iter()
15766            .map(|mut selection| {
15767                selection.start.0 =
15768                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
15769                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15770                snapshot.clip_offset_utf16(selection.start, Bias::Left)
15771                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15772            })
15773            .collect()
15774    }
15775
15776    fn report_editor_event(
15777        &self,
15778        event_type: &'static str,
15779        file_extension: Option<String>,
15780        cx: &App,
15781    ) {
15782        if cfg!(any(test, feature = "test-support")) {
15783            return;
15784        }
15785
15786        let Some(project) = &self.project else { return };
15787
15788        // If None, we are in a file without an extension
15789        let file = self
15790            .buffer
15791            .read(cx)
15792            .as_singleton()
15793            .and_then(|b| b.read(cx).file());
15794        let file_extension = file_extension.or(file
15795            .as_ref()
15796            .and_then(|file| Path::new(file.file_name(cx)).extension())
15797            .and_then(|e| e.to_str())
15798            .map(|a| a.to_string()));
15799
15800        let vim_mode = cx
15801            .global::<SettingsStore>()
15802            .raw_user_settings()
15803            .get("vim_mode")
15804            == Some(&serde_json::Value::Bool(true));
15805
15806        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15807        let copilot_enabled = edit_predictions_provider
15808            == language::language_settings::EditPredictionProvider::Copilot;
15809        let copilot_enabled_for_language = self
15810            .buffer
15811            .read(cx)
15812            .language_settings(cx)
15813            .show_edit_predictions;
15814
15815        let project = project.read(cx);
15816        telemetry::event!(
15817            event_type,
15818            file_extension,
15819            vim_mode,
15820            copilot_enabled,
15821            copilot_enabled_for_language,
15822            edit_predictions_provider,
15823            is_via_ssh = project.is_via_ssh(),
15824        );
15825    }
15826
15827    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15828    /// with each line being an array of {text, highlight} objects.
15829    fn copy_highlight_json(
15830        &mut self,
15831        _: &CopyHighlightJson,
15832        window: &mut Window,
15833        cx: &mut Context<Self>,
15834    ) {
15835        #[derive(Serialize)]
15836        struct Chunk<'a> {
15837            text: String,
15838            highlight: Option<&'a str>,
15839        }
15840
15841        let snapshot = self.buffer.read(cx).snapshot(cx);
15842        let range = self
15843            .selected_text_range(false, window, cx)
15844            .and_then(|selection| {
15845                if selection.range.is_empty() {
15846                    None
15847                } else {
15848                    Some(selection.range)
15849                }
15850            })
15851            .unwrap_or_else(|| 0..snapshot.len());
15852
15853        let chunks = snapshot.chunks(range, true);
15854        let mut lines = Vec::new();
15855        let mut line: VecDeque<Chunk> = VecDeque::new();
15856
15857        let Some(style) = self.style.as_ref() else {
15858            return;
15859        };
15860
15861        for chunk in chunks {
15862            let highlight = chunk
15863                .syntax_highlight_id
15864                .and_then(|id| id.name(&style.syntax));
15865            let mut chunk_lines = chunk.text.split('\n').peekable();
15866            while let Some(text) = chunk_lines.next() {
15867                let mut merged_with_last_token = false;
15868                if let Some(last_token) = line.back_mut() {
15869                    if last_token.highlight == highlight {
15870                        last_token.text.push_str(text);
15871                        merged_with_last_token = true;
15872                    }
15873                }
15874
15875                if !merged_with_last_token {
15876                    line.push_back(Chunk {
15877                        text: text.into(),
15878                        highlight,
15879                    });
15880                }
15881
15882                if chunk_lines.peek().is_some() {
15883                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
15884                        line.pop_front();
15885                    }
15886                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
15887                        line.pop_back();
15888                    }
15889
15890                    lines.push(mem::take(&mut line));
15891                }
15892            }
15893        }
15894
15895        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15896            return;
15897        };
15898        cx.write_to_clipboard(ClipboardItem::new_string(lines));
15899    }
15900
15901    pub fn open_context_menu(
15902        &mut self,
15903        _: &OpenContextMenu,
15904        window: &mut Window,
15905        cx: &mut Context<Self>,
15906    ) {
15907        self.request_autoscroll(Autoscroll::newest(), cx);
15908        let position = self.selections.newest_display(cx).start;
15909        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15910    }
15911
15912    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15913        &self.inlay_hint_cache
15914    }
15915
15916    pub fn replay_insert_event(
15917        &mut self,
15918        text: &str,
15919        relative_utf16_range: Option<Range<isize>>,
15920        window: &mut Window,
15921        cx: &mut Context<Self>,
15922    ) {
15923        if !self.input_enabled {
15924            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15925            return;
15926        }
15927        if let Some(relative_utf16_range) = relative_utf16_range {
15928            let selections = self.selections.all::<OffsetUtf16>(cx);
15929            self.change_selections(None, window, cx, |s| {
15930                let new_ranges = selections.into_iter().map(|range| {
15931                    let start = OffsetUtf16(
15932                        range
15933                            .head()
15934                            .0
15935                            .saturating_add_signed(relative_utf16_range.start),
15936                    );
15937                    let end = OffsetUtf16(
15938                        range
15939                            .head()
15940                            .0
15941                            .saturating_add_signed(relative_utf16_range.end),
15942                    );
15943                    start..end
15944                });
15945                s.select_ranges(new_ranges);
15946            });
15947        }
15948
15949        self.handle_input(text, window, cx);
15950    }
15951
15952    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15953        let Some(provider) = self.semantics_provider.as_ref() else {
15954            return false;
15955        };
15956
15957        let mut supports = false;
15958        self.buffer().update(cx, |this, cx| {
15959            this.for_each_buffer(|buffer| {
15960                supports |= provider.supports_inlay_hints(buffer, cx);
15961            });
15962        });
15963
15964        supports
15965    }
15966
15967    pub fn is_focused(&self, window: &Window) -> bool {
15968        self.focus_handle.is_focused(window)
15969    }
15970
15971    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15972        cx.emit(EditorEvent::Focused);
15973
15974        if let Some(descendant) = self
15975            .last_focused_descendant
15976            .take()
15977            .and_then(|descendant| descendant.upgrade())
15978        {
15979            window.focus(&descendant);
15980        } else {
15981            if let Some(blame) = self.blame.as_ref() {
15982                blame.update(cx, GitBlame::focus)
15983            }
15984
15985            self.blink_manager.update(cx, BlinkManager::enable);
15986            self.show_cursor_names(window, cx);
15987            self.buffer.update(cx, |buffer, cx| {
15988                buffer.finalize_last_transaction(cx);
15989                if self.leader_peer_id.is_none() {
15990                    buffer.set_active_selections(
15991                        &self.selections.disjoint_anchors(),
15992                        self.selections.line_mode,
15993                        self.cursor_shape,
15994                        cx,
15995                    );
15996                }
15997            });
15998        }
15999    }
16000
16001    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16002        cx.emit(EditorEvent::FocusedIn)
16003    }
16004
16005    fn handle_focus_out(
16006        &mut self,
16007        event: FocusOutEvent,
16008        _window: &mut Window,
16009        cx: &mut Context<Self>,
16010    ) {
16011        if event.blurred != self.focus_handle {
16012            self.last_focused_descendant = Some(event.blurred);
16013        }
16014        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
16015    }
16016
16017    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16018        self.blink_manager.update(cx, BlinkManager::disable);
16019        self.buffer
16020            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
16021
16022        if let Some(blame) = self.blame.as_ref() {
16023            blame.update(cx, GitBlame::blur)
16024        }
16025        if !self.hover_state.focused(window, cx) {
16026            hide_hover(self, cx);
16027        }
16028        if !self
16029            .context_menu
16030            .borrow()
16031            .as_ref()
16032            .is_some_and(|context_menu| context_menu.focused(window, cx))
16033        {
16034            self.hide_context_menu(window, cx);
16035        }
16036        self.discard_inline_completion(false, cx);
16037        cx.emit(EditorEvent::Blurred);
16038        cx.notify();
16039    }
16040
16041    pub fn register_action<A: Action>(
16042        &mut self,
16043        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
16044    ) -> Subscription {
16045        let id = self.next_editor_action_id.post_inc();
16046        let listener = Arc::new(listener);
16047        self.editor_actions.borrow_mut().insert(
16048            id,
16049            Box::new(move |window, _| {
16050                let listener = listener.clone();
16051                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
16052                    let action = action.downcast_ref().unwrap();
16053                    if phase == DispatchPhase::Bubble {
16054                        listener(action, window, cx)
16055                    }
16056                })
16057            }),
16058        );
16059
16060        let editor_actions = self.editor_actions.clone();
16061        Subscription::new(move || {
16062            editor_actions.borrow_mut().remove(&id);
16063        })
16064    }
16065
16066    pub fn file_header_size(&self) -> u32 {
16067        FILE_HEADER_HEIGHT
16068    }
16069
16070    pub fn restore(
16071        &mut self,
16072        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16073        window: &mut Window,
16074        cx: &mut Context<Self>,
16075    ) {
16076        let workspace = self.workspace();
16077        let project = self.project.as_ref();
16078        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16079            let mut tasks = Vec::new();
16080            for (buffer_id, changes) in revert_changes {
16081                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16082                    buffer.update(cx, |buffer, cx| {
16083                        buffer.edit(
16084                            changes
16085                                .into_iter()
16086                                .map(|(range, text)| (range, text.to_string())),
16087                            None,
16088                            cx,
16089                        );
16090                    });
16091
16092                    if let Some(project) =
16093                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16094                    {
16095                        project.update(cx, |project, cx| {
16096                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16097                        })
16098                    }
16099                }
16100            }
16101            tasks
16102        });
16103        cx.spawn_in(window, |_, mut cx| async move {
16104            for (buffer, task) in save_tasks {
16105                let result = task.await;
16106                if result.is_err() {
16107                    let Some(path) = buffer
16108                        .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16109                        .ok()
16110                    else {
16111                        continue;
16112                    };
16113                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16114                        let Some(task) = cx
16115                            .update_window_entity(&workspace, |workspace, window, cx| {
16116                                workspace
16117                                    .open_path_preview(path, None, false, false, false, window, cx)
16118                            })
16119                            .ok()
16120                        else {
16121                            continue;
16122                        };
16123                        task.await.log_err();
16124                    }
16125                }
16126            }
16127        })
16128        .detach();
16129        self.change_selections(None, window, cx, |selections| selections.refresh());
16130    }
16131
16132    pub fn to_pixel_point(
16133        &self,
16134        source: multi_buffer::Anchor,
16135        editor_snapshot: &EditorSnapshot,
16136        window: &mut Window,
16137    ) -> Option<gpui::Point<Pixels>> {
16138        let source_point = source.to_display_point(editor_snapshot);
16139        self.display_to_pixel_point(source_point, editor_snapshot, window)
16140    }
16141
16142    pub fn display_to_pixel_point(
16143        &self,
16144        source: DisplayPoint,
16145        editor_snapshot: &EditorSnapshot,
16146        window: &mut Window,
16147    ) -> Option<gpui::Point<Pixels>> {
16148        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16149        let text_layout_details = self.text_layout_details(window);
16150        let scroll_top = text_layout_details
16151            .scroll_anchor
16152            .scroll_position(editor_snapshot)
16153            .y;
16154
16155        if source.row().as_f32() < scroll_top.floor() {
16156            return None;
16157        }
16158        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16159        let source_y = line_height * (source.row().as_f32() - scroll_top);
16160        Some(gpui::Point::new(source_x, source_y))
16161    }
16162
16163    pub fn has_visible_completions_menu(&self) -> bool {
16164        !self.edit_prediction_preview_is_active()
16165            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16166                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16167            })
16168    }
16169
16170    pub fn register_addon<T: Addon>(&mut self, instance: T) {
16171        self.addons
16172            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16173    }
16174
16175    pub fn unregister_addon<T: Addon>(&mut self) {
16176        self.addons.remove(&std::any::TypeId::of::<T>());
16177    }
16178
16179    pub fn addon<T: Addon>(&self) -> Option<&T> {
16180        let type_id = std::any::TypeId::of::<T>();
16181        self.addons
16182            .get(&type_id)
16183            .and_then(|item| item.to_any().downcast_ref::<T>())
16184    }
16185
16186    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16187        let text_layout_details = self.text_layout_details(window);
16188        let style = &text_layout_details.editor_style;
16189        let font_id = window.text_system().resolve_font(&style.text.font());
16190        let font_size = style.text.font_size.to_pixels(window.rem_size());
16191        let line_height = style.text.line_height_in_pixels(window.rem_size());
16192        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16193
16194        gpui::Size::new(em_width, line_height)
16195    }
16196
16197    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16198        self.load_diff_task.clone()
16199    }
16200
16201    fn read_selections_from_db(
16202        &mut self,
16203        item_id: u64,
16204        workspace_id: WorkspaceId,
16205        window: &mut Window,
16206        cx: &mut Context<Editor>,
16207    ) {
16208        if !self.is_singleton(cx)
16209            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16210        {
16211            return;
16212        }
16213        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16214            return;
16215        };
16216        if selections.is_empty() {
16217            return;
16218        }
16219
16220        let snapshot = self.buffer.read(cx).snapshot(cx);
16221        self.change_selections(None, window, cx, |s| {
16222            s.select_ranges(selections.into_iter().map(|(start, end)| {
16223                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16224            }));
16225        });
16226    }
16227}
16228
16229fn insert_extra_newline_brackets(
16230    buffer: &MultiBufferSnapshot,
16231    range: Range<usize>,
16232    language: &language::LanguageScope,
16233) -> bool {
16234    let leading_whitespace_len = buffer
16235        .reversed_chars_at(range.start)
16236        .take_while(|c| c.is_whitespace() && *c != '\n')
16237        .map(|c| c.len_utf8())
16238        .sum::<usize>();
16239    let trailing_whitespace_len = buffer
16240        .chars_at(range.end)
16241        .take_while(|c| c.is_whitespace() && *c != '\n')
16242        .map(|c| c.len_utf8())
16243        .sum::<usize>();
16244    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16245
16246    language.brackets().any(|(pair, enabled)| {
16247        let pair_start = pair.start.trim_end();
16248        let pair_end = pair.end.trim_start();
16249
16250        enabled
16251            && pair.newline
16252            && buffer.contains_str_at(range.end, pair_end)
16253            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16254    })
16255}
16256
16257fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16258    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16259        [(buffer, range, _)] => (*buffer, range.clone()),
16260        _ => return false,
16261    };
16262    let pair = {
16263        let mut result: Option<BracketMatch> = None;
16264
16265        for pair in buffer
16266            .all_bracket_ranges(range.clone())
16267            .filter(move |pair| {
16268                pair.open_range.start <= range.start && pair.close_range.end >= range.end
16269            })
16270        {
16271            let len = pair.close_range.end - pair.open_range.start;
16272
16273            if let Some(existing) = &result {
16274                let existing_len = existing.close_range.end - existing.open_range.start;
16275                if len > existing_len {
16276                    continue;
16277                }
16278            }
16279
16280            result = Some(pair);
16281        }
16282
16283        result
16284    };
16285    let Some(pair) = pair else {
16286        return false;
16287    };
16288    pair.newline_only
16289        && buffer
16290            .chars_for_range(pair.open_range.end..range.start)
16291            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16292            .all(|c| c.is_whitespace() && c != '\n')
16293}
16294
16295fn get_uncommitted_diff_for_buffer(
16296    project: &Entity<Project>,
16297    buffers: impl IntoIterator<Item = Entity<Buffer>>,
16298    buffer: Entity<MultiBuffer>,
16299    cx: &mut App,
16300) -> Task<()> {
16301    let mut tasks = Vec::new();
16302    project.update(cx, |project, cx| {
16303        for buffer in buffers {
16304            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16305        }
16306    });
16307    cx.spawn(|mut cx| async move {
16308        let diffs = futures::future::join_all(tasks).await;
16309        buffer
16310            .update(&mut cx, |buffer, cx| {
16311                for diff in diffs.into_iter().flatten() {
16312                    buffer.add_diff(diff, cx);
16313                }
16314            })
16315            .ok();
16316    })
16317}
16318
16319fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16320    let tab_size = tab_size.get() as usize;
16321    let mut width = offset;
16322
16323    for ch in text.chars() {
16324        width += if ch == '\t' {
16325            tab_size - (width % tab_size)
16326        } else {
16327            1
16328        };
16329    }
16330
16331    width - offset
16332}
16333
16334#[cfg(test)]
16335mod tests {
16336    use super::*;
16337
16338    #[test]
16339    fn test_string_size_with_expanded_tabs() {
16340        let nz = |val| NonZeroU32::new(val).unwrap();
16341        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16342        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16343        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16344        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16345        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16346        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16347        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16348        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16349    }
16350}
16351
16352/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16353struct WordBreakingTokenizer<'a> {
16354    input: &'a str,
16355}
16356
16357impl<'a> WordBreakingTokenizer<'a> {
16358    fn new(input: &'a str) -> Self {
16359        Self { input }
16360    }
16361}
16362
16363fn is_char_ideographic(ch: char) -> bool {
16364    use unicode_script::Script::*;
16365    use unicode_script::UnicodeScript;
16366    matches!(ch.script(), Han | Tangut | Yi)
16367}
16368
16369fn is_grapheme_ideographic(text: &str) -> bool {
16370    text.chars().any(is_char_ideographic)
16371}
16372
16373fn is_grapheme_whitespace(text: &str) -> bool {
16374    text.chars().any(|x| x.is_whitespace())
16375}
16376
16377fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16378    text.chars().next().map_or(false, |ch| {
16379        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16380    })
16381}
16382
16383#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16384struct WordBreakToken<'a> {
16385    token: &'a str,
16386    grapheme_len: usize,
16387    is_whitespace: bool,
16388}
16389
16390impl<'a> Iterator for WordBreakingTokenizer<'a> {
16391    /// Yields a span, the count of graphemes in the token, and whether it was
16392    /// whitespace. Note that it also breaks at word boundaries.
16393    type Item = WordBreakToken<'a>;
16394
16395    fn next(&mut self) -> Option<Self::Item> {
16396        use unicode_segmentation::UnicodeSegmentation;
16397        if self.input.is_empty() {
16398            return None;
16399        }
16400
16401        let mut iter = self.input.graphemes(true).peekable();
16402        let mut offset = 0;
16403        let mut graphemes = 0;
16404        if let Some(first_grapheme) = iter.next() {
16405            let is_whitespace = is_grapheme_whitespace(first_grapheme);
16406            offset += first_grapheme.len();
16407            graphemes += 1;
16408            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16409                if let Some(grapheme) = iter.peek().copied() {
16410                    if should_stay_with_preceding_ideograph(grapheme) {
16411                        offset += grapheme.len();
16412                        graphemes += 1;
16413                    }
16414                }
16415            } else {
16416                let mut words = self.input[offset..].split_word_bound_indices().peekable();
16417                let mut next_word_bound = words.peek().copied();
16418                if next_word_bound.map_or(false, |(i, _)| i == 0) {
16419                    next_word_bound = words.next();
16420                }
16421                while let Some(grapheme) = iter.peek().copied() {
16422                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
16423                        break;
16424                    };
16425                    if is_grapheme_whitespace(grapheme) != is_whitespace {
16426                        break;
16427                    };
16428                    offset += grapheme.len();
16429                    graphemes += 1;
16430                    iter.next();
16431                }
16432            }
16433            let token = &self.input[..offset];
16434            self.input = &self.input[offset..];
16435            if is_whitespace {
16436                Some(WordBreakToken {
16437                    token: " ",
16438                    grapheme_len: 1,
16439                    is_whitespace: true,
16440                })
16441            } else {
16442                Some(WordBreakToken {
16443                    token,
16444                    grapheme_len: graphemes,
16445                    is_whitespace: false,
16446                })
16447            }
16448        } else {
16449            None
16450        }
16451    }
16452}
16453
16454#[test]
16455fn test_word_breaking_tokenizer() {
16456    let tests: &[(&str, &[(&str, usize, bool)])] = &[
16457        ("", &[]),
16458        ("  ", &[(" ", 1, true)]),
16459        ("Ʒ", &[("Ʒ", 1, false)]),
16460        ("Ǽ", &[("Ǽ", 1, false)]),
16461        ("", &[("", 1, false)]),
16462        ("⋑⋑", &[("⋑⋑", 2, false)]),
16463        (
16464            "原理,进而",
16465            &[
16466                ("", 1, false),
16467                ("理,", 2, false),
16468                ("", 1, false),
16469                ("", 1, false),
16470            ],
16471        ),
16472        (
16473            "hello world",
16474            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16475        ),
16476        (
16477            "hello, world",
16478            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16479        ),
16480        (
16481            "  hello world",
16482            &[
16483                (" ", 1, true),
16484                ("hello", 5, false),
16485                (" ", 1, true),
16486                ("world", 5, false),
16487            ],
16488        ),
16489        (
16490            "这是什么 \n 钢笔",
16491            &[
16492                ("", 1, false),
16493                ("", 1, false),
16494                ("", 1, false),
16495                ("", 1, false),
16496                (" ", 1, true),
16497                ("", 1, false),
16498                ("", 1, false),
16499            ],
16500        ),
16501        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16502    ];
16503
16504    for (input, result) in tests {
16505        assert_eq!(
16506            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16507            result
16508                .iter()
16509                .copied()
16510                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16511                    token,
16512                    grapheme_len,
16513                    is_whitespace,
16514                })
16515                .collect::<Vec<_>>()
16516        );
16517    }
16518}
16519
16520fn wrap_with_prefix(
16521    line_prefix: String,
16522    unwrapped_text: String,
16523    wrap_column: usize,
16524    tab_size: NonZeroU32,
16525) -> String {
16526    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16527    let mut wrapped_text = String::new();
16528    let mut current_line = line_prefix.clone();
16529
16530    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16531    let mut current_line_len = line_prefix_len;
16532    for WordBreakToken {
16533        token,
16534        grapheme_len,
16535        is_whitespace,
16536    } in tokenizer
16537    {
16538        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16539            wrapped_text.push_str(current_line.trim_end());
16540            wrapped_text.push('\n');
16541            current_line.truncate(line_prefix.len());
16542            current_line_len = line_prefix_len;
16543            if !is_whitespace {
16544                current_line.push_str(token);
16545                current_line_len += grapheme_len;
16546            }
16547        } else if !is_whitespace {
16548            current_line.push_str(token);
16549            current_line_len += grapheme_len;
16550        } else if current_line_len != line_prefix_len {
16551            current_line.push(' ');
16552            current_line_len += 1;
16553        }
16554    }
16555
16556    if !current_line.is_empty() {
16557        wrapped_text.push_str(&current_line);
16558    }
16559    wrapped_text
16560}
16561
16562#[test]
16563fn test_wrap_with_prefix() {
16564    assert_eq!(
16565        wrap_with_prefix(
16566            "# ".to_string(),
16567            "abcdefg".to_string(),
16568            4,
16569            NonZeroU32::new(4).unwrap()
16570        ),
16571        "# abcdefg"
16572    );
16573    assert_eq!(
16574        wrap_with_prefix(
16575            "".to_string(),
16576            "\thello world".to_string(),
16577            8,
16578            NonZeroU32::new(4).unwrap()
16579        ),
16580        "hello\nworld"
16581    );
16582    assert_eq!(
16583        wrap_with_prefix(
16584            "// ".to_string(),
16585            "xx \nyy zz aa bb cc".to_string(),
16586            12,
16587            NonZeroU32::new(4).unwrap()
16588        ),
16589        "// xx yy zz\n// aa bb cc"
16590    );
16591    assert_eq!(
16592        wrap_with_prefix(
16593            String::new(),
16594            "这是什么 \n 钢笔".to_string(),
16595            3,
16596            NonZeroU32::new(4).unwrap()
16597        ),
16598        "这是什\n么 钢\n"
16599    );
16600}
16601
16602pub trait CollaborationHub {
16603    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16604    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16605    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16606}
16607
16608impl CollaborationHub for Entity<Project> {
16609    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16610        self.read(cx).collaborators()
16611    }
16612
16613    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16614        self.read(cx).user_store().read(cx).participant_indices()
16615    }
16616
16617    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16618        let this = self.read(cx);
16619        let user_ids = this.collaborators().values().map(|c| c.user_id);
16620        this.user_store().read_with(cx, |user_store, cx| {
16621            user_store.participant_names(user_ids, cx)
16622        })
16623    }
16624}
16625
16626pub trait SemanticsProvider {
16627    fn hover(
16628        &self,
16629        buffer: &Entity<Buffer>,
16630        position: text::Anchor,
16631        cx: &mut App,
16632    ) -> Option<Task<Vec<project::Hover>>>;
16633
16634    fn inlay_hints(
16635        &self,
16636        buffer_handle: Entity<Buffer>,
16637        range: Range<text::Anchor>,
16638        cx: &mut App,
16639    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16640
16641    fn resolve_inlay_hint(
16642        &self,
16643        hint: InlayHint,
16644        buffer_handle: Entity<Buffer>,
16645        server_id: LanguageServerId,
16646        cx: &mut App,
16647    ) -> Option<Task<anyhow::Result<InlayHint>>>;
16648
16649    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16650
16651    fn document_highlights(
16652        &self,
16653        buffer: &Entity<Buffer>,
16654        position: text::Anchor,
16655        cx: &mut App,
16656    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16657
16658    fn definitions(
16659        &self,
16660        buffer: &Entity<Buffer>,
16661        position: text::Anchor,
16662        kind: GotoDefinitionKind,
16663        cx: &mut App,
16664    ) -> Option<Task<Result<Vec<LocationLink>>>>;
16665
16666    fn range_for_rename(
16667        &self,
16668        buffer: &Entity<Buffer>,
16669        position: text::Anchor,
16670        cx: &mut App,
16671    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16672
16673    fn perform_rename(
16674        &self,
16675        buffer: &Entity<Buffer>,
16676        position: text::Anchor,
16677        new_name: String,
16678        cx: &mut App,
16679    ) -> Option<Task<Result<ProjectTransaction>>>;
16680}
16681
16682pub trait CompletionProvider {
16683    fn completions(
16684        &self,
16685        buffer: &Entity<Buffer>,
16686        buffer_position: text::Anchor,
16687        trigger: CompletionContext,
16688        window: &mut Window,
16689        cx: &mut Context<Editor>,
16690    ) -> Task<Result<Vec<Completion>>>;
16691
16692    fn resolve_completions(
16693        &self,
16694        buffer: Entity<Buffer>,
16695        completion_indices: Vec<usize>,
16696        completions: Rc<RefCell<Box<[Completion]>>>,
16697        cx: &mut Context<Editor>,
16698    ) -> Task<Result<bool>>;
16699
16700    fn apply_additional_edits_for_completion(
16701        &self,
16702        _buffer: Entity<Buffer>,
16703        _completions: Rc<RefCell<Box<[Completion]>>>,
16704        _completion_index: usize,
16705        _push_to_history: bool,
16706        _cx: &mut Context<Editor>,
16707    ) -> Task<Result<Option<language::Transaction>>> {
16708        Task::ready(Ok(None))
16709    }
16710
16711    fn is_completion_trigger(
16712        &self,
16713        buffer: &Entity<Buffer>,
16714        position: language::Anchor,
16715        text: &str,
16716        trigger_in_words: bool,
16717        cx: &mut Context<Editor>,
16718    ) -> bool;
16719
16720    fn sort_completions(&self) -> bool {
16721        true
16722    }
16723}
16724
16725pub trait CodeActionProvider {
16726    fn id(&self) -> Arc<str>;
16727
16728    fn code_actions(
16729        &self,
16730        buffer: &Entity<Buffer>,
16731        range: Range<text::Anchor>,
16732        window: &mut Window,
16733        cx: &mut App,
16734    ) -> Task<Result<Vec<CodeAction>>>;
16735
16736    fn apply_code_action(
16737        &self,
16738        buffer_handle: Entity<Buffer>,
16739        action: CodeAction,
16740        excerpt_id: ExcerptId,
16741        push_to_history: bool,
16742        window: &mut Window,
16743        cx: &mut App,
16744    ) -> Task<Result<ProjectTransaction>>;
16745}
16746
16747impl CodeActionProvider for Entity<Project> {
16748    fn id(&self) -> Arc<str> {
16749        "project".into()
16750    }
16751
16752    fn code_actions(
16753        &self,
16754        buffer: &Entity<Buffer>,
16755        range: Range<text::Anchor>,
16756        _window: &mut Window,
16757        cx: &mut App,
16758    ) -> Task<Result<Vec<CodeAction>>> {
16759        self.update(cx, |project, cx| {
16760            project.code_actions(buffer, range, None, cx)
16761        })
16762    }
16763
16764    fn apply_code_action(
16765        &self,
16766        buffer_handle: Entity<Buffer>,
16767        action: CodeAction,
16768        _excerpt_id: ExcerptId,
16769        push_to_history: bool,
16770        _window: &mut Window,
16771        cx: &mut App,
16772    ) -> Task<Result<ProjectTransaction>> {
16773        self.update(cx, |project, cx| {
16774            project.apply_code_action(buffer_handle, action, push_to_history, cx)
16775        })
16776    }
16777}
16778
16779fn snippet_completions(
16780    project: &Project,
16781    buffer: &Entity<Buffer>,
16782    buffer_position: text::Anchor,
16783    cx: &mut App,
16784) -> Task<Result<Vec<Completion>>> {
16785    let language = buffer.read(cx).language_at(buffer_position);
16786    let language_name = language.as_ref().map(|language| language.lsp_id());
16787    let snippet_store = project.snippets().read(cx);
16788    let snippets = snippet_store.snippets_for(language_name, cx);
16789
16790    if snippets.is_empty() {
16791        return Task::ready(Ok(vec![]));
16792    }
16793    let snapshot = buffer.read(cx).text_snapshot();
16794    let chars: String = snapshot
16795        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16796        .collect();
16797
16798    let scope = language.map(|language| language.default_scope());
16799    let executor = cx.background_executor().clone();
16800
16801    cx.background_spawn(async move {
16802        let classifier = CharClassifier::new(scope).for_completion(true);
16803        let mut last_word = chars
16804            .chars()
16805            .take_while(|c| classifier.is_word(*c))
16806            .collect::<String>();
16807        last_word = last_word.chars().rev().collect();
16808
16809        if last_word.is_empty() {
16810            return Ok(vec![]);
16811        }
16812
16813        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16814        let to_lsp = |point: &text::Anchor| {
16815            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16816            point_to_lsp(end)
16817        };
16818        let lsp_end = to_lsp(&buffer_position);
16819
16820        let candidates = snippets
16821            .iter()
16822            .enumerate()
16823            .flat_map(|(ix, snippet)| {
16824                snippet
16825                    .prefix
16826                    .iter()
16827                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16828            })
16829            .collect::<Vec<StringMatchCandidate>>();
16830
16831        let mut matches = fuzzy::match_strings(
16832            &candidates,
16833            &last_word,
16834            last_word.chars().any(|c| c.is_uppercase()),
16835            100,
16836            &Default::default(),
16837            executor,
16838        )
16839        .await;
16840
16841        // Remove all candidates where the query's start does not match the start of any word in the candidate
16842        if let Some(query_start) = last_word.chars().next() {
16843            matches.retain(|string_match| {
16844                split_words(&string_match.string).any(|word| {
16845                    // Check that the first codepoint of the word as lowercase matches the first
16846                    // codepoint of the query as lowercase
16847                    word.chars()
16848                        .flat_map(|codepoint| codepoint.to_lowercase())
16849                        .zip(query_start.to_lowercase())
16850                        .all(|(word_cp, query_cp)| word_cp == query_cp)
16851                })
16852            });
16853        }
16854
16855        let matched_strings = matches
16856            .into_iter()
16857            .map(|m| m.string)
16858            .collect::<HashSet<_>>();
16859
16860        let result: Vec<Completion> = snippets
16861            .into_iter()
16862            .filter_map(|snippet| {
16863                let matching_prefix = snippet
16864                    .prefix
16865                    .iter()
16866                    .find(|prefix| matched_strings.contains(*prefix))?;
16867                let start = as_offset - last_word.len();
16868                let start = snapshot.anchor_before(start);
16869                let range = start..buffer_position;
16870                let lsp_start = to_lsp(&start);
16871                let lsp_range = lsp::Range {
16872                    start: lsp_start,
16873                    end: lsp_end,
16874                };
16875                Some(Completion {
16876                    old_range: range,
16877                    new_text: snippet.body.clone(),
16878                    resolved: false,
16879                    label: CodeLabel {
16880                        text: matching_prefix.clone(),
16881                        runs: vec![],
16882                        filter_range: 0..matching_prefix.len(),
16883                    },
16884                    server_id: LanguageServerId(usize::MAX),
16885                    documentation: snippet
16886                        .description
16887                        .clone()
16888                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
16889                    lsp_completion: lsp::CompletionItem {
16890                        label: snippet.prefix.first().unwrap().clone(),
16891                        kind: Some(CompletionItemKind::SNIPPET),
16892                        label_details: snippet.description.as_ref().map(|description| {
16893                            lsp::CompletionItemLabelDetails {
16894                                detail: Some(description.clone()),
16895                                description: None,
16896                            }
16897                        }),
16898                        insert_text_format: Some(InsertTextFormat::SNIPPET),
16899                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16900                            lsp::InsertReplaceEdit {
16901                                new_text: snippet.body.clone(),
16902                                insert: lsp_range,
16903                                replace: lsp_range,
16904                            },
16905                        )),
16906                        filter_text: Some(snippet.body.clone()),
16907                        sort_text: Some(char::MAX.to_string()),
16908                        ..Default::default()
16909                    },
16910                    confirm: None,
16911                })
16912            })
16913            .collect();
16914
16915        Ok(result)
16916    })
16917}
16918
16919impl CompletionProvider for Entity<Project> {
16920    fn completions(
16921        &self,
16922        buffer: &Entity<Buffer>,
16923        buffer_position: text::Anchor,
16924        options: CompletionContext,
16925        _window: &mut Window,
16926        cx: &mut Context<Editor>,
16927    ) -> Task<Result<Vec<Completion>>> {
16928        self.update(cx, |project, cx| {
16929            let snippets = snippet_completions(project, buffer, buffer_position, cx);
16930            let project_completions = project.completions(buffer, buffer_position, options, cx);
16931            cx.background_spawn(async move {
16932                let mut completions = project_completions.await?;
16933                let snippets_completions = snippets.await?;
16934                completions.extend(snippets_completions);
16935                Ok(completions)
16936            })
16937        })
16938    }
16939
16940    fn resolve_completions(
16941        &self,
16942        buffer: Entity<Buffer>,
16943        completion_indices: Vec<usize>,
16944        completions: Rc<RefCell<Box<[Completion]>>>,
16945        cx: &mut Context<Editor>,
16946    ) -> Task<Result<bool>> {
16947        self.update(cx, |project, cx| {
16948            project.lsp_store().update(cx, |lsp_store, cx| {
16949                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16950            })
16951        })
16952    }
16953
16954    fn apply_additional_edits_for_completion(
16955        &self,
16956        buffer: Entity<Buffer>,
16957        completions: Rc<RefCell<Box<[Completion]>>>,
16958        completion_index: usize,
16959        push_to_history: bool,
16960        cx: &mut Context<Editor>,
16961    ) -> Task<Result<Option<language::Transaction>>> {
16962        self.update(cx, |project, cx| {
16963            project.lsp_store().update(cx, |lsp_store, cx| {
16964                lsp_store.apply_additional_edits_for_completion(
16965                    buffer,
16966                    completions,
16967                    completion_index,
16968                    push_to_history,
16969                    cx,
16970                )
16971            })
16972        })
16973    }
16974
16975    fn is_completion_trigger(
16976        &self,
16977        buffer: &Entity<Buffer>,
16978        position: language::Anchor,
16979        text: &str,
16980        trigger_in_words: bool,
16981        cx: &mut Context<Editor>,
16982    ) -> bool {
16983        let mut chars = text.chars();
16984        let char = if let Some(char) = chars.next() {
16985            char
16986        } else {
16987            return false;
16988        };
16989        if chars.next().is_some() {
16990            return false;
16991        }
16992
16993        let buffer = buffer.read(cx);
16994        let snapshot = buffer.snapshot();
16995        if !snapshot.settings_at(position, cx).show_completions_on_input {
16996            return false;
16997        }
16998        let classifier = snapshot.char_classifier_at(position).for_completion(true);
16999        if trigger_in_words && classifier.is_word(char) {
17000            return true;
17001        }
17002
17003        buffer.completion_triggers().contains(text)
17004    }
17005}
17006
17007impl SemanticsProvider for Entity<Project> {
17008    fn hover(
17009        &self,
17010        buffer: &Entity<Buffer>,
17011        position: text::Anchor,
17012        cx: &mut App,
17013    ) -> Option<Task<Vec<project::Hover>>> {
17014        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
17015    }
17016
17017    fn document_highlights(
17018        &self,
17019        buffer: &Entity<Buffer>,
17020        position: text::Anchor,
17021        cx: &mut App,
17022    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
17023        Some(self.update(cx, |project, cx| {
17024            project.document_highlights(buffer, position, cx)
17025        }))
17026    }
17027
17028    fn definitions(
17029        &self,
17030        buffer: &Entity<Buffer>,
17031        position: text::Anchor,
17032        kind: GotoDefinitionKind,
17033        cx: &mut App,
17034    ) -> Option<Task<Result<Vec<LocationLink>>>> {
17035        Some(self.update(cx, |project, cx| match kind {
17036            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
17037            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
17038            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
17039            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
17040        }))
17041    }
17042
17043    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
17044        // TODO: make this work for remote projects
17045        self.update(cx, |this, cx| {
17046            buffer.update(cx, |buffer, cx| {
17047                this.any_language_server_supports_inlay_hints(buffer, cx)
17048            })
17049        })
17050    }
17051
17052    fn inlay_hints(
17053        &self,
17054        buffer_handle: Entity<Buffer>,
17055        range: Range<text::Anchor>,
17056        cx: &mut App,
17057    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
17058        Some(self.update(cx, |project, cx| {
17059            project.inlay_hints(buffer_handle, range, cx)
17060        }))
17061    }
17062
17063    fn resolve_inlay_hint(
17064        &self,
17065        hint: InlayHint,
17066        buffer_handle: Entity<Buffer>,
17067        server_id: LanguageServerId,
17068        cx: &mut App,
17069    ) -> Option<Task<anyhow::Result<InlayHint>>> {
17070        Some(self.update(cx, |project, cx| {
17071            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
17072        }))
17073    }
17074
17075    fn range_for_rename(
17076        &self,
17077        buffer: &Entity<Buffer>,
17078        position: text::Anchor,
17079        cx: &mut App,
17080    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17081        Some(self.update(cx, |project, cx| {
17082            let buffer = buffer.clone();
17083            let task = project.prepare_rename(buffer.clone(), position, cx);
17084            cx.spawn(|_, mut cx| async move {
17085                Ok(match task.await? {
17086                    PrepareRenameResponse::Success(range) => Some(range),
17087                    PrepareRenameResponse::InvalidPosition => None,
17088                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17089                        // Fallback on using TreeSitter info to determine identifier range
17090                        buffer.update(&mut cx, |buffer, _| {
17091                            let snapshot = buffer.snapshot();
17092                            let (range, kind) = snapshot.surrounding_word(position);
17093                            if kind != Some(CharKind::Word) {
17094                                return None;
17095                            }
17096                            Some(
17097                                snapshot.anchor_before(range.start)
17098                                    ..snapshot.anchor_after(range.end),
17099                            )
17100                        })?
17101                    }
17102                })
17103            })
17104        }))
17105    }
17106
17107    fn perform_rename(
17108        &self,
17109        buffer: &Entity<Buffer>,
17110        position: text::Anchor,
17111        new_name: String,
17112        cx: &mut App,
17113    ) -> Option<Task<Result<ProjectTransaction>>> {
17114        Some(self.update(cx, |project, cx| {
17115            project.perform_rename(buffer.clone(), position, new_name, cx)
17116        }))
17117    }
17118}
17119
17120fn inlay_hint_settings(
17121    location: Anchor,
17122    snapshot: &MultiBufferSnapshot,
17123    cx: &mut Context<Editor>,
17124) -> InlayHintSettings {
17125    let file = snapshot.file_at(location);
17126    let language = snapshot.language_at(location).map(|l| l.name());
17127    language_settings(language, file, cx).inlay_hints
17128}
17129
17130fn consume_contiguous_rows(
17131    contiguous_row_selections: &mut Vec<Selection<Point>>,
17132    selection: &Selection<Point>,
17133    display_map: &DisplaySnapshot,
17134    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17135) -> (MultiBufferRow, MultiBufferRow) {
17136    contiguous_row_selections.push(selection.clone());
17137    let start_row = MultiBufferRow(selection.start.row);
17138    let mut end_row = ending_row(selection, display_map);
17139
17140    while let Some(next_selection) = selections.peek() {
17141        if next_selection.start.row <= end_row.0 {
17142            end_row = ending_row(next_selection, display_map);
17143            contiguous_row_selections.push(selections.next().unwrap().clone());
17144        } else {
17145            break;
17146        }
17147    }
17148    (start_row, end_row)
17149}
17150
17151fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17152    if next_selection.end.column > 0 || next_selection.is_empty() {
17153        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17154    } else {
17155        MultiBufferRow(next_selection.end.row)
17156    }
17157}
17158
17159impl EditorSnapshot {
17160    pub fn remote_selections_in_range<'a>(
17161        &'a self,
17162        range: &'a Range<Anchor>,
17163        collaboration_hub: &dyn CollaborationHub,
17164        cx: &'a App,
17165    ) -> impl 'a + Iterator<Item = RemoteSelection> {
17166        let participant_names = collaboration_hub.user_names(cx);
17167        let participant_indices = collaboration_hub.user_participant_indices(cx);
17168        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17169        let collaborators_by_replica_id = collaborators_by_peer_id
17170            .iter()
17171            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17172            .collect::<HashMap<_, _>>();
17173        self.buffer_snapshot
17174            .selections_in_range(range, false)
17175            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17176                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17177                let participant_index = participant_indices.get(&collaborator.user_id).copied();
17178                let user_name = participant_names.get(&collaborator.user_id).cloned();
17179                Some(RemoteSelection {
17180                    replica_id,
17181                    selection,
17182                    cursor_shape,
17183                    line_mode,
17184                    participant_index,
17185                    peer_id: collaborator.peer_id,
17186                    user_name,
17187                })
17188            })
17189    }
17190
17191    pub fn hunks_for_ranges(
17192        &self,
17193        ranges: impl IntoIterator<Item = Range<Point>>,
17194    ) -> Vec<MultiBufferDiffHunk> {
17195        let mut hunks = Vec::new();
17196        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17197            HashMap::default();
17198        for query_range in ranges {
17199            let query_rows =
17200                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17201            for hunk in self.buffer_snapshot.diff_hunks_in_range(
17202                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17203            ) {
17204                // Include deleted hunks that are adjacent to the query range, because
17205                // otherwise they would be missed.
17206                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
17207                if hunk.status().is_deleted() {
17208                    intersects_range |= hunk.row_range.start == query_rows.end;
17209                    intersects_range |= hunk.row_range.end == query_rows.start;
17210                }
17211                if intersects_range {
17212                    if !processed_buffer_rows
17213                        .entry(hunk.buffer_id)
17214                        .or_default()
17215                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17216                    {
17217                        continue;
17218                    }
17219                    hunks.push(hunk);
17220                }
17221            }
17222        }
17223
17224        hunks
17225    }
17226
17227    fn display_diff_hunks_for_rows<'a>(
17228        &'a self,
17229        display_rows: Range<DisplayRow>,
17230        folded_buffers: &'a HashSet<BufferId>,
17231    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17232        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17233        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17234
17235        self.buffer_snapshot
17236            .diff_hunks_in_range(buffer_start..buffer_end)
17237            .filter_map(|hunk| {
17238                if folded_buffers.contains(&hunk.buffer_id) {
17239                    return None;
17240                }
17241
17242                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17243                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17244
17245                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17246                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17247
17248                let display_hunk = if hunk_display_start.column() != 0 {
17249                    DisplayDiffHunk::Folded {
17250                        display_row: hunk_display_start.row(),
17251                    }
17252                } else {
17253                    let mut end_row = hunk_display_end.row();
17254                    if hunk_display_end.column() > 0 {
17255                        end_row.0 += 1;
17256                    }
17257                    DisplayDiffHunk::Unfolded {
17258                        status: hunk.status(),
17259                        diff_base_byte_range: hunk.diff_base_byte_range,
17260                        display_row_range: hunk_display_start.row()..end_row,
17261                        multi_buffer_range: Anchor::range_in_buffer(
17262                            hunk.excerpt_id,
17263                            hunk.buffer_id,
17264                            hunk.buffer_range,
17265                        ),
17266                    }
17267                };
17268
17269                Some(display_hunk)
17270            })
17271    }
17272
17273    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17274        self.display_snapshot.buffer_snapshot.language_at(position)
17275    }
17276
17277    pub fn is_focused(&self) -> bool {
17278        self.is_focused
17279    }
17280
17281    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17282        self.placeholder_text.as_ref()
17283    }
17284
17285    pub fn scroll_position(&self) -> gpui::Point<f32> {
17286        self.scroll_anchor.scroll_position(&self.display_snapshot)
17287    }
17288
17289    fn gutter_dimensions(
17290        &self,
17291        font_id: FontId,
17292        font_size: Pixels,
17293        max_line_number_width: Pixels,
17294        cx: &App,
17295    ) -> Option<GutterDimensions> {
17296        if !self.show_gutter {
17297            return None;
17298        }
17299
17300        let descent = cx.text_system().descent(font_id, font_size);
17301        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17302        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17303
17304        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17305            matches!(
17306                ProjectSettings::get_global(cx).git.git_gutter,
17307                Some(GitGutterSetting::TrackedFiles)
17308            )
17309        });
17310        let gutter_settings = EditorSettings::get_global(cx).gutter;
17311        let show_line_numbers = self
17312            .show_line_numbers
17313            .unwrap_or(gutter_settings.line_numbers);
17314        let line_gutter_width = if show_line_numbers {
17315            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17316            let min_width_for_number_on_gutter = em_advance * 4.0;
17317            max_line_number_width.max(min_width_for_number_on_gutter)
17318        } else {
17319            0.0.into()
17320        };
17321
17322        let show_code_actions = self
17323            .show_code_actions
17324            .unwrap_or(gutter_settings.code_actions);
17325
17326        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17327
17328        let git_blame_entries_width =
17329            self.git_blame_gutter_max_author_length
17330                .map(|max_author_length| {
17331                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17332
17333                    /// The number of characters to dedicate to gaps and margins.
17334                    const SPACING_WIDTH: usize = 4;
17335
17336                    let max_char_count = max_author_length
17337                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17338                        + ::git::SHORT_SHA_LENGTH
17339                        + MAX_RELATIVE_TIMESTAMP.len()
17340                        + SPACING_WIDTH;
17341
17342                    em_advance * max_char_count
17343                });
17344
17345        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17346        left_padding += if show_code_actions || show_runnables {
17347            em_width * 3.0
17348        } else if show_git_gutter && show_line_numbers {
17349            em_width * 2.0
17350        } else if show_git_gutter || show_line_numbers {
17351            em_width
17352        } else {
17353            px(0.)
17354        };
17355
17356        let right_padding = if gutter_settings.folds && show_line_numbers {
17357            em_width * 4.0
17358        } else if gutter_settings.folds {
17359            em_width * 3.0
17360        } else if show_line_numbers {
17361            em_width
17362        } else {
17363            px(0.)
17364        };
17365
17366        Some(GutterDimensions {
17367            left_padding,
17368            right_padding,
17369            width: line_gutter_width + left_padding + right_padding,
17370            margin: -descent,
17371            git_blame_entries_width,
17372        })
17373    }
17374
17375    pub fn render_crease_toggle(
17376        &self,
17377        buffer_row: MultiBufferRow,
17378        row_contains_cursor: bool,
17379        editor: Entity<Editor>,
17380        window: &mut Window,
17381        cx: &mut App,
17382    ) -> Option<AnyElement> {
17383        let folded = self.is_line_folded(buffer_row);
17384        let mut is_foldable = false;
17385
17386        if let Some(crease) = self
17387            .crease_snapshot
17388            .query_row(buffer_row, &self.buffer_snapshot)
17389        {
17390            is_foldable = true;
17391            match crease {
17392                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17393                    if let Some(render_toggle) = render_toggle {
17394                        let toggle_callback =
17395                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17396                                if folded {
17397                                    editor.update(cx, |editor, cx| {
17398                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17399                                    });
17400                                } else {
17401                                    editor.update(cx, |editor, cx| {
17402                                        editor.unfold_at(
17403                                            &crate::UnfoldAt { buffer_row },
17404                                            window,
17405                                            cx,
17406                                        )
17407                                    });
17408                                }
17409                            });
17410                        return Some((render_toggle)(
17411                            buffer_row,
17412                            folded,
17413                            toggle_callback,
17414                            window,
17415                            cx,
17416                        ));
17417                    }
17418                }
17419            }
17420        }
17421
17422        is_foldable |= self.starts_indent(buffer_row);
17423
17424        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17425            Some(
17426                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17427                    .toggle_state(folded)
17428                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17429                        if folded {
17430                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17431                        } else {
17432                            this.fold_at(&FoldAt { buffer_row }, window, cx);
17433                        }
17434                    }))
17435                    .into_any_element(),
17436            )
17437        } else {
17438            None
17439        }
17440    }
17441
17442    pub fn render_crease_trailer(
17443        &self,
17444        buffer_row: MultiBufferRow,
17445        window: &mut Window,
17446        cx: &mut App,
17447    ) -> Option<AnyElement> {
17448        let folded = self.is_line_folded(buffer_row);
17449        if let Crease::Inline { render_trailer, .. } = self
17450            .crease_snapshot
17451            .query_row(buffer_row, &self.buffer_snapshot)?
17452        {
17453            let render_trailer = render_trailer.as_ref()?;
17454            Some(render_trailer(buffer_row, folded, window, cx))
17455        } else {
17456            None
17457        }
17458    }
17459}
17460
17461impl Deref for EditorSnapshot {
17462    type Target = DisplaySnapshot;
17463
17464    fn deref(&self) -> &Self::Target {
17465        &self.display_snapshot
17466    }
17467}
17468
17469#[derive(Clone, Debug, PartialEq, Eq)]
17470pub enum EditorEvent {
17471    InputIgnored {
17472        text: Arc<str>,
17473    },
17474    InputHandled {
17475        utf16_range_to_replace: Option<Range<isize>>,
17476        text: Arc<str>,
17477    },
17478    ExcerptsAdded {
17479        buffer: Entity<Buffer>,
17480        predecessor: ExcerptId,
17481        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17482    },
17483    ExcerptsRemoved {
17484        ids: Vec<ExcerptId>,
17485    },
17486    BufferFoldToggled {
17487        ids: Vec<ExcerptId>,
17488        folded: bool,
17489    },
17490    ExcerptsEdited {
17491        ids: Vec<ExcerptId>,
17492    },
17493    ExcerptsExpanded {
17494        ids: Vec<ExcerptId>,
17495    },
17496    BufferEdited,
17497    Edited {
17498        transaction_id: clock::Lamport,
17499    },
17500    Reparsed(BufferId),
17501    Focused,
17502    FocusedIn,
17503    Blurred,
17504    DirtyChanged,
17505    Saved,
17506    TitleChanged,
17507    DiffBaseChanged,
17508    SelectionsChanged {
17509        local: bool,
17510    },
17511    ScrollPositionChanged {
17512        local: bool,
17513        autoscroll: bool,
17514    },
17515    Closed,
17516    TransactionUndone {
17517        transaction_id: clock::Lamport,
17518    },
17519    TransactionBegun {
17520        transaction_id: clock::Lamport,
17521    },
17522    Reloaded,
17523    CursorShapeChanged,
17524}
17525
17526impl EventEmitter<EditorEvent> for Editor {}
17527
17528impl Focusable for Editor {
17529    fn focus_handle(&self, _cx: &App) -> FocusHandle {
17530        self.focus_handle.clone()
17531    }
17532}
17533
17534impl Render for Editor {
17535    fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17536        let settings = ThemeSettings::get_global(cx);
17537
17538        let mut text_style = match self.mode {
17539            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17540                color: cx.theme().colors().editor_foreground,
17541                font_family: settings.ui_font.family.clone(),
17542                font_features: settings.ui_font.features.clone(),
17543                font_fallbacks: settings.ui_font.fallbacks.clone(),
17544                font_size: rems(0.875).into(),
17545                font_weight: settings.ui_font.weight,
17546                line_height: relative(settings.buffer_line_height.value()),
17547                ..Default::default()
17548            },
17549            EditorMode::Full => TextStyle {
17550                color: cx.theme().colors().editor_foreground,
17551                font_family: settings.buffer_font.family.clone(),
17552                font_features: settings.buffer_font.features.clone(),
17553                font_fallbacks: settings.buffer_font.fallbacks.clone(),
17554                font_size: settings.buffer_font_size(cx).into(),
17555                font_weight: settings.buffer_font.weight,
17556                line_height: relative(settings.buffer_line_height.value()),
17557                ..Default::default()
17558            },
17559        };
17560        if let Some(text_style_refinement) = &self.text_style_refinement {
17561            text_style.refine(text_style_refinement)
17562        }
17563
17564        let background = match self.mode {
17565            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17566            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17567            EditorMode::Full => cx.theme().colors().editor_background,
17568        };
17569
17570        EditorElement::new(
17571            &cx.entity(),
17572            EditorStyle {
17573                background,
17574                local_player: cx.theme().players().local(),
17575                text: text_style,
17576                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17577                syntax: cx.theme().syntax().clone(),
17578                status: cx.theme().status().clone(),
17579                inlay_hints_style: make_inlay_hints_style(cx),
17580                inline_completion_styles: make_suggestion_styles(cx),
17581                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17582            },
17583        )
17584    }
17585}
17586
17587impl EntityInputHandler for Editor {
17588    fn text_for_range(
17589        &mut self,
17590        range_utf16: Range<usize>,
17591        adjusted_range: &mut Option<Range<usize>>,
17592        _: &mut Window,
17593        cx: &mut Context<Self>,
17594    ) -> Option<String> {
17595        let snapshot = self.buffer.read(cx).read(cx);
17596        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17597        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17598        if (start.0..end.0) != range_utf16 {
17599            adjusted_range.replace(start.0..end.0);
17600        }
17601        Some(snapshot.text_for_range(start..end).collect())
17602    }
17603
17604    fn selected_text_range(
17605        &mut self,
17606        ignore_disabled_input: bool,
17607        _: &mut Window,
17608        cx: &mut Context<Self>,
17609    ) -> Option<UTF16Selection> {
17610        // Prevent the IME menu from appearing when holding down an alphabetic key
17611        // while input is disabled.
17612        if !ignore_disabled_input && !self.input_enabled {
17613            return None;
17614        }
17615
17616        let selection = self.selections.newest::<OffsetUtf16>(cx);
17617        let range = selection.range();
17618
17619        Some(UTF16Selection {
17620            range: range.start.0..range.end.0,
17621            reversed: selection.reversed,
17622        })
17623    }
17624
17625    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17626        let snapshot = self.buffer.read(cx).read(cx);
17627        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17628        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17629    }
17630
17631    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17632        self.clear_highlights::<InputComposition>(cx);
17633        self.ime_transaction.take();
17634    }
17635
17636    fn replace_text_in_range(
17637        &mut self,
17638        range_utf16: Option<Range<usize>>,
17639        text: &str,
17640        window: &mut Window,
17641        cx: &mut Context<Self>,
17642    ) {
17643        if !self.input_enabled {
17644            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17645            return;
17646        }
17647
17648        self.transact(window, cx, |this, window, cx| {
17649            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17650                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17651                Some(this.selection_replacement_ranges(range_utf16, cx))
17652            } else {
17653                this.marked_text_ranges(cx)
17654            };
17655
17656            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17657                let newest_selection_id = this.selections.newest_anchor().id;
17658                this.selections
17659                    .all::<OffsetUtf16>(cx)
17660                    .iter()
17661                    .zip(ranges_to_replace.iter())
17662                    .find_map(|(selection, range)| {
17663                        if selection.id == newest_selection_id {
17664                            Some(
17665                                (range.start.0 as isize - selection.head().0 as isize)
17666                                    ..(range.end.0 as isize - selection.head().0 as isize),
17667                            )
17668                        } else {
17669                            None
17670                        }
17671                    })
17672            });
17673
17674            cx.emit(EditorEvent::InputHandled {
17675                utf16_range_to_replace: range_to_replace,
17676                text: text.into(),
17677            });
17678
17679            if let Some(new_selected_ranges) = new_selected_ranges {
17680                this.change_selections(None, window, cx, |selections| {
17681                    selections.select_ranges(new_selected_ranges)
17682                });
17683                this.backspace(&Default::default(), window, cx);
17684            }
17685
17686            this.handle_input(text, window, cx);
17687        });
17688
17689        if let Some(transaction) = self.ime_transaction {
17690            self.buffer.update(cx, |buffer, cx| {
17691                buffer.group_until_transaction(transaction, cx);
17692            });
17693        }
17694
17695        self.unmark_text(window, cx);
17696    }
17697
17698    fn replace_and_mark_text_in_range(
17699        &mut self,
17700        range_utf16: Option<Range<usize>>,
17701        text: &str,
17702        new_selected_range_utf16: Option<Range<usize>>,
17703        window: &mut Window,
17704        cx: &mut Context<Self>,
17705    ) {
17706        if !self.input_enabled {
17707            return;
17708        }
17709
17710        let transaction = self.transact(window, cx, |this, window, cx| {
17711            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17712                let snapshot = this.buffer.read(cx).read(cx);
17713                if let Some(relative_range_utf16) = range_utf16.as_ref() {
17714                    for marked_range in &mut marked_ranges {
17715                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17716                        marked_range.start.0 += relative_range_utf16.start;
17717                        marked_range.start =
17718                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17719                        marked_range.end =
17720                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17721                    }
17722                }
17723                Some(marked_ranges)
17724            } else if let Some(range_utf16) = range_utf16 {
17725                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17726                Some(this.selection_replacement_ranges(range_utf16, cx))
17727            } else {
17728                None
17729            };
17730
17731            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17732                let newest_selection_id = this.selections.newest_anchor().id;
17733                this.selections
17734                    .all::<OffsetUtf16>(cx)
17735                    .iter()
17736                    .zip(ranges_to_replace.iter())
17737                    .find_map(|(selection, range)| {
17738                        if selection.id == newest_selection_id {
17739                            Some(
17740                                (range.start.0 as isize - selection.head().0 as isize)
17741                                    ..(range.end.0 as isize - selection.head().0 as isize),
17742                            )
17743                        } else {
17744                            None
17745                        }
17746                    })
17747            });
17748
17749            cx.emit(EditorEvent::InputHandled {
17750                utf16_range_to_replace: range_to_replace,
17751                text: text.into(),
17752            });
17753
17754            if let Some(ranges) = ranges_to_replace {
17755                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17756            }
17757
17758            let marked_ranges = {
17759                let snapshot = this.buffer.read(cx).read(cx);
17760                this.selections
17761                    .disjoint_anchors()
17762                    .iter()
17763                    .map(|selection| {
17764                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17765                    })
17766                    .collect::<Vec<_>>()
17767            };
17768
17769            if text.is_empty() {
17770                this.unmark_text(window, cx);
17771            } else {
17772                this.highlight_text::<InputComposition>(
17773                    marked_ranges.clone(),
17774                    HighlightStyle {
17775                        underline: Some(UnderlineStyle {
17776                            thickness: px(1.),
17777                            color: None,
17778                            wavy: false,
17779                        }),
17780                        ..Default::default()
17781                    },
17782                    cx,
17783                );
17784            }
17785
17786            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17787            let use_autoclose = this.use_autoclose;
17788            let use_auto_surround = this.use_auto_surround;
17789            this.set_use_autoclose(false);
17790            this.set_use_auto_surround(false);
17791            this.handle_input(text, window, cx);
17792            this.set_use_autoclose(use_autoclose);
17793            this.set_use_auto_surround(use_auto_surround);
17794
17795            if let Some(new_selected_range) = new_selected_range_utf16 {
17796                let snapshot = this.buffer.read(cx).read(cx);
17797                let new_selected_ranges = marked_ranges
17798                    .into_iter()
17799                    .map(|marked_range| {
17800                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17801                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17802                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17803                        snapshot.clip_offset_utf16(new_start, Bias::Left)
17804                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17805                    })
17806                    .collect::<Vec<_>>();
17807
17808                drop(snapshot);
17809                this.change_selections(None, window, cx, |selections| {
17810                    selections.select_ranges(new_selected_ranges)
17811                });
17812            }
17813        });
17814
17815        self.ime_transaction = self.ime_transaction.or(transaction);
17816        if let Some(transaction) = self.ime_transaction {
17817            self.buffer.update(cx, |buffer, cx| {
17818                buffer.group_until_transaction(transaction, cx);
17819            });
17820        }
17821
17822        if self.text_highlights::<InputComposition>(cx).is_none() {
17823            self.ime_transaction.take();
17824        }
17825    }
17826
17827    fn bounds_for_range(
17828        &mut self,
17829        range_utf16: Range<usize>,
17830        element_bounds: gpui::Bounds<Pixels>,
17831        window: &mut Window,
17832        cx: &mut Context<Self>,
17833    ) -> Option<gpui::Bounds<Pixels>> {
17834        let text_layout_details = self.text_layout_details(window);
17835        let gpui::Size {
17836            width: em_width,
17837            height: line_height,
17838        } = self.character_size(window);
17839
17840        let snapshot = self.snapshot(window, cx);
17841        let scroll_position = snapshot.scroll_position();
17842        let scroll_left = scroll_position.x * em_width;
17843
17844        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17845        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17846            + self.gutter_dimensions.width
17847            + self.gutter_dimensions.margin;
17848        let y = line_height * (start.row().as_f32() - scroll_position.y);
17849
17850        Some(Bounds {
17851            origin: element_bounds.origin + point(x, y),
17852            size: size(em_width, line_height),
17853        })
17854    }
17855
17856    fn character_index_for_point(
17857        &mut self,
17858        point: gpui::Point<Pixels>,
17859        _window: &mut Window,
17860        _cx: &mut Context<Self>,
17861    ) -> Option<usize> {
17862        let position_map = self.last_position_map.as_ref()?;
17863        if !position_map.text_hitbox.contains(&point) {
17864            return None;
17865        }
17866        let display_point = position_map.point_for_position(point).previous_valid;
17867        let anchor = position_map
17868            .snapshot
17869            .display_point_to_anchor(display_point, Bias::Left);
17870        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17871        Some(utf16_offset.0)
17872    }
17873}
17874
17875trait SelectionExt {
17876    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17877    fn spanned_rows(
17878        &self,
17879        include_end_if_at_line_start: bool,
17880        map: &DisplaySnapshot,
17881    ) -> Range<MultiBufferRow>;
17882}
17883
17884impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17885    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17886        let start = self
17887            .start
17888            .to_point(&map.buffer_snapshot)
17889            .to_display_point(map);
17890        let end = self
17891            .end
17892            .to_point(&map.buffer_snapshot)
17893            .to_display_point(map);
17894        if self.reversed {
17895            end..start
17896        } else {
17897            start..end
17898        }
17899    }
17900
17901    fn spanned_rows(
17902        &self,
17903        include_end_if_at_line_start: bool,
17904        map: &DisplaySnapshot,
17905    ) -> Range<MultiBufferRow> {
17906        let start = self.start.to_point(&map.buffer_snapshot);
17907        let mut end = self.end.to_point(&map.buffer_snapshot);
17908        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17909            end.row -= 1;
17910        }
17911
17912        let buffer_start = map.prev_line_boundary(start).0;
17913        let buffer_end = map.next_line_boundary(end).0;
17914        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17915    }
17916}
17917
17918impl<T: InvalidationRegion> InvalidationStack<T> {
17919    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17920    where
17921        S: Clone + ToOffset,
17922    {
17923        while let Some(region) = self.last() {
17924            let all_selections_inside_invalidation_ranges =
17925                if selections.len() == region.ranges().len() {
17926                    selections
17927                        .iter()
17928                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17929                        .all(|(selection, invalidation_range)| {
17930                            let head = selection.head().to_offset(buffer);
17931                            invalidation_range.start <= head && invalidation_range.end >= head
17932                        })
17933                } else {
17934                    false
17935                };
17936
17937            if all_selections_inside_invalidation_ranges {
17938                break;
17939            } else {
17940                self.pop();
17941            }
17942        }
17943    }
17944}
17945
17946impl<T> Default for InvalidationStack<T> {
17947    fn default() -> Self {
17948        Self(Default::default())
17949    }
17950}
17951
17952impl<T> Deref for InvalidationStack<T> {
17953    type Target = Vec<T>;
17954
17955    fn deref(&self) -> &Self::Target {
17956        &self.0
17957    }
17958}
17959
17960impl<T> DerefMut for InvalidationStack<T> {
17961    fn deref_mut(&mut self) -> &mut Self::Target {
17962        &mut self.0
17963    }
17964}
17965
17966impl InvalidationRegion for SnippetState {
17967    fn ranges(&self) -> &[Range<Anchor>] {
17968        &self.ranges[self.active_index]
17969    }
17970}
17971
17972pub fn diagnostic_block_renderer(
17973    diagnostic: Diagnostic,
17974    max_message_rows: Option<u8>,
17975    allow_closing: bool,
17976) -> RenderBlock {
17977    let (text_without_backticks, code_ranges) =
17978        highlight_diagnostic_message(&diagnostic, max_message_rows);
17979
17980    Arc::new(move |cx: &mut BlockContext| {
17981        let group_id: SharedString = cx.block_id.to_string().into();
17982
17983        let mut text_style = cx.window.text_style().clone();
17984        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17985        let theme_settings = ThemeSettings::get_global(cx);
17986        text_style.font_family = theme_settings.buffer_font.family.clone();
17987        text_style.font_style = theme_settings.buffer_font.style;
17988        text_style.font_features = theme_settings.buffer_font.features.clone();
17989        text_style.font_weight = theme_settings.buffer_font.weight;
17990
17991        let multi_line_diagnostic = diagnostic.message.contains('\n');
17992
17993        let buttons = |diagnostic: &Diagnostic| {
17994            if multi_line_diagnostic {
17995                v_flex()
17996            } else {
17997                h_flex()
17998            }
17999            .when(allow_closing, |div| {
18000                div.children(diagnostic.is_primary.then(|| {
18001                    IconButton::new("close-block", IconName::XCircle)
18002                        .icon_color(Color::Muted)
18003                        .size(ButtonSize::Compact)
18004                        .style(ButtonStyle::Transparent)
18005                        .visible_on_hover(group_id.clone())
18006                        .on_click(move |_click, window, cx| {
18007                            window.dispatch_action(Box::new(Cancel), cx)
18008                        })
18009                        .tooltip(|window, cx| {
18010                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
18011                        })
18012                }))
18013            })
18014            .child(
18015                IconButton::new("copy-block", IconName::Copy)
18016                    .icon_color(Color::Muted)
18017                    .size(ButtonSize::Compact)
18018                    .style(ButtonStyle::Transparent)
18019                    .visible_on_hover(group_id.clone())
18020                    .on_click({
18021                        let message = diagnostic.message.clone();
18022                        move |_click, _, cx| {
18023                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
18024                        }
18025                    })
18026                    .tooltip(Tooltip::text("Copy diagnostic message")),
18027            )
18028        };
18029
18030        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
18031            AvailableSpace::min_size(),
18032            cx.window,
18033            cx.app,
18034        );
18035
18036        h_flex()
18037            .id(cx.block_id)
18038            .group(group_id.clone())
18039            .relative()
18040            .size_full()
18041            .block_mouse_down()
18042            .pl(cx.gutter_dimensions.width)
18043            .w(cx.max_width - cx.gutter_dimensions.full_width())
18044            .child(
18045                div()
18046                    .flex()
18047                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
18048                    .flex_shrink(),
18049            )
18050            .child(buttons(&diagnostic))
18051            .child(div().flex().flex_shrink_0().child(
18052                StyledText::new(text_without_backticks.clone()).with_default_highlights(
18053                    &text_style,
18054                    code_ranges.iter().map(|range| {
18055                        (
18056                            range.clone(),
18057                            HighlightStyle {
18058                                font_weight: Some(FontWeight::BOLD),
18059                                ..Default::default()
18060                            },
18061                        )
18062                    }),
18063                ),
18064            ))
18065            .into_any_element()
18066    })
18067}
18068
18069fn inline_completion_edit_text(
18070    current_snapshot: &BufferSnapshot,
18071    edits: &[(Range<Anchor>, String)],
18072    edit_preview: &EditPreview,
18073    include_deletions: bool,
18074    cx: &App,
18075) -> HighlightedText {
18076    let edits = edits
18077        .iter()
18078        .map(|(anchor, text)| {
18079            (
18080                anchor.start.text_anchor..anchor.end.text_anchor,
18081                text.clone(),
18082            )
18083        })
18084        .collect::<Vec<_>>();
18085
18086    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18087}
18088
18089pub fn highlight_diagnostic_message(
18090    diagnostic: &Diagnostic,
18091    mut max_message_rows: Option<u8>,
18092) -> (SharedString, Vec<Range<usize>>) {
18093    let mut text_without_backticks = String::new();
18094    let mut code_ranges = Vec::new();
18095
18096    if let Some(source) = &diagnostic.source {
18097        text_without_backticks.push_str(source);
18098        code_ranges.push(0..source.len());
18099        text_without_backticks.push_str(": ");
18100    }
18101
18102    let mut prev_offset = 0;
18103    let mut in_code_block = false;
18104    let has_row_limit = max_message_rows.is_some();
18105    let mut newline_indices = diagnostic
18106        .message
18107        .match_indices('\n')
18108        .filter(|_| has_row_limit)
18109        .map(|(ix, _)| ix)
18110        .fuse()
18111        .peekable();
18112
18113    for (quote_ix, _) in diagnostic
18114        .message
18115        .match_indices('`')
18116        .chain([(diagnostic.message.len(), "")])
18117    {
18118        let mut first_newline_ix = None;
18119        let mut last_newline_ix = None;
18120        while let Some(newline_ix) = newline_indices.peek() {
18121            if *newline_ix < quote_ix {
18122                if first_newline_ix.is_none() {
18123                    first_newline_ix = Some(*newline_ix);
18124                }
18125                last_newline_ix = Some(*newline_ix);
18126
18127                if let Some(rows_left) = &mut max_message_rows {
18128                    if *rows_left == 0 {
18129                        break;
18130                    } else {
18131                        *rows_left -= 1;
18132                    }
18133                }
18134                let _ = newline_indices.next();
18135            } else {
18136                break;
18137            }
18138        }
18139        let prev_len = text_without_backticks.len();
18140        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18141        text_without_backticks.push_str(new_text);
18142        if in_code_block {
18143            code_ranges.push(prev_len..text_without_backticks.len());
18144        }
18145        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18146        in_code_block = !in_code_block;
18147        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18148            text_without_backticks.push_str("...");
18149            break;
18150        }
18151    }
18152
18153    (text_without_backticks.into(), code_ranges)
18154}
18155
18156fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18157    match severity {
18158        DiagnosticSeverity::ERROR => colors.error,
18159        DiagnosticSeverity::WARNING => colors.warning,
18160        DiagnosticSeverity::INFORMATION => colors.info,
18161        DiagnosticSeverity::HINT => colors.info,
18162        _ => colors.ignored,
18163    }
18164}
18165
18166pub fn styled_runs_for_code_label<'a>(
18167    label: &'a CodeLabel,
18168    syntax_theme: &'a theme::SyntaxTheme,
18169) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18170    let fade_out = HighlightStyle {
18171        fade_out: Some(0.35),
18172        ..Default::default()
18173    };
18174
18175    let mut prev_end = label.filter_range.end;
18176    label
18177        .runs
18178        .iter()
18179        .enumerate()
18180        .flat_map(move |(ix, (range, highlight_id))| {
18181            let style = if let Some(style) = highlight_id.style(syntax_theme) {
18182                style
18183            } else {
18184                return Default::default();
18185            };
18186            let mut muted_style = style;
18187            muted_style.highlight(fade_out);
18188
18189            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18190            if range.start >= label.filter_range.end {
18191                if range.start > prev_end {
18192                    runs.push((prev_end..range.start, fade_out));
18193                }
18194                runs.push((range.clone(), muted_style));
18195            } else if range.end <= label.filter_range.end {
18196                runs.push((range.clone(), style));
18197            } else {
18198                runs.push((range.start..label.filter_range.end, style));
18199                runs.push((label.filter_range.end..range.end, muted_style));
18200            }
18201            prev_end = cmp::max(prev_end, range.end);
18202
18203            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18204                runs.push((prev_end..label.text.len(), fade_out));
18205            }
18206
18207            runs
18208        })
18209}
18210
18211pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18212    let mut prev_index = 0;
18213    let mut prev_codepoint: Option<char> = None;
18214    text.char_indices()
18215        .chain([(text.len(), '\0')])
18216        .filter_map(move |(index, codepoint)| {
18217            let prev_codepoint = prev_codepoint.replace(codepoint)?;
18218            let is_boundary = index == text.len()
18219                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18220                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18221            if is_boundary {
18222                let chunk = &text[prev_index..index];
18223                prev_index = index;
18224                Some(chunk)
18225            } else {
18226                None
18227            }
18228        })
18229}
18230
18231pub trait RangeToAnchorExt: Sized {
18232    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18233
18234    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18235        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18236        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18237    }
18238}
18239
18240impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18241    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18242        let start_offset = self.start.to_offset(snapshot);
18243        let end_offset = self.end.to_offset(snapshot);
18244        if start_offset == end_offset {
18245            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18246        } else {
18247            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18248        }
18249    }
18250}
18251
18252pub trait RowExt {
18253    fn as_f32(&self) -> f32;
18254
18255    fn next_row(&self) -> Self;
18256
18257    fn previous_row(&self) -> Self;
18258
18259    fn minus(&self, other: Self) -> u32;
18260}
18261
18262impl RowExt for DisplayRow {
18263    fn as_f32(&self) -> f32 {
18264        self.0 as f32
18265    }
18266
18267    fn next_row(&self) -> Self {
18268        Self(self.0 + 1)
18269    }
18270
18271    fn previous_row(&self) -> Self {
18272        Self(self.0.saturating_sub(1))
18273    }
18274
18275    fn minus(&self, other: Self) -> u32 {
18276        self.0 - other.0
18277    }
18278}
18279
18280impl RowExt for MultiBufferRow {
18281    fn as_f32(&self) -> f32 {
18282        self.0 as f32
18283    }
18284
18285    fn next_row(&self) -> Self {
18286        Self(self.0 + 1)
18287    }
18288
18289    fn previous_row(&self) -> Self {
18290        Self(self.0.saturating_sub(1))
18291    }
18292
18293    fn minus(&self, other: Self) -> u32 {
18294        self.0 - other.0
18295    }
18296}
18297
18298trait RowRangeExt {
18299    type Row;
18300
18301    fn len(&self) -> usize;
18302
18303    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18304}
18305
18306impl RowRangeExt for Range<MultiBufferRow> {
18307    type Row = MultiBufferRow;
18308
18309    fn len(&self) -> usize {
18310        (self.end.0 - self.start.0) as usize
18311    }
18312
18313    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18314        (self.start.0..self.end.0).map(MultiBufferRow)
18315    }
18316}
18317
18318impl RowRangeExt for Range<DisplayRow> {
18319    type Row = DisplayRow;
18320
18321    fn len(&self) -> usize {
18322        (self.end.0 - self.start.0) as usize
18323    }
18324
18325    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18326        (self.start.0..self.end.0).map(DisplayRow)
18327    }
18328}
18329
18330/// If select range has more than one line, we
18331/// just point the cursor to range.start.
18332fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18333    if range.start.row == range.end.row {
18334        range
18335    } else {
18336        range.start..range.start
18337    }
18338}
18339pub struct KillRing(ClipboardItem);
18340impl Global for KillRing {}
18341
18342const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18343
18344fn all_edits_insertions_or_deletions(
18345    edits: &Vec<(Range<Anchor>, String)>,
18346    snapshot: &MultiBufferSnapshot,
18347) -> bool {
18348    let mut all_insertions = true;
18349    let mut all_deletions = true;
18350
18351    for (range, new_text) in edits.iter() {
18352        let range_is_empty = range.to_offset(&snapshot).is_empty();
18353        let text_is_empty = new_text.is_empty();
18354
18355        if range_is_empty != text_is_empty {
18356            if range_is_empty {
18357                all_deletions = false;
18358            } else {
18359                all_insertions = false;
18360            }
18361        } else {
18362            return false;
18363        }
18364
18365        if !all_insertions && !all_deletions {
18366            return false;
18367        }
18368    }
18369    all_insertions || all_deletions
18370}
18371
18372struct MissingEditPredictionKeybindingTooltip;
18373
18374impl Render for MissingEditPredictionKeybindingTooltip {
18375    fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18376        ui::tooltip_container(window, cx, |container, _, cx| {
18377            container
18378                .flex_shrink_0()
18379                .max_w_80()
18380                .min_h(rems_from_px(124.))
18381                .justify_between()
18382                .child(
18383                    v_flex()
18384                        .flex_1()
18385                        .text_ui_sm(cx)
18386                        .child(Label::new("Conflict with Accept Keybinding"))
18387                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
18388                )
18389                .child(
18390                    h_flex()
18391                        .pb_1()
18392                        .gap_1()
18393                        .items_end()
18394                        .w_full()
18395                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
18396                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
18397                        }))
18398                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
18399                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
18400                        })),
18401                )
18402        })
18403    }
18404}