editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod commit_tooltip;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod jsx_tag_auto_close;
   32mod linked_editing_ranges;
   33mod lsp_ext;
   34mod mouse_context_menu;
   35pub mod movement;
   36mod persistence;
   37mod proposed_changes_editor;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45#[cfg(test)]
   46mod inline_completion_tests;
   47mod signature_help;
   48#[cfg(any(test, feature = "test-support"))]
   49pub mod test;
   50
   51pub(crate) use actions::*;
   52pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   53use aho_corasick::AhoCorasick;
   54use anyhow::{anyhow, Context as _, Result};
   55use blink_manager::BlinkManager;
   56use buffer_diff::DiffHunkStatus;
   57use client::{Collaborator, ParticipantIndex};
   58use clock::ReplicaId;
   59use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   60use convert_case::{Case, Casing};
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   65};
   66pub use editor_settings_controls::*;
   67use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use futures::{
   72    future::{self, Shared},
   73    FutureExt,
   74};
   75use fuzzy::StringMatchCandidate;
   76
   77use ::git::Restore;
   78use code_context_menus::{
   79    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   80    CompletionsMenu, ContextMenuOrigin,
   81};
   82use git::blame::GitBlame;
   83use gpui::{
   84    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   85    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   86    ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler,
   87    EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
   88    HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
   89    ParentElement, Pixels, Render, SharedString, Size, Stateful, Styled, StyledText, Subscription,
   90    Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   91    WeakEntity, WeakFocusHandle, Window,
   92};
   93use highlight_matching_bracket::refresh_matching_bracket_highlights;
   94use hover_popover::{hide_hover, HoverState};
   95use indent_guides::ActiveIndentGuidesState;
   96use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   97pub use inline_completion::Direction;
   98use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   99pub use items::MAX_TAB_TITLE_LEN;
  100use itertools::Itertools;
  101use language::{
  102    language_settings::{
  103        self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
  104    },
  105    point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
  106    Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, EditPredictionsMode,
  107    EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
  108    Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
  109};
  110use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  111use linked_editing_ranges::refresh_linked_ranges;
  112use mouse_context_menu::MouseContextMenu;
  113use persistence::DB;
  114pub use proposed_changes_editor::{
  115    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  116};
  117use smallvec::smallvec;
  118use std::iter::Peekable;
  119use task::{ResolvedTask, TaskTemplate, TaskVariables};
  120
  121use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  122pub use lsp::CompletionContext;
  123use lsp::{
  124    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  125    InsertTextFormat, LanguageServerId, LanguageServerName,
  126};
  127
  128use language::BufferSnapshot;
  129use movement::TextLayoutDetails;
  130pub use multi_buffer::{
  131    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  132    ToOffset, ToPoint,
  133};
  134use multi_buffer::{
  135    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  136    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  137};
  138use project::{
  139    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  140    project_settings::{GitGutterSetting, ProjectSettings},
  141    CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
  142    Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
  143    TaskSourceKind,
  144};
  145use rand::prelude::*;
  146use rpc::{proto::*, ErrorExt};
  147use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  148use selections_collection::{
  149    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  150};
  151use serde::{Deserialize, Serialize};
  152use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  153use smallvec::SmallVec;
  154use snippet::Snippet;
  155use std::{
  156    any::TypeId,
  157    borrow::Cow,
  158    cell::RefCell,
  159    cmp::{self, Ordering, Reverse},
  160    mem,
  161    num::NonZeroU32,
  162    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  163    path::{Path, PathBuf},
  164    rc::Rc,
  165    sync::Arc,
  166    time::{Duration, Instant},
  167};
  168pub use sum_tree::Bias;
  169use sum_tree::TreeMap;
  170use text::{BufferId, OffsetUtf16, Rope};
  171use theme::{
  172    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  173    ThemeColors, ThemeSettings,
  174};
  175use ui::{
  176    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  177    Tooltip,
  178};
  179use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  180use workspace::{
  181    item::{ItemHandle, PreviewTabsSettings},
  182    ItemId, RestoreOnStartupBehavior,
  183};
  184use workspace::{
  185    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  186    WorkspaceSettings,
  187};
  188use workspace::{
  189    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  190};
  191use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  192
  193use crate::hover_links::{find_url, find_url_from_range};
  194use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  195
  196pub const FILE_HEADER_HEIGHT: u32 = 2;
  197pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  198pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  199pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  200const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  201const MAX_LINE_LEN: usize = 1024;
  202const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  203const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  204pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  205#[doc(hidden)]
  206pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  207
  208pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  209pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  210pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  211
  212pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  213pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  214
  215const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  216    alt: true,
  217    shift: true,
  218    control: false,
  219    platform: false,
  220    function: false,
  221};
  222
  223#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  224pub enum InlayId {
  225    InlineCompletion(usize),
  226    Hint(usize),
  227}
  228
  229impl InlayId {
  230    fn id(&self) -> usize {
  231        match self {
  232            Self::InlineCompletion(id) => *id,
  233            Self::Hint(id) => *id,
  234        }
  235    }
  236}
  237
  238enum DocumentHighlightRead {}
  239enum DocumentHighlightWrite {}
  240enum InputComposition {}
  241enum SelectedTextHighlight {}
  242
  243#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  244pub enum Navigated {
  245    Yes,
  246    No,
  247}
  248
  249impl Navigated {
  250    pub fn from_bool(yes: bool) -> Navigated {
  251        if yes {
  252            Navigated::Yes
  253        } else {
  254            Navigated::No
  255        }
  256    }
  257}
  258
  259#[derive(Debug, Clone, PartialEq, Eq)]
  260enum DisplayDiffHunk {
  261    Folded {
  262        display_row: DisplayRow,
  263    },
  264    Unfolded {
  265        is_created_file: bool,
  266        diff_base_byte_range: Range<usize>,
  267        display_row_range: Range<DisplayRow>,
  268        multi_buffer_range: Range<Anchor>,
  269        status: DiffHunkStatus,
  270    },
  271}
  272
  273pub fn init_settings(cx: &mut App) {
  274    EditorSettings::register(cx);
  275}
  276
  277pub fn init(cx: &mut App) {
  278    init_settings(cx);
  279
  280    workspace::register_project_item::<Editor>(cx);
  281    workspace::FollowableViewRegistry::register::<Editor>(cx);
  282    workspace::register_serializable_item::<Editor>(cx);
  283
  284    cx.observe_new(
  285        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  286            workspace.register_action(Editor::new_file);
  287            workspace.register_action(Editor::new_file_vertical);
  288            workspace.register_action(Editor::new_file_horizontal);
  289            workspace.register_action(Editor::cancel_language_server_work);
  290        },
  291    )
  292    .detach();
  293
  294    cx.on_action(move |_: &workspace::NewFile, cx| {
  295        let app_state = workspace::AppState::global(cx);
  296        if let Some(app_state) = app_state.upgrade() {
  297            workspace::open_new(
  298                Default::default(),
  299                app_state,
  300                cx,
  301                |workspace, window, cx| {
  302                    Editor::new_file(workspace, &Default::default(), window, cx)
  303                },
  304            )
  305            .detach();
  306        }
  307    });
  308    cx.on_action(move |_: &workspace::NewWindow, cx| {
  309        let app_state = workspace::AppState::global(cx);
  310        if let Some(app_state) = app_state.upgrade() {
  311            workspace::open_new(
  312                Default::default(),
  313                app_state,
  314                cx,
  315                |workspace, window, cx| {
  316                    cx.activate(true);
  317                    Editor::new_file(workspace, &Default::default(), window, cx)
  318                },
  319            )
  320            .detach();
  321        }
  322    });
  323}
  324
  325pub struct SearchWithinRange;
  326
  327trait InvalidationRegion {
  328    fn ranges(&self) -> &[Range<Anchor>];
  329}
  330
  331#[derive(Clone, Debug, PartialEq)]
  332pub enum SelectPhase {
  333    Begin {
  334        position: DisplayPoint,
  335        add: bool,
  336        click_count: usize,
  337    },
  338    BeginColumnar {
  339        position: DisplayPoint,
  340        reset: bool,
  341        goal_column: u32,
  342    },
  343    Extend {
  344        position: DisplayPoint,
  345        click_count: usize,
  346    },
  347    Update {
  348        position: DisplayPoint,
  349        goal_column: u32,
  350        scroll_delta: gpui::Point<f32>,
  351    },
  352    End,
  353}
  354
  355#[derive(Clone, Debug)]
  356pub enum SelectMode {
  357    Character,
  358    Word(Range<Anchor>),
  359    Line(Range<Anchor>),
  360    All,
  361}
  362
  363#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  364pub enum EditorMode {
  365    SingleLine { auto_width: bool },
  366    AutoHeight { max_lines: usize },
  367    Full,
  368}
  369
  370#[derive(Copy, Clone, Debug)]
  371pub enum SoftWrap {
  372    /// Prefer not to wrap at all.
  373    ///
  374    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  375    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  376    GitDiff,
  377    /// Prefer a single line generally, unless an overly long line is encountered.
  378    None,
  379    /// Soft wrap lines that exceed the editor width.
  380    EditorWidth,
  381    /// Soft wrap lines at the preferred line length.
  382    Column(u32),
  383    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  384    Bounded(u32),
  385}
  386
  387#[derive(Clone)]
  388pub struct EditorStyle {
  389    pub background: Hsla,
  390    pub local_player: PlayerColor,
  391    pub text: TextStyle,
  392    pub scrollbar_width: Pixels,
  393    pub syntax: Arc<SyntaxTheme>,
  394    pub status: StatusColors,
  395    pub inlay_hints_style: HighlightStyle,
  396    pub inline_completion_styles: InlineCompletionStyles,
  397    pub unnecessary_code_fade: f32,
  398}
  399
  400impl Default for EditorStyle {
  401    fn default() -> Self {
  402        Self {
  403            background: Hsla::default(),
  404            local_player: PlayerColor::default(),
  405            text: TextStyle::default(),
  406            scrollbar_width: Pixels::default(),
  407            syntax: Default::default(),
  408            // HACK: Status colors don't have a real default.
  409            // We should look into removing the status colors from the editor
  410            // style and retrieve them directly from the theme.
  411            status: StatusColors::dark(),
  412            inlay_hints_style: HighlightStyle::default(),
  413            inline_completion_styles: InlineCompletionStyles {
  414                insertion: HighlightStyle::default(),
  415                whitespace: HighlightStyle::default(),
  416            },
  417            unnecessary_code_fade: Default::default(),
  418        }
  419    }
  420}
  421
  422pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  423    let show_background = language_settings::language_settings(None, None, cx)
  424        .inlay_hints
  425        .show_background;
  426
  427    HighlightStyle {
  428        color: Some(cx.theme().status().hint),
  429        background_color: show_background.then(|| cx.theme().status().hint_background),
  430        ..HighlightStyle::default()
  431    }
  432}
  433
  434pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  435    InlineCompletionStyles {
  436        insertion: HighlightStyle {
  437            color: Some(cx.theme().status().predictive),
  438            ..HighlightStyle::default()
  439        },
  440        whitespace: HighlightStyle {
  441            background_color: Some(cx.theme().status().created_background),
  442            ..HighlightStyle::default()
  443        },
  444    }
  445}
  446
  447type CompletionId = usize;
  448
  449pub(crate) enum EditDisplayMode {
  450    TabAccept,
  451    DiffPopover,
  452    Inline,
  453}
  454
  455enum InlineCompletion {
  456    Edit {
  457        edits: Vec<(Range<Anchor>, String)>,
  458        edit_preview: Option<EditPreview>,
  459        display_mode: EditDisplayMode,
  460        snapshot: BufferSnapshot,
  461    },
  462    Move {
  463        target: Anchor,
  464        snapshot: BufferSnapshot,
  465    },
  466}
  467
  468struct InlineCompletionState {
  469    inlay_ids: Vec<InlayId>,
  470    completion: InlineCompletion,
  471    completion_id: Option<SharedString>,
  472    invalidation_range: Range<Anchor>,
  473}
  474
  475enum EditPredictionSettings {
  476    Disabled,
  477    Enabled {
  478        show_in_menu: bool,
  479        preview_requires_modifier: bool,
  480    },
  481}
  482
  483enum InlineCompletionHighlight {}
  484
  485#[derive(Debug, Clone)]
  486struct InlineDiagnostic {
  487    message: SharedString,
  488    group_id: usize,
  489    is_primary: bool,
  490    start: Point,
  491    severity: DiagnosticSeverity,
  492}
  493
  494pub enum MenuInlineCompletionsPolicy {
  495    Never,
  496    ByProvider,
  497}
  498
  499pub enum EditPredictionPreview {
  500    /// Modifier is not pressed
  501    Inactive { released_too_fast: bool },
  502    /// Modifier pressed
  503    Active {
  504        since: Instant,
  505        previous_scroll_position: Option<ScrollAnchor>,
  506    },
  507}
  508
  509impl EditPredictionPreview {
  510    pub fn released_too_fast(&self) -> bool {
  511        match self {
  512            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  513            EditPredictionPreview::Active { .. } => false,
  514        }
  515    }
  516
  517    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  518        if let EditPredictionPreview::Active {
  519            previous_scroll_position,
  520            ..
  521        } = self
  522        {
  523            *previous_scroll_position = scroll_position;
  524        }
  525    }
  526}
  527
  528#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  529struct EditorActionId(usize);
  530
  531impl EditorActionId {
  532    pub fn post_inc(&mut self) -> Self {
  533        let answer = self.0;
  534
  535        *self = Self(answer + 1);
  536
  537        Self(answer)
  538    }
  539}
  540
  541// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  542// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  543
  544type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  545type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  546
  547#[derive(Default)]
  548struct ScrollbarMarkerState {
  549    scrollbar_size: Size<Pixels>,
  550    dirty: bool,
  551    markers: Arc<[PaintQuad]>,
  552    pending_refresh: Option<Task<Result<()>>>,
  553}
  554
  555impl ScrollbarMarkerState {
  556    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  557        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  558    }
  559}
  560
  561#[derive(Clone, Debug)]
  562struct RunnableTasks {
  563    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  564    offset: multi_buffer::Anchor,
  565    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  566    column: u32,
  567    // Values of all named captures, including those starting with '_'
  568    extra_variables: HashMap<String, String>,
  569    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  570    context_range: Range<BufferOffset>,
  571}
  572
  573impl RunnableTasks {
  574    fn resolve<'a>(
  575        &'a self,
  576        cx: &'a task::TaskContext,
  577    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  578        self.templates.iter().filter_map(|(kind, template)| {
  579            template
  580                .resolve_task(&kind.to_id_base(), cx)
  581                .map(|task| (kind.clone(), task))
  582        })
  583    }
  584}
  585
  586#[derive(Clone)]
  587struct ResolvedTasks {
  588    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  589    position: Anchor,
  590}
  591#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  592struct BufferOffset(usize);
  593
  594// Addons allow storing per-editor state in other crates (e.g. Vim)
  595pub trait Addon: 'static {
  596    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  597
  598    fn render_buffer_header_controls(
  599        &self,
  600        _: &ExcerptInfo,
  601        _: &Window,
  602        _: &App,
  603    ) -> Option<AnyElement> {
  604        None
  605    }
  606
  607    fn to_any(&self) -> &dyn std::any::Any;
  608}
  609
  610#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  611pub enum IsVimMode {
  612    Yes,
  613    No,
  614}
  615
  616/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  617///
  618/// See the [module level documentation](self) for more information.
  619pub struct Editor {
  620    focus_handle: FocusHandle,
  621    last_focused_descendant: Option<WeakFocusHandle>,
  622    /// The text buffer being edited
  623    buffer: Entity<MultiBuffer>,
  624    /// Map of how text in the buffer should be displayed.
  625    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  626    pub display_map: Entity<DisplayMap>,
  627    pub selections: SelectionsCollection,
  628    pub scroll_manager: ScrollManager,
  629    /// When inline assist editors are linked, they all render cursors because
  630    /// typing enters text into each of them, even the ones that aren't focused.
  631    pub(crate) show_cursor_when_unfocused: bool,
  632    columnar_selection_tail: Option<Anchor>,
  633    add_selections_state: Option<AddSelectionsState>,
  634    select_next_state: Option<SelectNextState>,
  635    select_prev_state: Option<SelectNextState>,
  636    selection_history: SelectionHistory,
  637    autoclose_regions: Vec<AutocloseRegion>,
  638    snippet_stack: InvalidationStack<SnippetState>,
  639    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  640    ime_transaction: Option<TransactionId>,
  641    active_diagnostics: Option<ActiveDiagnosticGroup>,
  642    show_inline_diagnostics: bool,
  643    inline_diagnostics_update: Task<()>,
  644    inline_diagnostics_enabled: bool,
  645    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  646    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  647
  648    // TODO: make this a access method
  649    pub project: Option<Entity<Project>>,
  650    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  651    completion_provider: Option<Box<dyn CompletionProvider>>,
  652    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  653    blink_manager: Entity<BlinkManager>,
  654    show_cursor_names: bool,
  655    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  656    pub show_local_selections: bool,
  657    mode: EditorMode,
  658    show_breadcrumbs: bool,
  659    show_gutter: bool,
  660    show_scrollbars: bool,
  661    show_line_numbers: Option<bool>,
  662    use_relative_line_numbers: Option<bool>,
  663    show_git_diff_gutter: Option<bool>,
  664    show_code_actions: Option<bool>,
  665    show_runnables: Option<bool>,
  666    show_wrap_guides: Option<bool>,
  667    show_indent_guides: Option<bool>,
  668    placeholder_text: Option<Arc<str>>,
  669    highlight_order: usize,
  670    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  671    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  672    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  673    scrollbar_marker_state: ScrollbarMarkerState,
  674    active_indent_guides_state: ActiveIndentGuidesState,
  675    nav_history: Option<ItemNavHistory>,
  676    context_menu: RefCell<Option<CodeContextMenu>>,
  677    mouse_context_menu: Option<MouseContextMenu>,
  678    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  679    signature_help_state: SignatureHelpState,
  680    auto_signature_help: Option<bool>,
  681    find_all_references_task_sources: Vec<Anchor>,
  682    next_completion_id: CompletionId,
  683    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  684    code_actions_task: Option<Task<Result<()>>>,
  685    selection_highlight_task: Option<Task<()>>,
  686    document_highlights_task: Option<Task<()>>,
  687    linked_editing_range_task: Option<Task<Option<()>>>,
  688    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  689    pending_rename: Option<RenameState>,
  690    searchable: bool,
  691    cursor_shape: CursorShape,
  692    current_line_highlight: Option<CurrentLineHighlight>,
  693    collapse_matches: bool,
  694    autoindent_mode: Option<AutoindentMode>,
  695    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  696    input_enabled: bool,
  697    use_modal_editing: bool,
  698    read_only: bool,
  699    leader_peer_id: Option<PeerId>,
  700    remote_id: Option<ViewId>,
  701    hover_state: HoverState,
  702    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  703    gutter_hovered: bool,
  704    hovered_link_state: Option<HoveredLinkState>,
  705    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  706    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  707    active_inline_completion: Option<InlineCompletionState>,
  708    /// Used to prevent flickering as the user types while the menu is open
  709    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  710    edit_prediction_settings: EditPredictionSettings,
  711    inline_completions_hidden_for_vim_mode: bool,
  712    show_inline_completions_override: Option<bool>,
  713    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  714    edit_prediction_preview: EditPredictionPreview,
  715    edit_prediction_indent_conflict: bool,
  716    edit_prediction_requires_modifier_in_indent_conflict: bool,
  717    inlay_hint_cache: InlayHintCache,
  718    next_inlay_id: usize,
  719    _subscriptions: Vec<Subscription>,
  720    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  721    gutter_dimensions: GutterDimensions,
  722    style: Option<EditorStyle>,
  723    text_style_refinement: Option<TextStyleRefinement>,
  724    next_editor_action_id: EditorActionId,
  725    editor_actions:
  726        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  727    use_autoclose: bool,
  728    use_auto_surround: bool,
  729    auto_replace_emoji_shortcode: bool,
  730    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  731    show_git_blame_gutter: bool,
  732    show_git_blame_inline: bool,
  733    show_git_blame_inline_delay_task: Option<Task<()>>,
  734    git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
  735    git_blame_inline_enabled: bool,
  736    serialize_dirty_buffers: bool,
  737    show_selection_menu: Option<bool>,
  738    blame: Option<Entity<GitBlame>>,
  739    blame_subscription: Option<Subscription>,
  740    custom_context_menu: Option<
  741        Box<
  742            dyn 'static
  743                + Fn(
  744                    &mut Self,
  745                    DisplayPoint,
  746                    &mut Window,
  747                    &mut Context<Self>,
  748                ) -> Option<Entity<ui::ContextMenu>>,
  749        >,
  750    >,
  751    last_bounds: Option<Bounds<Pixels>>,
  752    last_position_map: Option<Rc<PositionMap>>,
  753    expect_bounds_change: Option<Bounds<Pixels>>,
  754    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  755    tasks_update_task: Option<Task<()>>,
  756    in_project_search: bool,
  757    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  758    breadcrumb_header: Option<String>,
  759    focused_block: Option<FocusedBlock>,
  760    next_scroll_position: NextScrollCursorCenterTopBottom,
  761    addons: HashMap<TypeId, Box<dyn Addon>>,
  762    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  763    load_diff_task: Option<Shared<Task<()>>>,
  764    selection_mark_mode: bool,
  765    toggle_fold_multiple_buffers: Task<()>,
  766    _scroll_cursor_center_top_bottom_task: Task<()>,
  767    serialize_selections: Task<()>,
  768}
  769
  770#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  771enum NextScrollCursorCenterTopBottom {
  772    #[default]
  773    Center,
  774    Top,
  775    Bottom,
  776}
  777
  778impl NextScrollCursorCenterTopBottom {
  779    fn next(&self) -> Self {
  780        match self {
  781            Self::Center => Self::Top,
  782            Self::Top => Self::Bottom,
  783            Self::Bottom => Self::Center,
  784        }
  785    }
  786}
  787
  788#[derive(Clone)]
  789pub struct EditorSnapshot {
  790    pub mode: EditorMode,
  791    show_gutter: bool,
  792    show_line_numbers: Option<bool>,
  793    show_git_diff_gutter: Option<bool>,
  794    show_code_actions: Option<bool>,
  795    show_runnables: Option<bool>,
  796    git_blame_gutter_max_author_length: Option<usize>,
  797    pub display_snapshot: DisplaySnapshot,
  798    pub placeholder_text: Option<Arc<str>>,
  799    is_focused: bool,
  800    scroll_anchor: ScrollAnchor,
  801    ongoing_scroll: OngoingScroll,
  802    current_line_highlight: CurrentLineHighlight,
  803    gutter_hovered: bool,
  804}
  805
  806const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  807
  808#[derive(Default, Debug, Clone, Copy)]
  809pub struct GutterDimensions {
  810    pub left_padding: Pixels,
  811    pub right_padding: Pixels,
  812    pub width: Pixels,
  813    pub margin: Pixels,
  814    pub git_blame_entries_width: Option<Pixels>,
  815}
  816
  817impl GutterDimensions {
  818    /// The full width of the space taken up by the gutter.
  819    pub fn full_width(&self) -> Pixels {
  820        self.margin + self.width
  821    }
  822
  823    /// The width of the space reserved for the fold indicators,
  824    /// use alongside 'justify_end' and `gutter_width` to
  825    /// right align content with the line numbers
  826    pub fn fold_area_width(&self) -> Pixels {
  827        self.margin + self.right_padding
  828    }
  829}
  830
  831#[derive(Debug)]
  832pub struct RemoteSelection {
  833    pub replica_id: ReplicaId,
  834    pub selection: Selection<Anchor>,
  835    pub cursor_shape: CursorShape,
  836    pub peer_id: PeerId,
  837    pub line_mode: bool,
  838    pub participant_index: Option<ParticipantIndex>,
  839    pub user_name: Option<SharedString>,
  840}
  841
  842#[derive(Clone, Debug)]
  843struct SelectionHistoryEntry {
  844    selections: Arc<[Selection<Anchor>]>,
  845    select_next_state: Option<SelectNextState>,
  846    select_prev_state: Option<SelectNextState>,
  847    add_selections_state: Option<AddSelectionsState>,
  848}
  849
  850enum SelectionHistoryMode {
  851    Normal,
  852    Undoing,
  853    Redoing,
  854}
  855
  856#[derive(Clone, PartialEq, Eq, Hash)]
  857struct HoveredCursor {
  858    replica_id: u16,
  859    selection_id: usize,
  860}
  861
  862impl Default for SelectionHistoryMode {
  863    fn default() -> Self {
  864        Self::Normal
  865    }
  866}
  867
  868#[derive(Default)]
  869struct SelectionHistory {
  870    #[allow(clippy::type_complexity)]
  871    selections_by_transaction:
  872        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  873    mode: SelectionHistoryMode,
  874    undo_stack: VecDeque<SelectionHistoryEntry>,
  875    redo_stack: VecDeque<SelectionHistoryEntry>,
  876}
  877
  878impl SelectionHistory {
  879    fn insert_transaction(
  880        &mut self,
  881        transaction_id: TransactionId,
  882        selections: Arc<[Selection<Anchor>]>,
  883    ) {
  884        self.selections_by_transaction
  885            .insert(transaction_id, (selections, None));
  886    }
  887
  888    #[allow(clippy::type_complexity)]
  889    fn transaction(
  890        &self,
  891        transaction_id: TransactionId,
  892    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  893        self.selections_by_transaction.get(&transaction_id)
  894    }
  895
  896    #[allow(clippy::type_complexity)]
  897    fn transaction_mut(
  898        &mut self,
  899        transaction_id: TransactionId,
  900    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  901        self.selections_by_transaction.get_mut(&transaction_id)
  902    }
  903
  904    fn push(&mut self, entry: SelectionHistoryEntry) {
  905        if !entry.selections.is_empty() {
  906            match self.mode {
  907                SelectionHistoryMode::Normal => {
  908                    self.push_undo(entry);
  909                    self.redo_stack.clear();
  910                }
  911                SelectionHistoryMode::Undoing => self.push_redo(entry),
  912                SelectionHistoryMode::Redoing => self.push_undo(entry),
  913            }
  914        }
  915    }
  916
  917    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  918        if self
  919            .undo_stack
  920            .back()
  921            .map_or(true, |e| e.selections != entry.selections)
  922        {
  923            self.undo_stack.push_back(entry);
  924            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  925                self.undo_stack.pop_front();
  926            }
  927        }
  928    }
  929
  930    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  931        if self
  932            .redo_stack
  933            .back()
  934            .map_or(true, |e| e.selections != entry.selections)
  935        {
  936            self.redo_stack.push_back(entry);
  937            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  938                self.redo_stack.pop_front();
  939            }
  940        }
  941    }
  942}
  943
  944struct RowHighlight {
  945    index: usize,
  946    range: Range<Anchor>,
  947    color: Hsla,
  948    should_autoscroll: bool,
  949}
  950
  951#[derive(Clone, Debug)]
  952struct AddSelectionsState {
  953    above: bool,
  954    stack: Vec<usize>,
  955}
  956
  957#[derive(Clone)]
  958struct SelectNextState {
  959    query: AhoCorasick,
  960    wordwise: bool,
  961    done: bool,
  962}
  963
  964impl std::fmt::Debug for SelectNextState {
  965    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  966        f.debug_struct(std::any::type_name::<Self>())
  967            .field("wordwise", &self.wordwise)
  968            .field("done", &self.done)
  969            .finish()
  970    }
  971}
  972
  973#[derive(Debug)]
  974struct AutocloseRegion {
  975    selection_id: usize,
  976    range: Range<Anchor>,
  977    pair: BracketPair,
  978}
  979
  980#[derive(Debug)]
  981struct SnippetState {
  982    ranges: Vec<Vec<Range<Anchor>>>,
  983    active_index: usize,
  984    choices: Vec<Option<Vec<String>>>,
  985}
  986
  987#[doc(hidden)]
  988pub struct RenameState {
  989    pub range: Range<Anchor>,
  990    pub old_name: Arc<str>,
  991    pub editor: Entity<Editor>,
  992    block_id: CustomBlockId,
  993}
  994
  995struct InvalidationStack<T>(Vec<T>);
  996
  997struct RegisteredInlineCompletionProvider {
  998    provider: Arc<dyn InlineCompletionProviderHandle>,
  999    _subscription: Subscription,
 1000}
 1001
 1002#[derive(Debug, PartialEq, Eq)]
 1003struct ActiveDiagnosticGroup {
 1004    primary_range: Range<Anchor>,
 1005    primary_message: String,
 1006    group_id: usize,
 1007    blocks: HashMap<CustomBlockId, Diagnostic>,
 1008    is_valid: bool,
 1009}
 1010
 1011#[derive(Serialize, Deserialize, Clone, Debug)]
 1012pub struct ClipboardSelection {
 1013    /// The number of bytes in this selection.
 1014    pub len: usize,
 1015    /// Whether this was a full-line selection.
 1016    pub is_entire_line: bool,
 1017    /// The indentation of the first line when this content was originally copied.
 1018    pub first_line_indent: u32,
 1019}
 1020
 1021#[derive(Debug)]
 1022pub(crate) struct NavigationData {
 1023    cursor_anchor: Anchor,
 1024    cursor_position: Point,
 1025    scroll_anchor: ScrollAnchor,
 1026    scroll_top_row: u32,
 1027}
 1028
 1029#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1030pub enum GotoDefinitionKind {
 1031    Symbol,
 1032    Declaration,
 1033    Type,
 1034    Implementation,
 1035}
 1036
 1037#[derive(Debug, Clone)]
 1038enum InlayHintRefreshReason {
 1039    ModifiersChanged(bool),
 1040    Toggle(bool),
 1041    SettingsChange(InlayHintSettings),
 1042    NewLinesShown,
 1043    BufferEdited(HashSet<Arc<Language>>),
 1044    RefreshRequested,
 1045    ExcerptsRemoved(Vec<ExcerptId>),
 1046}
 1047
 1048impl InlayHintRefreshReason {
 1049    fn description(&self) -> &'static str {
 1050        match self {
 1051            Self::ModifiersChanged(_) => "modifiers changed",
 1052            Self::Toggle(_) => "toggle",
 1053            Self::SettingsChange(_) => "settings change",
 1054            Self::NewLinesShown => "new lines shown",
 1055            Self::BufferEdited(_) => "buffer edited",
 1056            Self::RefreshRequested => "refresh requested",
 1057            Self::ExcerptsRemoved(_) => "excerpts removed",
 1058        }
 1059    }
 1060}
 1061
 1062pub enum FormatTarget {
 1063    Buffers,
 1064    Ranges(Vec<Range<MultiBufferPoint>>),
 1065}
 1066
 1067pub(crate) struct FocusedBlock {
 1068    id: BlockId,
 1069    focus_handle: WeakFocusHandle,
 1070}
 1071
 1072#[derive(Clone)]
 1073enum JumpData {
 1074    MultiBufferRow {
 1075        row: MultiBufferRow,
 1076        line_offset_from_top: u32,
 1077    },
 1078    MultiBufferPoint {
 1079        excerpt_id: ExcerptId,
 1080        position: Point,
 1081        anchor: text::Anchor,
 1082        line_offset_from_top: u32,
 1083    },
 1084}
 1085
 1086pub enum MultibufferSelectionMode {
 1087    First,
 1088    All,
 1089}
 1090
 1091impl Editor {
 1092    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1093        let buffer = cx.new(|cx| Buffer::local("", cx));
 1094        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1095        Self::new(
 1096            EditorMode::SingleLine { auto_width: false },
 1097            buffer,
 1098            None,
 1099            false,
 1100            window,
 1101            cx,
 1102        )
 1103    }
 1104
 1105    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1106        let buffer = cx.new(|cx| Buffer::local("", cx));
 1107        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1108        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1109    }
 1110
 1111    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1112        let buffer = cx.new(|cx| Buffer::local("", cx));
 1113        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1114        Self::new(
 1115            EditorMode::SingleLine { auto_width: true },
 1116            buffer,
 1117            None,
 1118            false,
 1119            window,
 1120            cx,
 1121        )
 1122    }
 1123
 1124    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1125        let buffer = cx.new(|cx| Buffer::local("", cx));
 1126        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1127        Self::new(
 1128            EditorMode::AutoHeight { max_lines },
 1129            buffer,
 1130            None,
 1131            false,
 1132            window,
 1133            cx,
 1134        )
 1135    }
 1136
 1137    pub fn for_buffer(
 1138        buffer: Entity<Buffer>,
 1139        project: Option<Entity<Project>>,
 1140        window: &mut Window,
 1141        cx: &mut Context<Self>,
 1142    ) -> Self {
 1143        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1144        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1145    }
 1146
 1147    pub fn for_multibuffer(
 1148        buffer: Entity<MultiBuffer>,
 1149        project: Option<Entity<Project>>,
 1150        show_excerpt_controls: bool,
 1151        window: &mut Window,
 1152        cx: &mut Context<Self>,
 1153    ) -> Self {
 1154        Self::new(
 1155            EditorMode::Full,
 1156            buffer,
 1157            project,
 1158            show_excerpt_controls,
 1159            window,
 1160            cx,
 1161        )
 1162    }
 1163
 1164    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1165        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1166        let mut clone = Self::new(
 1167            self.mode,
 1168            self.buffer.clone(),
 1169            self.project.clone(),
 1170            show_excerpt_controls,
 1171            window,
 1172            cx,
 1173        );
 1174        self.display_map.update(cx, |display_map, cx| {
 1175            let snapshot = display_map.snapshot(cx);
 1176            clone.display_map.update(cx, |display_map, cx| {
 1177                display_map.set_state(&snapshot, cx);
 1178            });
 1179        });
 1180        clone.selections.clone_state(&self.selections);
 1181        clone.scroll_manager.clone_state(&self.scroll_manager);
 1182        clone.searchable = self.searchable;
 1183        clone
 1184    }
 1185
 1186    pub fn new(
 1187        mode: EditorMode,
 1188        buffer: Entity<MultiBuffer>,
 1189        project: Option<Entity<Project>>,
 1190        show_excerpt_controls: bool,
 1191        window: &mut Window,
 1192        cx: &mut Context<Self>,
 1193    ) -> Self {
 1194        let style = window.text_style();
 1195        let font_size = style.font_size.to_pixels(window.rem_size());
 1196        let editor = cx.entity().downgrade();
 1197        let fold_placeholder = FoldPlaceholder {
 1198            constrain_width: true,
 1199            render: Arc::new(move |fold_id, fold_range, cx| {
 1200                let editor = editor.clone();
 1201                div()
 1202                    .id(fold_id)
 1203                    .bg(cx.theme().colors().ghost_element_background)
 1204                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1205                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1206                    .rounded_xs()
 1207                    .size_full()
 1208                    .cursor_pointer()
 1209                    .child("")
 1210                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1211                    .on_click(move |_, _window, cx| {
 1212                        editor
 1213                            .update(cx, |editor, cx| {
 1214                                editor.unfold_ranges(
 1215                                    &[fold_range.start..fold_range.end],
 1216                                    true,
 1217                                    false,
 1218                                    cx,
 1219                                );
 1220                                cx.stop_propagation();
 1221                            })
 1222                            .ok();
 1223                    })
 1224                    .into_any()
 1225            }),
 1226            merge_adjacent: true,
 1227            ..Default::default()
 1228        };
 1229        let display_map = cx.new(|cx| {
 1230            DisplayMap::new(
 1231                buffer.clone(),
 1232                style.font(),
 1233                font_size,
 1234                None,
 1235                show_excerpt_controls,
 1236                FILE_HEADER_HEIGHT,
 1237                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1238                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1239                fold_placeholder,
 1240                cx,
 1241            )
 1242        });
 1243
 1244        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1245
 1246        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1247
 1248        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1249            .then(|| language_settings::SoftWrap::None);
 1250
 1251        let mut project_subscriptions = Vec::new();
 1252        if mode == EditorMode::Full {
 1253            if let Some(project) = project.as_ref() {
 1254                project_subscriptions.push(cx.subscribe_in(
 1255                    project,
 1256                    window,
 1257                    |editor, _, event, window, cx| {
 1258                        if let project::Event::RefreshInlayHints = event {
 1259                            editor
 1260                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1261                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1262                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1263                                let focus_handle = editor.focus_handle(cx);
 1264                                if focus_handle.is_focused(window) {
 1265                                    let snapshot = buffer.read(cx).snapshot();
 1266                                    for (range, snippet) in snippet_edits {
 1267                                        let editor_range =
 1268                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1269                                        editor
 1270                                            .insert_snippet(
 1271                                                &[editor_range],
 1272                                                snippet.clone(),
 1273                                                window,
 1274                                                cx,
 1275                                            )
 1276                                            .ok();
 1277                                    }
 1278                                }
 1279                            }
 1280                        }
 1281                    },
 1282                ));
 1283                if let Some(task_inventory) = project
 1284                    .read(cx)
 1285                    .task_store()
 1286                    .read(cx)
 1287                    .task_inventory()
 1288                    .cloned()
 1289                {
 1290                    project_subscriptions.push(cx.observe_in(
 1291                        &task_inventory,
 1292                        window,
 1293                        |editor, _, window, cx| {
 1294                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1295                        },
 1296                    ));
 1297                }
 1298            }
 1299        }
 1300
 1301        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1302
 1303        let inlay_hint_settings =
 1304            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1305        let focus_handle = cx.focus_handle();
 1306        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1307            .detach();
 1308        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1309            .detach();
 1310        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1311            .detach();
 1312        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1313            .detach();
 1314
 1315        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1316            Some(false)
 1317        } else {
 1318            None
 1319        };
 1320
 1321        let mut code_action_providers = Vec::new();
 1322        let mut load_uncommitted_diff = None;
 1323        if let Some(project) = project.clone() {
 1324            load_uncommitted_diff = Some(
 1325                get_uncommitted_diff_for_buffer(
 1326                    &project,
 1327                    buffer.read(cx).all_buffers(),
 1328                    buffer.clone(),
 1329                    cx,
 1330                )
 1331                .shared(),
 1332            );
 1333            code_action_providers.push(Rc::new(project) as Rc<_>);
 1334        }
 1335
 1336        let mut this = Self {
 1337            focus_handle,
 1338            show_cursor_when_unfocused: false,
 1339            last_focused_descendant: None,
 1340            buffer: buffer.clone(),
 1341            display_map: display_map.clone(),
 1342            selections,
 1343            scroll_manager: ScrollManager::new(cx),
 1344            columnar_selection_tail: None,
 1345            add_selections_state: None,
 1346            select_next_state: None,
 1347            select_prev_state: None,
 1348            selection_history: Default::default(),
 1349            autoclose_regions: Default::default(),
 1350            snippet_stack: Default::default(),
 1351            select_larger_syntax_node_stack: Vec::new(),
 1352            ime_transaction: Default::default(),
 1353            active_diagnostics: None,
 1354            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1355            inline_diagnostics_update: Task::ready(()),
 1356            inline_diagnostics: Vec::new(),
 1357            soft_wrap_mode_override,
 1358            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1359            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1360            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1361            project,
 1362            blink_manager: blink_manager.clone(),
 1363            show_local_selections: true,
 1364            show_scrollbars: true,
 1365            mode,
 1366            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1367            show_gutter: mode == EditorMode::Full,
 1368            show_line_numbers: None,
 1369            use_relative_line_numbers: None,
 1370            show_git_diff_gutter: None,
 1371            show_code_actions: None,
 1372            show_runnables: None,
 1373            show_wrap_guides: None,
 1374            show_indent_guides,
 1375            placeholder_text: None,
 1376            highlight_order: 0,
 1377            highlighted_rows: HashMap::default(),
 1378            background_highlights: Default::default(),
 1379            gutter_highlights: TreeMap::default(),
 1380            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1381            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1382            nav_history: None,
 1383            context_menu: RefCell::new(None),
 1384            mouse_context_menu: None,
 1385            completion_tasks: Default::default(),
 1386            signature_help_state: SignatureHelpState::default(),
 1387            auto_signature_help: None,
 1388            find_all_references_task_sources: Vec::new(),
 1389            next_completion_id: 0,
 1390            next_inlay_id: 0,
 1391            code_action_providers,
 1392            available_code_actions: Default::default(),
 1393            code_actions_task: Default::default(),
 1394            selection_highlight_task: Default::default(),
 1395            document_highlights_task: Default::default(),
 1396            linked_editing_range_task: Default::default(),
 1397            pending_rename: Default::default(),
 1398            searchable: true,
 1399            cursor_shape: EditorSettings::get_global(cx)
 1400                .cursor_shape
 1401                .unwrap_or_default(),
 1402            current_line_highlight: None,
 1403            autoindent_mode: Some(AutoindentMode::EachLine),
 1404            collapse_matches: false,
 1405            workspace: None,
 1406            input_enabled: true,
 1407            use_modal_editing: mode == EditorMode::Full,
 1408            read_only: false,
 1409            use_autoclose: true,
 1410            use_auto_surround: true,
 1411            auto_replace_emoji_shortcode: false,
 1412            jsx_tag_auto_close_enabled_in_any_buffer: 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        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1497
 1498        if mode == EditorMode::Full {
 1499            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1500            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1501
 1502            if this.git_blame_inline_enabled {
 1503                this.git_blame_inline_enabled = true;
 1504                this.start_git_blame_inline(false, window, cx);
 1505            }
 1506
 1507            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1508                if let Some(project) = this.project.as_ref() {
 1509                    let handle = project.update(cx, |project, cx| {
 1510                        project.register_buffer_with_language_servers(&buffer, cx)
 1511                    });
 1512                    this.registered_buffers
 1513                        .insert(buffer.read(cx).remote_id(), handle);
 1514                }
 1515            }
 1516        }
 1517
 1518        this.report_editor_event("Editor Opened", None, cx);
 1519        this
 1520    }
 1521
 1522    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1523        self.mouse_context_menu
 1524            .as_ref()
 1525            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1526    }
 1527
 1528    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1529        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1530    }
 1531
 1532    fn key_context_internal(
 1533        &self,
 1534        has_active_edit_prediction: bool,
 1535        window: &Window,
 1536        cx: &App,
 1537    ) -> KeyContext {
 1538        let mut key_context = KeyContext::new_with_defaults();
 1539        key_context.add("Editor");
 1540        let mode = match self.mode {
 1541            EditorMode::SingleLine { .. } => "single_line",
 1542            EditorMode::AutoHeight { .. } => "auto_height",
 1543            EditorMode::Full => "full",
 1544        };
 1545
 1546        if EditorSettings::jupyter_enabled(cx) {
 1547            key_context.add("jupyter");
 1548        }
 1549
 1550        key_context.set("mode", mode);
 1551        if self.pending_rename.is_some() {
 1552            key_context.add("renaming");
 1553        }
 1554
 1555        match self.context_menu.borrow().as_ref() {
 1556            Some(CodeContextMenu::Completions(_)) => {
 1557                key_context.add("menu");
 1558                key_context.add("showing_completions");
 1559            }
 1560            Some(CodeContextMenu::CodeActions(_)) => {
 1561                key_context.add("menu");
 1562                key_context.add("showing_code_actions")
 1563            }
 1564            None => {}
 1565        }
 1566
 1567        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1568        if !self.focus_handle(cx).contains_focused(window, cx)
 1569            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1570        {
 1571            for addon in self.addons.values() {
 1572                addon.extend_key_context(&mut key_context, cx)
 1573            }
 1574        }
 1575
 1576        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1577            if let Some(extension) = singleton_buffer
 1578                .read(cx)
 1579                .file()
 1580                .and_then(|file| file.path().extension()?.to_str())
 1581            {
 1582                key_context.set("extension", extension.to_string());
 1583            }
 1584        } else {
 1585            key_context.add("multibuffer");
 1586        }
 1587
 1588        if has_active_edit_prediction {
 1589            if self.edit_prediction_in_conflict() {
 1590                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1591            } else {
 1592                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1593                key_context.add("copilot_suggestion");
 1594            }
 1595        }
 1596
 1597        if self.selection_mark_mode {
 1598            key_context.add("selection_mode");
 1599        }
 1600
 1601        key_context
 1602    }
 1603
 1604    pub fn edit_prediction_in_conflict(&self) -> bool {
 1605        if !self.show_edit_predictions_in_menu() {
 1606            return false;
 1607        }
 1608
 1609        let showing_completions = self
 1610            .context_menu
 1611            .borrow()
 1612            .as_ref()
 1613            .map_or(false, |context| {
 1614                matches!(context, CodeContextMenu::Completions(_))
 1615            });
 1616
 1617        showing_completions
 1618            || self.edit_prediction_requires_modifier()
 1619            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1620            // bindings to insert tab characters.
 1621            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1622    }
 1623
 1624    pub fn accept_edit_prediction_keybind(
 1625        &self,
 1626        window: &Window,
 1627        cx: &App,
 1628    ) -> AcceptEditPredictionBinding {
 1629        let key_context = self.key_context_internal(true, window, cx);
 1630        let in_conflict = self.edit_prediction_in_conflict();
 1631
 1632        AcceptEditPredictionBinding(
 1633            window
 1634                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1635                .into_iter()
 1636                .filter(|binding| {
 1637                    !in_conflict
 1638                        || binding
 1639                            .keystrokes()
 1640                            .first()
 1641                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1642                })
 1643                .rev()
 1644                .min_by_key(|binding| {
 1645                    binding
 1646                        .keystrokes()
 1647                        .first()
 1648                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1649                }),
 1650        )
 1651    }
 1652
 1653    pub fn new_file(
 1654        workspace: &mut Workspace,
 1655        _: &workspace::NewFile,
 1656        window: &mut Window,
 1657        cx: &mut Context<Workspace>,
 1658    ) {
 1659        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1660            "Failed to create buffer",
 1661            window,
 1662            cx,
 1663            |e, _, _| match e.error_code() {
 1664                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1665                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1666                e.error_tag("required").unwrap_or("the latest version")
 1667            )),
 1668                _ => None,
 1669            },
 1670        );
 1671    }
 1672
 1673    pub fn new_in_workspace(
 1674        workspace: &mut Workspace,
 1675        window: &mut Window,
 1676        cx: &mut Context<Workspace>,
 1677    ) -> Task<Result<Entity<Editor>>> {
 1678        let project = workspace.project().clone();
 1679        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1680
 1681        cx.spawn_in(window, |workspace, mut cx| async move {
 1682            let buffer = create.await?;
 1683            workspace.update_in(&mut cx, |workspace, window, cx| {
 1684                let editor =
 1685                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1686                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1687                editor
 1688            })
 1689        })
 1690    }
 1691
 1692    fn new_file_vertical(
 1693        workspace: &mut Workspace,
 1694        _: &workspace::NewFileSplitVertical,
 1695        window: &mut Window,
 1696        cx: &mut Context<Workspace>,
 1697    ) {
 1698        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1699    }
 1700
 1701    fn new_file_horizontal(
 1702        workspace: &mut Workspace,
 1703        _: &workspace::NewFileSplitHorizontal,
 1704        window: &mut Window,
 1705        cx: &mut Context<Workspace>,
 1706    ) {
 1707        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1708    }
 1709
 1710    fn new_file_in_direction(
 1711        workspace: &mut Workspace,
 1712        direction: SplitDirection,
 1713        window: &mut Window,
 1714        cx: &mut Context<Workspace>,
 1715    ) {
 1716        let project = workspace.project().clone();
 1717        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1718
 1719        cx.spawn_in(window, |workspace, mut cx| async move {
 1720            let buffer = create.await?;
 1721            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1722                workspace.split_item(
 1723                    direction,
 1724                    Box::new(
 1725                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1726                    ),
 1727                    window,
 1728                    cx,
 1729                )
 1730            })?;
 1731            anyhow::Ok(())
 1732        })
 1733        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1734            match e.error_code() {
 1735                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1736                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1737                e.error_tag("required").unwrap_or("the latest version")
 1738            )),
 1739                _ => None,
 1740            }
 1741        });
 1742    }
 1743
 1744    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1745        self.leader_peer_id
 1746    }
 1747
 1748    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1749        &self.buffer
 1750    }
 1751
 1752    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1753        self.workspace.as_ref()?.0.upgrade()
 1754    }
 1755
 1756    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1757        self.buffer().read(cx).title(cx)
 1758    }
 1759
 1760    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1761        let git_blame_gutter_max_author_length = self
 1762            .render_git_blame_gutter(cx)
 1763            .then(|| {
 1764                if let Some(blame) = self.blame.as_ref() {
 1765                    let max_author_length =
 1766                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1767                    Some(max_author_length)
 1768                } else {
 1769                    None
 1770                }
 1771            })
 1772            .flatten();
 1773
 1774        EditorSnapshot {
 1775            mode: self.mode,
 1776            show_gutter: self.show_gutter,
 1777            show_line_numbers: self.show_line_numbers,
 1778            show_git_diff_gutter: self.show_git_diff_gutter,
 1779            show_code_actions: self.show_code_actions,
 1780            show_runnables: self.show_runnables,
 1781            git_blame_gutter_max_author_length,
 1782            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1783            scroll_anchor: self.scroll_manager.anchor(),
 1784            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1785            placeholder_text: self.placeholder_text.clone(),
 1786            is_focused: self.focus_handle.is_focused(window),
 1787            current_line_highlight: self
 1788                .current_line_highlight
 1789                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1790            gutter_hovered: self.gutter_hovered,
 1791        }
 1792    }
 1793
 1794    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1795        self.buffer.read(cx).language_at(point, cx)
 1796    }
 1797
 1798    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1799        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1800    }
 1801
 1802    pub fn active_excerpt(
 1803        &self,
 1804        cx: &App,
 1805    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1806        self.buffer
 1807            .read(cx)
 1808            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1809    }
 1810
 1811    pub fn mode(&self) -> EditorMode {
 1812        self.mode
 1813    }
 1814
 1815    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1816        self.collaboration_hub.as_deref()
 1817    }
 1818
 1819    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1820        self.collaboration_hub = Some(hub);
 1821    }
 1822
 1823    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1824        self.in_project_search = in_project_search;
 1825    }
 1826
 1827    pub fn set_custom_context_menu(
 1828        &mut self,
 1829        f: impl 'static
 1830            + Fn(
 1831                &mut Self,
 1832                DisplayPoint,
 1833                &mut Window,
 1834                &mut Context<Self>,
 1835            ) -> Option<Entity<ui::ContextMenu>>,
 1836    ) {
 1837        self.custom_context_menu = Some(Box::new(f))
 1838    }
 1839
 1840    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1841        self.completion_provider = provider;
 1842    }
 1843
 1844    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1845        self.semantics_provider.clone()
 1846    }
 1847
 1848    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1849        self.semantics_provider = provider;
 1850    }
 1851
 1852    pub fn set_edit_prediction_provider<T>(
 1853        &mut self,
 1854        provider: Option<Entity<T>>,
 1855        window: &mut Window,
 1856        cx: &mut Context<Self>,
 1857    ) where
 1858        T: EditPredictionProvider,
 1859    {
 1860        self.edit_prediction_provider =
 1861            provider.map(|provider| RegisteredInlineCompletionProvider {
 1862                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1863                    if this.focus_handle.is_focused(window) {
 1864                        this.update_visible_inline_completion(window, cx);
 1865                    }
 1866                }),
 1867                provider: Arc::new(provider),
 1868            });
 1869        self.update_edit_prediction_settings(cx);
 1870        self.refresh_inline_completion(false, false, window, cx);
 1871    }
 1872
 1873    pub fn placeholder_text(&self) -> Option<&str> {
 1874        self.placeholder_text.as_deref()
 1875    }
 1876
 1877    pub fn set_placeholder_text(
 1878        &mut self,
 1879        placeholder_text: impl Into<Arc<str>>,
 1880        cx: &mut Context<Self>,
 1881    ) {
 1882        let placeholder_text = Some(placeholder_text.into());
 1883        if self.placeholder_text != placeholder_text {
 1884            self.placeholder_text = placeholder_text;
 1885            cx.notify();
 1886        }
 1887    }
 1888
 1889    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1890        self.cursor_shape = cursor_shape;
 1891
 1892        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1893        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1894
 1895        cx.notify();
 1896    }
 1897
 1898    pub fn set_current_line_highlight(
 1899        &mut self,
 1900        current_line_highlight: Option<CurrentLineHighlight>,
 1901    ) {
 1902        self.current_line_highlight = current_line_highlight;
 1903    }
 1904
 1905    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1906        self.collapse_matches = collapse_matches;
 1907    }
 1908
 1909    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1910        let buffers = self.buffer.read(cx).all_buffers();
 1911        let Some(project) = self.project.as_ref() else {
 1912            return;
 1913        };
 1914        project.update(cx, |project, cx| {
 1915            for buffer in buffers {
 1916                self.registered_buffers
 1917                    .entry(buffer.read(cx).remote_id())
 1918                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1919            }
 1920        })
 1921    }
 1922
 1923    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1924        if self.collapse_matches {
 1925            return range.start..range.start;
 1926        }
 1927        range.clone()
 1928    }
 1929
 1930    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1931        if self.display_map.read(cx).clip_at_line_ends != clip {
 1932            self.display_map
 1933                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1934        }
 1935    }
 1936
 1937    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1938        self.input_enabled = input_enabled;
 1939    }
 1940
 1941    pub fn set_inline_completions_hidden_for_vim_mode(
 1942        &mut self,
 1943        hidden: bool,
 1944        window: &mut Window,
 1945        cx: &mut Context<Self>,
 1946    ) {
 1947        if hidden != self.inline_completions_hidden_for_vim_mode {
 1948            self.inline_completions_hidden_for_vim_mode = hidden;
 1949            if hidden {
 1950                self.update_visible_inline_completion(window, cx);
 1951            } else {
 1952                self.refresh_inline_completion(true, false, window, cx);
 1953            }
 1954        }
 1955    }
 1956
 1957    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1958        self.menu_inline_completions_policy = value;
 1959    }
 1960
 1961    pub fn set_autoindent(&mut self, autoindent: bool) {
 1962        if autoindent {
 1963            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1964        } else {
 1965            self.autoindent_mode = None;
 1966        }
 1967    }
 1968
 1969    pub fn read_only(&self, cx: &App) -> bool {
 1970        self.read_only || self.buffer.read(cx).read_only()
 1971    }
 1972
 1973    pub fn set_read_only(&mut self, read_only: bool) {
 1974        self.read_only = read_only;
 1975    }
 1976
 1977    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1978        self.use_autoclose = autoclose;
 1979    }
 1980
 1981    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1982        self.use_auto_surround = auto_surround;
 1983    }
 1984
 1985    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1986        self.auto_replace_emoji_shortcode = auto_replace;
 1987    }
 1988
 1989    pub fn toggle_edit_predictions(
 1990        &mut self,
 1991        _: &ToggleEditPrediction,
 1992        window: &mut Window,
 1993        cx: &mut Context<Self>,
 1994    ) {
 1995        if self.show_inline_completions_override.is_some() {
 1996            self.set_show_edit_predictions(None, window, cx);
 1997        } else {
 1998            let show_edit_predictions = !self.edit_predictions_enabled();
 1999            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2000        }
 2001    }
 2002
 2003    pub fn set_show_edit_predictions(
 2004        &mut self,
 2005        show_edit_predictions: Option<bool>,
 2006        window: &mut Window,
 2007        cx: &mut Context<Self>,
 2008    ) {
 2009        self.show_inline_completions_override = show_edit_predictions;
 2010        self.update_edit_prediction_settings(cx);
 2011
 2012        if let Some(false) = show_edit_predictions {
 2013            self.discard_inline_completion(false, cx);
 2014        } else {
 2015            self.refresh_inline_completion(false, true, window, cx);
 2016        }
 2017    }
 2018
 2019    fn inline_completions_disabled_in_scope(
 2020        &self,
 2021        buffer: &Entity<Buffer>,
 2022        buffer_position: language::Anchor,
 2023        cx: &App,
 2024    ) -> bool {
 2025        let snapshot = buffer.read(cx).snapshot();
 2026        let settings = snapshot.settings_at(buffer_position, cx);
 2027
 2028        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2029            return false;
 2030        };
 2031
 2032        scope.override_name().map_or(false, |scope_name| {
 2033            settings
 2034                .edit_predictions_disabled_in
 2035                .iter()
 2036                .any(|s| s == scope_name)
 2037        })
 2038    }
 2039
 2040    pub fn set_use_modal_editing(&mut self, to: bool) {
 2041        self.use_modal_editing = to;
 2042    }
 2043
 2044    pub fn use_modal_editing(&self) -> bool {
 2045        self.use_modal_editing
 2046    }
 2047
 2048    fn selections_did_change(
 2049        &mut self,
 2050        local: bool,
 2051        old_cursor_position: &Anchor,
 2052        show_completions: bool,
 2053        window: &mut Window,
 2054        cx: &mut Context<Self>,
 2055    ) {
 2056        window.invalidate_character_coordinates();
 2057
 2058        // Copy selections to primary selection buffer
 2059        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2060        if local {
 2061            let selections = self.selections.all::<usize>(cx);
 2062            let buffer_handle = self.buffer.read(cx).read(cx);
 2063
 2064            let mut text = String::new();
 2065            for (index, selection) in selections.iter().enumerate() {
 2066                let text_for_selection = buffer_handle
 2067                    .text_for_range(selection.start..selection.end)
 2068                    .collect::<String>();
 2069
 2070                text.push_str(&text_for_selection);
 2071                if index != selections.len() - 1 {
 2072                    text.push('\n');
 2073                }
 2074            }
 2075
 2076            if !text.is_empty() {
 2077                cx.write_to_primary(ClipboardItem::new_string(text));
 2078            }
 2079        }
 2080
 2081        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2082            self.buffer.update(cx, |buffer, cx| {
 2083                buffer.set_active_selections(
 2084                    &self.selections.disjoint_anchors(),
 2085                    self.selections.line_mode,
 2086                    self.cursor_shape,
 2087                    cx,
 2088                )
 2089            });
 2090        }
 2091        let display_map = self
 2092            .display_map
 2093            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2094        let buffer = &display_map.buffer_snapshot;
 2095        self.add_selections_state = None;
 2096        self.select_next_state = None;
 2097        self.select_prev_state = None;
 2098        self.select_larger_syntax_node_stack.clear();
 2099        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2100        self.snippet_stack
 2101            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2102        self.take_rename(false, window, cx);
 2103
 2104        let new_cursor_position = self.selections.newest_anchor().head();
 2105
 2106        self.push_to_nav_history(
 2107            *old_cursor_position,
 2108            Some(new_cursor_position.to_point(buffer)),
 2109            cx,
 2110        );
 2111
 2112        if local {
 2113            let new_cursor_position = self.selections.newest_anchor().head();
 2114            let mut context_menu = self.context_menu.borrow_mut();
 2115            let completion_menu = match context_menu.as_ref() {
 2116                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2117                _ => {
 2118                    *context_menu = None;
 2119                    None
 2120                }
 2121            };
 2122            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2123                if !self.registered_buffers.contains_key(&buffer_id) {
 2124                    if let Some(project) = self.project.as_ref() {
 2125                        project.update(cx, |project, cx| {
 2126                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2127                                return;
 2128                            };
 2129                            self.registered_buffers.insert(
 2130                                buffer_id,
 2131                                project.register_buffer_with_language_servers(&buffer, cx),
 2132                            );
 2133                        })
 2134                    }
 2135                }
 2136            }
 2137
 2138            if let Some(completion_menu) = completion_menu {
 2139                let cursor_position = new_cursor_position.to_offset(buffer);
 2140                let (word_range, kind) =
 2141                    buffer.surrounding_word(completion_menu.initial_position, true);
 2142                if kind == Some(CharKind::Word)
 2143                    && word_range.to_inclusive().contains(&cursor_position)
 2144                {
 2145                    let mut completion_menu = completion_menu.clone();
 2146                    drop(context_menu);
 2147
 2148                    let query = Self::completion_query(buffer, cursor_position);
 2149                    cx.spawn(move |this, mut cx| async move {
 2150                        completion_menu
 2151                            .filter(query.as_deref(), cx.background_executor().clone())
 2152                            .await;
 2153
 2154                        this.update(&mut cx, |this, cx| {
 2155                            let mut context_menu = this.context_menu.borrow_mut();
 2156                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2157                            else {
 2158                                return;
 2159                            };
 2160
 2161                            if menu.id > completion_menu.id {
 2162                                return;
 2163                            }
 2164
 2165                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2166                            drop(context_menu);
 2167                            cx.notify();
 2168                        })
 2169                    })
 2170                    .detach();
 2171
 2172                    if show_completions {
 2173                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2174                    }
 2175                } else {
 2176                    drop(context_menu);
 2177                    self.hide_context_menu(window, cx);
 2178                }
 2179            } else {
 2180                drop(context_menu);
 2181            }
 2182
 2183            hide_hover(self, cx);
 2184
 2185            if old_cursor_position.to_display_point(&display_map).row()
 2186                != new_cursor_position.to_display_point(&display_map).row()
 2187            {
 2188                self.available_code_actions.take();
 2189            }
 2190            self.refresh_code_actions(window, cx);
 2191            self.refresh_document_highlights(cx);
 2192            self.refresh_selected_text_highlights(window, cx);
 2193            refresh_matching_bracket_highlights(self, window, cx);
 2194            self.update_visible_inline_completion(window, cx);
 2195            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2196            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2197            if self.git_blame_inline_enabled {
 2198                self.start_inline_blame_timer(window, cx);
 2199            }
 2200        }
 2201
 2202        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2203        cx.emit(EditorEvent::SelectionsChanged { local });
 2204
 2205        let selections = &self.selections.disjoint;
 2206        if selections.len() == 1 {
 2207            cx.emit(SearchEvent::ActiveMatchChanged)
 2208        }
 2209        if local
 2210            && self.is_singleton(cx)
 2211            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2212        {
 2213            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2214                let background_executor = cx.background_executor().clone();
 2215                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2216                let snapshot = self.buffer().read(cx).snapshot(cx);
 2217                let selections = selections.clone();
 2218                self.serialize_selections = cx.background_spawn(async move {
 2219                    background_executor.timer(Duration::from_millis(100)).await;
 2220                    let selections = selections
 2221                        .iter()
 2222                        .map(|selection| {
 2223                            (
 2224                                selection.start.to_offset(&snapshot),
 2225                                selection.end.to_offset(&snapshot),
 2226                            )
 2227                        })
 2228                        .collect();
 2229                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2230                        .await
 2231                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2232                        .log_err();
 2233                });
 2234            }
 2235        }
 2236
 2237        cx.notify();
 2238    }
 2239
 2240    pub fn sync_selections(
 2241        &mut self,
 2242        other: Entity<Editor>,
 2243        cx: &mut Context<Self>,
 2244    ) -> gpui::Subscription {
 2245        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2246        self.selections.change_with(cx, |selections| {
 2247            selections.select_anchors(other_selections);
 2248        });
 2249
 2250        let other_subscription =
 2251            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2252                EditorEvent::SelectionsChanged { local: true } => {
 2253                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2254                    if other_selections.is_empty() {
 2255                        return;
 2256                    }
 2257                    this.selections.change_with(cx, |selections| {
 2258                        selections.select_anchors(other_selections);
 2259                    });
 2260                }
 2261                _ => {}
 2262            });
 2263
 2264        let this_subscription =
 2265            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2266                EditorEvent::SelectionsChanged { local: true } => {
 2267                    let these_selections = this.selections.disjoint.to_vec();
 2268                    if these_selections.is_empty() {
 2269                        return;
 2270                    }
 2271                    other.update(cx, |other_editor, cx| {
 2272                        other_editor.selections.change_with(cx, |selections| {
 2273                            selections.select_anchors(these_selections);
 2274                        })
 2275                    });
 2276                }
 2277                _ => {}
 2278            });
 2279
 2280        Subscription::join(other_subscription, this_subscription)
 2281    }
 2282
 2283    pub fn change_selections<R>(
 2284        &mut self,
 2285        autoscroll: Option<Autoscroll>,
 2286        window: &mut Window,
 2287        cx: &mut Context<Self>,
 2288        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2289    ) -> R {
 2290        self.change_selections_inner(autoscroll, true, window, cx, change)
 2291    }
 2292
 2293    fn change_selections_inner<R>(
 2294        &mut self,
 2295        autoscroll: Option<Autoscroll>,
 2296        request_completions: bool,
 2297        window: &mut Window,
 2298        cx: &mut Context<Self>,
 2299        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2300    ) -> R {
 2301        let old_cursor_position = self.selections.newest_anchor().head();
 2302        self.push_to_selection_history();
 2303
 2304        let (changed, result) = self.selections.change_with(cx, change);
 2305
 2306        if changed {
 2307            if let Some(autoscroll) = autoscroll {
 2308                self.request_autoscroll(autoscroll, cx);
 2309            }
 2310            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2311
 2312            if self.should_open_signature_help_automatically(
 2313                &old_cursor_position,
 2314                self.signature_help_state.backspace_pressed(),
 2315                cx,
 2316            ) {
 2317                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2318            }
 2319            self.signature_help_state.set_backspace_pressed(false);
 2320        }
 2321
 2322        result
 2323    }
 2324
 2325    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2326    where
 2327        I: IntoIterator<Item = (Range<S>, T)>,
 2328        S: ToOffset,
 2329        T: Into<Arc<str>>,
 2330    {
 2331        if self.read_only(cx) {
 2332            return;
 2333        }
 2334
 2335        self.buffer
 2336            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2337    }
 2338
 2339    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2340    where
 2341        I: IntoIterator<Item = (Range<S>, T)>,
 2342        S: ToOffset,
 2343        T: Into<Arc<str>>,
 2344    {
 2345        if self.read_only(cx) {
 2346            return;
 2347        }
 2348
 2349        self.buffer.update(cx, |buffer, cx| {
 2350            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2351        });
 2352    }
 2353
 2354    pub fn edit_with_block_indent<I, S, T>(
 2355        &mut self,
 2356        edits: I,
 2357        original_indent_columns: Vec<Option<u32>>,
 2358        cx: &mut Context<Self>,
 2359    ) where
 2360        I: IntoIterator<Item = (Range<S>, T)>,
 2361        S: ToOffset,
 2362        T: Into<Arc<str>>,
 2363    {
 2364        if self.read_only(cx) {
 2365            return;
 2366        }
 2367
 2368        self.buffer.update(cx, |buffer, cx| {
 2369            buffer.edit(
 2370                edits,
 2371                Some(AutoindentMode::Block {
 2372                    original_indent_columns,
 2373                }),
 2374                cx,
 2375            )
 2376        });
 2377    }
 2378
 2379    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2380        self.hide_context_menu(window, cx);
 2381
 2382        match phase {
 2383            SelectPhase::Begin {
 2384                position,
 2385                add,
 2386                click_count,
 2387            } => self.begin_selection(position, add, click_count, window, cx),
 2388            SelectPhase::BeginColumnar {
 2389                position,
 2390                goal_column,
 2391                reset,
 2392            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2393            SelectPhase::Extend {
 2394                position,
 2395                click_count,
 2396            } => self.extend_selection(position, click_count, window, cx),
 2397            SelectPhase::Update {
 2398                position,
 2399                goal_column,
 2400                scroll_delta,
 2401            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2402            SelectPhase::End => self.end_selection(window, cx),
 2403        }
 2404    }
 2405
 2406    fn extend_selection(
 2407        &mut self,
 2408        position: DisplayPoint,
 2409        click_count: usize,
 2410        window: &mut Window,
 2411        cx: &mut Context<Self>,
 2412    ) {
 2413        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2414        let tail = self.selections.newest::<usize>(cx).tail();
 2415        self.begin_selection(position, false, click_count, window, cx);
 2416
 2417        let position = position.to_offset(&display_map, Bias::Left);
 2418        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2419
 2420        let mut pending_selection = self
 2421            .selections
 2422            .pending_anchor()
 2423            .expect("extend_selection not called with pending selection");
 2424        if position >= tail {
 2425            pending_selection.start = tail_anchor;
 2426        } else {
 2427            pending_selection.end = tail_anchor;
 2428            pending_selection.reversed = true;
 2429        }
 2430
 2431        let mut pending_mode = self.selections.pending_mode().unwrap();
 2432        match &mut pending_mode {
 2433            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2434            _ => {}
 2435        }
 2436
 2437        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2438            s.set_pending(pending_selection, pending_mode)
 2439        });
 2440    }
 2441
 2442    fn begin_selection(
 2443        &mut self,
 2444        position: DisplayPoint,
 2445        add: bool,
 2446        click_count: usize,
 2447        window: &mut Window,
 2448        cx: &mut Context<Self>,
 2449    ) {
 2450        if !self.focus_handle.is_focused(window) {
 2451            self.last_focused_descendant = None;
 2452            window.focus(&self.focus_handle);
 2453        }
 2454
 2455        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2456        let buffer = &display_map.buffer_snapshot;
 2457        let newest_selection = self.selections.newest_anchor().clone();
 2458        let position = display_map.clip_point(position, Bias::Left);
 2459
 2460        let start;
 2461        let end;
 2462        let mode;
 2463        let mut auto_scroll;
 2464        match click_count {
 2465            1 => {
 2466                start = buffer.anchor_before(position.to_point(&display_map));
 2467                end = start;
 2468                mode = SelectMode::Character;
 2469                auto_scroll = true;
 2470            }
 2471            2 => {
 2472                let range = movement::surrounding_word(&display_map, position);
 2473                start = buffer.anchor_before(range.start.to_point(&display_map));
 2474                end = buffer.anchor_before(range.end.to_point(&display_map));
 2475                mode = SelectMode::Word(start..end);
 2476                auto_scroll = true;
 2477            }
 2478            3 => {
 2479                let position = display_map
 2480                    .clip_point(position, Bias::Left)
 2481                    .to_point(&display_map);
 2482                let line_start = display_map.prev_line_boundary(position).0;
 2483                let next_line_start = buffer.clip_point(
 2484                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2485                    Bias::Left,
 2486                );
 2487                start = buffer.anchor_before(line_start);
 2488                end = buffer.anchor_before(next_line_start);
 2489                mode = SelectMode::Line(start..end);
 2490                auto_scroll = true;
 2491            }
 2492            _ => {
 2493                start = buffer.anchor_before(0);
 2494                end = buffer.anchor_before(buffer.len());
 2495                mode = SelectMode::All;
 2496                auto_scroll = false;
 2497            }
 2498        }
 2499        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2500
 2501        let point_to_delete: Option<usize> = {
 2502            let selected_points: Vec<Selection<Point>> =
 2503                self.selections.disjoint_in_range(start..end, cx);
 2504
 2505            if !add || click_count > 1 {
 2506                None
 2507            } else if !selected_points.is_empty() {
 2508                Some(selected_points[0].id)
 2509            } else {
 2510                let clicked_point_already_selected =
 2511                    self.selections.disjoint.iter().find(|selection| {
 2512                        selection.start.to_point(buffer) == start.to_point(buffer)
 2513                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2514                    });
 2515
 2516                clicked_point_already_selected.map(|selection| selection.id)
 2517            }
 2518        };
 2519
 2520        let selections_count = self.selections.count();
 2521
 2522        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2523            if let Some(point_to_delete) = point_to_delete {
 2524                s.delete(point_to_delete);
 2525
 2526                if selections_count == 1 {
 2527                    s.set_pending_anchor_range(start..end, mode);
 2528                }
 2529            } else {
 2530                if !add {
 2531                    s.clear_disjoint();
 2532                } else if click_count > 1 {
 2533                    s.delete(newest_selection.id)
 2534                }
 2535
 2536                s.set_pending_anchor_range(start..end, mode);
 2537            }
 2538        });
 2539    }
 2540
 2541    fn begin_columnar_selection(
 2542        &mut self,
 2543        position: DisplayPoint,
 2544        goal_column: u32,
 2545        reset: bool,
 2546        window: &mut Window,
 2547        cx: &mut Context<Self>,
 2548    ) {
 2549        if !self.focus_handle.is_focused(window) {
 2550            self.last_focused_descendant = None;
 2551            window.focus(&self.focus_handle);
 2552        }
 2553
 2554        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2555
 2556        if reset {
 2557            let pointer_position = display_map
 2558                .buffer_snapshot
 2559                .anchor_before(position.to_point(&display_map));
 2560
 2561            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2562                s.clear_disjoint();
 2563                s.set_pending_anchor_range(
 2564                    pointer_position..pointer_position,
 2565                    SelectMode::Character,
 2566                );
 2567            });
 2568        }
 2569
 2570        let tail = self.selections.newest::<Point>(cx).tail();
 2571        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2572
 2573        if !reset {
 2574            self.select_columns(
 2575                tail.to_display_point(&display_map),
 2576                position,
 2577                goal_column,
 2578                &display_map,
 2579                window,
 2580                cx,
 2581            );
 2582        }
 2583    }
 2584
 2585    fn update_selection(
 2586        &mut self,
 2587        position: DisplayPoint,
 2588        goal_column: u32,
 2589        scroll_delta: gpui::Point<f32>,
 2590        window: &mut Window,
 2591        cx: &mut Context<Self>,
 2592    ) {
 2593        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2594
 2595        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2596            let tail = tail.to_display_point(&display_map);
 2597            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2598        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2599            let buffer = self.buffer.read(cx).snapshot(cx);
 2600            let head;
 2601            let tail;
 2602            let mode = self.selections.pending_mode().unwrap();
 2603            match &mode {
 2604                SelectMode::Character => {
 2605                    head = position.to_point(&display_map);
 2606                    tail = pending.tail().to_point(&buffer);
 2607                }
 2608                SelectMode::Word(original_range) => {
 2609                    let original_display_range = original_range.start.to_display_point(&display_map)
 2610                        ..original_range.end.to_display_point(&display_map);
 2611                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2612                        ..original_display_range.end.to_point(&display_map);
 2613                    if movement::is_inside_word(&display_map, position)
 2614                        || original_display_range.contains(&position)
 2615                    {
 2616                        let word_range = movement::surrounding_word(&display_map, position);
 2617                        if word_range.start < original_display_range.start {
 2618                            head = word_range.start.to_point(&display_map);
 2619                        } else {
 2620                            head = word_range.end.to_point(&display_map);
 2621                        }
 2622                    } else {
 2623                        head = position.to_point(&display_map);
 2624                    }
 2625
 2626                    if head <= original_buffer_range.start {
 2627                        tail = original_buffer_range.end;
 2628                    } else {
 2629                        tail = original_buffer_range.start;
 2630                    }
 2631                }
 2632                SelectMode::Line(original_range) => {
 2633                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2634
 2635                    let position = display_map
 2636                        .clip_point(position, Bias::Left)
 2637                        .to_point(&display_map);
 2638                    let line_start = display_map.prev_line_boundary(position).0;
 2639                    let next_line_start = buffer.clip_point(
 2640                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2641                        Bias::Left,
 2642                    );
 2643
 2644                    if line_start < original_range.start {
 2645                        head = line_start
 2646                    } else {
 2647                        head = next_line_start
 2648                    }
 2649
 2650                    if head <= original_range.start {
 2651                        tail = original_range.end;
 2652                    } else {
 2653                        tail = original_range.start;
 2654                    }
 2655                }
 2656                SelectMode::All => {
 2657                    return;
 2658                }
 2659            };
 2660
 2661            if head < tail {
 2662                pending.start = buffer.anchor_before(head);
 2663                pending.end = buffer.anchor_before(tail);
 2664                pending.reversed = true;
 2665            } else {
 2666                pending.start = buffer.anchor_before(tail);
 2667                pending.end = buffer.anchor_before(head);
 2668                pending.reversed = false;
 2669            }
 2670
 2671            self.change_selections(None, window, cx, |s| {
 2672                s.set_pending(pending, mode);
 2673            });
 2674        } else {
 2675            log::error!("update_selection dispatched with no pending selection");
 2676            return;
 2677        }
 2678
 2679        self.apply_scroll_delta(scroll_delta, window, cx);
 2680        cx.notify();
 2681    }
 2682
 2683    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2684        self.columnar_selection_tail.take();
 2685        if self.selections.pending_anchor().is_some() {
 2686            let selections = self.selections.all::<usize>(cx);
 2687            self.change_selections(None, window, cx, |s| {
 2688                s.select(selections);
 2689                s.clear_pending();
 2690            });
 2691        }
 2692    }
 2693
 2694    fn select_columns(
 2695        &mut self,
 2696        tail: DisplayPoint,
 2697        head: DisplayPoint,
 2698        goal_column: u32,
 2699        display_map: &DisplaySnapshot,
 2700        window: &mut Window,
 2701        cx: &mut Context<Self>,
 2702    ) {
 2703        let start_row = cmp::min(tail.row(), head.row());
 2704        let end_row = cmp::max(tail.row(), head.row());
 2705        let start_column = cmp::min(tail.column(), goal_column);
 2706        let end_column = cmp::max(tail.column(), goal_column);
 2707        let reversed = start_column < tail.column();
 2708
 2709        let selection_ranges = (start_row.0..=end_row.0)
 2710            .map(DisplayRow)
 2711            .filter_map(|row| {
 2712                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2713                    let start = display_map
 2714                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2715                        .to_point(display_map);
 2716                    let end = display_map
 2717                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2718                        .to_point(display_map);
 2719                    if reversed {
 2720                        Some(end..start)
 2721                    } else {
 2722                        Some(start..end)
 2723                    }
 2724                } else {
 2725                    None
 2726                }
 2727            })
 2728            .collect::<Vec<_>>();
 2729
 2730        self.change_selections(None, window, cx, |s| {
 2731            s.select_ranges(selection_ranges);
 2732        });
 2733        cx.notify();
 2734    }
 2735
 2736    pub fn has_pending_nonempty_selection(&self) -> bool {
 2737        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2738            Some(Selection { start, end, .. }) => start != end,
 2739            None => false,
 2740        };
 2741
 2742        pending_nonempty_selection
 2743            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2744    }
 2745
 2746    pub fn has_pending_selection(&self) -> bool {
 2747        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2748    }
 2749
 2750    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2751        self.selection_mark_mode = false;
 2752
 2753        if self.clear_expanded_diff_hunks(cx) {
 2754            cx.notify();
 2755            return;
 2756        }
 2757        if self.dismiss_menus_and_popups(true, window, cx) {
 2758            return;
 2759        }
 2760
 2761        if self.mode == EditorMode::Full
 2762            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2763        {
 2764            return;
 2765        }
 2766
 2767        cx.propagate();
 2768    }
 2769
 2770    pub fn dismiss_menus_and_popups(
 2771        &mut self,
 2772        is_user_requested: bool,
 2773        window: &mut Window,
 2774        cx: &mut Context<Self>,
 2775    ) -> bool {
 2776        if self.take_rename(false, window, cx).is_some() {
 2777            return true;
 2778        }
 2779
 2780        if hide_hover(self, cx) {
 2781            return true;
 2782        }
 2783
 2784        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2785            return true;
 2786        }
 2787
 2788        if self.hide_context_menu(window, cx).is_some() {
 2789            return true;
 2790        }
 2791
 2792        if self.mouse_context_menu.take().is_some() {
 2793            return true;
 2794        }
 2795
 2796        if is_user_requested && self.discard_inline_completion(true, cx) {
 2797            return true;
 2798        }
 2799
 2800        if self.snippet_stack.pop().is_some() {
 2801            return true;
 2802        }
 2803
 2804        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2805            self.dismiss_diagnostics(cx);
 2806            return true;
 2807        }
 2808
 2809        false
 2810    }
 2811
 2812    fn linked_editing_ranges_for(
 2813        &self,
 2814        selection: Range<text::Anchor>,
 2815        cx: &App,
 2816    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2817        if self.linked_edit_ranges.is_empty() {
 2818            return None;
 2819        }
 2820        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2821            selection.end.buffer_id.and_then(|end_buffer_id| {
 2822                if selection.start.buffer_id != Some(end_buffer_id) {
 2823                    return None;
 2824                }
 2825                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2826                let snapshot = buffer.read(cx).snapshot();
 2827                self.linked_edit_ranges
 2828                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2829                    .map(|ranges| (ranges, snapshot, buffer))
 2830            })?;
 2831        use text::ToOffset as TO;
 2832        // find offset from the start of current range to current cursor position
 2833        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2834
 2835        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2836        let start_difference = start_offset - start_byte_offset;
 2837        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2838        let end_difference = end_offset - start_byte_offset;
 2839        // Current range has associated linked ranges.
 2840        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2841        for range in linked_ranges.iter() {
 2842            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2843            let end_offset = start_offset + end_difference;
 2844            let start_offset = start_offset + start_difference;
 2845            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2846                continue;
 2847            }
 2848            if self.selections.disjoint_anchor_ranges().any(|s| {
 2849                if s.start.buffer_id != selection.start.buffer_id
 2850                    || s.end.buffer_id != selection.end.buffer_id
 2851                {
 2852                    return false;
 2853                }
 2854                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2855                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2856            }) {
 2857                continue;
 2858            }
 2859            let start = buffer_snapshot.anchor_after(start_offset);
 2860            let end = buffer_snapshot.anchor_after(end_offset);
 2861            linked_edits
 2862                .entry(buffer.clone())
 2863                .or_default()
 2864                .push(start..end);
 2865        }
 2866        Some(linked_edits)
 2867    }
 2868
 2869    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2870        let text: Arc<str> = text.into();
 2871
 2872        if self.read_only(cx) {
 2873            return;
 2874        }
 2875
 2876        let selections = self.selections.all_adjusted(cx);
 2877        let mut bracket_inserted = false;
 2878        let mut edits = Vec::new();
 2879        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2880        let mut new_selections = Vec::with_capacity(selections.len());
 2881        let mut new_autoclose_regions = Vec::new();
 2882        let snapshot = self.buffer.read(cx).read(cx);
 2883
 2884        for (selection, autoclose_region) in
 2885            self.selections_with_autoclose_regions(selections, &snapshot)
 2886        {
 2887            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2888                // Determine if the inserted text matches the opening or closing
 2889                // bracket of any of this language's bracket pairs.
 2890                let mut bracket_pair = None;
 2891                let mut is_bracket_pair_start = false;
 2892                let mut is_bracket_pair_end = false;
 2893                if !text.is_empty() {
 2894                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2895                    //  and they are removing the character that triggered IME popup.
 2896                    for (pair, enabled) in scope.brackets() {
 2897                        if !pair.close && !pair.surround {
 2898                            continue;
 2899                        }
 2900
 2901                        if enabled && pair.start.ends_with(text.as_ref()) {
 2902                            let prefix_len = pair.start.len() - text.len();
 2903                            let preceding_text_matches_prefix = prefix_len == 0
 2904                                || (selection.start.column >= (prefix_len as u32)
 2905                                    && snapshot.contains_str_at(
 2906                                        Point::new(
 2907                                            selection.start.row,
 2908                                            selection.start.column - (prefix_len as u32),
 2909                                        ),
 2910                                        &pair.start[..prefix_len],
 2911                                    ));
 2912                            if preceding_text_matches_prefix {
 2913                                bracket_pair = Some(pair.clone());
 2914                                is_bracket_pair_start = true;
 2915                                break;
 2916                            }
 2917                        }
 2918                        if pair.end.as_str() == text.as_ref() {
 2919                            bracket_pair = Some(pair.clone());
 2920                            is_bracket_pair_end = true;
 2921                            break;
 2922                        }
 2923                    }
 2924                }
 2925
 2926                if let Some(bracket_pair) = bracket_pair {
 2927                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 2928                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2929                    let auto_surround =
 2930                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2931                    if selection.is_empty() {
 2932                        if is_bracket_pair_start {
 2933                            // If the inserted text is a suffix of an opening bracket and the
 2934                            // selection is preceded by the rest of the opening bracket, then
 2935                            // insert the closing bracket.
 2936                            let following_text_allows_autoclose = snapshot
 2937                                .chars_at(selection.start)
 2938                                .next()
 2939                                .map_or(true, |c| scope.should_autoclose_before(c));
 2940
 2941                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2942                                && bracket_pair.start.len() == 1
 2943                            {
 2944                                let target = bracket_pair.start.chars().next().unwrap();
 2945                                let current_line_count = snapshot
 2946                                    .reversed_chars_at(selection.start)
 2947                                    .take_while(|&c| c != '\n')
 2948                                    .filter(|&c| c == target)
 2949                                    .count();
 2950                                current_line_count % 2 == 1
 2951                            } else {
 2952                                false
 2953                            };
 2954
 2955                            if autoclose
 2956                                && bracket_pair.close
 2957                                && following_text_allows_autoclose
 2958                                && !is_closing_quote
 2959                            {
 2960                                let anchor = snapshot.anchor_before(selection.end);
 2961                                new_selections.push((selection.map(|_| anchor), text.len()));
 2962                                new_autoclose_regions.push((
 2963                                    anchor,
 2964                                    text.len(),
 2965                                    selection.id,
 2966                                    bracket_pair.clone(),
 2967                                ));
 2968                                edits.push((
 2969                                    selection.range(),
 2970                                    format!("{}{}", text, bracket_pair.end).into(),
 2971                                ));
 2972                                bracket_inserted = true;
 2973                                continue;
 2974                            }
 2975                        }
 2976
 2977                        if let Some(region) = autoclose_region {
 2978                            // If the selection is followed by an auto-inserted closing bracket,
 2979                            // then don't insert that closing bracket again; just move the selection
 2980                            // past the closing bracket.
 2981                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2982                                && text.as_ref() == region.pair.end.as_str();
 2983                            if should_skip {
 2984                                let anchor = snapshot.anchor_after(selection.end);
 2985                                new_selections
 2986                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2987                                continue;
 2988                            }
 2989                        }
 2990
 2991                        let always_treat_brackets_as_autoclosed = snapshot
 2992                            .language_settings_at(selection.start, cx)
 2993                            .always_treat_brackets_as_autoclosed;
 2994                        if always_treat_brackets_as_autoclosed
 2995                            && is_bracket_pair_end
 2996                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2997                        {
 2998                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2999                            // and the inserted text is a closing bracket and the selection is followed
 3000                            // by the closing bracket then move the selection past the closing bracket.
 3001                            let anchor = snapshot.anchor_after(selection.end);
 3002                            new_selections.push((selection.map(|_| anchor), text.len()));
 3003                            continue;
 3004                        }
 3005                    }
 3006                    // If an opening bracket is 1 character long and is typed while
 3007                    // text is selected, then surround that text with the bracket pair.
 3008                    else if auto_surround
 3009                        && bracket_pair.surround
 3010                        && is_bracket_pair_start
 3011                        && bracket_pair.start.chars().count() == 1
 3012                    {
 3013                        edits.push((selection.start..selection.start, text.clone()));
 3014                        edits.push((
 3015                            selection.end..selection.end,
 3016                            bracket_pair.end.as_str().into(),
 3017                        ));
 3018                        bracket_inserted = true;
 3019                        new_selections.push((
 3020                            Selection {
 3021                                id: selection.id,
 3022                                start: snapshot.anchor_after(selection.start),
 3023                                end: snapshot.anchor_before(selection.end),
 3024                                reversed: selection.reversed,
 3025                                goal: selection.goal,
 3026                            },
 3027                            0,
 3028                        ));
 3029                        continue;
 3030                    }
 3031                }
 3032            }
 3033
 3034            if self.auto_replace_emoji_shortcode
 3035                && selection.is_empty()
 3036                && text.as_ref().ends_with(':')
 3037            {
 3038                if let Some(possible_emoji_short_code) =
 3039                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3040                {
 3041                    if !possible_emoji_short_code.is_empty() {
 3042                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3043                            let emoji_shortcode_start = Point::new(
 3044                                selection.start.row,
 3045                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3046                            );
 3047
 3048                            // Remove shortcode from buffer
 3049                            edits.push((
 3050                                emoji_shortcode_start..selection.start,
 3051                                "".to_string().into(),
 3052                            ));
 3053                            new_selections.push((
 3054                                Selection {
 3055                                    id: selection.id,
 3056                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3057                                    end: snapshot.anchor_before(selection.start),
 3058                                    reversed: selection.reversed,
 3059                                    goal: selection.goal,
 3060                                },
 3061                                0,
 3062                            ));
 3063
 3064                            // Insert emoji
 3065                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3066                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3067                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3068
 3069                            continue;
 3070                        }
 3071                    }
 3072                }
 3073            }
 3074
 3075            // If not handling any auto-close operation, then just replace the selected
 3076            // text with the given input and move the selection to the end of the
 3077            // newly inserted text.
 3078            let anchor = snapshot.anchor_after(selection.end);
 3079            if !self.linked_edit_ranges.is_empty() {
 3080                let start_anchor = snapshot.anchor_before(selection.start);
 3081
 3082                let is_word_char = text.chars().next().map_or(true, |char| {
 3083                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3084                    classifier.is_word(char)
 3085                });
 3086
 3087                if is_word_char {
 3088                    if let Some(ranges) = self
 3089                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3090                    {
 3091                        for (buffer, edits) in ranges {
 3092                            linked_edits
 3093                                .entry(buffer.clone())
 3094                                .or_default()
 3095                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3096                        }
 3097                    }
 3098                }
 3099            }
 3100
 3101            new_selections.push((selection.map(|_| anchor), 0));
 3102            edits.push((selection.start..selection.end, text.clone()));
 3103        }
 3104
 3105        drop(snapshot);
 3106
 3107        self.transact(window, cx, |this, window, cx| {
 3108            let initial_buffer_versions =
 3109                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3110
 3111            this.buffer.update(cx, |buffer, cx| {
 3112                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3113            });
 3114            for (buffer, edits) in linked_edits {
 3115                buffer.update(cx, |buffer, cx| {
 3116                    let snapshot = buffer.snapshot();
 3117                    let edits = edits
 3118                        .into_iter()
 3119                        .map(|(range, text)| {
 3120                            use text::ToPoint as TP;
 3121                            let end_point = TP::to_point(&range.end, &snapshot);
 3122                            let start_point = TP::to_point(&range.start, &snapshot);
 3123                            (start_point..end_point, text)
 3124                        })
 3125                        .sorted_by_key(|(range, _)| range.start)
 3126                        .collect::<Vec<_>>();
 3127                    buffer.edit(edits, None, cx);
 3128                })
 3129            }
 3130            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3131            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3132            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3133            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3134                .zip(new_selection_deltas)
 3135                .map(|(selection, delta)| Selection {
 3136                    id: selection.id,
 3137                    start: selection.start + delta,
 3138                    end: selection.end + delta,
 3139                    reversed: selection.reversed,
 3140                    goal: SelectionGoal::None,
 3141                })
 3142                .collect::<Vec<_>>();
 3143
 3144            let mut i = 0;
 3145            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3146                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3147                let start = map.buffer_snapshot.anchor_before(position);
 3148                let end = map.buffer_snapshot.anchor_after(position);
 3149                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3150                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3151                        Ordering::Less => i += 1,
 3152                        Ordering::Greater => break,
 3153                        Ordering::Equal => {
 3154                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3155                                Ordering::Less => i += 1,
 3156                                Ordering::Equal => break,
 3157                                Ordering::Greater => break,
 3158                            }
 3159                        }
 3160                    }
 3161                }
 3162                this.autoclose_regions.insert(
 3163                    i,
 3164                    AutocloseRegion {
 3165                        selection_id,
 3166                        range: start..end,
 3167                        pair,
 3168                    },
 3169                );
 3170            }
 3171
 3172            let had_active_inline_completion = this.has_active_inline_completion();
 3173            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3174                s.select(new_selections)
 3175            });
 3176
 3177            if !bracket_inserted {
 3178                if let Some(on_type_format_task) =
 3179                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3180                {
 3181                    on_type_format_task.detach_and_log_err(cx);
 3182                }
 3183            }
 3184
 3185            let editor_settings = EditorSettings::get_global(cx);
 3186            if bracket_inserted
 3187                && (editor_settings.auto_signature_help
 3188                    || editor_settings.show_signature_help_after_edits)
 3189            {
 3190                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3191            }
 3192
 3193            let trigger_in_words =
 3194                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3195            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3196            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3197            this.refresh_inline_completion(true, false, window, cx);
 3198            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3199        });
 3200    }
 3201
 3202    fn find_possible_emoji_shortcode_at_position(
 3203        snapshot: &MultiBufferSnapshot,
 3204        position: Point,
 3205    ) -> Option<String> {
 3206        let mut chars = Vec::new();
 3207        let mut found_colon = false;
 3208        for char in snapshot.reversed_chars_at(position).take(100) {
 3209            // Found a possible emoji shortcode in the middle of the buffer
 3210            if found_colon {
 3211                if char.is_whitespace() {
 3212                    chars.reverse();
 3213                    return Some(chars.iter().collect());
 3214                }
 3215                // If the previous character is not a whitespace, we are in the middle of a word
 3216                // and we only want to complete the shortcode if the word is made up of other emojis
 3217                let mut containing_word = String::new();
 3218                for ch in snapshot
 3219                    .reversed_chars_at(position)
 3220                    .skip(chars.len() + 1)
 3221                    .take(100)
 3222                {
 3223                    if ch.is_whitespace() {
 3224                        break;
 3225                    }
 3226                    containing_word.push(ch);
 3227                }
 3228                let containing_word = containing_word.chars().rev().collect::<String>();
 3229                if util::word_consists_of_emojis(containing_word.as_str()) {
 3230                    chars.reverse();
 3231                    return Some(chars.iter().collect());
 3232                }
 3233            }
 3234
 3235            if char.is_whitespace() || !char.is_ascii() {
 3236                return None;
 3237            }
 3238            if char == ':' {
 3239                found_colon = true;
 3240            } else {
 3241                chars.push(char);
 3242            }
 3243        }
 3244        // Found a possible emoji shortcode at the beginning of the buffer
 3245        chars.reverse();
 3246        Some(chars.iter().collect())
 3247    }
 3248
 3249    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3250        self.transact(window, cx, |this, window, cx| {
 3251            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3252                let selections = this.selections.all::<usize>(cx);
 3253                let multi_buffer = this.buffer.read(cx);
 3254                let buffer = multi_buffer.snapshot(cx);
 3255                selections
 3256                    .iter()
 3257                    .map(|selection| {
 3258                        let start_point = selection.start.to_point(&buffer);
 3259                        let mut indent =
 3260                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3261                        indent.len = cmp::min(indent.len, start_point.column);
 3262                        let start = selection.start;
 3263                        let end = selection.end;
 3264                        let selection_is_empty = start == end;
 3265                        let language_scope = buffer.language_scope_at(start);
 3266                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3267                            &language_scope
 3268                        {
 3269                            let insert_extra_newline =
 3270                                insert_extra_newline_brackets(&buffer, start..end, language)
 3271                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3272
 3273                            // Comment extension on newline is allowed only for cursor selections
 3274                            let comment_delimiter = maybe!({
 3275                                if !selection_is_empty {
 3276                                    return None;
 3277                                }
 3278
 3279                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3280                                    return None;
 3281                                }
 3282
 3283                                let delimiters = language.line_comment_prefixes();
 3284                                let max_len_of_delimiter =
 3285                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3286                                let (snapshot, range) =
 3287                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3288
 3289                                let mut index_of_first_non_whitespace = 0;
 3290                                let comment_candidate = snapshot
 3291                                    .chars_for_range(range)
 3292                                    .skip_while(|c| {
 3293                                        let should_skip = c.is_whitespace();
 3294                                        if should_skip {
 3295                                            index_of_first_non_whitespace += 1;
 3296                                        }
 3297                                        should_skip
 3298                                    })
 3299                                    .take(max_len_of_delimiter)
 3300                                    .collect::<String>();
 3301                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3302                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3303                                })?;
 3304                                let cursor_is_placed_after_comment_marker =
 3305                                    index_of_first_non_whitespace + comment_prefix.len()
 3306                                        <= start_point.column as usize;
 3307                                if cursor_is_placed_after_comment_marker {
 3308                                    Some(comment_prefix.clone())
 3309                                } else {
 3310                                    None
 3311                                }
 3312                            });
 3313                            (comment_delimiter, insert_extra_newline)
 3314                        } else {
 3315                            (None, false)
 3316                        };
 3317
 3318                        let capacity_for_delimiter = comment_delimiter
 3319                            .as_deref()
 3320                            .map(str::len)
 3321                            .unwrap_or_default();
 3322                        let mut new_text =
 3323                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3324                        new_text.push('\n');
 3325                        new_text.extend(indent.chars());
 3326                        if let Some(delimiter) = &comment_delimiter {
 3327                            new_text.push_str(delimiter);
 3328                        }
 3329                        if insert_extra_newline {
 3330                            new_text = new_text.repeat(2);
 3331                        }
 3332
 3333                        let anchor = buffer.anchor_after(end);
 3334                        let new_selection = selection.map(|_| anchor);
 3335                        (
 3336                            (start..end, new_text),
 3337                            (insert_extra_newline, new_selection),
 3338                        )
 3339                    })
 3340                    .unzip()
 3341            };
 3342
 3343            this.edit_with_autoindent(edits, cx);
 3344            let buffer = this.buffer.read(cx).snapshot(cx);
 3345            let new_selections = selection_fixup_info
 3346                .into_iter()
 3347                .map(|(extra_newline_inserted, new_selection)| {
 3348                    let mut cursor = new_selection.end.to_point(&buffer);
 3349                    if extra_newline_inserted {
 3350                        cursor.row -= 1;
 3351                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3352                    }
 3353                    new_selection.map(|_| cursor)
 3354                })
 3355                .collect();
 3356
 3357            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3358                s.select(new_selections)
 3359            });
 3360            this.refresh_inline_completion(true, false, window, cx);
 3361        });
 3362    }
 3363
 3364    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3365        let buffer = self.buffer.read(cx);
 3366        let snapshot = buffer.snapshot(cx);
 3367
 3368        let mut edits = Vec::new();
 3369        let mut rows = Vec::new();
 3370
 3371        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3372            let cursor = selection.head();
 3373            let row = cursor.row;
 3374
 3375            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3376
 3377            let newline = "\n".to_string();
 3378            edits.push((start_of_line..start_of_line, newline));
 3379
 3380            rows.push(row + rows_inserted as u32);
 3381        }
 3382
 3383        self.transact(window, cx, |editor, window, cx| {
 3384            editor.edit(edits, cx);
 3385
 3386            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3387                let mut index = 0;
 3388                s.move_cursors_with(|map, _, _| {
 3389                    let row = rows[index];
 3390                    index += 1;
 3391
 3392                    let point = Point::new(row, 0);
 3393                    let boundary = map.next_line_boundary(point).1;
 3394                    let clipped = map.clip_point(boundary, Bias::Left);
 3395
 3396                    (clipped, SelectionGoal::None)
 3397                });
 3398            });
 3399
 3400            let mut indent_edits = Vec::new();
 3401            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3402            for row in rows {
 3403                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3404                for (row, indent) in indents {
 3405                    if indent.len == 0 {
 3406                        continue;
 3407                    }
 3408
 3409                    let text = match indent.kind {
 3410                        IndentKind::Space => " ".repeat(indent.len as usize),
 3411                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3412                    };
 3413                    let point = Point::new(row.0, 0);
 3414                    indent_edits.push((point..point, text));
 3415                }
 3416            }
 3417            editor.edit(indent_edits, cx);
 3418        });
 3419    }
 3420
 3421    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3422        let buffer = self.buffer.read(cx);
 3423        let snapshot = buffer.snapshot(cx);
 3424
 3425        let mut edits = Vec::new();
 3426        let mut rows = Vec::new();
 3427        let mut rows_inserted = 0;
 3428
 3429        for selection in self.selections.all_adjusted(cx) {
 3430            let cursor = selection.head();
 3431            let row = cursor.row;
 3432
 3433            let point = Point::new(row + 1, 0);
 3434            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3435
 3436            let newline = "\n".to_string();
 3437            edits.push((start_of_line..start_of_line, newline));
 3438
 3439            rows_inserted += 1;
 3440            rows.push(row + rows_inserted);
 3441        }
 3442
 3443        self.transact(window, cx, |editor, window, cx| {
 3444            editor.edit(edits, cx);
 3445
 3446            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3447                let mut index = 0;
 3448                s.move_cursors_with(|map, _, _| {
 3449                    let row = rows[index];
 3450                    index += 1;
 3451
 3452                    let point = Point::new(row, 0);
 3453                    let boundary = map.next_line_boundary(point).1;
 3454                    let clipped = map.clip_point(boundary, Bias::Left);
 3455
 3456                    (clipped, SelectionGoal::None)
 3457                });
 3458            });
 3459
 3460            let mut indent_edits = Vec::new();
 3461            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3462            for row in rows {
 3463                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3464                for (row, indent) in indents {
 3465                    if indent.len == 0 {
 3466                        continue;
 3467                    }
 3468
 3469                    let text = match indent.kind {
 3470                        IndentKind::Space => " ".repeat(indent.len as usize),
 3471                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3472                    };
 3473                    let point = Point::new(row.0, 0);
 3474                    indent_edits.push((point..point, text));
 3475                }
 3476            }
 3477            editor.edit(indent_edits, cx);
 3478        });
 3479    }
 3480
 3481    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3482        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3483            original_indent_columns: Vec::new(),
 3484        });
 3485        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3486    }
 3487
 3488    fn insert_with_autoindent_mode(
 3489        &mut self,
 3490        text: &str,
 3491        autoindent_mode: Option<AutoindentMode>,
 3492        window: &mut Window,
 3493        cx: &mut Context<Self>,
 3494    ) {
 3495        if self.read_only(cx) {
 3496            return;
 3497        }
 3498
 3499        let text: Arc<str> = text.into();
 3500        self.transact(window, cx, |this, window, cx| {
 3501            let old_selections = this.selections.all_adjusted(cx);
 3502            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3503                let anchors = {
 3504                    let snapshot = buffer.read(cx);
 3505                    old_selections
 3506                        .iter()
 3507                        .map(|s| {
 3508                            let anchor = snapshot.anchor_after(s.head());
 3509                            s.map(|_| anchor)
 3510                        })
 3511                        .collect::<Vec<_>>()
 3512                };
 3513                buffer.edit(
 3514                    old_selections
 3515                        .iter()
 3516                        .map(|s| (s.start..s.end, text.clone())),
 3517                    autoindent_mode,
 3518                    cx,
 3519                );
 3520                anchors
 3521            });
 3522
 3523            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3524                s.select_anchors(selection_anchors);
 3525            });
 3526
 3527            cx.notify();
 3528        });
 3529    }
 3530
 3531    fn trigger_completion_on_input(
 3532        &mut self,
 3533        text: &str,
 3534        trigger_in_words: bool,
 3535        window: &mut Window,
 3536        cx: &mut Context<Self>,
 3537    ) {
 3538        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3539            self.show_completions(
 3540                &ShowCompletions {
 3541                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3542                },
 3543                window,
 3544                cx,
 3545            );
 3546        } else {
 3547            self.hide_context_menu(window, cx);
 3548        }
 3549    }
 3550
 3551    fn is_completion_trigger(
 3552        &self,
 3553        text: &str,
 3554        trigger_in_words: bool,
 3555        cx: &mut Context<Self>,
 3556    ) -> bool {
 3557        let position = self.selections.newest_anchor().head();
 3558        let multibuffer = self.buffer.read(cx);
 3559        let Some(buffer) = position
 3560            .buffer_id
 3561            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3562        else {
 3563            return false;
 3564        };
 3565
 3566        if let Some(completion_provider) = &self.completion_provider {
 3567            completion_provider.is_completion_trigger(
 3568                &buffer,
 3569                position.text_anchor,
 3570                text,
 3571                trigger_in_words,
 3572                cx,
 3573            )
 3574        } else {
 3575            false
 3576        }
 3577    }
 3578
 3579    /// If any empty selections is touching the start of its innermost containing autoclose
 3580    /// region, expand it to select the brackets.
 3581    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3582        let selections = self.selections.all::<usize>(cx);
 3583        let buffer = self.buffer.read(cx).read(cx);
 3584        let new_selections = self
 3585            .selections_with_autoclose_regions(selections, &buffer)
 3586            .map(|(mut selection, region)| {
 3587                if !selection.is_empty() {
 3588                    return selection;
 3589                }
 3590
 3591                if let Some(region) = region {
 3592                    let mut range = region.range.to_offset(&buffer);
 3593                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3594                        range.start -= region.pair.start.len();
 3595                        if buffer.contains_str_at(range.start, &region.pair.start)
 3596                            && buffer.contains_str_at(range.end, &region.pair.end)
 3597                        {
 3598                            range.end += region.pair.end.len();
 3599                            selection.start = range.start;
 3600                            selection.end = range.end;
 3601
 3602                            return selection;
 3603                        }
 3604                    }
 3605                }
 3606
 3607                let always_treat_brackets_as_autoclosed = buffer
 3608                    .language_settings_at(selection.start, cx)
 3609                    .always_treat_brackets_as_autoclosed;
 3610
 3611                if !always_treat_brackets_as_autoclosed {
 3612                    return selection;
 3613                }
 3614
 3615                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3616                    for (pair, enabled) in scope.brackets() {
 3617                        if !enabled || !pair.close {
 3618                            continue;
 3619                        }
 3620
 3621                        if buffer.contains_str_at(selection.start, &pair.end) {
 3622                            let pair_start_len = pair.start.len();
 3623                            if buffer.contains_str_at(
 3624                                selection.start.saturating_sub(pair_start_len),
 3625                                &pair.start,
 3626                            ) {
 3627                                selection.start -= pair_start_len;
 3628                                selection.end += pair.end.len();
 3629
 3630                                return selection;
 3631                            }
 3632                        }
 3633                    }
 3634                }
 3635
 3636                selection
 3637            })
 3638            .collect();
 3639
 3640        drop(buffer);
 3641        self.change_selections(None, window, cx, |selections| {
 3642            selections.select(new_selections)
 3643        });
 3644    }
 3645
 3646    /// Iterate the given selections, and for each one, find the smallest surrounding
 3647    /// autoclose region. This uses the ordering of the selections and the autoclose
 3648    /// regions to avoid repeated comparisons.
 3649    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3650        &'a self,
 3651        selections: impl IntoIterator<Item = Selection<D>>,
 3652        buffer: &'a MultiBufferSnapshot,
 3653    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3654        let mut i = 0;
 3655        let mut regions = self.autoclose_regions.as_slice();
 3656        selections.into_iter().map(move |selection| {
 3657            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3658
 3659            let mut enclosing = None;
 3660            while let Some(pair_state) = regions.get(i) {
 3661                if pair_state.range.end.to_offset(buffer) < range.start {
 3662                    regions = &regions[i + 1..];
 3663                    i = 0;
 3664                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3665                    break;
 3666                } else {
 3667                    if pair_state.selection_id == selection.id {
 3668                        enclosing = Some(pair_state);
 3669                    }
 3670                    i += 1;
 3671                }
 3672            }
 3673
 3674            (selection, enclosing)
 3675        })
 3676    }
 3677
 3678    /// Remove any autoclose regions that no longer contain their selection.
 3679    fn invalidate_autoclose_regions(
 3680        &mut self,
 3681        mut selections: &[Selection<Anchor>],
 3682        buffer: &MultiBufferSnapshot,
 3683    ) {
 3684        self.autoclose_regions.retain(|state| {
 3685            let mut i = 0;
 3686            while let Some(selection) = selections.get(i) {
 3687                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3688                    selections = &selections[1..];
 3689                    continue;
 3690                }
 3691                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3692                    break;
 3693                }
 3694                if selection.id == state.selection_id {
 3695                    return true;
 3696                } else {
 3697                    i += 1;
 3698                }
 3699            }
 3700            false
 3701        });
 3702    }
 3703
 3704    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3705        let offset = position.to_offset(buffer);
 3706        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3707        if offset > word_range.start && kind == Some(CharKind::Word) {
 3708            Some(
 3709                buffer
 3710                    .text_for_range(word_range.start..offset)
 3711                    .collect::<String>(),
 3712            )
 3713        } else {
 3714            None
 3715        }
 3716    }
 3717
 3718    pub fn toggle_inlay_hints(
 3719        &mut self,
 3720        _: &ToggleInlayHints,
 3721        _: &mut Window,
 3722        cx: &mut Context<Self>,
 3723    ) {
 3724        self.refresh_inlay_hints(
 3725            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 3726            cx,
 3727        );
 3728    }
 3729
 3730    pub fn inlay_hints_enabled(&self) -> bool {
 3731        self.inlay_hint_cache.enabled
 3732    }
 3733
 3734    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3735        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3736            return;
 3737        }
 3738
 3739        let reason_description = reason.description();
 3740        let ignore_debounce = matches!(
 3741            reason,
 3742            InlayHintRefreshReason::SettingsChange(_)
 3743                | InlayHintRefreshReason::Toggle(_)
 3744                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3745                | InlayHintRefreshReason::ModifiersChanged(_)
 3746        );
 3747        let (invalidate_cache, required_languages) = match reason {
 3748            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 3749                match self.inlay_hint_cache.modifiers_override(enabled) {
 3750                    Some(enabled) => {
 3751                        if enabled {
 3752                            (InvalidationStrategy::RefreshRequested, None)
 3753                        } else {
 3754                            self.splice_inlays(
 3755                                &self
 3756                                    .visible_inlay_hints(cx)
 3757                                    .iter()
 3758                                    .map(|inlay| inlay.id)
 3759                                    .collect::<Vec<InlayId>>(),
 3760                                Vec::new(),
 3761                                cx,
 3762                            );
 3763                            return;
 3764                        }
 3765                    }
 3766                    None => return,
 3767                }
 3768            }
 3769            InlayHintRefreshReason::Toggle(enabled) => {
 3770                if self.inlay_hint_cache.toggle(enabled) {
 3771                    if enabled {
 3772                        (InvalidationStrategy::RefreshRequested, None)
 3773                    } else {
 3774                        self.splice_inlays(
 3775                            &self
 3776                                .visible_inlay_hints(cx)
 3777                                .iter()
 3778                                .map(|inlay| inlay.id)
 3779                                .collect::<Vec<InlayId>>(),
 3780                            Vec::new(),
 3781                            cx,
 3782                        );
 3783                        return;
 3784                    }
 3785                } else {
 3786                    return;
 3787                }
 3788            }
 3789            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3790                match self.inlay_hint_cache.update_settings(
 3791                    &self.buffer,
 3792                    new_settings,
 3793                    self.visible_inlay_hints(cx),
 3794                    cx,
 3795                ) {
 3796                    ControlFlow::Break(Some(InlaySplice {
 3797                        to_remove,
 3798                        to_insert,
 3799                    })) => {
 3800                        self.splice_inlays(&to_remove, to_insert, cx);
 3801                        return;
 3802                    }
 3803                    ControlFlow::Break(None) => return,
 3804                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3805                }
 3806            }
 3807            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3808                if let Some(InlaySplice {
 3809                    to_remove,
 3810                    to_insert,
 3811                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3812                {
 3813                    self.splice_inlays(&to_remove, to_insert, cx);
 3814                }
 3815                return;
 3816            }
 3817            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3818            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3819                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3820            }
 3821            InlayHintRefreshReason::RefreshRequested => {
 3822                (InvalidationStrategy::RefreshRequested, None)
 3823            }
 3824        };
 3825
 3826        if let Some(InlaySplice {
 3827            to_remove,
 3828            to_insert,
 3829        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3830            reason_description,
 3831            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3832            invalidate_cache,
 3833            ignore_debounce,
 3834            cx,
 3835        ) {
 3836            self.splice_inlays(&to_remove, to_insert, cx);
 3837        }
 3838    }
 3839
 3840    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3841        self.display_map
 3842            .read(cx)
 3843            .current_inlays()
 3844            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3845            .cloned()
 3846            .collect()
 3847    }
 3848
 3849    pub fn excerpts_for_inlay_hints_query(
 3850        &self,
 3851        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3852        cx: &mut Context<Editor>,
 3853    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3854        let Some(project) = self.project.as_ref() else {
 3855            return HashMap::default();
 3856        };
 3857        let project = project.read(cx);
 3858        let multi_buffer = self.buffer().read(cx);
 3859        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3860        let multi_buffer_visible_start = self
 3861            .scroll_manager
 3862            .anchor()
 3863            .anchor
 3864            .to_point(&multi_buffer_snapshot);
 3865        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3866            multi_buffer_visible_start
 3867                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3868            Bias::Left,
 3869        );
 3870        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3871        multi_buffer_snapshot
 3872            .range_to_buffer_ranges(multi_buffer_visible_range)
 3873            .into_iter()
 3874            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3875            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3876                let buffer_file = project::File::from_dyn(buffer.file())?;
 3877                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3878                let worktree_entry = buffer_worktree
 3879                    .read(cx)
 3880                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3881                if worktree_entry.is_ignored {
 3882                    return None;
 3883                }
 3884
 3885                let language = buffer.language()?;
 3886                if let Some(restrict_to_languages) = restrict_to_languages {
 3887                    if !restrict_to_languages.contains(language) {
 3888                        return None;
 3889                    }
 3890                }
 3891                Some((
 3892                    excerpt_id,
 3893                    (
 3894                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3895                        buffer.version().clone(),
 3896                        excerpt_visible_range,
 3897                    ),
 3898                ))
 3899            })
 3900            .collect()
 3901    }
 3902
 3903    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3904        TextLayoutDetails {
 3905            text_system: window.text_system().clone(),
 3906            editor_style: self.style.clone().unwrap(),
 3907            rem_size: window.rem_size(),
 3908            scroll_anchor: self.scroll_manager.anchor(),
 3909            visible_rows: self.visible_line_count(),
 3910            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3911        }
 3912    }
 3913
 3914    pub fn splice_inlays(
 3915        &self,
 3916        to_remove: &[InlayId],
 3917        to_insert: Vec<Inlay>,
 3918        cx: &mut Context<Self>,
 3919    ) {
 3920        self.display_map.update(cx, |display_map, cx| {
 3921            display_map.splice_inlays(to_remove, to_insert, cx)
 3922        });
 3923        cx.notify();
 3924    }
 3925
 3926    fn trigger_on_type_formatting(
 3927        &self,
 3928        input: String,
 3929        window: &mut Window,
 3930        cx: &mut Context<Self>,
 3931    ) -> Option<Task<Result<()>>> {
 3932        if input.len() != 1 {
 3933            return None;
 3934        }
 3935
 3936        let project = self.project.as_ref()?;
 3937        let position = self.selections.newest_anchor().head();
 3938        let (buffer, buffer_position) = self
 3939            .buffer
 3940            .read(cx)
 3941            .text_anchor_for_position(position, cx)?;
 3942
 3943        let settings = language_settings::language_settings(
 3944            buffer
 3945                .read(cx)
 3946                .language_at(buffer_position)
 3947                .map(|l| l.name()),
 3948            buffer.read(cx).file(),
 3949            cx,
 3950        );
 3951        if !settings.use_on_type_format {
 3952            return None;
 3953        }
 3954
 3955        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3956        // hence we do LSP request & edit on host side only — add formats to host's history.
 3957        let push_to_lsp_host_history = true;
 3958        // If this is not the host, append its history with new edits.
 3959        let push_to_client_history = project.read(cx).is_via_collab();
 3960
 3961        let on_type_formatting = project.update(cx, |project, cx| {
 3962            project.on_type_format(
 3963                buffer.clone(),
 3964                buffer_position,
 3965                input,
 3966                push_to_lsp_host_history,
 3967                cx,
 3968            )
 3969        });
 3970        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3971            if let Some(transaction) = on_type_formatting.await? {
 3972                if push_to_client_history {
 3973                    buffer
 3974                        .update(&mut cx, |buffer, _| {
 3975                            buffer.push_transaction(transaction, Instant::now());
 3976                        })
 3977                        .ok();
 3978                }
 3979                editor.update(&mut cx, |editor, cx| {
 3980                    editor.refresh_document_highlights(cx);
 3981                })?;
 3982            }
 3983            Ok(())
 3984        }))
 3985    }
 3986
 3987    pub fn show_completions(
 3988        &mut self,
 3989        options: &ShowCompletions,
 3990        window: &mut Window,
 3991        cx: &mut Context<Self>,
 3992    ) {
 3993        if self.pending_rename.is_some() {
 3994            return;
 3995        }
 3996
 3997        let Some(provider) = self.completion_provider.as_ref() else {
 3998            return;
 3999        };
 4000
 4001        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4002            return;
 4003        }
 4004
 4005        let position = self.selections.newest_anchor().head();
 4006        if position.diff_base_anchor.is_some() {
 4007            return;
 4008        }
 4009        let (buffer, buffer_position) =
 4010            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4011                output
 4012            } else {
 4013                return;
 4014            };
 4015        let show_completion_documentation = buffer
 4016            .read(cx)
 4017            .snapshot()
 4018            .settings_at(buffer_position, cx)
 4019            .show_completion_documentation;
 4020
 4021        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4022
 4023        let trigger_kind = match &options.trigger {
 4024            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4025                CompletionTriggerKind::TRIGGER_CHARACTER
 4026            }
 4027            _ => CompletionTriggerKind::INVOKED,
 4028        };
 4029        let completion_context = CompletionContext {
 4030            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4031                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4032                    Some(String::from(trigger))
 4033                } else {
 4034                    None
 4035                }
 4036            }),
 4037            trigger_kind,
 4038        };
 4039        let completions =
 4040            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 4041        let sort_completions = provider.sort_completions();
 4042
 4043        let id = post_inc(&mut self.next_completion_id);
 4044        let task = cx.spawn_in(window, |editor, mut cx| {
 4045            async move {
 4046                editor.update(&mut cx, |this, _| {
 4047                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4048                })?;
 4049                let completions = completions.await.log_err();
 4050                let menu = if let Some(completions) = completions {
 4051                    let mut menu = CompletionsMenu::new(
 4052                        id,
 4053                        sort_completions,
 4054                        show_completion_documentation,
 4055                        position,
 4056                        buffer.clone(),
 4057                        completions.into(),
 4058                    );
 4059
 4060                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4061                        .await;
 4062
 4063                    menu.visible().then_some(menu)
 4064                } else {
 4065                    None
 4066                };
 4067
 4068                editor.update_in(&mut cx, |editor, window, cx| {
 4069                    match editor.context_menu.borrow().as_ref() {
 4070                        None => {}
 4071                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4072                            if prev_menu.id > id {
 4073                                return;
 4074                            }
 4075                        }
 4076                        _ => return,
 4077                    }
 4078
 4079                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4080                        let mut menu = menu.unwrap();
 4081                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4082
 4083                        *editor.context_menu.borrow_mut() =
 4084                            Some(CodeContextMenu::Completions(menu));
 4085
 4086                        if editor.show_edit_predictions_in_menu() {
 4087                            editor.update_visible_inline_completion(window, cx);
 4088                        } else {
 4089                            editor.discard_inline_completion(false, cx);
 4090                        }
 4091
 4092                        cx.notify();
 4093                    } else if editor.completion_tasks.len() <= 1 {
 4094                        // If there are no more completion tasks and the last menu was
 4095                        // empty, we should hide it.
 4096                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4097                        // If it was already hidden and we don't show inline
 4098                        // completions in the menu, we should also show the
 4099                        // inline-completion when available.
 4100                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4101                            editor.update_visible_inline_completion(window, cx);
 4102                        }
 4103                    }
 4104                })?;
 4105
 4106                Ok::<_, anyhow::Error>(())
 4107            }
 4108            .log_err()
 4109        });
 4110
 4111        self.completion_tasks.push((id, task));
 4112    }
 4113
 4114    pub fn confirm_completion(
 4115        &mut self,
 4116        action: &ConfirmCompletion,
 4117        window: &mut Window,
 4118        cx: &mut Context<Self>,
 4119    ) -> Option<Task<Result<()>>> {
 4120        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4121    }
 4122
 4123    pub fn compose_completion(
 4124        &mut self,
 4125        action: &ComposeCompletion,
 4126        window: &mut Window,
 4127        cx: &mut Context<Self>,
 4128    ) -> Option<Task<Result<()>>> {
 4129        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4130    }
 4131
 4132    fn do_completion(
 4133        &mut self,
 4134        item_ix: Option<usize>,
 4135        intent: CompletionIntent,
 4136        window: &mut Window,
 4137        cx: &mut Context<Editor>,
 4138    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4139        use language::ToOffset as _;
 4140
 4141        let completions_menu =
 4142            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4143                menu
 4144            } else {
 4145                return None;
 4146            };
 4147
 4148        let entries = completions_menu.entries.borrow();
 4149        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4150        if self.show_edit_predictions_in_menu() {
 4151            self.discard_inline_completion(true, cx);
 4152        }
 4153        let candidate_id = mat.candidate_id;
 4154        drop(entries);
 4155
 4156        let buffer_handle = completions_menu.buffer;
 4157        let completion = completions_menu
 4158            .completions
 4159            .borrow()
 4160            .get(candidate_id)?
 4161            .clone();
 4162        cx.stop_propagation();
 4163
 4164        let snippet;
 4165        let text;
 4166
 4167        if completion.is_snippet() {
 4168            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4169            text = snippet.as_ref().unwrap().text.clone();
 4170        } else {
 4171            snippet = None;
 4172            text = completion.new_text.clone();
 4173        };
 4174        let selections = self.selections.all::<usize>(cx);
 4175        let buffer = buffer_handle.read(cx);
 4176        let old_range = completion.old_range.to_offset(buffer);
 4177        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4178
 4179        let newest_selection = self.selections.newest_anchor();
 4180        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4181            return None;
 4182        }
 4183
 4184        let lookbehind = newest_selection
 4185            .start
 4186            .text_anchor
 4187            .to_offset(buffer)
 4188            .saturating_sub(old_range.start);
 4189        let lookahead = old_range
 4190            .end
 4191            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4192        let mut common_prefix_len = old_text
 4193            .bytes()
 4194            .zip(text.bytes())
 4195            .take_while(|(a, b)| a == b)
 4196            .count();
 4197
 4198        let snapshot = self.buffer.read(cx).snapshot(cx);
 4199        let mut range_to_replace: Option<Range<isize>> = None;
 4200        let mut ranges = Vec::new();
 4201        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4202        for selection in &selections {
 4203            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4204                let start = selection.start.saturating_sub(lookbehind);
 4205                let end = selection.end + lookahead;
 4206                if selection.id == newest_selection.id {
 4207                    range_to_replace = Some(
 4208                        ((start + common_prefix_len) as isize - selection.start as isize)
 4209                            ..(end as isize - selection.start as isize),
 4210                    );
 4211                }
 4212                ranges.push(start + common_prefix_len..end);
 4213            } else {
 4214                common_prefix_len = 0;
 4215                ranges.clear();
 4216                ranges.extend(selections.iter().map(|s| {
 4217                    if s.id == newest_selection.id {
 4218                        range_to_replace = Some(
 4219                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4220                                - selection.start as isize
 4221                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4222                                    - selection.start as isize,
 4223                        );
 4224                        old_range.clone()
 4225                    } else {
 4226                        s.start..s.end
 4227                    }
 4228                }));
 4229                break;
 4230            }
 4231            if !self.linked_edit_ranges.is_empty() {
 4232                let start_anchor = snapshot.anchor_before(selection.head());
 4233                let end_anchor = snapshot.anchor_after(selection.tail());
 4234                if let Some(ranges) = self
 4235                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4236                {
 4237                    for (buffer, edits) in ranges {
 4238                        linked_edits.entry(buffer.clone()).or_default().extend(
 4239                            edits
 4240                                .into_iter()
 4241                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4242                        );
 4243                    }
 4244                }
 4245            }
 4246        }
 4247        let text = &text[common_prefix_len..];
 4248
 4249        cx.emit(EditorEvent::InputHandled {
 4250            utf16_range_to_replace: range_to_replace,
 4251            text: text.into(),
 4252        });
 4253
 4254        self.transact(window, cx, |this, window, cx| {
 4255            if let Some(mut snippet) = snippet {
 4256                snippet.text = text.to_string();
 4257                for tabstop in snippet
 4258                    .tabstops
 4259                    .iter_mut()
 4260                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4261                {
 4262                    tabstop.start -= common_prefix_len as isize;
 4263                    tabstop.end -= common_prefix_len as isize;
 4264                }
 4265
 4266                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4267            } else {
 4268                this.buffer.update(cx, |buffer, cx| {
 4269                    buffer.edit(
 4270                        ranges.iter().map(|range| (range.clone(), text)),
 4271                        this.autoindent_mode.clone(),
 4272                        cx,
 4273                    );
 4274                });
 4275            }
 4276            for (buffer, edits) in linked_edits {
 4277                buffer.update(cx, |buffer, cx| {
 4278                    let snapshot = buffer.snapshot();
 4279                    let edits = edits
 4280                        .into_iter()
 4281                        .map(|(range, text)| {
 4282                            use text::ToPoint as TP;
 4283                            let end_point = TP::to_point(&range.end, &snapshot);
 4284                            let start_point = TP::to_point(&range.start, &snapshot);
 4285                            (start_point..end_point, text)
 4286                        })
 4287                        .sorted_by_key(|(range, _)| range.start)
 4288                        .collect::<Vec<_>>();
 4289                    buffer.edit(edits, None, cx);
 4290                })
 4291            }
 4292
 4293            this.refresh_inline_completion(true, false, window, cx);
 4294        });
 4295
 4296        let show_new_completions_on_confirm = completion
 4297            .confirm
 4298            .as_ref()
 4299            .map_or(false, |confirm| confirm(intent, window, cx));
 4300        if show_new_completions_on_confirm {
 4301            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4302        }
 4303
 4304        let provider = self.completion_provider.as_ref()?;
 4305        drop(completion);
 4306        let apply_edits = provider.apply_additional_edits_for_completion(
 4307            buffer_handle,
 4308            completions_menu.completions.clone(),
 4309            candidate_id,
 4310            true,
 4311            cx,
 4312        );
 4313
 4314        let editor_settings = EditorSettings::get_global(cx);
 4315        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4316            // After the code completion is finished, users often want to know what signatures are needed.
 4317            // so we should automatically call signature_help
 4318            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4319        }
 4320
 4321        Some(cx.foreground_executor().spawn(async move {
 4322            apply_edits.await?;
 4323            Ok(())
 4324        }))
 4325    }
 4326
 4327    pub fn toggle_code_actions(
 4328        &mut self,
 4329        action: &ToggleCodeActions,
 4330        window: &mut Window,
 4331        cx: &mut Context<Self>,
 4332    ) {
 4333        let mut context_menu = self.context_menu.borrow_mut();
 4334        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4335            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4336                // Toggle if we're selecting the same one
 4337                *context_menu = None;
 4338                cx.notify();
 4339                return;
 4340            } else {
 4341                // Otherwise, clear it and start a new one
 4342                *context_menu = None;
 4343                cx.notify();
 4344            }
 4345        }
 4346        drop(context_menu);
 4347        let snapshot = self.snapshot(window, cx);
 4348        let deployed_from_indicator = action.deployed_from_indicator;
 4349        let mut task = self.code_actions_task.take();
 4350        let action = action.clone();
 4351        cx.spawn_in(window, |editor, mut cx| async move {
 4352            while let Some(prev_task) = task {
 4353                prev_task.await.log_err();
 4354                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4355            }
 4356
 4357            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4358                if editor.focus_handle.is_focused(window) {
 4359                    let multibuffer_point = action
 4360                        .deployed_from_indicator
 4361                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4362                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4363                    let (buffer, buffer_row) = snapshot
 4364                        .buffer_snapshot
 4365                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4366                        .and_then(|(buffer_snapshot, range)| {
 4367                            editor
 4368                                .buffer
 4369                                .read(cx)
 4370                                .buffer(buffer_snapshot.remote_id())
 4371                                .map(|buffer| (buffer, range.start.row))
 4372                        })?;
 4373                    let (_, code_actions) = editor
 4374                        .available_code_actions
 4375                        .clone()
 4376                        .and_then(|(location, code_actions)| {
 4377                            let snapshot = location.buffer.read(cx).snapshot();
 4378                            let point_range = location.range.to_point(&snapshot);
 4379                            let point_range = point_range.start.row..=point_range.end.row;
 4380                            if point_range.contains(&buffer_row) {
 4381                                Some((location, code_actions))
 4382                            } else {
 4383                                None
 4384                            }
 4385                        })
 4386                        .unzip();
 4387                    let buffer_id = buffer.read(cx).remote_id();
 4388                    let tasks = editor
 4389                        .tasks
 4390                        .get(&(buffer_id, buffer_row))
 4391                        .map(|t| Arc::new(t.to_owned()));
 4392                    if tasks.is_none() && code_actions.is_none() {
 4393                        return None;
 4394                    }
 4395
 4396                    editor.completion_tasks.clear();
 4397                    editor.discard_inline_completion(false, cx);
 4398                    let task_context =
 4399                        tasks
 4400                            .as_ref()
 4401                            .zip(editor.project.clone())
 4402                            .map(|(tasks, project)| {
 4403                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4404                            });
 4405
 4406                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4407                        let task_context = match task_context {
 4408                            Some(task_context) => task_context.await,
 4409                            None => None,
 4410                        };
 4411                        let resolved_tasks =
 4412                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4413                                Rc::new(ResolvedTasks {
 4414                                    templates: tasks.resolve(&task_context).collect(),
 4415                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4416                                        multibuffer_point.row,
 4417                                        tasks.column,
 4418                                    )),
 4419                                })
 4420                            });
 4421                        let spawn_straight_away = resolved_tasks
 4422                            .as_ref()
 4423                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4424                            && code_actions
 4425                                .as_ref()
 4426                                .map_or(true, |actions| actions.is_empty());
 4427                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4428                            *editor.context_menu.borrow_mut() =
 4429                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4430                                    buffer,
 4431                                    actions: CodeActionContents {
 4432                                        tasks: resolved_tasks,
 4433                                        actions: code_actions,
 4434                                    },
 4435                                    selected_item: Default::default(),
 4436                                    scroll_handle: UniformListScrollHandle::default(),
 4437                                    deployed_from_indicator,
 4438                                }));
 4439                            if spawn_straight_away {
 4440                                if let Some(task) = editor.confirm_code_action(
 4441                                    &ConfirmCodeAction { item_ix: Some(0) },
 4442                                    window,
 4443                                    cx,
 4444                                ) {
 4445                                    cx.notify();
 4446                                    return task;
 4447                                }
 4448                            }
 4449                            cx.notify();
 4450                            Task::ready(Ok(()))
 4451                        }) {
 4452                            task.await
 4453                        } else {
 4454                            Ok(())
 4455                        }
 4456                    }))
 4457                } else {
 4458                    Some(Task::ready(Ok(())))
 4459                }
 4460            })?;
 4461            if let Some(task) = spawned_test_task {
 4462                task.await?;
 4463            }
 4464
 4465            Ok::<_, anyhow::Error>(())
 4466        })
 4467        .detach_and_log_err(cx);
 4468    }
 4469
 4470    pub fn confirm_code_action(
 4471        &mut self,
 4472        action: &ConfirmCodeAction,
 4473        window: &mut Window,
 4474        cx: &mut Context<Self>,
 4475    ) -> Option<Task<Result<()>>> {
 4476        let actions_menu =
 4477            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4478                menu
 4479            } else {
 4480                return None;
 4481            };
 4482        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4483        let action = actions_menu.actions.get(action_ix)?;
 4484        let title = action.label();
 4485        let buffer = actions_menu.buffer;
 4486        let workspace = self.workspace()?;
 4487
 4488        match action {
 4489            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4490                workspace.update(cx, |workspace, cx| {
 4491                    workspace::tasks::schedule_resolved_task(
 4492                        workspace,
 4493                        task_source_kind,
 4494                        resolved_task,
 4495                        false,
 4496                        cx,
 4497                    );
 4498
 4499                    Some(Task::ready(Ok(())))
 4500                })
 4501            }
 4502            CodeActionsItem::CodeAction {
 4503                excerpt_id,
 4504                action,
 4505                provider,
 4506            } => {
 4507                let apply_code_action =
 4508                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4509                let workspace = workspace.downgrade();
 4510                Some(cx.spawn_in(window, |editor, cx| async move {
 4511                    let project_transaction = apply_code_action.await?;
 4512                    Self::open_project_transaction(
 4513                        &editor,
 4514                        workspace,
 4515                        project_transaction,
 4516                        title,
 4517                        cx,
 4518                    )
 4519                    .await
 4520                }))
 4521            }
 4522        }
 4523    }
 4524
 4525    pub async fn open_project_transaction(
 4526        this: &WeakEntity<Editor>,
 4527        workspace: WeakEntity<Workspace>,
 4528        transaction: ProjectTransaction,
 4529        title: String,
 4530        mut cx: AsyncWindowContext,
 4531    ) -> Result<()> {
 4532        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4533        cx.update(|_, cx| {
 4534            entries.sort_unstable_by_key(|(buffer, _)| {
 4535                buffer.read(cx).file().map(|f| f.path().clone())
 4536            });
 4537        })?;
 4538
 4539        // If the project transaction's edits are all contained within this editor, then
 4540        // avoid opening a new editor to display them.
 4541
 4542        if let Some((buffer, transaction)) = entries.first() {
 4543            if entries.len() == 1 {
 4544                let excerpt = this.update(&mut cx, |editor, cx| {
 4545                    editor
 4546                        .buffer()
 4547                        .read(cx)
 4548                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4549                })?;
 4550                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4551                    if excerpted_buffer == *buffer {
 4552                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4553                            let excerpt_range = excerpt_range.to_offset(buffer);
 4554                            buffer
 4555                                .edited_ranges_for_transaction::<usize>(transaction)
 4556                                .all(|range| {
 4557                                    excerpt_range.start <= range.start
 4558                                        && excerpt_range.end >= range.end
 4559                                })
 4560                        })?;
 4561
 4562                        if all_edits_within_excerpt {
 4563                            return Ok(());
 4564                        }
 4565                    }
 4566                }
 4567            }
 4568        } else {
 4569            return Ok(());
 4570        }
 4571
 4572        let mut ranges_to_highlight = Vec::new();
 4573        let excerpt_buffer = cx.new(|cx| {
 4574            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4575            for (buffer_handle, transaction) in &entries {
 4576                let buffer = buffer_handle.read(cx);
 4577                ranges_to_highlight.extend(
 4578                    multibuffer.push_excerpts_with_context_lines(
 4579                        buffer_handle.clone(),
 4580                        buffer
 4581                            .edited_ranges_for_transaction::<usize>(transaction)
 4582                            .collect(),
 4583                        DEFAULT_MULTIBUFFER_CONTEXT,
 4584                        cx,
 4585                    ),
 4586                );
 4587            }
 4588            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4589            multibuffer
 4590        })?;
 4591
 4592        workspace.update_in(&mut cx, |workspace, window, cx| {
 4593            let project = workspace.project().clone();
 4594            let editor = cx
 4595                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4596            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4597            editor.update(cx, |editor, cx| {
 4598                editor.highlight_background::<Self>(
 4599                    &ranges_to_highlight,
 4600                    |theme| theme.editor_highlighted_line_background,
 4601                    cx,
 4602                );
 4603            });
 4604        })?;
 4605
 4606        Ok(())
 4607    }
 4608
 4609    pub fn clear_code_action_providers(&mut self) {
 4610        self.code_action_providers.clear();
 4611        self.available_code_actions.take();
 4612    }
 4613
 4614    pub fn add_code_action_provider(
 4615        &mut self,
 4616        provider: Rc<dyn CodeActionProvider>,
 4617        window: &mut Window,
 4618        cx: &mut Context<Self>,
 4619    ) {
 4620        if self
 4621            .code_action_providers
 4622            .iter()
 4623            .any(|existing_provider| existing_provider.id() == provider.id())
 4624        {
 4625            return;
 4626        }
 4627
 4628        self.code_action_providers.push(provider);
 4629        self.refresh_code_actions(window, cx);
 4630    }
 4631
 4632    pub fn remove_code_action_provider(
 4633        &mut self,
 4634        id: Arc<str>,
 4635        window: &mut Window,
 4636        cx: &mut Context<Self>,
 4637    ) {
 4638        self.code_action_providers
 4639            .retain(|provider| provider.id() != id);
 4640        self.refresh_code_actions(window, cx);
 4641    }
 4642
 4643    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4644        let buffer = self.buffer.read(cx);
 4645        let newest_selection = self.selections.newest_anchor().clone();
 4646        if newest_selection.head().diff_base_anchor.is_some() {
 4647            return None;
 4648        }
 4649        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4650        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4651        if start_buffer != end_buffer {
 4652            return None;
 4653        }
 4654
 4655        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4656            cx.background_executor()
 4657                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4658                .await;
 4659
 4660            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4661                let providers = this.code_action_providers.clone();
 4662                let tasks = this
 4663                    .code_action_providers
 4664                    .iter()
 4665                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4666                    .collect::<Vec<_>>();
 4667                (providers, tasks)
 4668            })?;
 4669
 4670            let mut actions = Vec::new();
 4671            for (provider, provider_actions) in
 4672                providers.into_iter().zip(future::join_all(tasks).await)
 4673            {
 4674                if let Some(provider_actions) = provider_actions.log_err() {
 4675                    actions.extend(provider_actions.into_iter().map(|action| {
 4676                        AvailableCodeAction {
 4677                            excerpt_id: newest_selection.start.excerpt_id,
 4678                            action,
 4679                            provider: provider.clone(),
 4680                        }
 4681                    }));
 4682                }
 4683            }
 4684
 4685            this.update(&mut cx, |this, cx| {
 4686                this.available_code_actions = if actions.is_empty() {
 4687                    None
 4688                } else {
 4689                    Some((
 4690                        Location {
 4691                            buffer: start_buffer,
 4692                            range: start..end,
 4693                        },
 4694                        actions.into(),
 4695                    ))
 4696                };
 4697                cx.notify();
 4698            })
 4699        }));
 4700        None
 4701    }
 4702
 4703    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4704        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4705            self.show_git_blame_inline = false;
 4706
 4707            self.show_git_blame_inline_delay_task =
 4708                Some(cx.spawn_in(window, |this, mut cx| async move {
 4709                    cx.background_executor().timer(delay).await;
 4710
 4711                    this.update(&mut cx, |this, cx| {
 4712                        this.show_git_blame_inline = true;
 4713                        cx.notify();
 4714                    })
 4715                    .log_err();
 4716                }));
 4717        }
 4718    }
 4719
 4720    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4721        if self.pending_rename.is_some() {
 4722            return None;
 4723        }
 4724
 4725        let provider = self.semantics_provider.clone()?;
 4726        let buffer = self.buffer.read(cx);
 4727        let newest_selection = self.selections.newest_anchor().clone();
 4728        let cursor_position = newest_selection.head();
 4729        let (cursor_buffer, cursor_buffer_position) =
 4730            buffer.text_anchor_for_position(cursor_position, cx)?;
 4731        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4732        if cursor_buffer != tail_buffer {
 4733            return None;
 4734        }
 4735        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4736        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4737            cx.background_executor()
 4738                .timer(Duration::from_millis(debounce))
 4739                .await;
 4740
 4741            let highlights = if let Some(highlights) = cx
 4742                .update(|cx| {
 4743                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4744                })
 4745                .ok()
 4746                .flatten()
 4747            {
 4748                highlights.await.log_err()
 4749            } else {
 4750                None
 4751            };
 4752
 4753            if let Some(highlights) = highlights {
 4754                this.update(&mut cx, |this, cx| {
 4755                    if this.pending_rename.is_some() {
 4756                        return;
 4757                    }
 4758
 4759                    let buffer_id = cursor_position.buffer_id;
 4760                    let buffer = this.buffer.read(cx);
 4761                    if !buffer
 4762                        .text_anchor_for_position(cursor_position, cx)
 4763                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4764                    {
 4765                        return;
 4766                    }
 4767
 4768                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4769                    let mut write_ranges = Vec::new();
 4770                    let mut read_ranges = Vec::new();
 4771                    for highlight in highlights {
 4772                        for (excerpt_id, excerpt_range) in
 4773                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4774                        {
 4775                            let start = highlight
 4776                                .range
 4777                                .start
 4778                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4779                            let end = highlight
 4780                                .range
 4781                                .end
 4782                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4783                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4784                                continue;
 4785                            }
 4786
 4787                            let range = Anchor {
 4788                                buffer_id,
 4789                                excerpt_id,
 4790                                text_anchor: start,
 4791                                diff_base_anchor: None,
 4792                            }..Anchor {
 4793                                buffer_id,
 4794                                excerpt_id,
 4795                                text_anchor: end,
 4796                                diff_base_anchor: None,
 4797                            };
 4798                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4799                                write_ranges.push(range);
 4800                            } else {
 4801                                read_ranges.push(range);
 4802                            }
 4803                        }
 4804                    }
 4805
 4806                    this.highlight_background::<DocumentHighlightRead>(
 4807                        &read_ranges,
 4808                        |theme| theme.editor_document_highlight_read_background,
 4809                        cx,
 4810                    );
 4811                    this.highlight_background::<DocumentHighlightWrite>(
 4812                        &write_ranges,
 4813                        |theme| theme.editor_document_highlight_write_background,
 4814                        cx,
 4815                    );
 4816                    cx.notify();
 4817                })
 4818                .log_err();
 4819            }
 4820        }));
 4821        None
 4822    }
 4823
 4824    pub fn refresh_selected_text_highlights(
 4825        &mut self,
 4826        window: &mut Window,
 4827        cx: &mut Context<Editor>,
 4828    ) {
 4829        self.selection_highlight_task.take();
 4830        if !EditorSettings::get_global(cx).selection_highlight {
 4831            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4832            return;
 4833        }
 4834        if self.selections.count() != 1 || self.selections.line_mode {
 4835            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4836            return;
 4837        }
 4838        let selection = self.selections.newest::<Point>(cx);
 4839        if selection.is_empty() || selection.start.row != selection.end.row {
 4840            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4841            return;
 4842        }
 4843        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4844        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4845            cx.background_executor()
 4846                .timer(Duration::from_millis(debounce))
 4847                .await;
 4848            let Some(Some(matches_task)) = editor
 4849                .update_in(&mut cx, |editor, _, cx| {
 4850                    if editor.selections.count() != 1 || editor.selections.line_mode {
 4851                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4852                        return None;
 4853                    }
 4854                    let selection = editor.selections.newest::<Point>(cx);
 4855                    if selection.is_empty() || selection.start.row != selection.end.row {
 4856                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4857                        return None;
 4858                    }
 4859                    let buffer = editor.buffer().read(cx).snapshot(cx);
 4860                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 4861                    if query.trim().is_empty() {
 4862                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4863                        return None;
 4864                    }
 4865                    Some(cx.background_spawn(async move {
 4866                        let mut ranges = Vec::new();
 4867                        let selection_anchors = selection.range().to_anchors(&buffer);
 4868                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 4869                            for (search_buffer, search_range, excerpt_id) in
 4870                                buffer.range_to_buffer_ranges(range)
 4871                            {
 4872                                ranges.extend(
 4873                                    project::search::SearchQuery::text(
 4874                                        query.clone(),
 4875                                        false,
 4876                                        false,
 4877                                        false,
 4878                                        Default::default(),
 4879                                        Default::default(),
 4880                                        None,
 4881                                    )
 4882                                    .unwrap()
 4883                                    .search(search_buffer, Some(search_range.clone()))
 4884                                    .await
 4885                                    .into_iter()
 4886                                    .filter_map(
 4887                                        |match_range| {
 4888                                            let start = search_buffer.anchor_after(
 4889                                                search_range.start + match_range.start,
 4890                                            );
 4891                                            let end = search_buffer.anchor_before(
 4892                                                search_range.start + match_range.end,
 4893                                            );
 4894                                            let range = Anchor::range_in_buffer(
 4895                                                excerpt_id,
 4896                                                search_buffer.remote_id(),
 4897                                                start..end,
 4898                                            );
 4899                                            (range != selection_anchors).then_some(range)
 4900                                        },
 4901                                    ),
 4902                                );
 4903                            }
 4904                        }
 4905                        ranges
 4906                    }))
 4907                })
 4908                .log_err()
 4909            else {
 4910                return;
 4911            };
 4912            let matches = matches_task.await;
 4913            editor
 4914                .update_in(&mut cx, |editor, _, cx| {
 4915                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4916                    if !matches.is_empty() {
 4917                        editor.highlight_background::<SelectedTextHighlight>(
 4918                            &matches,
 4919                            |theme| theme.editor_document_highlight_bracket_background,
 4920                            cx,
 4921                        )
 4922                    }
 4923                })
 4924                .log_err();
 4925        }));
 4926    }
 4927
 4928    pub fn refresh_inline_completion(
 4929        &mut self,
 4930        debounce: bool,
 4931        user_requested: bool,
 4932        window: &mut Window,
 4933        cx: &mut Context<Self>,
 4934    ) -> Option<()> {
 4935        let provider = self.edit_prediction_provider()?;
 4936        let cursor = self.selections.newest_anchor().head();
 4937        let (buffer, cursor_buffer_position) =
 4938            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4939
 4940        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4941            self.discard_inline_completion(false, cx);
 4942            return None;
 4943        }
 4944
 4945        if !user_requested
 4946            && (!self.should_show_edit_predictions()
 4947                || !self.is_focused(window)
 4948                || buffer.read(cx).is_empty())
 4949        {
 4950            self.discard_inline_completion(false, cx);
 4951            return None;
 4952        }
 4953
 4954        self.update_visible_inline_completion(window, cx);
 4955        provider.refresh(
 4956            self.project.clone(),
 4957            buffer,
 4958            cursor_buffer_position,
 4959            debounce,
 4960            cx,
 4961        );
 4962        Some(())
 4963    }
 4964
 4965    fn show_edit_predictions_in_menu(&self) -> bool {
 4966        match self.edit_prediction_settings {
 4967            EditPredictionSettings::Disabled => false,
 4968            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4969        }
 4970    }
 4971
 4972    pub fn edit_predictions_enabled(&self) -> bool {
 4973        match self.edit_prediction_settings {
 4974            EditPredictionSettings::Disabled => false,
 4975            EditPredictionSettings::Enabled { .. } => true,
 4976        }
 4977    }
 4978
 4979    fn edit_prediction_requires_modifier(&self) -> bool {
 4980        match self.edit_prediction_settings {
 4981            EditPredictionSettings::Disabled => false,
 4982            EditPredictionSettings::Enabled {
 4983                preview_requires_modifier,
 4984                ..
 4985            } => preview_requires_modifier,
 4986        }
 4987    }
 4988
 4989    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 4990        if self.edit_prediction_provider.is_none() {
 4991            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 4992        } else {
 4993            let selection = self.selections.newest_anchor();
 4994            let cursor = selection.head();
 4995
 4996            if let Some((buffer, cursor_buffer_position)) =
 4997                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4998            {
 4999                self.edit_prediction_settings =
 5000                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5001            }
 5002        }
 5003    }
 5004
 5005    fn edit_prediction_settings_at_position(
 5006        &self,
 5007        buffer: &Entity<Buffer>,
 5008        buffer_position: language::Anchor,
 5009        cx: &App,
 5010    ) -> EditPredictionSettings {
 5011        if self.mode != EditorMode::Full
 5012            || !self.show_inline_completions_override.unwrap_or(true)
 5013            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5014        {
 5015            return EditPredictionSettings::Disabled;
 5016        }
 5017
 5018        let buffer = buffer.read(cx);
 5019
 5020        let file = buffer.file();
 5021
 5022        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5023            return EditPredictionSettings::Disabled;
 5024        };
 5025
 5026        let by_provider = matches!(
 5027            self.menu_inline_completions_policy,
 5028            MenuInlineCompletionsPolicy::ByProvider
 5029        );
 5030
 5031        let show_in_menu = by_provider
 5032            && self
 5033                .edit_prediction_provider
 5034                .as_ref()
 5035                .map_or(false, |provider| {
 5036                    provider.provider.show_completions_in_menu()
 5037                });
 5038
 5039        let preview_requires_modifier =
 5040            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5041
 5042        EditPredictionSettings::Enabled {
 5043            show_in_menu,
 5044            preview_requires_modifier,
 5045        }
 5046    }
 5047
 5048    fn should_show_edit_predictions(&self) -> bool {
 5049        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5050    }
 5051
 5052    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5053        matches!(
 5054            self.edit_prediction_preview,
 5055            EditPredictionPreview::Active { .. }
 5056        )
 5057    }
 5058
 5059    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5060        let cursor = self.selections.newest_anchor().head();
 5061        if let Some((buffer, cursor_position)) =
 5062            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5063        {
 5064            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5065        } else {
 5066            false
 5067        }
 5068    }
 5069
 5070    fn edit_predictions_enabled_in_buffer(
 5071        &self,
 5072        buffer: &Entity<Buffer>,
 5073        buffer_position: language::Anchor,
 5074        cx: &App,
 5075    ) -> bool {
 5076        maybe!({
 5077            let provider = self.edit_prediction_provider()?;
 5078            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5079                return Some(false);
 5080            }
 5081            let buffer = buffer.read(cx);
 5082            let Some(file) = buffer.file() else {
 5083                return Some(true);
 5084            };
 5085            let settings = all_language_settings(Some(file), cx);
 5086            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5087        })
 5088        .unwrap_or(false)
 5089    }
 5090
 5091    fn cycle_inline_completion(
 5092        &mut self,
 5093        direction: Direction,
 5094        window: &mut Window,
 5095        cx: &mut Context<Self>,
 5096    ) -> Option<()> {
 5097        let provider = self.edit_prediction_provider()?;
 5098        let cursor = self.selections.newest_anchor().head();
 5099        let (buffer, cursor_buffer_position) =
 5100            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5101        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5102            return None;
 5103        }
 5104
 5105        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5106        self.update_visible_inline_completion(window, cx);
 5107
 5108        Some(())
 5109    }
 5110
 5111    pub fn show_inline_completion(
 5112        &mut self,
 5113        _: &ShowEditPrediction,
 5114        window: &mut Window,
 5115        cx: &mut Context<Self>,
 5116    ) {
 5117        if !self.has_active_inline_completion() {
 5118            self.refresh_inline_completion(false, true, window, cx);
 5119            return;
 5120        }
 5121
 5122        self.update_visible_inline_completion(window, cx);
 5123    }
 5124
 5125    pub fn display_cursor_names(
 5126        &mut self,
 5127        _: &DisplayCursorNames,
 5128        window: &mut Window,
 5129        cx: &mut Context<Self>,
 5130    ) {
 5131        self.show_cursor_names(window, cx);
 5132    }
 5133
 5134    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5135        self.show_cursor_names = true;
 5136        cx.notify();
 5137        cx.spawn_in(window, |this, mut cx| async move {
 5138            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5139            this.update(&mut cx, |this, cx| {
 5140                this.show_cursor_names = false;
 5141                cx.notify()
 5142            })
 5143            .ok()
 5144        })
 5145        .detach();
 5146    }
 5147
 5148    pub fn next_edit_prediction(
 5149        &mut self,
 5150        _: &NextEditPrediction,
 5151        window: &mut Window,
 5152        cx: &mut Context<Self>,
 5153    ) {
 5154        if self.has_active_inline_completion() {
 5155            self.cycle_inline_completion(Direction::Next, window, cx);
 5156        } else {
 5157            let is_copilot_disabled = self
 5158                .refresh_inline_completion(false, true, window, cx)
 5159                .is_none();
 5160            if is_copilot_disabled {
 5161                cx.propagate();
 5162            }
 5163        }
 5164    }
 5165
 5166    pub fn previous_edit_prediction(
 5167        &mut self,
 5168        _: &PreviousEditPrediction,
 5169        window: &mut Window,
 5170        cx: &mut Context<Self>,
 5171    ) {
 5172        if self.has_active_inline_completion() {
 5173            self.cycle_inline_completion(Direction::Prev, window, cx);
 5174        } else {
 5175            let is_copilot_disabled = self
 5176                .refresh_inline_completion(false, true, window, cx)
 5177                .is_none();
 5178            if is_copilot_disabled {
 5179                cx.propagate();
 5180            }
 5181        }
 5182    }
 5183
 5184    pub fn accept_edit_prediction(
 5185        &mut self,
 5186        _: &AcceptEditPrediction,
 5187        window: &mut Window,
 5188        cx: &mut Context<Self>,
 5189    ) {
 5190        if self.show_edit_predictions_in_menu() {
 5191            self.hide_context_menu(window, cx);
 5192        }
 5193
 5194        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5195            return;
 5196        };
 5197
 5198        self.report_inline_completion_event(
 5199            active_inline_completion.completion_id.clone(),
 5200            true,
 5201            cx,
 5202        );
 5203
 5204        match &active_inline_completion.completion {
 5205            InlineCompletion::Move { target, .. } => {
 5206                let target = *target;
 5207
 5208                if let Some(position_map) = &self.last_position_map {
 5209                    if position_map
 5210                        .visible_row_range
 5211                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5212                        || !self.edit_prediction_requires_modifier()
 5213                    {
 5214                        self.unfold_ranges(&[target..target], true, false, cx);
 5215                        // Note that this is also done in vim's handler of the Tab action.
 5216                        self.change_selections(
 5217                            Some(Autoscroll::newest()),
 5218                            window,
 5219                            cx,
 5220                            |selections| {
 5221                                selections.select_anchor_ranges([target..target]);
 5222                            },
 5223                        );
 5224                        self.clear_row_highlights::<EditPredictionPreview>();
 5225
 5226                        self.edit_prediction_preview
 5227                            .set_previous_scroll_position(None);
 5228                    } else {
 5229                        self.edit_prediction_preview
 5230                            .set_previous_scroll_position(Some(
 5231                                position_map.snapshot.scroll_anchor,
 5232                            ));
 5233
 5234                        self.highlight_rows::<EditPredictionPreview>(
 5235                            target..target,
 5236                            cx.theme().colors().editor_highlighted_line_background,
 5237                            true,
 5238                            cx,
 5239                        );
 5240                        self.request_autoscroll(Autoscroll::fit(), cx);
 5241                    }
 5242                }
 5243            }
 5244            InlineCompletion::Edit { edits, .. } => {
 5245                if let Some(provider) = self.edit_prediction_provider() {
 5246                    provider.accept(cx);
 5247                }
 5248
 5249                let snapshot = self.buffer.read(cx).snapshot(cx);
 5250                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5251
 5252                self.buffer.update(cx, |buffer, cx| {
 5253                    buffer.edit(edits.iter().cloned(), None, cx)
 5254                });
 5255
 5256                self.change_selections(None, window, cx, |s| {
 5257                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5258                });
 5259
 5260                self.update_visible_inline_completion(window, cx);
 5261                if self.active_inline_completion.is_none() {
 5262                    self.refresh_inline_completion(true, true, window, cx);
 5263                }
 5264
 5265                cx.notify();
 5266            }
 5267        }
 5268
 5269        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5270    }
 5271
 5272    pub fn accept_partial_inline_completion(
 5273        &mut self,
 5274        _: &AcceptPartialEditPrediction,
 5275        window: &mut Window,
 5276        cx: &mut Context<Self>,
 5277    ) {
 5278        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5279            return;
 5280        };
 5281        if self.selections.count() != 1 {
 5282            return;
 5283        }
 5284
 5285        self.report_inline_completion_event(
 5286            active_inline_completion.completion_id.clone(),
 5287            true,
 5288            cx,
 5289        );
 5290
 5291        match &active_inline_completion.completion {
 5292            InlineCompletion::Move { target, .. } => {
 5293                let target = *target;
 5294                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5295                    selections.select_anchor_ranges([target..target]);
 5296                });
 5297            }
 5298            InlineCompletion::Edit { edits, .. } => {
 5299                // Find an insertion that starts at the cursor position.
 5300                let snapshot = self.buffer.read(cx).snapshot(cx);
 5301                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5302                let insertion = edits.iter().find_map(|(range, text)| {
 5303                    let range = range.to_offset(&snapshot);
 5304                    if range.is_empty() && range.start == cursor_offset {
 5305                        Some(text)
 5306                    } else {
 5307                        None
 5308                    }
 5309                });
 5310
 5311                if let Some(text) = insertion {
 5312                    let mut partial_completion = text
 5313                        .chars()
 5314                        .by_ref()
 5315                        .take_while(|c| c.is_alphabetic())
 5316                        .collect::<String>();
 5317                    if partial_completion.is_empty() {
 5318                        partial_completion = text
 5319                            .chars()
 5320                            .by_ref()
 5321                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5322                            .collect::<String>();
 5323                    }
 5324
 5325                    cx.emit(EditorEvent::InputHandled {
 5326                        utf16_range_to_replace: None,
 5327                        text: partial_completion.clone().into(),
 5328                    });
 5329
 5330                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5331
 5332                    self.refresh_inline_completion(true, true, window, cx);
 5333                    cx.notify();
 5334                } else {
 5335                    self.accept_edit_prediction(&Default::default(), window, cx);
 5336                }
 5337            }
 5338        }
 5339    }
 5340
 5341    fn discard_inline_completion(
 5342        &mut self,
 5343        should_report_inline_completion_event: bool,
 5344        cx: &mut Context<Self>,
 5345    ) -> bool {
 5346        if should_report_inline_completion_event {
 5347            let completion_id = self
 5348                .active_inline_completion
 5349                .as_ref()
 5350                .and_then(|active_completion| active_completion.completion_id.clone());
 5351
 5352            self.report_inline_completion_event(completion_id, false, cx);
 5353        }
 5354
 5355        if let Some(provider) = self.edit_prediction_provider() {
 5356            provider.discard(cx);
 5357        }
 5358
 5359        self.take_active_inline_completion(cx)
 5360    }
 5361
 5362    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5363        let Some(provider) = self.edit_prediction_provider() else {
 5364            return;
 5365        };
 5366
 5367        let Some((_, buffer, _)) = self
 5368            .buffer
 5369            .read(cx)
 5370            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5371        else {
 5372            return;
 5373        };
 5374
 5375        let extension = buffer
 5376            .read(cx)
 5377            .file()
 5378            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5379
 5380        let event_type = match accepted {
 5381            true => "Edit Prediction Accepted",
 5382            false => "Edit Prediction Discarded",
 5383        };
 5384        telemetry::event!(
 5385            event_type,
 5386            provider = provider.name(),
 5387            prediction_id = id,
 5388            suggestion_accepted = accepted,
 5389            file_extension = extension,
 5390        );
 5391    }
 5392
 5393    pub fn has_active_inline_completion(&self) -> bool {
 5394        self.active_inline_completion.is_some()
 5395    }
 5396
 5397    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5398        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5399            return false;
 5400        };
 5401
 5402        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5403        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5404        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5405        true
 5406    }
 5407
 5408    /// Returns true when we're displaying the edit prediction popover below the cursor
 5409    /// like we are not previewing and the LSP autocomplete menu is visible
 5410    /// or we are in `when_holding_modifier` mode.
 5411    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5412        if self.edit_prediction_preview_is_active()
 5413            || !self.show_edit_predictions_in_menu()
 5414            || !self.edit_predictions_enabled()
 5415        {
 5416            return false;
 5417        }
 5418
 5419        if self.has_visible_completions_menu() {
 5420            return true;
 5421        }
 5422
 5423        has_completion && self.edit_prediction_requires_modifier()
 5424    }
 5425
 5426    fn handle_modifiers_changed(
 5427        &mut self,
 5428        modifiers: Modifiers,
 5429        position_map: &PositionMap,
 5430        window: &mut Window,
 5431        cx: &mut Context<Self>,
 5432    ) {
 5433        if self.show_edit_predictions_in_menu() {
 5434            self.update_edit_prediction_preview(&modifiers, window, cx);
 5435        }
 5436
 5437        self.update_selection_mode(&modifiers, position_map, window, cx);
 5438
 5439        let mouse_position = window.mouse_position();
 5440        if !position_map.text_hitbox.is_hovered(window) {
 5441            return;
 5442        }
 5443
 5444        self.update_hovered_link(
 5445            position_map.point_for_position(mouse_position),
 5446            &position_map.snapshot,
 5447            modifiers,
 5448            window,
 5449            cx,
 5450        )
 5451    }
 5452
 5453    fn update_selection_mode(
 5454        &mut self,
 5455        modifiers: &Modifiers,
 5456        position_map: &PositionMap,
 5457        window: &mut Window,
 5458        cx: &mut Context<Self>,
 5459    ) {
 5460        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5461            return;
 5462        }
 5463
 5464        let mouse_position = window.mouse_position();
 5465        let point_for_position = position_map.point_for_position(mouse_position);
 5466        let position = point_for_position.previous_valid;
 5467
 5468        self.select(
 5469            SelectPhase::BeginColumnar {
 5470                position,
 5471                reset: false,
 5472                goal_column: point_for_position.exact_unclipped.column(),
 5473            },
 5474            window,
 5475            cx,
 5476        );
 5477    }
 5478
 5479    fn update_edit_prediction_preview(
 5480        &mut self,
 5481        modifiers: &Modifiers,
 5482        window: &mut Window,
 5483        cx: &mut Context<Self>,
 5484    ) {
 5485        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5486        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5487            return;
 5488        };
 5489
 5490        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5491            if matches!(
 5492                self.edit_prediction_preview,
 5493                EditPredictionPreview::Inactive { .. }
 5494            ) {
 5495                self.edit_prediction_preview = EditPredictionPreview::Active {
 5496                    previous_scroll_position: None,
 5497                    since: Instant::now(),
 5498                };
 5499
 5500                self.update_visible_inline_completion(window, cx);
 5501                cx.notify();
 5502            }
 5503        } else if let EditPredictionPreview::Active {
 5504            previous_scroll_position,
 5505            since,
 5506        } = self.edit_prediction_preview
 5507        {
 5508            if let (Some(previous_scroll_position), Some(position_map)) =
 5509                (previous_scroll_position, self.last_position_map.as_ref())
 5510            {
 5511                self.set_scroll_position(
 5512                    previous_scroll_position
 5513                        .scroll_position(&position_map.snapshot.display_snapshot),
 5514                    window,
 5515                    cx,
 5516                );
 5517            }
 5518
 5519            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 5520                released_too_fast: since.elapsed() < Duration::from_millis(200),
 5521            };
 5522            self.clear_row_highlights::<EditPredictionPreview>();
 5523            self.update_visible_inline_completion(window, cx);
 5524            cx.notify();
 5525        }
 5526    }
 5527
 5528    fn update_visible_inline_completion(
 5529        &mut self,
 5530        _window: &mut Window,
 5531        cx: &mut Context<Self>,
 5532    ) -> Option<()> {
 5533        let selection = self.selections.newest_anchor();
 5534        let cursor = selection.head();
 5535        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5536        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5537        let excerpt_id = cursor.excerpt_id;
 5538
 5539        let show_in_menu = self.show_edit_predictions_in_menu();
 5540        let completions_menu_has_precedence = !show_in_menu
 5541            && (self.context_menu.borrow().is_some()
 5542                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5543
 5544        if completions_menu_has_precedence
 5545            || !offset_selection.is_empty()
 5546            || self
 5547                .active_inline_completion
 5548                .as_ref()
 5549                .map_or(false, |completion| {
 5550                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5551                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5552                    !invalidation_range.contains(&offset_selection.head())
 5553                })
 5554        {
 5555            self.discard_inline_completion(false, cx);
 5556            return None;
 5557        }
 5558
 5559        self.take_active_inline_completion(cx);
 5560        let Some(provider) = self.edit_prediction_provider() else {
 5561            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5562            return None;
 5563        };
 5564
 5565        let (buffer, cursor_buffer_position) =
 5566            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5567
 5568        self.edit_prediction_settings =
 5569            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5570
 5571        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 5572
 5573        if self.edit_prediction_indent_conflict {
 5574            let cursor_point = cursor.to_point(&multibuffer);
 5575
 5576            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 5577
 5578            if let Some((_, indent)) = indents.iter().next() {
 5579                if indent.len == cursor_point.column {
 5580                    self.edit_prediction_indent_conflict = false;
 5581                }
 5582            }
 5583        }
 5584
 5585        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5586        let edits = inline_completion
 5587            .edits
 5588            .into_iter()
 5589            .flat_map(|(range, new_text)| {
 5590                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5591                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5592                Some((start..end, new_text))
 5593            })
 5594            .collect::<Vec<_>>();
 5595        if edits.is_empty() {
 5596            return None;
 5597        }
 5598
 5599        let first_edit_start = edits.first().unwrap().0.start;
 5600        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5601        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5602
 5603        let last_edit_end = edits.last().unwrap().0.end;
 5604        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5605        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5606
 5607        let cursor_row = cursor.to_point(&multibuffer).row;
 5608
 5609        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5610
 5611        let mut inlay_ids = Vec::new();
 5612        let invalidation_row_range;
 5613        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5614            Some(cursor_row..edit_end_row)
 5615        } else if cursor_row > edit_end_row {
 5616            Some(edit_start_row..cursor_row)
 5617        } else {
 5618            None
 5619        };
 5620        let is_move =
 5621            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5622        let completion = if is_move {
 5623            invalidation_row_range =
 5624                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5625            let target = first_edit_start;
 5626            InlineCompletion::Move { target, snapshot }
 5627        } else {
 5628            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5629                && !self.inline_completions_hidden_for_vim_mode;
 5630
 5631            if show_completions_in_buffer {
 5632                if edits
 5633                    .iter()
 5634                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5635                {
 5636                    let mut inlays = Vec::new();
 5637                    for (range, new_text) in &edits {
 5638                        let inlay = Inlay::inline_completion(
 5639                            post_inc(&mut self.next_inlay_id),
 5640                            range.start,
 5641                            new_text.as_str(),
 5642                        );
 5643                        inlay_ids.push(inlay.id);
 5644                        inlays.push(inlay);
 5645                    }
 5646
 5647                    self.splice_inlays(&[], inlays, cx);
 5648                } else {
 5649                    let background_color = cx.theme().status().deleted_background;
 5650                    self.highlight_text::<InlineCompletionHighlight>(
 5651                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5652                        HighlightStyle {
 5653                            background_color: Some(background_color),
 5654                            ..Default::default()
 5655                        },
 5656                        cx,
 5657                    );
 5658                }
 5659            }
 5660
 5661            invalidation_row_range = edit_start_row..edit_end_row;
 5662
 5663            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5664                if provider.show_tab_accept_marker() {
 5665                    EditDisplayMode::TabAccept
 5666                } else {
 5667                    EditDisplayMode::Inline
 5668                }
 5669            } else {
 5670                EditDisplayMode::DiffPopover
 5671            };
 5672
 5673            InlineCompletion::Edit {
 5674                edits,
 5675                edit_preview: inline_completion.edit_preview,
 5676                display_mode,
 5677                snapshot,
 5678            }
 5679        };
 5680
 5681        let invalidation_range = multibuffer
 5682            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5683            ..multibuffer.anchor_after(Point::new(
 5684                invalidation_row_range.end,
 5685                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5686            ));
 5687
 5688        self.stale_inline_completion_in_menu = None;
 5689        self.active_inline_completion = Some(InlineCompletionState {
 5690            inlay_ids,
 5691            completion,
 5692            completion_id: inline_completion.id,
 5693            invalidation_range,
 5694        });
 5695
 5696        cx.notify();
 5697
 5698        Some(())
 5699    }
 5700
 5701    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5702        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5703    }
 5704
 5705    fn render_code_actions_indicator(
 5706        &self,
 5707        _style: &EditorStyle,
 5708        row: DisplayRow,
 5709        is_active: bool,
 5710        cx: &mut Context<Self>,
 5711    ) -> Option<IconButton> {
 5712        if self.available_code_actions.is_some() {
 5713            Some(
 5714                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5715                    .shape(ui::IconButtonShape::Square)
 5716                    .icon_size(IconSize::XSmall)
 5717                    .icon_color(Color::Muted)
 5718                    .toggle_state(is_active)
 5719                    .tooltip({
 5720                        let focus_handle = self.focus_handle.clone();
 5721                        move |window, cx| {
 5722                            Tooltip::for_action_in(
 5723                                "Toggle Code Actions",
 5724                                &ToggleCodeActions {
 5725                                    deployed_from_indicator: None,
 5726                                },
 5727                                &focus_handle,
 5728                                window,
 5729                                cx,
 5730                            )
 5731                        }
 5732                    })
 5733                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5734                        window.focus(&editor.focus_handle(cx));
 5735                        editor.toggle_code_actions(
 5736                            &ToggleCodeActions {
 5737                                deployed_from_indicator: Some(row),
 5738                            },
 5739                            window,
 5740                            cx,
 5741                        );
 5742                    })),
 5743            )
 5744        } else {
 5745            None
 5746        }
 5747    }
 5748
 5749    fn clear_tasks(&mut self) {
 5750        self.tasks.clear()
 5751    }
 5752
 5753    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5754        if self.tasks.insert(key, value).is_some() {
 5755            // This case should hopefully be rare, but just in case...
 5756            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5757        }
 5758    }
 5759
 5760    fn build_tasks_context(
 5761        project: &Entity<Project>,
 5762        buffer: &Entity<Buffer>,
 5763        buffer_row: u32,
 5764        tasks: &Arc<RunnableTasks>,
 5765        cx: &mut Context<Self>,
 5766    ) -> Task<Option<task::TaskContext>> {
 5767        let position = Point::new(buffer_row, tasks.column);
 5768        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5769        let location = Location {
 5770            buffer: buffer.clone(),
 5771            range: range_start..range_start,
 5772        };
 5773        // Fill in the environmental variables from the tree-sitter captures
 5774        let mut captured_task_variables = TaskVariables::default();
 5775        for (capture_name, value) in tasks.extra_variables.clone() {
 5776            captured_task_variables.insert(
 5777                task::VariableName::Custom(capture_name.into()),
 5778                value.clone(),
 5779            );
 5780        }
 5781        project.update(cx, |project, cx| {
 5782            project.task_store().update(cx, |task_store, cx| {
 5783                task_store.task_context_for_location(captured_task_variables, location, cx)
 5784            })
 5785        })
 5786    }
 5787
 5788    pub fn spawn_nearest_task(
 5789        &mut self,
 5790        action: &SpawnNearestTask,
 5791        window: &mut Window,
 5792        cx: &mut Context<Self>,
 5793    ) {
 5794        let Some((workspace, _)) = self.workspace.clone() else {
 5795            return;
 5796        };
 5797        let Some(project) = self.project.clone() else {
 5798            return;
 5799        };
 5800
 5801        // Try to find a closest, enclosing node using tree-sitter that has a
 5802        // task
 5803        let Some((buffer, buffer_row, tasks)) = self
 5804            .find_enclosing_node_task(cx)
 5805            // Or find the task that's closest in row-distance.
 5806            .or_else(|| self.find_closest_task(cx))
 5807        else {
 5808            return;
 5809        };
 5810
 5811        let reveal_strategy = action.reveal;
 5812        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5813        cx.spawn_in(window, |_, mut cx| async move {
 5814            let context = task_context.await?;
 5815            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5816
 5817            let resolved = resolved_task.resolved.as_mut()?;
 5818            resolved.reveal = reveal_strategy;
 5819
 5820            workspace
 5821                .update(&mut cx, |workspace, cx| {
 5822                    workspace::tasks::schedule_resolved_task(
 5823                        workspace,
 5824                        task_source_kind,
 5825                        resolved_task,
 5826                        false,
 5827                        cx,
 5828                    );
 5829                })
 5830                .ok()
 5831        })
 5832        .detach();
 5833    }
 5834
 5835    fn find_closest_task(
 5836        &mut self,
 5837        cx: &mut Context<Self>,
 5838    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5839        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5840
 5841        let ((buffer_id, row), tasks) = self
 5842            .tasks
 5843            .iter()
 5844            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5845
 5846        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5847        let tasks = Arc::new(tasks.to_owned());
 5848        Some((buffer, *row, tasks))
 5849    }
 5850
 5851    fn find_enclosing_node_task(
 5852        &mut self,
 5853        cx: &mut Context<Self>,
 5854    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5855        let snapshot = self.buffer.read(cx).snapshot(cx);
 5856        let offset = self.selections.newest::<usize>(cx).head();
 5857        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5858        let buffer_id = excerpt.buffer().remote_id();
 5859
 5860        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5861        let mut cursor = layer.node().walk();
 5862
 5863        while cursor.goto_first_child_for_byte(offset).is_some() {
 5864            if cursor.node().end_byte() == offset {
 5865                cursor.goto_next_sibling();
 5866            }
 5867        }
 5868
 5869        // Ascend to the smallest ancestor that contains the range and has a task.
 5870        loop {
 5871            let node = cursor.node();
 5872            let node_range = node.byte_range();
 5873            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5874
 5875            // Check if this node contains our offset
 5876            if node_range.start <= offset && node_range.end >= offset {
 5877                // If it contains offset, check for task
 5878                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5879                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5880                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5881                }
 5882            }
 5883
 5884            if !cursor.goto_parent() {
 5885                break;
 5886            }
 5887        }
 5888        None
 5889    }
 5890
 5891    fn render_run_indicator(
 5892        &self,
 5893        _style: &EditorStyle,
 5894        is_active: bool,
 5895        row: DisplayRow,
 5896        cx: &mut Context<Self>,
 5897    ) -> IconButton {
 5898        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5899            .shape(ui::IconButtonShape::Square)
 5900            .icon_size(IconSize::XSmall)
 5901            .icon_color(Color::Muted)
 5902            .toggle_state(is_active)
 5903            .on_click(cx.listener(move |editor, _e, window, cx| {
 5904                window.focus(&editor.focus_handle(cx));
 5905                editor.toggle_code_actions(
 5906                    &ToggleCodeActions {
 5907                        deployed_from_indicator: Some(row),
 5908                    },
 5909                    window,
 5910                    cx,
 5911                );
 5912            }))
 5913    }
 5914
 5915    pub fn context_menu_visible(&self) -> bool {
 5916        !self.edit_prediction_preview_is_active()
 5917            && self
 5918                .context_menu
 5919                .borrow()
 5920                .as_ref()
 5921                .map_or(false, |menu| menu.visible())
 5922    }
 5923
 5924    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5925        self.context_menu
 5926            .borrow()
 5927            .as_ref()
 5928            .map(|menu| menu.origin())
 5929    }
 5930
 5931    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 5932    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 5933
 5934    fn render_edit_prediction_popover(
 5935        &mut self,
 5936        text_bounds: &Bounds<Pixels>,
 5937        content_origin: gpui::Point<Pixels>,
 5938        editor_snapshot: &EditorSnapshot,
 5939        visible_row_range: Range<DisplayRow>,
 5940        scroll_top: f32,
 5941        scroll_bottom: f32,
 5942        line_layouts: &[LineWithInvisibles],
 5943        line_height: Pixels,
 5944        scroll_pixel_position: gpui::Point<Pixels>,
 5945        newest_selection_head: Option<DisplayPoint>,
 5946        editor_width: Pixels,
 5947        style: &EditorStyle,
 5948        window: &mut Window,
 5949        cx: &mut App,
 5950    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5951        let active_inline_completion = self.active_inline_completion.as_ref()?;
 5952
 5953        if self.edit_prediction_visible_in_cursor_popover(true) {
 5954            return None;
 5955        }
 5956
 5957        match &active_inline_completion.completion {
 5958            InlineCompletion::Move { target, .. } => {
 5959                let target_display_point = target.to_display_point(editor_snapshot);
 5960
 5961                if self.edit_prediction_requires_modifier() {
 5962                    if !self.edit_prediction_preview_is_active() {
 5963                        return None;
 5964                    }
 5965
 5966                    self.render_edit_prediction_modifier_jump_popover(
 5967                        text_bounds,
 5968                        content_origin,
 5969                        visible_row_range,
 5970                        line_layouts,
 5971                        line_height,
 5972                        scroll_pixel_position,
 5973                        newest_selection_head,
 5974                        target_display_point,
 5975                        window,
 5976                        cx,
 5977                    )
 5978                } else {
 5979                    self.render_edit_prediction_eager_jump_popover(
 5980                        text_bounds,
 5981                        content_origin,
 5982                        editor_snapshot,
 5983                        visible_row_range,
 5984                        scroll_top,
 5985                        scroll_bottom,
 5986                        line_height,
 5987                        scroll_pixel_position,
 5988                        target_display_point,
 5989                        editor_width,
 5990                        window,
 5991                        cx,
 5992                    )
 5993                }
 5994            }
 5995            InlineCompletion::Edit {
 5996                display_mode: EditDisplayMode::Inline,
 5997                ..
 5998            } => None,
 5999            InlineCompletion::Edit {
 6000                display_mode: EditDisplayMode::TabAccept,
 6001                edits,
 6002                ..
 6003            } => {
 6004                let range = &edits.first()?.0;
 6005                let target_display_point = range.end.to_display_point(editor_snapshot);
 6006
 6007                self.render_edit_prediction_end_of_line_popover(
 6008                    "Accept",
 6009                    editor_snapshot,
 6010                    visible_row_range,
 6011                    target_display_point,
 6012                    line_height,
 6013                    scroll_pixel_position,
 6014                    content_origin,
 6015                    editor_width,
 6016                    window,
 6017                    cx,
 6018                )
 6019            }
 6020            InlineCompletion::Edit {
 6021                edits,
 6022                edit_preview,
 6023                display_mode: EditDisplayMode::DiffPopover,
 6024                snapshot,
 6025            } => self.render_edit_prediction_diff_popover(
 6026                text_bounds,
 6027                content_origin,
 6028                editor_snapshot,
 6029                visible_row_range,
 6030                line_layouts,
 6031                line_height,
 6032                scroll_pixel_position,
 6033                newest_selection_head,
 6034                editor_width,
 6035                style,
 6036                edits,
 6037                edit_preview,
 6038                snapshot,
 6039                window,
 6040                cx,
 6041            ),
 6042        }
 6043    }
 6044
 6045    fn render_edit_prediction_modifier_jump_popover(
 6046        &mut self,
 6047        text_bounds: &Bounds<Pixels>,
 6048        content_origin: gpui::Point<Pixels>,
 6049        visible_row_range: Range<DisplayRow>,
 6050        line_layouts: &[LineWithInvisibles],
 6051        line_height: Pixels,
 6052        scroll_pixel_position: gpui::Point<Pixels>,
 6053        newest_selection_head: Option<DisplayPoint>,
 6054        target_display_point: DisplayPoint,
 6055        window: &mut Window,
 6056        cx: &mut App,
 6057    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6058        let scrolled_content_origin =
 6059            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 6060
 6061        const SCROLL_PADDING_Y: Pixels = px(12.);
 6062
 6063        if target_display_point.row() < visible_row_range.start {
 6064            return self.render_edit_prediction_scroll_popover(
 6065                |_| SCROLL_PADDING_Y,
 6066                IconName::ArrowUp,
 6067                visible_row_range,
 6068                line_layouts,
 6069                newest_selection_head,
 6070                scrolled_content_origin,
 6071                window,
 6072                cx,
 6073            );
 6074        } else if target_display_point.row() >= visible_row_range.end {
 6075            return self.render_edit_prediction_scroll_popover(
 6076                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 6077                IconName::ArrowDown,
 6078                visible_row_range,
 6079                line_layouts,
 6080                newest_selection_head,
 6081                scrolled_content_origin,
 6082                window,
 6083                cx,
 6084            );
 6085        }
 6086
 6087        const POLE_WIDTH: Pixels = px(2.);
 6088
 6089        let line_layout =
 6090            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 6091        let target_column = target_display_point.column() as usize;
 6092
 6093        let target_x = line_layout.x_for_index(target_column);
 6094        let target_y =
 6095            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 6096
 6097        let flag_on_right = target_x < text_bounds.size.width / 2.;
 6098
 6099        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 6100        border_color.l += 0.001;
 6101
 6102        let mut element = v_flex()
 6103            .items_end()
 6104            .when(flag_on_right, |el| el.items_start())
 6105            .child(if flag_on_right {
 6106                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6107                    .rounded_bl(px(0.))
 6108                    .rounded_tl(px(0.))
 6109                    .border_l_2()
 6110                    .border_color(border_color)
 6111            } else {
 6112                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6113                    .rounded_br(px(0.))
 6114                    .rounded_tr(px(0.))
 6115                    .border_r_2()
 6116                    .border_color(border_color)
 6117            })
 6118            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 6119            .into_any();
 6120
 6121        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6122
 6123        let mut origin = scrolled_content_origin + point(target_x, target_y)
 6124            - point(
 6125                if flag_on_right {
 6126                    POLE_WIDTH
 6127                } else {
 6128                    size.width - POLE_WIDTH
 6129                },
 6130                size.height - line_height,
 6131            );
 6132
 6133        origin.x = origin.x.max(content_origin.x);
 6134
 6135        element.prepaint_at(origin, window, cx);
 6136
 6137        Some((element, origin))
 6138    }
 6139
 6140    fn render_edit_prediction_scroll_popover(
 6141        &mut self,
 6142        to_y: impl Fn(Size<Pixels>) -> Pixels,
 6143        scroll_icon: IconName,
 6144        visible_row_range: Range<DisplayRow>,
 6145        line_layouts: &[LineWithInvisibles],
 6146        newest_selection_head: Option<DisplayPoint>,
 6147        scrolled_content_origin: gpui::Point<Pixels>,
 6148        window: &mut Window,
 6149        cx: &mut App,
 6150    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6151        let mut element = self
 6152            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 6153            .into_any();
 6154
 6155        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6156
 6157        let cursor = newest_selection_head?;
 6158        let cursor_row_layout =
 6159            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6160        let cursor_column = cursor.column() as usize;
 6161
 6162        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6163
 6164        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6165
 6166        element.prepaint_at(origin, window, cx);
 6167        Some((element, origin))
 6168    }
 6169
 6170    fn render_edit_prediction_eager_jump_popover(
 6171        &mut self,
 6172        text_bounds: &Bounds<Pixels>,
 6173        content_origin: gpui::Point<Pixels>,
 6174        editor_snapshot: &EditorSnapshot,
 6175        visible_row_range: Range<DisplayRow>,
 6176        scroll_top: f32,
 6177        scroll_bottom: f32,
 6178        line_height: Pixels,
 6179        scroll_pixel_position: gpui::Point<Pixels>,
 6180        target_display_point: DisplayPoint,
 6181        editor_width: Pixels,
 6182        window: &mut Window,
 6183        cx: &mut App,
 6184    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6185        if target_display_point.row().as_f32() < scroll_top {
 6186            let mut element = self
 6187                .render_edit_prediction_line_popover(
 6188                    "Jump to Edit",
 6189                    Some(IconName::ArrowUp),
 6190                    window,
 6191                    cx,
 6192                )?
 6193                .into_any();
 6194
 6195            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6196            let offset = point(
 6197                (text_bounds.size.width - size.width) / 2.,
 6198                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6199            );
 6200
 6201            let origin = text_bounds.origin + offset;
 6202            element.prepaint_at(origin, window, cx);
 6203            Some((element, origin))
 6204        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6205            let mut element = self
 6206                .render_edit_prediction_line_popover(
 6207                    "Jump to Edit",
 6208                    Some(IconName::ArrowDown),
 6209                    window,
 6210                    cx,
 6211                )?
 6212                .into_any();
 6213
 6214            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6215            let offset = point(
 6216                (text_bounds.size.width - size.width) / 2.,
 6217                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6218            );
 6219
 6220            let origin = text_bounds.origin + offset;
 6221            element.prepaint_at(origin, window, cx);
 6222            Some((element, origin))
 6223        } else {
 6224            self.render_edit_prediction_end_of_line_popover(
 6225                "Jump to Edit",
 6226                editor_snapshot,
 6227                visible_row_range,
 6228                target_display_point,
 6229                line_height,
 6230                scroll_pixel_position,
 6231                content_origin,
 6232                editor_width,
 6233                window,
 6234                cx,
 6235            )
 6236        }
 6237    }
 6238
 6239    fn render_edit_prediction_end_of_line_popover(
 6240        self: &mut Editor,
 6241        label: &'static str,
 6242        editor_snapshot: &EditorSnapshot,
 6243        visible_row_range: Range<DisplayRow>,
 6244        target_display_point: DisplayPoint,
 6245        line_height: Pixels,
 6246        scroll_pixel_position: gpui::Point<Pixels>,
 6247        content_origin: gpui::Point<Pixels>,
 6248        editor_width: Pixels,
 6249        window: &mut Window,
 6250        cx: &mut App,
 6251    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6252        let target_line_end = DisplayPoint::new(
 6253            target_display_point.row(),
 6254            editor_snapshot.line_len(target_display_point.row()),
 6255        );
 6256
 6257        let mut element = self
 6258            .render_edit_prediction_line_popover(label, None, window, cx)?
 6259            .into_any();
 6260
 6261        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6262
 6263        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 6264
 6265        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 6266        let mut origin = start_point
 6267            + line_origin
 6268            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 6269        origin.x = origin.x.max(content_origin.x);
 6270
 6271        let max_x = content_origin.x + editor_width - size.width;
 6272
 6273        if origin.x > max_x {
 6274            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 6275
 6276            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 6277                origin.y += offset;
 6278                IconName::ArrowUp
 6279            } else {
 6280                origin.y -= offset;
 6281                IconName::ArrowDown
 6282            };
 6283
 6284            element = self
 6285                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 6286                .into_any();
 6287
 6288            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6289
 6290            origin.x = content_origin.x + editor_width - size.width - px(2.);
 6291        }
 6292
 6293        element.prepaint_at(origin, window, cx);
 6294        Some((element, origin))
 6295    }
 6296
 6297    fn render_edit_prediction_diff_popover(
 6298        self: &Editor,
 6299        text_bounds: &Bounds<Pixels>,
 6300        content_origin: gpui::Point<Pixels>,
 6301        editor_snapshot: &EditorSnapshot,
 6302        visible_row_range: Range<DisplayRow>,
 6303        line_layouts: &[LineWithInvisibles],
 6304        line_height: Pixels,
 6305        scroll_pixel_position: gpui::Point<Pixels>,
 6306        newest_selection_head: Option<DisplayPoint>,
 6307        editor_width: Pixels,
 6308        style: &EditorStyle,
 6309        edits: &Vec<(Range<Anchor>, String)>,
 6310        edit_preview: &Option<language::EditPreview>,
 6311        snapshot: &language::BufferSnapshot,
 6312        window: &mut Window,
 6313        cx: &mut App,
 6314    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6315        let edit_start = edits
 6316            .first()
 6317            .unwrap()
 6318            .0
 6319            .start
 6320            .to_display_point(editor_snapshot);
 6321        let edit_end = edits
 6322            .last()
 6323            .unwrap()
 6324            .0
 6325            .end
 6326            .to_display_point(editor_snapshot);
 6327
 6328        let is_visible = visible_row_range.contains(&edit_start.row())
 6329            || visible_row_range.contains(&edit_end.row());
 6330        if !is_visible {
 6331            return None;
 6332        }
 6333
 6334        let highlighted_edits =
 6335            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 6336
 6337        let styled_text = highlighted_edits.to_styled_text(&style.text);
 6338        let line_count = highlighted_edits.text.lines().count();
 6339
 6340        const BORDER_WIDTH: Pixels = px(1.);
 6341
 6342        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 6343        let has_keybind = keybind.is_some();
 6344
 6345        let mut element = h_flex()
 6346            .items_start()
 6347            .child(
 6348                h_flex()
 6349                    .bg(cx.theme().colors().editor_background)
 6350                    .border(BORDER_WIDTH)
 6351                    .shadow_sm()
 6352                    .border_color(cx.theme().colors().border)
 6353                    .rounded_l_lg()
 6354                    .when(line_count > 1, |el| el.rounded_br_lg())
 6355                    .pr_1()
 6356                    .child(styled_text),
 6357            )
 6358            .child(
 6359                h_flex()
 6360                    .h(line_height + BORDER_WIDTH * px(2.))
 6361                    .px_1p5()
 6362                    .gap_1()
 6363                    // Workaround: For some reason, there's a gap if we don't do this
 6364                    .ml(-BORDER_WIDTH)
 6365                    .shadow(smallvec![gpui::BoxShadow {
 6366                        color: gpui::black().opacity(0.05),
 6367                        offset: point(px(1.), px(1.)),
 6368                        blur_radius: px(2.),
 6369                        spread_radius: px(0.),
 6370                    }])
 6371                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 6372                    .border(BORDER_WIDTH)
 6373                    .border_color(cx.theme().colors().border)
 6374                    .rounded_r_lg()
 6375                    .id("edit_prediction_diff_popover_keybind")
 6376                    .when(!has_keybind, |el| {
 6377                        let status_colors = cx.theme().status();
 6378
 6379                        el.bg(status_colors.error_background)
 6380                            .border_color(status_colors.error.opacity(0.6))
 6381                            .child(Icon::new(IconName::Info).color(Color::Error))
 6382                            .cursor_default()
 6383                            .hoverable_tooltip(move |_window, cx| {
 6384                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 6385                            })
 6386                    })
 6387                    .children(keybind),
 6388            )
 6389            .into_any();
 6390
 6391        let longest_row =
 6392            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 6393        let longest_line_width = if visible_row_range.contains(&longest_row) {
 6394            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 6395        } else {
 6396            layout_line(
 6397                longest_row,
 6398                editor_snapshot,
 6399                style,
 6400                editor_width,
 6401                |_| false,
 6402                window,
 6403                cx,
 6404            )
 6405            .width
 6406        };
 6407
 6408        let viewport_bounds =
 6409            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 6410                right: -EditorElement::SCROLLBAR_WIDTH,
 6411                ..Default::default()
 6412            });
 6413
 6414        let x_after_longest =
 6415            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 6416                - scroll_pixel_position.x;
 6417
 6418        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6419
 6420        // Fully visible if it can be displayed within the window (allow overlapping other
 6421        // panes). However, this is only allowed if the popover starts within text_bounds.
 6422        let can_position_to_the_right = x_after_longest < text_bounds.right()
 6423            && x_after_longest + element_bounds.width < viewport_bounds.right();
 6424
 6425        let mut origin = if can_position_to_the_right {
 6426            point(
 6427                x_after_longest,
 6428                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 6429                    - scroll_pixel_position.y,
 6430            )
 6431        } else {
 6432            let cursor_row = newest_selection_head.map(|head| head.row());
 6433            let above_edit = edit_start
 6434                .row()
 6435                .0
 6436                .checked_sub(line_count as u32)
 6437                .map(DisplayRow);
 6438            let below_edit = Some(edit_end.row() + 1);
 6439            let above_cursor =
 6440                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 6441            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 6442
 6443            // Place the edit popover adjacent to the edit if there is a location
 6444            // available that is onscreen and does not obscure the cursor. Otherwise,
 6445            // place it adjacent to the cursor.
 6446            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 6447                .into_iter()
 6448                .flatten()
 6449                .find(|&start_row| {
 6450                    let end_row = start_row + line_count as u32;
 6451                    visible_row_range.contains(&start_row)
 6452                        && visible_row_range.contains(&end_row)
 6453                        && cursor_row.map_or(true, |cursor_row| {
 6454                            !((start_row..end_row).contains(&cursor_row))
 6455                        })
 6456                })?;
 6457
 6458            content_origin
 6459                + point(
 6460                    -scroll_pixel_position.x,
 6461                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 6462                )
 6463        };
 6464
 6465        origin.x -= BORDER_WIDTH;
 6466
 6467        window.defer_draw(element, origin, 1);
 6468
 6469        // Do not return an element, since it will already be drawn due to defer_draw.
 6470        None
 6471    }
 6472
 6473    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 6474        px(30.)
 6475    }
 6476
 6477    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 6478        if self.read_only(cx) {
 6479            cx.theme().players().read_only()
 6480        } else {
 6481            self.style.as_ref().unwrap().local_player
 6482        }
 6483    }
 6484
 6485    fn render_edit_prediction_accept_keybind(
 6486        &self,
 6487        window: &mut Window,
 6488        cx: &App,
 6489    ) -> Option<AnyElement> {
 6490        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 6491        let accept_keystroke = accept_binding.keystroke()?;
 6492
 6493        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6494
 6495        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 6496            Color::Accent
 6497        } else {
 6498            Color::Muted
 6499        };
 6500
 6501        h_flex()
 6502            .px_0p5()
 6503            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 6504            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6505            .text_size(TextSize::XSmall.rems(cx))
 6506            .child(h_flex().children(ui::render_modifiers(
 6507                &accept_keystroke.modifiers,
 6508                PlatformStyle::platform(),
 6509                Some(modifiers_color),
 6510                Some(IconSize::XSmall.rems().into()),
 6511                true,
 6512            )))
 6513            .when(is_platform_style_mac, |parent| {
 6514                parent.child(accept_keystroke.key.clone())
 6515            })
 6516            .when(!is_platform_style_mac, |parent| {
 6517                parent.child(
 6518                    Key::new(
 6519                        util::capitalize(&accept_keystroke.key),
 6520                        Some(Color::Default),
 6521                    )
 6522                    .size(Some(IconSize::XSmall.rems().into())),
 6523                )
 6524            })
 6525            .into_any()
 6526            .into()
 6527    }
 6528
 6529    fn render_edit_prediction_line_popover(
 6530        &self,
 6531        label: impl Into<SharedString>,
 6532        icon: Option<IconName>,
 6533        window: &mut Window,
 6534        cx: &App,
 6535    ) -> Option<Stateful<Div>> {
 6536        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 6537
 6538        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 6539        let has_keybind = keybind.is_some();
 6540
 6541        let result = h_flex()
 6542            .id("ep-line-popover")
 6543            .py_0p5()
 6544            .pl_1()
 6545            .pr(padding_right)
 6546            .gap_1()
 6547            .rounded_md()
 6548            .border_1()
 6549            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6550            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 6551            .shadow_sm()
 6552            .when(!has_keybind, |el| {
 6553                let status_colors = cx.theme().status();
 6554
 6555                el.bg(status_colors.error_background)
 6556                    .border_color(status_colors.error.opacity(0.6))
 6557                    .pl_2()
 6558                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 6559                    .cursor_default()
 6560                    .hoverable_tooltip(move |_window, cx| {
 6561                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 6562                    })
 6563            })
 6564            .children(keybind)
 6565            .child(
 6566                Label::new(label)
 6567                    .size(LabelSize::Small)
 6568                    .when(!has_keybind, |el| {
 6569                        el.color(cx.theme().status().error.into()).strikethrough()
 6570                    }),
 6571            )
 6572            .when(!has_keybind, |el| {
 6573                el.child(
 6574                    h_flex().ml_1().child(
 6575                        Icon::new(IconName::Info)
 6576                            .size(IconSize::Small)
 6577                            .color(cx.theme().status().error.into()),
 6578                    ),
 6579                )
 6580            })
 6581            .when_some(icon, |element, icon| {
 6582                element.child(
 6583                    div()
 6584                        .mt(px(1.5))
 6585                        .child(Icon::new(icon).size(IconSize::Small)),
 6586                )
 6587            });
 6588
 6589        Some(result)
 6590    }
 6591
 6592    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 6593        let accent_color = cx.theme().colors().text_accent;
 6594        let editor_bg_color = cx.theme().colors().editor_background;
 6595        editor_bg_color.blend(accent_color.opacity(0.1))
 6596    }
 6597
 6598    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 6599        let accent_color = cx.theme().colors().text_accent;
 6600        let editor_bg_color = cx.theme().colors().editor_background;
 6601        editor_bg_color.blend(accent_color.opacity(0.6))
 6602    }
 6603
 6604    fn render_edit_prediction_cursor_popover(
 6605        &self,
 6606        min_width: Pixels,
 6607        max_width: Pixels,
 6608        cursor_point: Point,
 6609        style: &EditorStyle,
 6610        accept_keystroke: Option<&gpui::Keystroke>,
 6611        _window: &Window,
 6612        cx: &mut Context<Editor>,
 6613    ) -> Option<AnyElement> {
 6614        let provider = self.edit_prediction_provider.as_ref()?;
 6615
 6616        if provider.provider.needs_terms_acceptance(cx) {
 6617            return Some(
 6618                h_flex()
 6619                    .min_w(min_width)
 6620                    .flex_1()
 6621                    .px_2()
 6622                    .py_1()
 6623                    .gap_3()
 6624                    .elevation_2(cx)
 6625                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 6626                    .id("accept-terms")
 6627                    .cursor_pointer()
 6628                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 6629                    .on_click(cx.listener(|this, _event, window, cx| {
 6630                        cx.stop_propagation();
 6631                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 6632                        window.dispatch_action(
 6633                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 6634                            cx,
 6635                        );
 6636                    }))
 6637                    .child(
 6638                        h_flex()
 6639                            .flex_1()
 6640                            .gap_2()
 6641                            .child(Icon::new(IconName::ZedPredict))
 6642                            .child(Label::new("Accept Terms of Service"))
 6643                            .child(div().w_full())
 6644                            .child(
 6645                                Icon::new(IconName::ArrowUpRight)
 6646                                    .color(Color::Muted)
 6647                                    .size(IconSize::Small),
 6648                            )
 6649                            .into_any_element(),
 6650                    )
 6651                    .into_any(),
 6652            );
 6653        }
 6654
 6655        let is_refreshing = provider.provider.is_refreshing(cx);
 6656
 6657        fn pending_completion_container() -> Div {
 6658            h_flex()
 6659                .h_full()
 6660                .flex_1()
 6661                .gap_2()
 6662                .child(Icon::new(IconName::ZedPredict))
 6663        }
 6664
 6665        let completion = match &self.active_inline_completion {
 6666            Some(prediction) => {
 6667                if !self.has_visible_completions_menu() {
 6668                    const RADIUS: Pixels = px(6.);
 6669                    const BORDER_WIDTH: Pixels = px(1.);
 6670
 6671                    return Some(
 6672                        h_flex()
 6673                            .elevation_2(cx)
 6674                            .border(BORDER_WIDTH)
 6675                            .border_color(cx.theme().colors().border)
 6676                            .when(accept_keystroke.is_none(), |el| {
 6677                                el.border_color(cx.theme().status().error)
 6678                            })
 6679                            .rounded(RADIUS)
 6680                            .rounded_tl(px(0.))
 6681                            .overflow_hidden()
 6682                            .child(div().px_1p5().child(match &prediction.completion {
 6683                                InlineCompletion::Move { target, snapshot } => {
 6684                                    use text::ToPoint as _;
 6685                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 6686                                    {
 6687                                        Icon::new(IconName::ZedPredictDown)
 6688                                    } else {
 6689                                        Icon::new(IconName::ZedPredictUp)
 6690                                    }
 6691                                }
 6692                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 6693                            }))
 6694                            .child(
 6695                                h_flex()
 6696                                    .gap_1()
 6697                                    .py_1()
 6698                                    .px_2()
 6699                                    .rounded_r(RADIUS - BORDER_WIDTH)
 6700                                    .border_l_1()
 6701                                    .border_color(cx.theme().colors().border)
 6702                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6703                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 6704                                        el.child(
 6705                                            Label::new("Hold")
 6706                                                .size(LabelSize::Small)
 6707                                                .when(accept_keystroke.is_none(), |el| {
 6708                                                    el.strikethrough()
 6709                                                })
 6710                                                .line_height_style(LineHeightStyle::UiLabel),
 6711                                        )
 6712                                    })
 6713                                    .id("edit_prediction_cursor_popover_keybind")
 6714                                    .when(accept_keystroke.is_none(), |el| {
 6715                                        let status_colors = cx.theme().status();
 6716
 6717                                        el.bg(status_colors.error_background)
 6718                                            .border_color(status_colors.error.opacity(0.6))
 6719                                            .child(Icon::new(IconName::Info).color(Color::Error))
 6720                                            .cursor_default()
 6721                                            .hoverable_tooltip(move |_window, cx| {
 6722                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 6723                                                    .into()
 6724                                            })
 6725                                    })
 6726                                    .when_some(
 6727                                        accept_keystroke.as_ref(),
 6728                                        |el, accept_keystroke| {
 6729                                            el.child(h_flex().children(ui::render_modifiers(
 6730                                                &accept_keystroke.modifiers,
 6731                                                PlatformStyle::platform(),
 6732                                                Some(Color::Default),
 6733                                                Some(IconSize::XSmall.rems().into()),
 6734                                                false,
 6735                                            )))
 6736                                        },
 6737                                    ),
 6738                            )
 6739                            .into_any(),
 6740                    );
 6741                }
 6742
 6743                self.render_edit_prediction_cursor_popover_preview(
 6744                    prediction,
 6745                    cursor_point,
 6746                    style,
 6747                    cx,
 6748                )?
 6749            }
 6750
 6751            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 6752                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 6753                    stale_completion,
 6754                    cursor_point,
 6755                    style,
 6756                    cx,
 6757                )?,
 6758
 6759                None => {
 6760                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6761                }
 6762            },
 6763
 6764            None => pending_completion_container().child(Label::new("No Prediction")),
 6765        };
 6766
 6767        let completion = if is_refreshing {
 6768            completion
 6769                .with_animation(
 6770                    "loading-completion",
 6771                    Animation::new(Duration::from_secs(2))
 6772                        .repeat()
 6773                        .with_easing(pulsating_between(0.4, 0.8)),
 6774                    |label, delta| label.opacity(delta),
 6775                )
 6776                .into_any_element()
 6777        } else {
 6778            completion.into_any_element()
 6779        };
 6780
 6781        let has_completion = self.active_inline_completion.is_some();
 6782
 6783        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6784        Some(
 6785            h_flex()
 6786                .min_w(min_width)
 6787                .max_w(max_width)
 6788                .flex_1()
 6789                .elevation_2(cx)
 6790                .border_color(cx.theme().colors().border)
 6791                .child(
 6792                    div()
 6793                        .flex_1()
 6794                        .py_1()
 6795                        .px_2()
 6796                        .overflow_hidden()
 6797                        .child(completion),
 6798                )
 6799                .when_some(accept_keystroke, |el, accept_keystroke| {
 6800                    if !accept_keystroke.modifiers.modified() {
 6801                        return el;
 6802                    }
 6803
 6804                    el.child(
 6805                        h_flex()
 6806                            .h_full()
 6807                            .border_l_1()
 6808                            .rounded_r_lg()
 6809                            .border_color(cx.theme().colors().border)
 6810                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6811                            .gap_1()
 6812                            .py_1()
 6813                            .px_2()
 6814                            .child(
 6815                                h_flex()
 6816                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6817                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6818                                    .child(h_flex().children(ui::render_modifiers(
 6819                                        &accept_keystroke.modifiers,
 6820                                        PlatformStyle::platform(),
 6821                                        Some(if !has_completion {
 6822                                            Color::Muted
 6823                                        } else {
 6824                                            Color::Default
 6825                                        }),
 6826                                        None,
 6827                                        false,
 6828                                    ))),
 6829                            )
 6830                            .child(Label::new("Preview").into_any_element())
 6831                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6832                    )
 6833                })
 6834                .into_any(),
 6835        )
 6836    }
 6837
 6838    fn render_edit_prediction_cursor_popover_preview(
 6839        &self,
 6840        completion: &InlineCompletionState,
 6841        cursor_point: Point,
 6842        style: &EditorStyle,
 6843        cx: &mut Context<Editor>,
 6844    ) -> Option<Div> {
 6845        use text::ToPoint as _;
 6846
 6847        fn render_relative_row_jump(
 6848            prefix: impl Into<String>,
 6849            current_row: u32,
 6850            target_row: u32,
 6851        ) -> Div {
 6852            let (row_diff, arrow) = if target_row < current_row {
 6853                (current_row - target_row, IconName::ArrowUp)
 6854            } else {
 6855                (target_row - current_row, IconName::ArrowDown)
 6856            };
 6857
 6858            h_flex()
 6859                .child(
 6860                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6861                        .color(Color::Muted)
 6862                        .size(LabelSize::Small),
 6863                )
 6864                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6865        }
 6866
 6867        match &completion.completion {
 6868            InlineCompletion::Move {
 6869                target, snapshot, ..
 6870            } => Some(
 6871                h_flex()
 6872                    .px_2()
 6873                    .gap_2()
 6874                    .flex_1()
 6875                    .child(
 6876                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6877                            Icon::new(IconName::ZedPredictDown)
 6878                        } else {
 6879                            Icon::new(IconName::ZedPredictUp)
 6880                        },
 6881                    )
 6882                    .child(Label::new("Jump to Edit")),
 6883            ),
 6884
 6885            InlineCompletion::Edit {
 6886                edits,
 6887                edit_preview,
 6888                snapshot,
 6889                display_mode: _,
 6890            } => {
 6891                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6892
 6893                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6894                    &snapshot,
 6895                    &edits,
 6896                    edit_preview.as_ref()?,
 6897                    true,
 6898                    cx,
 6899                )
 6900                .first_line_preview();
 6901
 6902                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6903                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 6904
 6905                let preview = h_flex()
 6906                    .gap_1()
 6907                    .min_w_16()
 6908                    .child(styled_text)
 6909                    .when(has_more_lines, |parent| parent.child(""));
 6910
 6911                let left = if first_edit_row != cursor_point.row {
 6912                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6913                        .into_any_element()
 6914                } else {
 6915                    Icon::new(IconName::ZedPredict).into_any_element()
 6916                };
 6917
 6918                Some(
 6919                    h_flex()
 6920                        .h_full()
 6921                        .flex_1()
 6922                        .gap_2()
 6923                        .pr_1()
 6924                        .overflow_x_hidden()
 6925                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6926                        .child(left)
 6927                        .child(preview),
 6928                )
 6929            }
 6930        }
 6931    }
 6932
 6933    fn render_context_menu(
 6934        &self,
 6935        style: &EditorStyle,
 6936        max_height_in_lines: u32,
 6937        y_flipped: bool,
 6938        window: &mut Window,
 6939        cx: &mut Context<Editor>,
 6940    ) -> Option<AnyElement> {
 6941        let menu = self.context_menu.borrow();
 6942        let menu = menu.as_ref()?;
 6943        if !menu.visible() {
 6944            return None;
 6945        };
 6946        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6947    }
 6948
 6949    fn render_context_menu_aside(
 6950        &mut self,
 6951        max_size: Size<Pixels>,
 6952        window: &mut Window,
 6953        cx: &mut Context<Editor>,
 6954    ) -> Option<AnyElement> {
 6955        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 6956            if menu.visible() {
 6957                menu.render_aside(self, max_size, window, cx)
 6958            } else {
 6959                None
 6960            }
 6961        })
 6962    }
 6963
 6964    fn hide_context_menu(
 6965        &mut self,
 6966        window: &mut Window,
 6967        cx: &mut Context<Self>,
 6968    ) -> Option<CodeContextMenu> {
 6969        cx.notify();
 6970        self.completion_tasks.clear();
 6971        let context_menu = self.context_menu.borrow_mut().take();
 6972        self.stale_inline_completion_in_menu.take();
 6973        self.update_visible_inline_completion(window, cx);
 6974        context_menu
 6975    }
 6976
 6977    fn show_snippet_choices(
 6978        &mut self,
 6979        choices: &Vec<String>,
 6980        selection: Range<Anchor>,
 6981        cx: &mut Context<Self>,
 6982    ) {
 6983        if selection.start.buffer_id.is_none() {
 6984            return;
 6985        }
 6986        let buffer_id = selection.start.buffer_id.unwrap();
 6987        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6988        let id = post_inc(&mut self.next_completion_id);
 6989
 6990        if let Some(buffer) = buffer {
 6991            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6992                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6993            ));
 6994        }
 6995    }
 6996
 6997    pub fn insert_snippet(
 6998        &mut self,
 6999        insertion_ranges: &[Range<usize>],
 7000        snippet: Snippet,
 7001        window: &mut Window,
 7002        cx: &mut Context<Self>,
 7003    ) -> Result<()> {
 7004        struct Tabstop<T> {
 7005            is_end_tabstop: bool,
 7006            ranges: Vec<Range<T>>,
 7007            choices: Option<Vec<String>>,
 7008        }
 7009
 7010        let tabstops = self.buffer.update(cx, |buffer, cx| {
 7011            let snippet_text: Arc<str> = snippet.text.clone().into();
 7012            buffer.edit(
 7013                insertion_ranges
 7014                    .iter()
 7015                    .cloned()
 7016                    .map(|range| (range, snippet_text.clone())),
 7017                Some(AutoindentMode::EachLine),
 7018                cx,
 7019            );
 7020
 7021            let snapshot = &*buffer.read(cx);
 7022            let snippet = &snippet;
 7023            snippet
 7024                .tabstops
 7025                .iter()
 7026                .map(|tabstop| {
 7027                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 7028                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 7029                    });
 7030                    let mut tabstop_ranges = tabstop
 7031                        .ranges
 7032                        .iter()
 7033                        .flat_map(|tabstop_range| {
 7034                            let mut delta = 0_isize;
 7035                            insertion_ranges.iter().map(move |insertion_range| {
 7036                                let insertion_start = insertion_range.start as isize + delta;
 7037                                delta +=
 7038                                    snippet.text.len() as isize - insertion_range.len() as isize;
 7039
 7040                                let start = ((insertion_start + tabstop_range.start) as usize)
 7041                                    .min(snapshot.len());
 7042                                let end = ((insertion_start + tabstop_range.end) as usize)
 7043                                    .min(snapshot.len());
 7044                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 7045                            })
 7046                        })
 7047                        .collect::<Vec<_>>();
 7048                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 7049
 7050                    Tabstop {
 7051                        is_end_tabstop,
 7052                        ranges: tabstop_ranges,
 7053                        choices: tabstop.choices.clone(),
 7054                    }
 7055                })
 7056                .collect::<Vec<_>>()
 7057        });
 7058        if let Some(tabstop) = tabstops.first() {
 7059            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7060                s.select_ranges(tabstop.ranges.iter().cloned());
 7061            });
 7062
 7063            if let Some(choices) = &tabstop.choices {
 7064                if let Some(selection) = tabstop.ranges.first() {
 7065                    self.show_snippet_choices(choices, selection.clone(), cx)
 7066                }
 7067            }
 7068
 7069            // If we're already at the last tabstop and it's at the end of the snippet,
 7070            // we're done, we don't need to keep the state around.
 7071            if !tabstop.is_end_tabstop {
 7072                let choices = tabstops
 7073                    .iter()
 7074                    .map(|tabstop| tabstop.choices.clone())
 7075                    .collect();
 7076
 7077                let ranges = tabstops
 7078                    .into_iter()
 7079                    .map(|tabstop| tabstop.ranges)
 7080                    .collect::<Vec<_>>();
 7081
 7082                self.snippet_stack.push(SnippetState {
 7083                    active_index: 0,
 7084                    ranges,
 7085                    choices,
 7086                });
 7087            }
 7088
 7089            // Check whether the just-entered snippet ends with an auto-closable bracket.
 7090            if self.autoclose_regions.is_empty() {
 7091                let snapshot = self.buffer.read(cx).snapshot(cx);
 7092                for selection in &mut self.selections.all::<Point>(cx) {
 7093                    let selection_head = selection.head();
 7094                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 7095                        continue;
 7096                    };
 7097
 7098                    let mut bracket_pair = None;
 7099                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 7100                    let prev_chars = snapshot
 7101                        .reversed_chars_at(selection_head)
 7102                        .collect::<String>();
 7103                    for (pair, enabled) in scope.brackets() {
 7104                        if enabled
 7105                            && pair.close
 7106                            && prev_chars.starts_with(pair.start.as_str())
 7107                            && next_chars.starts_with(pair.end.as_str())
 7108                        {
 7109                            bracket_pair = Some(pair.clone());
 7110                            break;
 7111                        }
 7112                    }
 7113                    if let Some(pair) = bracket_pair {
 7114                        let start = snapshot.anchor_after(selection_head);
 7115                        let end = snapshot.anchor_after(selection_head);
 7116                        self.autoclose_regions.push(AutocloseRegion {
 7117                            selection_id: selection.id,
 7118                            range: start..end,
 7119                            pair,
 7120                        });
 7121                    }
 7122                }
 7123            }
 7124        }
 7125        Ok(())
 7126    }
 7127
 7128    pub fn move_to_next_snippet_tabstop(
 7129        &mut self,
 7130        window: &mut Window,
 7131        cx: &mut Context<Self>,
 7132    ) -> bool {
 7133        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 7134    }
 7135
 7136    pub fn move_to_prev_snippet_tabstop(
 7137        &mut self,
 7138        window: &mut Window,
 7139        cx: &mut Context<Self>,
 7140    ) -> bool {
 7141        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 7142    }
 7143
 7144    pub fn move_to_snippet_tabstop(
 7145        &mut self,
 7146        bias: Bias,
 7147        window: &mut Window,
 7148        cx: &mut Context<Self>,
 7149    ) -> bool {
 7150        if let Some(mut snippet) = self.snippet_stack.pop() {
 7151            match bias {
 7152                Bias::Left => {
 7153                    if snippet.active_index > 0 {
 7154                        snippet.active_index -= 1;
 7155                    } else {
 7156                        self.snippet_stack.push(snippet);
 7157                        return false;
 7158                    }
 7159                }
 7160                Bias::Right => {
 7161                    if snippet.active_index + 1 < snippet.ranges.len() {
 7162                        snippet.active_index += 1;
 7163                    } else {
 7164                        self.snippet_stack.push(snippet);
 7165                        return false;
 7166                    }
 7167                }
 7168            }
 7169            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 7170                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7171                    s.select_anchor_ranges(current_ranges.iter().cloned())
 7172                });
 7173
 7174                if let Some(choices) = &snippet.choices[snippet.active_index] {
 7175                    if let Some(selection) = current_ranges.first() {
 7176                        self.show_snippet_choices(&choices, selection.clone(), cx);
 7177                    }
 7178                }
 7179
 7180                // If snippet state is not at the last tabstop, push it back on the stack
 7181                if snippet.active_index + 1 < snippet.ranges.len() {
 7182                    self.snippet_stack.push(snippet);
 7183                }
 7184                return true;
 7185            }
 7186        }
 7187
 7188        false
 7189    }
 7190
 7191    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 7192        self.transact(window, cx, |this, window, cx| {
 7193            this.select_all(&SelectAll, window, cx);
 7194            this.insert("", window, cx);
 7195        });
 7196    }
 7197
 7198    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 7199        self.transact(window, cx, |this, window, cx| {
 7200            this.select_autoclose_pair(window, cx);
 7201            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 7202            if !this.linked_edit_ranges.is_empty() {
 7203                let selections = this.selections.all::<MultiBufferPoint>(cx);
 7204                let snapshot = this.buffer.read(cx).snapshot(cx);
 7205
 7206                for selection in selections.iter() {
 7207                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 7208                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 7209                    if selection_start.buffer_id != selection_end.buffer_id {
 7210                        continue;
 7211                    }
 7212                    if let Some(ranges) =
 7213                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 7214                    {
 7215                        for (buffer, entries) in ranges {
 7216                            linked_ranges.entry(buffer).or_default().extend(entries);
 7217                        }
 7218                    }
 7219                }
 7220            }
 7221
 7222            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7223            if !this.selections.line_mode {
 7224                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 7225                for selection in &mut selections {
 7226                    if selection.is_empty() {
 7227                        let old_head = selection.head();
 7228                        let mut new_head =
 7229                            movement::left(&display_map, old_head.to_display_point(&display_map))
 7230                                .to_point(&display_map);
 7231                        if let Some((buffer, line_buffer_range)) = display_map
 7232                            .buffer_snapshot
 7233                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 7234                        {
 7235                            let indent_size =
 7236                                buffer.indent_size_for_line(line_buffer_range.start.row);
 7237                            let indent_len = match indent_size.kind {
 7238                                IndentKind::Space => {
 7239                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 7240                                }
 7241                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 7242                            };
 7243                            if old_head.column <= indent_size.len && old_head.column > 0 {
 7244                                let indent_len = indent_len.get();
 7245                                new_head = cmp::min(
 7246                                    new_head,
 7247                                    MultiBufferPoint::new(
 7248                                        old_head.row,
 7249                                        ((old_head.column - 1) / indent_len) * indent_len,
 7250                                    ),
 7251                                );
 7252                            }
 7253                        }
 7254
 7255                        selection.set_head(new_head, SelectionGoal::None);
 7256                    }
 7257                }
 7258            }
 7259
 7260            this.signature_help_state.set_backspace_pressed(true);
 7261            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7262                s.select(selections)
 7263            });
 7264            this.insert("", window, cx);
 7265            let empty_str: Arc<str> = Arc::from("");
 7266            for (buffer, edits) in linked_ranges {
 7267                let snapshot = buffer.read(cx).snapshot();
 7268                use text::ToPoint as TP;
 7269
 7270                let edits = edits
 7271                    .into_iter()
 7272                    .map(|range| {
 7273                        let end_point = TP::to_point(&range.end, &snapshot);
 7274                        let mut start_point = TP::to_point(&range.start, &snapshot);
 7275
 7276                        if end_point == start_point {
 7277                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 7278                                .saturating_sub(1);
 7279                            start_point =
 7280                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 7281                        };
 7282
 7283                        (start_point..end_point, empty_str.clone())
 7284                    })
 7285                    .sorted_by_key(|(range, _)| range.start)
 7286                    .collect::<Vec<_>>();
 7287                buffer.update(cx, |this, cx| {
 7288                    this.edit(edits, None, cx);
 7289                })
 7290            }
 7291            this.refresh_inline_completion(true, false, window, cx);
 7292            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 7293        });
 7294    }
 7295
 7296    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 7297        self.transact(window, cx, |this, window, cx| {
 7298            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7299                let line_mode = s.line_mode;
 7300                s.move_with(|map, selection| {
 7301                    if selection.is_empty() && !line_mode {
 7302                        let cursor = movement::right(map, selection.head());
 7303                        selection.end = cursor;
 7304                        selection.reversed = true;
 7305                        selection.goal = SelectionGoal::None;
 7306                    }
 7307                })
 7308            });
 7309            this.insert("", window, cx);
 7310            this.refresh_inline_completion(true, false, window, cx);
 7311        });
 7312    }
 7313
 7314    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 7315        if self.move_to_prev_snippet_tabstop(window, cx) {
 7316            return;
 7317        }
 7318
 7319        self.outdent(&Outdent, window, cx);
 7320    }
 7321
 7322    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 7323        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 7324            return;
 7325        }
 7326
 7327        let mut selections = self.selections.all_adjusted(cx);
 7328        let buffer = self.buffer.read(cx);
 7329        let snapshot = buffer.snapshot(cx);
 7330        let rows_iter = selections.iter().map(|s| s.head().row);
 7331        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 7332
 7333        let mut edits = Vec::new();
 7334        let mut prev_edited_row = 0;
 7335        let mut row_delta = 0;
 7336        for selection in &mut selections {
 7337            if selection.start.row != prev_edited_row {
 7338                row_delta = 0;
 7339            }
 7340            prev_edited_row = selection.end.row;
 7341
 7342            // If the selection is non-empty, then increase the indentation of the selected lines.
 7343            if !selection.is_empty() {
 7344                row_delta =
 7345                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7346                continue;
 7347            }
 7348
 7349            // If the selection is empty and the cursor is in the leading whitespace before the
 7350            // suggested indentation, then auto-indent the line.
 7351            let cursor = selection.head();
 7352            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 7353            if let Some(suggested_indent) =
 7354                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 7355            {
 7356                if cursor.column < suggested_indent.len
 7357                    && cursor.column <= current_indent.len
 7358                    && current_indent.len <= suggested_indent.len
 7359                {
 7360                    selection.start = Point::new(cursor.row, suggested_indent.len);
 7361                    selection.end = selection.start;
 7362                    if row_delta == 0 {
 7363                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 7364                            cursor.row,
 7365                            current_indent,
 7366                            suggested_indent,
 7367                        ));
 7368                        row_delta = suggested_indent.len - current_indent.len;
 7369                    }
 7370                    continue;
 7371                }
 7372            }
 7373
 7374            // Otherwise, insert a hard or soft tab.
 7375            let settings = buffer.language_settings_at(cursor, cx);
 7376            let tab_size = if settings.hard_tabs {
 7377                IndentSize::tab()
 7378            } else {
 7379                let tab_size = settings.tab_size.get();
 7380                let char_column = snapshot
 7381                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 7382                    .flat_map(str::chars)
 7383                    .count()
 7384                    + row_delta as usize;
 7385                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 7386                IndentSize::spaces(chars_to_next_tab_stop)
 7387            };
 7388            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 7389            selection.end = selection.start;
 7390            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 7391            row_delta += tab_size.len;
 7392        }
 7393
 7394        self.transact(window, cx, |this, window, cx| {
 7395            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7396            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7397                s.select(selections)
 7398            });
 7399            this.refresh_inline_completion(true, false, window, cx);
 7400        });
 7401    }
 7402
 7403    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 7404        if self.read_only(cx) {
 7405            return;
 7406        }
 7407        let mut selections = self.selections.all::<Point>(cx);
 7408        let mut prev_edited_row = 0;
 7409        let mut row_delta = 0;
 7410        let mut edits = Vec::new();
 7411        let buffer = self.buffer.read(cx);
 7412        let snapshot = buffer.snapshot(cx);
 7413        for selection in &mut selections {
 7414            if selection.start.row != prev_edited_row {
 7415                row_delta = 0;
 7416            }
 7417            prev_edited_row = selection.end.row;
 7418
 7419            row_delta =
 7420                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7421        }
 7422
 7423        self.transact(window, cx, |this, window, cx| {
 7424            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7425            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7426                s.select(selections)
 7427            });
 7428        });
 7429    }
 7430
 7431    fn indent_selection(
 7432        buffer: &MultiBuffer,
 7433        snapshot: &MultiBufferSnapshot,
 7434        selection: &mut Selection<Point>,
 7435        edits: &mut Vec<(Range<Point>, String)>,
 7436        delta_for_start_row: u32,
 7437        cx: &App,
 7438    ) -> u32 {
 7439        let settings = buffer.language_settings_at(selection.start, cx);
 7440        let tab_size = settings.tab_size.get();
 7441        let indent_kind = if settings.hard_tabs {
 7442            IndentKind::Tab
 7443        } else {
 7444            IndentKind::Space
 7445        };
 7446        let mut start_row = selection.start.row;
 7447        let mut end_row = selection.end.row + 1;
 7448
 7449        // If a selection ends at the beginning of a line, don't indent
 7450        // that last line.
 7451        if selection.end.column == 0 && selection.end.row > selection.start.row {
 7452            end_row -= 1;
 7453        }
 7454
 7455        // Avoid re-indenting a row that has already been indented by a
 7456        // previous selection, but still update this selection's column
 7457        // to reflect that indentation.
 7458        if delta_for_start_row > 0 {
 7459            start_row += 1;
 7460            selection.start.column += delta_for_start_row;
 7461            if selection.end.row == selection.start.row {
 7462                selection.end.column += delta_for_start_row;
 7463            }
 7464        }
 7465
 7466        let mut delta_for_end_row = 0;
 7467        let has_multiple_rows = start_row + 1 != end_row;
 7468        for row in start_row..end_row {
 7469            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 7470            let indent_delta = match (current_indent.kind, indent_kind) {
 7471                (IndentKind::Space, IndentKind::Space) => {
 7472                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 7473                    IndentSize::spaces(columns_to_next_tab_stop)
 7474                }
 7475                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 7476                (_, IndentKind::Tab) => IndentSize::tab(),
 7477            };
 7478
 7479            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 7480                0
 7481            } else {
 7482                selection.start.column
 7483            };
 7484            let row_start = Point::new(row, start);
 7485            edits.push((
 7486                row_start..row_start,
 7487                indent_delta.chars().collect::<String>(),
 7488            ));
 7489
 7490            // Update this selection's endpoints to reflect the indentation.
 7491            if row == selection.start.row {
 7492                selection.start.column += indent_delta.len;
 7493            }
 7494            if row == selection.end.row {
 7495                selection.end.column += indent_delta.len;
 7496                delta_for_end_row = indent_delta.len;
 7497            }
 7498        }
 7499
 7500        if selection.start.row == selection.end.row {
 7501            delta_for_start_row + delta_for_end_row
 7502        } else {
 7503            delta_for_end_row
 7504        }
 7505    }
 7506
 7507    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 7508        if self.read_only(cx) {
 7509            return;
 7510        }
 7511        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7512        let selections = self.selections.all::<Point>(cx);
 7513        let mut deletion_ranges = Vec::new();
 7514        let mut last_outdent = None;
 7515        {
 7516            let buffer = self.buffer.read(cx);
 7517            let snapshot = buffer.snapshot(cx);
 7518            for selection in &selections {
 7519                let settings = buffer.language_settings_at(selection.start, cx);
 7520                let tab_size = settings.tab_size.get();
 7521                let mut rows = selection.spanned_rows(false, &display_map);
 7522
 7523                // Avoid re-outdenting a row that has already been outdented by a
 7524                // previous selection.
 7525                if let Some(last_row) = last_outdent {
 7526                    if last_row == rows.start {
 7527                        rows.start = rows.start.next_row();
 7528                    }
 7529                }
 7530                let has_multiple_rows = rows.len() > 1;
 7531                for row in rows.iter_rows() {
 7532                    let indent_size = snapshot.indent_size_for_line(row);
 7533                    if indent_size.len > 0 {
 7534                        let deletion_len = match indent_size.kind {
 7535                            IndentKind::Space => {
 7536                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 7537                                if columns_to_prev_tab_stop == 0 {
 7538                                    tab_size
 7539                                } else {
 7540                                    columns_to_prev_tab_stop
 7541                                }
 7542                            }
 7543                            IndentKind::Tab => 1,
 7544                        };
 7545                        let start = if has_multiple_rows
 7546                            || deletion_len > selection.start.column
 7547                            || indent_size.len < selection.start.column
 7548                        {
 7549                            0
 7550                        } else {
 7551                            selection.start.column - deletion_len
 7552                        };
 7553                        deletion_ranges.push(
 7554                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 7555                        );
 7556                        last_outdent = Some(row);
 7557                    }
 7558                }
 7559            }
 7560        }
 7561
 7562        self.transact(window, cx, |this, window, cx| {
 7563            this.buffer.update(cx, |buffer, cx| {
 7564                let empty_str: Arc<str> = Arc::default();
 7565                buffer.edit(
 7566                    deletion_ranges
 7567                        .into_iter()
 7568                        .map(|range| (range, empty_str.clone())),
 7569                    None,
 7570                    cx,
 7571                );
 7572            });
 7573            let selections = this.selections.all::<usize>(cx);
 7574            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7575                s.select(selections)
 7576            });
 7577        });
 7578    }
 7579
 7580    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 7581        if self.read_only(cx) {
 7582            return;
 7583        }
 7584        let selections = self
 7585            .selections
 7586            .all::<usize>(cx)
 7587            .into_iter()
 7588            .map(|s| s.range());
 7589
 7590        self.transact(window, cx, |this, window, cx| {
 7591            this.buffer.update(cx, |buffer, cx| {
 7592                buffer.autoindent_ranges(selections, cx);
 7593            });
 7594            let selections = this.selections.all::<usize>(cx);
 7595            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7596                s.select(selections)
 7597            });
 7598        });
 7599    }
 7600
 7601    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 7602        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7603        let selections = self.selections.all::<Point>(cx);
 7604
 7605        let mut new_cursors = Vec::new();
 7606        let mut edit_ranges = Vec::new();
 7607        let mut selections = selections.iter().peekable();
 7608        while let Some(selection) = selections.next() {
 7609            let mut rows = selection.spanned_rows(false, &display_map);
 7610            let goal_display_column = selection.head().to_display_point(&display_map).column();
 7611
 7612            // Accumulate contiguous regions of rows that we want to delete.
 7613            while let Some(next_selection) = selections.peek() {
 7614                let next_rows = next_selection.spanned_rows(false, &display_map);
 7615                if next_rows.start <= rows.end {
 7616                    rows.end = next_rows.end;
 7617                    selections.next().unwrap();
 7618                } else {
 7619                    break;
 7620                }
 7621            }
 7622
 7623            let buffer = &display_map.buffer_snapshot;
 7624            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 7625            let edit_end;
 7626            let cursor_buffer_row;
 7627            if buffer.max_point().row >= rows.end.0 {
 7628                // If there's a line after the range, delete the \n from the end of the row range
 7629                // and position the cursor on the next line.
 7630                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 7631                cursor_buffer_row = rows.end;
 7632            } else {
 7633                // If there isn't a line after the range, delete the \n from the line before the
 7634                // start of the row range and position the cursor there.
 7635                edit_start = edit_start.saturating_sub(1);
 7636                edit_end = buffer.len();
 7637                cursor_buffer_row = rows.start.previous_row();
 7638            }
 7639
 7640            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 7641            *cursor.column_mut() =
 7642                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 7643
 7644            new_cursors.push((
 7645                selection.id,
 7646                buffer.anchor_after(cursor.to_point(&display_map)),
 7647            ));
 7648            edit_ranges.push(edit_start..edit_end);
 7649        }
 7650
 7651        self.transact(window, cx, |this, window, cx| {
 7652            let buffer = this.buffer.update(cx, |buffer, cx| {
 7653                let empty_str: Arc<str> = Arc::default();
 7654                buffer.edit(
 7655                    edit_ranges
 7656                        .into_iter()
 7657                        .map(|range| (range, empty_str.clone())),
 7658                    None,
 7659                    cx,
 7660                );
 7661                buffer.snapshot(cx)
 7662            });
 7663            let new_selections = new_cursors
 7664                .into_iter()
 7665                .map(|(id, cursor)| {
 7666                    let cursor = cursor.to_point(&buffer);
 7667                    Selection {
 7668                        id,
 7669                        start: cursor,
 7670                        end: cursor,
 7671                        reversed: false,
 7672                        goal: SelectionGoal::None,
 7673                    }
 7674                })
 7675                .collect();
 7676
 7677            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7678                s.select(new_selections);
 7679            });
 7680        });
 7681    }
 7682
 7683    pub fn join_lines_impl(
 7684        &mut self,
 7685        insert_whitespace: bool,
 7686        window: &mut Window,
 7687        cx: &mut Context<Self>,
 7688    ) {
 7689        if self.read_only(cx) {
 7690            return;
 7691        }
 7692        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 7693        for selection in self.selections.all::<Point>(cx) {
 7694            let start = MultiBufferRow(selection.start.row);
 7695            // Treat single line selections as if they include the next line. Otherwise this action
 7696            // would do nothing for single line selections individual cursors.
 7697            let end = if selection.start.row == selection.end.row {
 7698                MultiBufferRow(selection.start.row + 1)
 7699            } else {
 7700                MultiBufferRow(selection.end.row)
 7701            };
 7702
 7703            if let Some(last_row_range) = row_ranges.last_mut() {
 7704                if start <= last_row_range.end {
 7705                    last_row_range.end = end;
 7706                    continue;
 7707                }
 7708            }
 7709            row_ranges.push(start..end);
 7710        }
 7711
 7712        let snapshot = self.buffer.read(cx).snapshot(cx);
 7713        let mut cursor_positions = Vec::new();
 7714        for row_range in &row_ranges {
 7715            let anchor = snapshot.anchor_before(Point::new(
 7716                row_range.end.previous_row().0,
 7717                snapshot.line_len(row_range.end.previous_row()),
 7718            ));
 7719            cursor_positions.push(anchor..anchor);
 7720        }
 7721
 7722        self.transact(window, cx, |this, window, cx| {
 7723            for row_range in row_ranges.into_iter().rev() {
 7724                for row in row_range.iter_rows().rev() {
 7725                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 7726                    let next_line_row = row.next_row();
 7727                    let indent = snapshot.indent_size_for_line(next_line_row);
 7728                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7729
 7730                    let replace =
 7731                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7732                            " "
 7733                        } else {
 7734                            ""
 7735                        };
 7736
 7737                    this.buffer.update(cx, |buffer, cx| {
 7738                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7739                    });
 7740                }
 7741            }
 7742
 7743            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7744                s.select_anchor_ranges(cursor_positions)
 7745            });
 7746        });
 7747    }
 7748
 7749    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7750        self.join_lines_impl(true, window, cx);
 7751    }
 7752
 7753    pub fn sort_lines_case_sensitive(
 7754        &mut self,
 7755        _: &SortLinesCaseSensitive,
 7756        window: &mut Window,
 7757        cx: &mut Context<Self>,
 7758    ) {
 7759        self.manipulate_lines(window, cx, |lines| lines.sort())
 7760    }
 7761
 7762    pub fn sort_lines_case_insensitive(
 7763        &mut self,
 7764        _: &SortLinesCaseInsensitive,
 7765        window: &mut Window,
 7766        cx: &mut Context<Self>,
 7767    ) {
 7768        self.manipulate_lines(window, cx, |lines| {
 7769            lines.sort_by_key(|line| line.to_lowercase())
 7770        })
 7771    }
 7772
 7773    pub fn unique_lines_case_insensitive(
 7774        &mut self,
 7775        _: &UniqueLinesCaseInsensitive,
 7776        window: &mut Window,
 7777        cx: &mut Context<Self>,
 7778    ) {
 7779        self.manipulate_lines(window, cx, |lines| {
 7780            let mut seen = HashSet::default();
 7781            lines.retain(|line| seen.insert(line.to_lowercase()));
 7782        })
 7783    }
 7784
 7785    pub fn unique_lines_case_sensitive(
 7786        &mut self,
 7787        _: &UniqueLinesCaseSensitive,
 7788        window: &mut Window,
 7789        cx: &mut Context<Self>,
 7790    ) {
 7791        self.manipulate_lines(window, cx, |lines| {
 7792            let mut seen = HashSet::default();
 7793            lines.retain(|line| seen.insert(*line));
 7794        })
 7795    }
 7796
 7797    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7798        let Some(project) = self.project.clone() else {
 7799            return;
 7800        };
 7801        self.reload(project, window, cx)
 7802            .detach_and_notify_err(window, cx);
 7803    }
 7804
 7805    pub fn restore_file(
 7806        &mut self,
 7807        _: &::git::RestoreFile,
 7808        window: &mut Window,
 7809        cx: &mut Context<Self>,
 7810    ) {
 7811        let mut buffer_ids = HashSet::default();
 7812        let snapshot = self.buffer().read(cx).snapshot(cx);
 7813        for selection in self.selections.all::<usize>(cx) {
 7814            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 7815        }
 7816
 7817        let buffer = self.buffer().read(cx);
 7818        let ranges = buffer_ids
 7819            .into_iter()
 7820            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 7821            .collect::<Vec<_>>();
 7822
 7823        self.restore_hunks_in_ranges(ranges, window, cx);
 7824    }
 7825
 7826    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 7827        let selections = self
 7828            .selections
 7829            .all(cx)
 7830            .into_iter()
 7831            .map(|s| s.range())
 7832            .collect();
 7833        self.restore_hunks_in_ranges(selections, window, cx);
 7834    }
 7835
 7836    fn restore_hunks_in_ranges(
 7837        &mut self,
 7838        ranges: Vec<Range<Point>>,
 7839        window: &mut Window,
 7840        cx: &mut Context<Editor>,
 7841    ) {
 7842        let mut revert_changes = HashMap::default();
 7843        let chunk_by = self
 7844            .snapshot(window, cx)
 7845            .hunks_for_ranges(ranges)
 7846            .into_iter()
 7847            .chunk_by(|hunk| hunk.buffer_id);
 7848        for (buffer_id, hunks) in &chunk_by {
 7849            let hunks = hunks.collect::<Vec<_>>();
 7850            for hunk in &hunks {
 7851                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 7852            }
 7853            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 7854        }
 7855        drop(chunk_by);
 7856        if !revert_changes.is_empty() {
 7857            self.transact(window, cx, |editor, window, cx| {
 7858                editor.restore(revert_changes, window, cx);
 7859            });
 7860        }
 7861    }
 7862
 7863    pub fn open_active_item_in_terminal(
 7864        &mut self,
 7865        _: &OpenInTerminal,
 7866        window: &mut Window,
 7867        cx: &mut Context<Self>,
 7868    ) {
 7869        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7870            let project_path = buffer.read(cx).project_path(cx)?;
 7871            let project = self.project.as_ref()?.read(cx);
 7872            let entry = project.entry_for_path(&project_path, cx)?;
 7873            let parent = match &entry.canonical_path {
 7874                Some(canonical_path) => canonical_path.to_path_buf(),
 7875                None => project.absolute_path(&project_path, cx)?,
 7876            }
 7877            .parent()?
 7878            .to_path_buf();
 7879            Some(parent)
 7880        }) {
 7881            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7882        }
 7883    }
 7884
 7885    pub fn prepare_restore_change(
 7886        &self,
 7887        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7888        hunk: &MultiBufferDiffHunk,
 7889        cx: &mut App,
 7890    ) -> Option<()> {
 7891        if hunk.is_created_file() {
 7892            return None;
 7893        }
 7894        let buffer = self.buffer.read(cx);
 7895        let diff = buffer.diff_for(hunk.buffer_id)?;
 7896        let buffer = buffer.buffer(hunk.buffer_id)?;
 7897        let buffer = buffer.read(cx);
 7898        let original_text = diff
 7899            .read(cx)
 7900            .base_text()
 7901            .as_rope()
 7902            .slice(hunk.diff_base_byte_range.clone());
 7903        let buffer_snapshot = buffer.snapshot();
 7904        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7905        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7906            probe
 7907                .0
 7908                .start
 7909                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7910                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7911        }) {
 7912            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7913            Some(())
 7914        } else {
 7915            None
 7916        }
 7917    }
 7918
 7919    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7920        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7921    }
 7922
 7923    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7924        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7925    }
 7926
 7927    fn manipulate_lines<Fn>(
 7928        &mut self,
 7929        window: &mut Window,
 7930        cx: &mut Context<Self>,
 7931        mut callback: Fn,
 7932    ) where
 7933        Fn: FnMut(&mut Vec<&str>),
 7934    {
 7935        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7936        let buffer = self.buffer.read(cx).snapshot(cx);
 7937
 7938        let mut edits = Vec::new();
 7939
 7940        let selections = self.selections.all::<Point>(cx);
 7941        let mut selections = selections.iter().peekable();
 7942        let mut contiguous_row_selections = Vec::new();
 7943        let mut new_selections = Vec::new();
 7944        let mut added_lines = 0;
 7945        let mut removed_lines = 0;
 7946
 7947        while let Some(selection) = selections.next() {
 7948            let (start_row, end_row) = consume_contiguous_rows(
 7949                &mut contiguous_row_selections,
 7950                selection,
 7951                &display_map,
 7952                &mut selections,
 7953            );
 7954
 7955            let start_point = Point::new(start_row.0, 0);
 7956            let end_point = Point::new(
 7957                end_row.previous_row().0,
 7958                buffer.line_len(end_row.previous_row()),
 7959            );
 7960            let text = buffer
 7961                .text_for_range(start_point..end_point)
 7962                .collect::<String>();
 7963
 7964            let mut lines = text.split('\n').collect_vec();
 7965
 7966            let lines_before = lines.len();
 7967            callback(&mut lines);
 7968            let lines_after = lines.len();
 7969
 7970            edits.push((start_point..end_point, lines.join("\n")));
 7971
 7972            // Selections must change based on added and removed line count
 7973            let start_row =
 7974                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7975            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7976            new_selections.push(Selection {
 7977                id: selection.id,
 7978                start: start_row,
 7979                end: end_row,
 7980                goal: SelectionGoal::None,
 7981                reversed: selection.reversed,
 7982            });
 7983
 7984            if lines_after > lines_before {
 7985                added_lines += lines_after - lines_before;
 7986            } else if lines_before > lines_after {
 7987                removed_lines += lines_before - lines_after;
 7988            }
 7989        }
 7990
 7991        self.transact(window, cx, |this, window, cx| {
 7992            let buffer = this.buffer.update(cx, |buffer, cx| {
 7993                buffer.edit(edits, None, cx);
 7994                buffer.snapshot(cx)
 7995            });
 7996
 7997            // Recalculate offsets on newly edited buffer
 7998            let new_selections = new_selections
 7999                .iter()
 8000                .map(|s| {
 8001                    let start_point = Point::new(s.start.0, 0);
 8002                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 8003                    Selection {
 8004                        id: s.id,
 8005                        start: buffer.point_to_offset(start_point),
 8006                        end: buffer.point_to_offset(end_point),
 8007                        goal: s.goal,
 8008                        reversed: s.reversed,
 8009                    }
 8010                })
 8011                .collect();
 8012
 8013            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8014                s.select(new_selections);
 8015            });
 8016
 8017            this.request_autoscroll(Autoscroll::fit(), cx);
 8018        });
 8019    }
 8020
 8021    pub fn convert_to_upper_case(
 8022        &mut self,
 8023        _: &ConvertToUpperCase,
 8024        window: &mut Window,
 8025        cx: &mut Context<Self>,
 8026    ) {
 8027        self.manipulate_text(window, cx, |text| text.to_uppercase())
 8028    }
 8029
 8030    pub fn convert_to_lower_case(
 8031        &mut self,
 8032        _: &ConvertToLowerCase,
 8033        window: &mut Window,
 8034        cx: &mut Context<Self>,
 8035    ) {
 8036        self.manipulate_text(window, cx, |text| text.to_lowercase())
 8037    }
 8038
 8039    pub fn convert_to_title_case(
 8040        &mut self,
 8041        _: &ConvertToTitleCase,
 8042        window: &mut Window,
 8043        cx: &mut Context<Self>,
 8044    ) {
 8045        self.manipulate_text(window, cx, |text| {
 8046            text.split('\n')
 8047                .map(|line| line.to_case(Case::Title))
 8048                .join("\n")
 8049        })
 8050    }
 8051
 8052    pub fn convert_to_snake_case(
 8053        &mut self,
 8054        _: &ConvertToSnakeCase,
 8055        window: &mut Window,
 8056        cx: &mut Context<Self>,
 8057    ) {
 8058        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 8059    }
 8060
 8061    pub fn convert_to_kebab_case(
 8062        &mut self,
 8063        _: &ConvertToKebabCase,
 8064        window: &mut Window,
 8065        cx: &mut Context<Self>,
 8066    ) {
 8067        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 8068    }
 8069
 8070    pub fn convert_to_upper_camel_case(
 8071        &mut self,
 8072        _: &ConvertToUpperCamelCase,
 8073        window: &mut Window,
 8074        cx: &mut Context<Self>,
 8075    ) {
 8076        self.manipulate_text(window, cx, |text| {
 8077            text.split('\n')
 8078                .map(|line| line.to_case(Case::UpperCamel))
 8079                .join("\n")
 8080        })
 8081    }
 8082
 8083    pub fn convert_to_lower_camel_case(
 8084        &mut self,
 8085        _: &ConvertToLowerCamelCase,
 8086        window: &mut Window,
 8087        cx: &mut Context<Self>,
 8088    ) {
 8089        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 8090    }
 8091
 8092    pub fn convert_to_opposite_case(
 8093        &mut self,
 8094        _: &ConvertToOppositeCase,
 8095        window: &mut Window,
 8096        cx: &mut Context<Self>,
 8097    ) {
 8098        self.manipulate_text(window, cx, |text| {
 8099            text.chars()
 8100                .fold(String::with_capacity(text.len()), |mut t, c| {
 8101                    if c.is_uppercase() {
 8102                        t.extend(c.to_lowercase());
 8103                    } else {
 8104                        t.extend(c.to_uppercase());
 8105                    }
 8106                    t
 8107                })
 8108        })
 8109    }
 8110
 8111    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 8112    where
 8113        Fn: FnMut(&str) -> String,
 8114    {
 8115        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8116        let buffer = self.buffer.read(cx).snapshot(cx);
 8117
 8118        let mut new_selections = Vec::new();
 8119        let mut edits = Vec::new();
 8120        let mut selection_adjustment = 0i32;
 8121
 8122        for selection in self.selections.all::<usize>(cx) {
 8123            let selection_is_empty = selection.is_empty();
 8124
 8125            let (start, end) = if selection_is_empty {
 8126                let word_range = movement::surrounding_word(
 8127                    &display_map,
 8128                    selection.start.to_display_point(&display_map),
 8129                );
 8130                let start = word_range.start.to_offset(&display_map, Bias::Left);
 8131                let end = word_range.end.to_offset(&display_map, Bias::Left);
 8132                (start, end)
 8133            } else {
 8134                (selection.start, selection.end)
 8135            };
 8136
 8137            let text = buffer.text_for_range(start..end).collect::<String>();
 8138            let old_length = text.len() as i32;
 8139            let text = callback(&text);
 8140
 8141            new_selections.push(Selection {
 8142                start: (start as i32 - selection_adjustment) as usize,
 8143                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 8144                goal: SelectionGoal::None,
 8145                ..selection
 8146            });
 8147
 8148            selection_adjustment += old_length - text.len() as i32;
 8149
 8150            edits.push((start..end, text));
 8151        }
 8152
 8153        self.transact(window, cx, |this, window, cx| {
 8154            this.buffer.update(cx, |buffer, cx| {
 8155                buffer.edit(edits, None, cx);
 8156            });
 8157
 8158            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8159                s.select(new_selections);
 8160            });
 8161
 8162            this.request_autoscroll(Autoscroll::fit(), cx);
 8163        });
 8164    }
 8165
 8166    pub fn duplicate(
 8167        &mut self,
 8168        upwards: bool,
 8169        whole_lines: bool,
 8170        window: &mut Window,
 8171        cx: &mut Context<Self>,
 8172    ) {
 8173        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8174        let buffer = &display_map.buffer_snapshot;
 8175        let selections = self.selections.all::<Point>(cx);
 8176
 8177        let mut edits = Vec::new();
 8178        let mut selections_iter = selections.iter().peekable();
 8179        while let Some(selection) = selections_iter.next() {
 8180            let mut rows = selection.spanned_rows(false, &display_map);
 8181            // duplicate line-wise
 8182            if whole_lines || selection.start == selection.end {
 8183                // Avoid duplicating the same lines twice.
 8184                while let Some(next_selection) = selections_iter.peek() {
 8185                    let next_rows = next_selection.spanned_rows(false, &display_map);
 8186                    if next_rows.start < rows.end {
 8187                        rows.end = next_rows.end;
 8188                        selections_iter.next().unwrap();
 8189                    } else {
 8190                        break;
 8191                    }
 8192                }
 8193
 8194                // Copy the text from the selected row region and splice it either at the start
 8195                // or end of the region.
 8196                let start = Point::new(rows.start.0, 0);
 8197                let end = Point::new(
 8198                    rows.end.previous_row().0,
 8199                    buffer.line_len(rows.end.previous_row()),
 8200                );
 8201                let text = buffer
 8202                    .text_for_range(start..end)
 8203                    .chain(Some("\n"))
 8204                    .collect::<String>();
 8205                let insert_location = if upwards {
 8206                    Point::new(rows.end.0, 0)
 8207                } else {
 8208                    start
 8209                };
 8210                edits.push((insert_location..insert_location, text));
 8211            } else {
 8212                // duplicate character-wise
 8213                let start = selection.start;
 8214                let end = selection.end;
 8215                let text = buffer.text_for_range(start..end).collect::<String>();
 8216                edits.push((selection.end..selection.end, text));
 8217            }
 8218        }
 8219
 8220        self.transact(window, cx, |this, _, cx| {
 8221            this.buffer.update(cx, |buffer, cx| {
 8222                buffer.edit(edits, None, cx);
 8223            });
 8224
 8225            this.request_autoscroll(Autoscroll::fit(), cx);
 8226        });
 8227    }
 8228
 8229    pub fn duplicate_line_up(
 8230        &mut self,
 8231        _: &DuplicateLineUp,
 8232        window: &mut Window,
 8233        cx: &mut Context<Self>,
 8234    ) {
 8235        self.duplicate(true, true, window, cx);
 8236    }
 8237
 8238    pub fn duplicate_line_down(
 8239        &mut self,
 8240        _: &DuplicateLineDown,
 8241        window: &mut Window,
 8242        cx: &mut Context<Self>,
 8243    ) {
 8244        self.duplicate(false, true, window, cx);
 8245    }
 8246
 8247    pub fn duplicate_selection(
 8248        &mut self,
 8249        _: &DuplicateSelection,
 8250        window: &mut Window,
 8251        cx: &mut Context<Self>,
 8252    ) {
 8253        self.duplicate(false, false, window, cx);
 8254    }
 8255
 8256    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 8257        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8258        let buffer = self.buffer.read(cx).snapshot(cx);
 8259
 8260        let mut edits = Vec::new();
 8261        let mut unfold_ranges = Vec::new();
 8262        let mut refold_creases = Vec::new();
 8263
 8264        let selections = self.selections.all::<Point>(cx);
 8265        let mut selections = selections.iter().peekable();
 8266        let mut contiguous_row_selections = Vec::new();
 8267        let mut new_selections = Vec::new();
 8268
 8269        while let Some(selection) = selections.next() {
 8270            // Find all the selections that span a contiguous row range
 8271            let (start_row, end_row) = consume_contiguous_rows(
 8272                &mut contiguous_row_selections,
 8273                selection,
 8274                &display_map,
 8275                &mut selections,
 8276            );
 8277
 8278            // Move the text spanned by the row range to be before the line preceding the row range
 8279            if start_row.0 > 0 {
 8280                let range_to_move = Point::new(
 8281                    start_row.previous_row().0,
 8282                    buffer.line_len(start_row.previous_row()),
 8283                )
 8284                    ..Point::new(
 8285                        end_row.previous_row().0,
 8286                        buffer.line_len(end_row.previous_row()),
 8287                    );
 8288                let insertion_point = display_map
 8289                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 8290                    .0;
 8291
 8292                // Don't move lines across excerpts
 8293                if buffer
 8294                    .excerpt_containing(insertion_point..range_to_move.end)
 8295                    .is_some()
 8296                {
 8297                    let text = buffer
 8298                        .text_for_range(range_to_move.clone())
 8299                        .flat_map(|s| s.chars())
 8300                        .skip(1)
 8301                        .chain(['\n'])
 8302                        .collect::<String>();
 8303
 8304                    edits.push((
 8305                        buffer.anchor_after(range_to_move.start)
 8306                            ..buffer.anchor_before(range_to_move.end),
 8307                        String::new(),
 8308                    ));
 8309                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8310                    edits.push((insertion_anchor..insertion_anchor, text));
 8311
 8312                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 8313
 8314                    // Move selections up
 8315                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8316                        |mut selection| {
 8317                            selection.start.row -= row_delta;
 8318                            selection.end.row -= row_delta;
 8319                            selection
 8320                        },
 8321                    ));
 8322
 8323                    // Move folds up
 8324                    unfold_ranges.push(range_to_move.clone());
 8325                    for fold in display_map.folds_in_range(
 8326                        buffer.anchor_before(range_to_move.start)
 8327                            ..buffer.anchor_after(range_to_move.end),
 8328                    ) {
 8329                        let mut start = fold.range.start.to_point(&buffer);
 8330                        let mut end = fold.range.end.to_point(&buffer);
 8331                        start.row -= row_delta;
 8332                        end.row -= row_delta;
 8333                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8334                    }
 8335                }
 8336            }
 8337
 8338            // If we didn't move line(s), preserve the existing selections
 8339            new_selections.append(&mut contiguous_row_selections);
 8340        }
 8341
 8342        self.transact(window, cx, |this, window, cx| {
 8343            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8344            this.buffer.update(cx, |buffer, cx| {
 8345                for (range, text) in edits {
 8346                    buffer.edit([(range, text)], None, cx);
 8347                }
 8348            });
 8349            this.fold_creases(refold_creases, true, window, cx);
 8350            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8351                s.select(new_selections);
 8352            })
 8353        });
 8354    }
 8355
 8356    pub fn move_line_down(
 8357        &mut self,
 8358        _: &MoveLineDown,
 8359        window: &mut Window,
 8360        cx: &mut Context<Self>,
 8361    ) {
 8362        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8363        let buffer = self.buffer.read(cx).snapshot(cx);
 8364
 8365        let mut edits = Vec::new();
 8366        let mut unfold_ranges = Vec::new();
 8367        let mut refold_creases = Vec::new();
 8368
 8369        let selections = self.selections.all::<Point>(cx);
 8370        let mut selections = selections.iter().peekable();
 8371        let mut contiguous_row_selections = Vec::new();
 8372        let mut new_selections = Vec::new();
 8373
 8374        while let Some(selection) = selections.next() {
 8375            // Find all the selections that span a contiguous row range
 8376            let (start_row, end_row) = consume_contiguous_rows(
 8377                &mut contiguous_row_selections,
 8378                selection,
 8379                &display_map,
 8380                &mut selections,
 8381            );
 8382
 8383            // Move the text spanned by the row range to be after the last line of the row range
 8384            if end_row.0 <= buffer.max_point().row {
 8385                let range_to_move =
 8386                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 8387                let insertion_point = display_map
 8388                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 8389                    .0;
 8390
 8391                // Don't move lines across excerpt boundaries
 8392                if buffer
 8393                    .excerpt_containing(range_to_move.start..insertion_point)
 8394                    .is_some()
 8395                {
 8396                    let mut text = String::from("\n");
 8397                    text.extend(buffer.text_for_range(range_to_move.clone()));
 8398                    text.pop(); // Drop trailing newline
 8399                    edits.push((
 8400                        buffer.anchor_after(range_to_move.start)
 8401                            ..buffer.anchor_before(range_to_move.end),
 8402                        String::new(),
 8403                    ));
 8404                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8405                    edits.push((insertion_anchor..insertion_anchor, text));
 8406
 8407                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 8408
 8409                    // Move selections down
 8410                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8411                        |mut selection| {
 8412                            selection.start.row += row_delta;
 8413                            selection.end.row += row_delta;
 8414                            selection
 8415                        },
 8416                    ));
 8417
 8418                    // Move folds down
 8419                    unfold_ranges.push(range_to_move.clone());
 8420                    for fold in display_map.folds_in_range(
 8421                        buffer.anchor_before(range_to_move.start)
 8422                            ..buffer.anchor_after(range_to_move.end),
 8423                    ) {
 8424                        let mut start = fold.range.start.to_point(&buffer);
 8425                        let mut end = fold.range.end.to_point(&buffer);
 8426                        start.row += row_delta;
 8427                        end.row += row_delta;
 8428                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8429                    }
 8430                }
 8431            }
 8432
 8433            // If we didn't move line(s), preserve the existing selections
 8434            new_selections.append(&mut contiguous_row_selections);
 8435        }
 8436
 8437        self.transact(window, cx, |this, window, cx| {
 8438            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8439            this.buffer.update(cx, |buffer, cx| {
 8440                for (range, text) in edits {
 8441                    buffer.edit([(range, text)], None, cx);
 8442                }
 8443            });
 8444            this.fold_creases(refold_creases, true, window, cx);
 8445            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8446                s.select(new_selections)
 8447            });
 8448        });
 8449    }
 8450
 8451    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 8452        let text_layout_details = &self.text_layout_details(window);
 8453        self.transact(window, cx, |this, window, cx| {
 8454            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8455                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 8456                let line_mode = s.line_mode;
 8457                s.move_with(|display_map, selection| {
 8458                    if !selection.is_empty() || line_mode {
 8459                        return;
 8460                    }
 8461
 8462                    let mut head = selection.head();
 8463                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 8464                    if head.column() == display_map.line_len(head.row()) {
 8465                        transpose_offset = display_map
 8466                            .buffer_snapshot
 8467                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8468                    }
 8469
 8470                    if transpose_offset == 0 {
 8471                        return;
 8472                    }
 8473
 8474                    *head.column_mut() += 1;
 8475                    head = display_map.clip_point(head, Bias::Right);
 8476                    let goal = SelectionGoal::HorizontalPosition(
 8477                        display_map
 8478                            .x_for_display_point(head, text_layout_details)
 8479                            .into(),
 8480                    );
 8481                    selection.collapse_to(head, goal);
 8482
 8483                    let transpose_start = display_map
 8484                        .buffer_snapshot
 8485                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8486                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 8487                        let transpose_end = display_map
 8488                            .buffer_snapshot
 8489                            .clip_offset(transpose_offset + 1, Bias::Right);
 8490                        if let Some(ch) =
 8491                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 8492                        {
 8493                            edits.push((transpose_start..transpose_offset, String::new()));
 8494                            edits.push((transpose_end..transpose_end, ch.to_string()));
 8495                        }
 8496                    }
 8497                });
 8498                edits
 8499            });
 8500            this.buffer
 8501                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8502            let selections = this.selections.all::<usize>(cx);
 8503            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8504                s.select(selections);
 8505            });
 8506        });
 8507    }
 8508
 8509    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 8510        self.rewrap_impl(IsVimMode::No, cx)
 8511    }
 8512
 8513    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 8514        let buffer = self.buffer.read(cx).snapshot(cx);
 8515        let selections = self.selections.all::<Point>(cx);
 8516        let mut selections = selections.iter().peekable();
 8517
 8518        let mut edits = Vec::new();
 8519        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 8520
 8521        while let Some(selection) = selections.next() {
 8522            let mut start_row = selection.start.row;
 8523            let mut end_row = selection.end.row;
 8524
 8525            // Skip selections that overlap with a range that has already been rewrapped.
 8526            let selection_range = start_row..end_row;
 8527            if rewrapped_row_ranges
 8528                .iter()
 8529                .any(|range| range.overlaps(&selection_range))
 8530            {
 8531                continue;
 8532            }
 8533
 8534            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 8535
 8536            // Since not all lines in the selection may be at the same indent
 8537            // level, choose the indent size that is the most common between all
 8538            // of the lines.
 8539            //
 8540            // If there is a tie, we use the deepest indent.
 8541            let (indent_size, indent_end) = {
 8542                let mut indent_size_occurrences = HashMap::default();
 8543                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 8544
 8545                for row in start_row..=end_row {
 8546                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 8547                    rows_by_indent_size.entry(indent).or_default().push(row);
 8548                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 8549                }
 8550
 8551                let indent_size = indent_size_occurrences
 8552                    .into_iter()
 8553                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 8554                    .map(|(indent, _)| indent)
 8555                    .unwrap_or_default();
 8556                let row = rows_by_indent_size[&indent_size][0];
 8557                let indent_end = Point::new(row, indent_size.len);
 8558
 8559                (indent_size, indent_end)
 8560            };
 8561
 8562            let mut line_prefix = indent_size.chars().collect::<String>();
 8563
 8564            let mut inside_comment = false;
 8565            if let Some(comment_prefix) =
 8566                buffer
 8567                    .language_scope_at(selection.head())
 8568                    .and_then(|language| {
 8569                        language
 8570                            .line_comment_prefixes()
 8571                            .iter()
 8572                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 8573                            .cloned()
 8574                    })
 8575            {
 8576                line_prefix.push_str(&comment_prefix);
 8577                inside_comment = true;
 8578            }
 8579
 8580            let language_settings = buffer.language_settings_at(selection.head(), cx);
 8581            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 8582                RewrapBehavior::InComments => inside_comment,
 8583                RewrapBehavior::InSelections => !selection.is_empty(),
 8584                RewrapBehavior::Anywhere => true,
 8585            };
 8586
 8587            let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
 8588            if !should_rewrap {
 8589                continue;
 8590            }
 8591
 8592            if selection.is_empty() {
 8593                'expand_upwards: while start_row > 0 {
 8594                    let prev_row = start_row - 1;
 8595                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 8596                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 8597                    {
 8598                        start_row = prev_row;
 8599                    } else {
 8600                        break 'expand_upwards;
 8601                    }
 8602                }
 8603
 8604                'expand_downwards: while end_row < buffer.max_point().row {
 8605                    let next_row = end_row + 1;
 8606                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 8607                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 8608                    {
 8609                        end_row = next_row;
 8610                    } else {
 8611                        break 'expand_downwards;
 8612                    }
 8613                }
 8614            }
 8615
 8616            let start = Point::new(start_row, 0);
 8617            let start_offset = start.to_offset(&buffer);
 8618            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 8619            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 8620            let Some(lines_without_prefixes) = selection_text
 8621                .lines()
 8622                .map(|line| {
 8623                    line.strip_prefix(&line_prefix)
 8624                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 8625                        .ok_or_else(|| {
 8626                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 8627                        })
 8628                })
 8629                .collect::<Result<Vec<_>, _>>()
 8630                .log_err()
 8631            else {
 8632                continue;
 8633            };
 8634
 8635            let wrap_column = buffer
 8636                .language_settings_at(Point::new(start_row, 0), cx)
 8637                .preferred_line_length as usize;
 8638            let wrapped_text = wrap_with_prefix(
 8639                line_prefix,
 8640                lines_without_prefixes.join(" "),
 8641                wrap_column,
 8642                tab_size,
 8643            );
 8644
 8645            // TODO: should always use char-based diff while still supporting cursor behavior that
 8646            // matches vim.
 8647            let mut diff_options = DiffOptions::default();
 8648            if is_vim_mode == IsVimMode::Yes {
 8649                diff_options.max_word_diff_len = 0;
 8650                diff_options.max_word_diff_line_count = 0;
 8651            } else {
 8652                diff_options.max_word_diff_len = usize::MAX;
 8653                diff_options.max_word_diff_line_count = usize::MAX;
 8654            }
 8655
 8656            for (old_range, new_text) in
 8657                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 8658            {
 8659                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 8660                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 8661                edits.push((edit_start..edit_end, new_text));
 8662            }
 8663
 8664            rewrapped_row_ranges.push(start_row..=end_row);
 8665        }
 8666
 8667        self.buffer
 8668            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8669    }
 8670
 8671    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 8672        let mut text = String::new();
 8673        let buffer = self.buffer.read(cx).snapshot(cx);
 8674        let mut selections = self.selections.all::<Point>(cx);
 8675        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8676        {
 8677            let max_point = buffer.max_point();
 8678            let mut is_first = true;
 8679            for selection in &mut selections {
 8680                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8681                if is_entire_line {
 8682                    selection.start = Point::new(selection.start.row, 0);
 8683                    if !selection.is_empty() && selection.end.column == 0 {
 8684                        selection.end = cmp::min(max_point, selection.end);
 8685                    } else {
 8686                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 8687                    }
 8688                    selection.goal = SelectionGoal::None;
 8689                }
 8690                if is_first {
 8691                    is_first = false;
 8692                } else {
 8693                    text += "\n";
 8694                }
 8695                let mut len = 0;
 8696                for chunk in buffer.text_for_range(selection.start..selection.end) {
 8697                    text.push_str(chunk);
 8698                    len += chunk.len();
 8699                }
 8700                clipboard_selections.push(ClipboardSelection {
 8701                    len,
 8702                    is_entire_line,
 8703                    first_line_indent: buffer
 8704                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 8705                        .len,
 8706                });
 8707            }
 8708        }
 8709
 8710        self.transact(window, cx, |this, window, cx| {
 8711            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8712                s.select(selections);
 8713            });
 8714            this.insert("", window, cx);
 8715        });
 8716        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 8717    }
 8718
 8719    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8720        let item = self.cut_common(window, cx);
 8721        cx.write_to_clipboard(item);
 8722    }
 8723
 8724    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8725        self.change_selections(None, window, cx, |s| {
 8726            s.move_with(|snapshot, sel| {
 8727                if sel.is_empty() {
 8728                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8729                }
 8730            });
 8731        });
 8732        let item = self.cut_common(window, cx);
 8733        cx.set_global(KillRing(item))
 8734    }
 8735
 8736    pub fn kill_ring_yank(
 8737        &mut self,
 8738        _: &KillRingYank,
 8739        window: &mut Window,
 8740        cx: &mut Context<Self>,
 8741    ) {
 8742        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8743            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8744                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8745            } else {
 8746                return;
 8747            }
 8748        } else {
 8749            return;
 8750        };
 8751        self.do_paste(&text, metadata, false, window, cx);
 8752    }
 8753
 8754    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8755        let selections = self.selections.all::<Point>(cx);
 8756        let buffer = self.buffer.read(cx).read(cx);
 8757        let mut text = String::new();
 8758
 8759        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8760        {
 8761            let max_point = buffer.max_point();
 8762            let mut is_first = true;
 8763            for selection in selections.iter() {
 8764                let mut start = selection.start;
 8765                let mut end = selection.end;
 8766                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8767                if is_entire_line {
 8768                    start = Point::new(start.row, 0);
 8769                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8770                }
 8771                if is_first {
 8772                    is_first = false;
 8773                } else {
 8774                    text += "\n";
 8775                }
 8776                let mut len = 0;
 8777                for chunk in buffer.text_for_range(start..end) {
 8778                    text.push_str(chunk);
 8779                    len += chunk.len();
 8780                }
 8781                clipboard_selections.push(ClipboardSelection {
 8782                    len,
 8783                    is_entire_line,
 8784                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 8785                });
 8786            }
 8787        }
 8788
 8789        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8790            text,
 8791            clipboard_selections,
 8792        ));
 8793    }
 8794
 8795    pub fn do_paste(
 8796        &mut self,
 8797        text: &String,
 8798        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8799        handle_entire_lines: bool,
 8800        window: &mut Window,
 8801        cx: &mut Context<Self>,
 8802    ) {
 8803        if self.read_only(cx) {
 8804            return;
 8805        }
 8806
 8807        let clipboard_text = Cow::Borrowed(text);
 8808
 8809        self.transact(window, cx, |this, window, cx| {
 8810            if let Some(mut clipboard_selections) = clipboard_selections {
 8811                let old_selections = this.selections.all::<usize>(cx);
 8812                let all_selections_were_entire_line =
 8813                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8814                let first_selection_indent_column =
 8815                    clipboard_selections.first().map(|s| s.first_line_indent);
 8816                if clipboard_selections.len() != old_selections.len() {
 8817                    clipboard_selections.drain(..);
 8818                }
 8819                let cursor_offset = this.selections.last::<usize>(cx).head();
 8820                let mut auto_indent_on_paste = true;
 8821
 8822                this.buffer.update(cx, |buffer, cx| {
 8823                    let snapshot = buffer.read(cx);
 8824                    auto_indent_on_paste = snapshot
 8825                        .language_settings_at(cursor_offset, cx)
 8826                        .auto_indent_on_paste;
 8827
 8828                    let mut start_offset = 0;
 8829                    let mut edits = Vec::new();
 8830                    let mut original_indent_columns = Vec::new();
 8831                    for (ix, selection) in old_selections.iter().enumerate() {
 8832                        let to_insert;
 8833                        let entire_line;
 8834                        let original_indent_column;
 8835                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8836                            let end_offset = start_offset + clipboard_selection.len;
 8837                            to_insert = &clipboard_text[start_offset..end_offset];
 8838                            entire_line = clipboard_selection.is_entire_line;
 8839                            start_offset = end_offset + 1;
 8840                            original_indent_column = Some(clipboard_selection.first_line_indent);
 8841                        } else {
 8842                            to_insert = clipboard_text.as_str();
 8843                            entire_line = all_selections_were_entire_line;
 8844                            original_indent_column = first_selection_indent_column
 8845                        }
 8846
 8847                        // If the corresponding selection was empty when this slice of the
 8848                        // clipboard text was written, then the entire line containing the
 8849                        // selection was copied. If this selection is also currently empty,
 8850                        // then paste the line before the current line of the buffer.
 8851                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8852                            let column = selection.start.to_point(&snapshot).column as usize;
 8853                            let line_start = selection.start - column;
 8854                            line_start..line_start
 8855                        } else {
 8856                            selection.range()
 8857                        };
 8858
 8859                        edits.push((range, to_insert));
 8860                        original_indent_columns.push(original_indent_column);
 8861                    }
 8862                    drop(snapshot);
 8863
 8864                    buffer.edit(
 8865                        edits,
 8866                        if auto_indent_on_paste {
 8867                            Some(AutoindentMode::Block {
 8868                                original_indent_columns,
 8869                            })
 8870                        } else {
 8871                            None
 8872                        },
 8873                        cx,
 8874                    );
 8875                });
 8876
 8877                let selections = this.selections.all::<usize>(cx);
 8878                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8879                    s.select(selections)
 8880                });
 8881            } else {
 8882                this.insert(&clipboard_text, window, cx);
 8883            }
 8884        });
 8885    }
 8886
 8887    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8888        if let Some(item) = cx.read_from_clipboard() {
 8889            let entries = item.entries();
 8890
 8891            match entries.first() {
 8892                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8893                // of all the pasted entries.
 8894                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8895                    .do_paste(
 8896                        clipboard_string.text(),
 8897                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8898                        true,
 8899                        window,
 8900                        cx,
 8901                    ),
 8902                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8903            }
 8904        }
 8905    }
 8906
 8907    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8908        if self.read_only(cx) {
 8909            return;
 8910        }
 8911
 8912        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8913            if let Some((selections, _)) =
 8914                self.selection_history.transaction(transaction_id).cloned()
 8915            {
 8916                self.change_selections(None, window, cx, |s| {
 8917                    s.select_anchors(selections.to_vec());
 8918                });
 8919            } else {
 8920                log::error!(
 8921                    "No entry in selection_history found for undo. \
 8922                     This may correspond to a bug where undo does not update the selection. \
 8923                     If this is occurring, please add details to \
 8924                     https://github.com/zed-industries/zed/issues/22692"
 8925                );
 8926            }
 8927            self.request_autoscroll(Autoscroll::fit(), cx);
 8928            self.unmark_text(window, cx);
 8929            self.refresh_inline_completion(true, false, window, cx);
 8930            cx.emit(EditorEvent::Edited { transaction_id });
 8931            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8932        }
 8933    }
 8934
 8935    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8936        if self.read_only(cx) {
 8937            return;
 8938        }
 8939
 8940        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8941            if let Some((_, Some(selections))) =
 8942                self.selection_history.transaction(transaction_id).cloned()
 8943            {
 8944                self.change_selections(None, window, cx, |s| {
 8945                    s.select_anchors(selections.to_vec());
 8946                });
 8947            } else {
 8948                log::error!(
 8949                    "No entry in selection_history found for redo. \
 8950                     This may correspond to a bug where undo does not update the selection. \
 8951                     If this is occurring, please add details to \
 8952                     https://github.com/zed-industries/zed/issues/22692"
 8953                );
 8954            }
 8955            self.request_autoscroll(Autoscroll::fit(), cx);
 8956            self.unmark_text(window, cx);
 8957            self.refresh_inline_completion(true, false, window, cx);
 8958            cx.emit(EditorEvent::Edited { transaction_id });
 8959        }
 8960    }
 8961
 8962    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8963        self.buffer
 8964            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8965    }
 8966
 8967    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8968        self.buffer
 8969            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8970    }
 8971
 8972    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8973        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8974            let line_mode = s.line_mode;
 8975            s.move_with(|map, selection| {
 8976                let cursor = if selection.is_empty() && !line_mode {
 8977                    movement::left(map, selection.start)
 8978                } else {
 8979                    selection.start
 8980                };
 8981                selection.collapse_to(cursor, SelectionGoal::None);
 8982            });
 8983        })
 8984    }
 8985
 8986    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8987        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8988            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8989        })
 8990    }
 8991
 8992    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8993        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8994            let line_mode = s.line_mode;
 8995            s.move_with(|map, selection| {
 8996                let cursor = if selection.is_empty() && !line_mode {
 8997                    movement::right(map, selection.end)
 8998                } else {
 8999                    selection.end
 9000                };
 9001                selection.collapse_to(cursor, SelectionGoal::None)
 9002            });
 9003        })
 9004    }
 9005
 9006    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 9007        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9008            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 9009        })
 9010    }
 9011
 9012    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 9013        if self.take_rename(true, window, cx).is_some() {
 9014            return;
 9015        }
 9016
 9017        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9018            cx.propagate();
 9019            return;
 9020        }
 9021
 9022        let text_layout_details = &self.text_layout_details(window);
 9023        let selection_count = self.selections.count();
 9024        let first_selection = self.selections.first_anchor();
 9025
 9026        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9027            let line_mode = s.line_mode;
 9028            s.move_with(|map, selection| {
 9029                if !selection.is_empty() && !line_mode {
 9030                    selection.goal = SelectionGoal::None;
 9031                }
 9032                let (cursor, goal) = movement::up(
 9033                    map,
 9034                    selection.start,
 9035                    selection.goal,
 9036                    false,
 9037                    text_layout_details,
 9038                );
 9039                selection.collapse_to(cursor, goal);
 9040            });
 9041        });
 9042
 9043        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9044        {
 9045            cx.propagate();
 9046        }
 9047    }
 9048
 9049    pub fn move_up_by_lines(
 9050        &mut self,
 9051        action: &MoveUpByLines,
 9052        window: &mut Window,
 9053        cx: &mut Context<Self>,
 9054    ) {
 9055        if self.take_rename(true, window, cx).is_some() {
 9056            return;
 9057        }
 9058
 9059        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9060            cx.propagate();
 9061            return;
 9062        }
 9063
 9064        let text_layout_details = &self.text_layout_details(window);
 9065
 9066        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9067            let line_mode = s.line_mode;
 9068            s.move_with(|map, selection| {
 9069                if !selection.is_empty() && !line_mode {
 9070                    selection.goal = SelectionGoal::None;
 9071                }
 9072                let (cursor, goal) = movement::up_by_rows(
 9073                    map,
 9074                    selection.start,
 9075                    action.lines,
 9076                    selection.goal,
 9077                    false,
 9078                    text_layout_details,
 9079                );
 9080                selection.collapse_to(cursor, goal);
 9081            });
 9082        })
 9083    }
 9084
 9085    pub fn move_down_by_lines(
 9086        &mut self,
 9087        action: &MoveDownByLines,
 9088        window: &mut Window,
 9089        cx: &mut Context<Self>,
 9090    ) {
 9091        if self.take_rename(true, window, cx).is_some() {
 9092            return;
 9093        }
 9094
 9095        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9096            cx.propagate();
 9097            return;
 9098        }
 9099
 9100        let text_layout_details = &self.text_layout_details(window);
 9101
 9102        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9103            let line_mode = s.line_mode;
 9104            s.move_with(|map, selection| {
 9105                if !selection.is_empty() && !line_mode {
 9106                    selection.goal = SelectionGoal::None;
 9107                }
 9108                let (cursor, goal) = movement::down_by_rows(
 9109                    map,
 9110                    selection.start,
 9111                    action.lines,
 9112                    selection.goal,
 9113                    false,
 9114                    text_layout_details,
 9115                );
 9116                selection.collapse_to(cursor, goal);
 9117            });
 9118        })
 9119    }
 9120
 9121    pub fn select_down_by_lines(
 9122        &mut self,
 9123        action: &SelectDownByLines,
 9124        window: &mut Window,
 9125        cx: &mut Context<Self>,
 9126    ) {
 9127        let text_layout_details = &self.text_layout_details(window);
 9128        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9129            s.move_heads_with(|map, head, goal| {
 9130                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9131            })
 9132        })
 9133    }
 9134
 9135    pub fn select_up_by_lines(
 9136        &mut self,
 9137        action: &SelectUpByLines,
 9138        window: &mut Window,
 9139        cx: &mut Context<Self>,
 9140    ) {
 9141        let text_layout_details = &self.text_layout_details(window);
 9142        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9143            s.move_heads_with(|map, head, goal| {
 9144                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9145            })
 9146        })
 9147    }
 9148
 9149    pub fn select_page_up(
 9150        &mut self,
 9151        _: &SelectPageUp,
 9152        window: &mut Window,
 9153        cx: &mut Context<Self>,
 9154    ) {
 9155        let Some(row_count) = self.visible_row_count() else {
 9156            return;
 9157        };
 9158
 9159        let text_layout_details = &self.text_layout_details(window);
 9160
 9161        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9162            s.move_heads_with(|map, head, goal| {
 9163                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 9164            })
 9165        })
 9166    }
 9167
 9168    pub fn move_page_up(
 9169        &mut self,
 9170        action: &MovePageUp,
 9171        window: &mut Window,
 9172        cx: &mut Context<Self>,
 9173    ) {
 9174        if self.take_rename(true, window, cx).is_some() {
 9175            return;
 9176        }
 9177
 9178        if self
 9179            .context_menu
 9180            .borrow_mut()
 9181            .as_mut()
 9182            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 9183            .unwrap_or(false)
 9184        {
 9185            return;
 9186        }
 9187
 9188        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9189            cx.propagate();
 9190            return;
 9191        }
 9192
 9193        let Some(row_count) = self.visible_row_count() else {
 9194            return;
 9195        };
 9196
 9197        let autoscroll = if action.center_cursor {
 9198            Autoscroll::center()
 9199        } else {
 9200            Autoscroll::fit()
 9201        };
 9202
 9203        let text_layout_details = &self.text_layout_details(window);
 9204
 9205        self.change_selections(Some(autoscroll), window, cx, |s| {
 9206            let line_mode = s.line_mode;
 9207            s.move_with(|map, selection| {
 9208                if !selection.is_empty() && !line_mode {
 9209                    selection.goal = SelectionGoal::None;
 9210                }
 9211                let (cursor, goal) = movement::up_by_rows(
 9212                    map,
 9213                    selection.end,
 9214                    row_count,
 9215                    selection.goal,
 9216                    false,
 9217                    text_layout_details,
 9218                );
 9219                selection.collapse_to(cursor, goal);
 9220            });
 9221        });
 9222    }
 9223
 9224    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 9225        let text_layout_details = &self.text_layout_details(window);
 9226        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9227            s.move_heads_with(|map, head, goal| {
 9228                movement::up(map, head, goal, false, text_layout_details)
 9229            })
 9230        })
 9231    }
 9232
 9233    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 9234        self.take_rename(true, window, cx);
 9235
 9236        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9237            cx.propagate();
 9238            return;
 9239        }
 9240
 9241        let text_layout_details = &self.text_layout_details(window);
 9242        let selection_count = self.selections.count();
 9243        let first_selection = self.selections.first_anchor();
 9244
 9245        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9246            let line_mode = s.line_mode;
 9247            s.move_with(|map, selection| {
 9248                if !selection.is_empty() && !line_mode {
 9249                    selection.goal = SelectionGoal::None;
 9250                }
 9251                let (cursor, goal) = movement::down(
 9252                    map,
 9253                    selection.end,
 9254                    selection.goal,
 9255                    false,
 9256                    text_layout_details,
 9257                );
 9258                selection.collapse_to(cursor, goal);
 9259            });
 9260        });
 9261
 9262        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9263        {
 9264            cx.propagate();
 9265        }
 9266    }
 9267
 9268    pub fn select_page_down(
 9269        &mut self,
 9270        _: &SelectPageDown,
 9271        window: &mut Window,
 9272        cx: &mut Context<Self>,
 9273    ) {
 9274        let Some(row_count) = self.visible_row_count() else {
 9275            return;
 9276        };
 9277
 9278        let text_layout_details = &self.text_layout_details(window);
 9279
 9280        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9281            s.move_heads_with(|map, head, goal| {
 9282                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 9283            })
 9284        })
 9285    }
 9286
 9287    pub fn move_page_down(
 9288        &mut self,
 9289        action: &MovePageDown,
 9290        window: &mut Window,
 9291        cx: &mut Context<Self>,
 9292    ) {
 9293        if self.take_rename(true, window, cx).is_some() {
 9294            return;
 9295        }
 9296
 9297        if self
 9298            .context_menu
 9299            .borrow_mut()
 9300            .as_mut()
 9301            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 9302            .unwrap_or(false)
 9303        {
 9304            return;
 9305        }
 9306
 9307        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9308            cx.propagate();
 9309            return;
 9310        }
 9311
 9312        let Some(row_count) = self.visible_row_count() else {
 9313            return;
 9314        };
 9315
 9316        let autoscroll = if action.center_cursor {
 9317            Autoscroll::center()
 9318        } else {
 9319            Autoscroll::fit()
 9320        };
 9321
 9322        let text_layout_details = &self.text_layout_details(window);
 9323        self.change_selections(Some(autoscroll), window, cx, |s| {
 9324            let line_mode = s.line_mode;
 9325            s.move_with(|map, selection| {
 9326                if !selection.is_empty() && !line_mode {
 9327                    selection.goal = SelectionGoal::None;
 9328                }
 9329                let (cursor, goal) = movement::down_by_rows(
 9330                    map,
 9331                    selection.end,
 9332                    row_count,
 9333                    selection.goal,
 9334                    false,
 9335                    text_layout_details,
 9336                );
 9337                selection.collapse_to(cursor, goal);
 9338            });
 9339        });
 9340    }
 9341
 9342    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 9343        let text_layout_details = &self.text_layout_details(window);
 9344        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9345            s.move_heads_with(|map, head, goal| {
 9346                movement::down(map, head, goal, false, text_layout_details)
 9347            })
 9348        });
 9349    }
 9350
 9351    pub fn context_menu_first(
 9352        &mut self,
 9353        _: &ContextMenuFirst,
 9354        _window: &mut Window,
 9355        cx: &mut Context<Self>,
 9356    ) {
 9357        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9358            context_menu.select_first(self.completion_provider.as_deref(), cx);
 9359        }
 9360    }
 9361
 9362    pub fn context_menu_prev(
 9363        &mut self,
 9364        _: &ContextMenuPrevious,
 9365        _window: &mut Window,
 9366        cx: &mut Context<Self>,
 9367    ) {
 9368        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9369            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 9370        }
 9371    }
 9372
 9373    pub fn context_menu_next(
 9374        &mut self,
 9375        _: &ContextMenuNext,
 9376        _window: &mut Window,
 9377        cx: &mut Context<Self>,
 9378    ) {
 9379        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9380            context_menu.select_next(self.completion_provider.as_deref(), cx);
 9381        }
 9382    }
 9383
 9384    pub fn context_menu_last(
 9385        &mut self,
 9386        _: &ContextMenuLast,
 9387        _window: &mut Window,
 9388        cx: &mut Context<Self>,
 9389    ) {
 9390        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9391            context_menu.select_last(self.completion_provider.as_deref(), cx);
 9392        }
 9393    }
 9394
 9395    pub fn move_to_previous_word_start(
 9396        &mut self,
 9397        _: &MoveToPreviousWordStart,
 9398        window: &mut Window,
 9399        cx: &mut Context<Self>,
 9400    ) {
 9401        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9402            s.move_cursors_with(|map, head, _| {
 9403                (
 9404                    movement::previous_word_start(map, head),
 9405                    SelectionGoal::None,
 9406                )
 9407            });
 9408        })
 9409    }
 9410
 9411    pub fn move_to_previous_subword_start(
 9412        &mut self,
 9413        _: &MoveToPreviousSubwordStart,
 9414        window: &mut Window,
 9415        cx: &mut Context<Self>,
 9416    ) {
 9417        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9418            s.move_cursors_with(|map, head, _| {
 9419                (
 9420                    movement::previous_subword_start(map, head),
 9421                    SelectionGoal::None,
 9422                )
 9423            });
 9424        })
 9425    }
 9426
 9427    pub fn select_to_previous_word_start(
 9428        &mut self,
 9429        _: &SelectToPreviousWordStart,
 9430        window: &mut Window,
 9431        cx: &mut Context<Self>,
 9432    ) {
 9433        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9434            s.move_heads_with(|map, head, _| {
 9435                (
 9436                    movement::previous_word_start(map, head),
 9437                    SelectionGoal::None,
 9438                )
 9439            });
 9440        })
 9441    }
 9442
 9443    pub fn select_to_previous_subword_start(
 9444        &mut self,
 9445        _: &SelectToPreviousSubwordStart,
 9446        window: &mut Window,
 9447        cx: &mut Context<Self>,
 9448    ) {
 9449        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9450            s.move_heads_with(|map, head, _| {
 9451                (
 9452                    movement::previous_subword_start(map, head),
 9453                    SelectionGoal::None,
 9454                )
 9455            });
 9456        })
 9457    }
 9458
 9459    pub fn delete_to_previous_word_start(
 9460        &mut self,
 9461        action: &DeleteToPreviousWordStart,
 9462        window: &mut Window,
 9463        cx: &mut Context<Self>,
 9464    ) {
 9465        self.transact(window, cx, |this, window, cx| {
 9466            this.select_autoclose_pair(window, cx);
 9467            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9468                let line_mode = s.line_mode;
 9469                s.move_with(|map, selection| {
 9470                    if selection.is_empty() && !line_mode {
 9471                        let cursor = if action.ignore_newlines {
 9472                            movement::previous_word_start(map, selection.head())
 9473                        } else {
 9474                            movement::previous_word_start_or_newline(map, selection.head())
 9475                        };
 9476                        selection.set_head(cursor, SelectionGoal::None);
 9477                    }
 9478                });
 9479            });
 9480            this.insert("", window, cx);
 9481        });
 9482    }
 9483
 9484    pub fn delete_to_previous_subword_start(
 9485        &mut self,
 9486        _: &DeleteToPreviousSubwordStart,
 9487        window: &mut Window,
 9488        cx: &mut Context<Self>,
 9489    ) {
 9490        self.transact(window, cx, |this, window, cx| {
 9491            this.select_autoclose_pair(window, cx);
 9492            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9493                let line_mode = s.line_mode;
 9494                s.move_with(|map, selection| {
 9495                    if selection.is_empty() && !line_mode {
 9496                        let cursor = movement::previous_subword_start(map, selection.head());
 9497                        selection.set_head(cursor, SelectionGoal::None);
 9498                    }
 9499                });
 9500            });
 9501            this.insert("", window, cx);
 9502        });
 9503    }
 9504
 9505    pub fn move_to_next_word_end(
 9506        &mut self,
 9507        _: &MoveToNextWordEnd,
 9508        window: &mut Window,
 9509        cx: &mut Context<Self>,
 9510    ) {
 9511        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9512            s.move_cursors_with(|map, head, _| {
 9513                (movement::next_word_end(map, head), SelectionGoal::None)
 9514            });
 9515        })
 9516    }
 9517
 9518    pub fn move_to_next_subword_end(
 9519        &mut self,
 9520        _: &MoveToNextSubwordEnd,
 9521        window: &mut Window,
 9522        cx: &mut Context<Self>,
 9523    ) {
 9524        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9525            s.move_cursors_with(|map, head, _| {
 9526                (movement::next_subword_end(map, head), SelectionGoal::None)
 9527            });
 9528        })
 9529    }
 9530
 9531    pub fn select_to_next_word_end(
 9532        &mut self,
 9533        _: &SelectToNextWordEnd,
 9534        window: &mut Window,
 9535        cx: &mut Context<Self>,
 9536    ) {
 9537        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9538            s.move_heads_with(|map, head, _| {
 9539                (movement::next_word_end(map, head), SelectionGoal::None)
 9540            });
 9541        })
 9542    }
 9543
 9544    pub fn select_to_next_subword_end(
 9545        &mut self,
 9546        _: &SelectToNextSubwordEnd,
 9547        window: &mut Window,
 9548        cx: &mut Context<Self>,
 9549    ) {
 9550        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9551            s.move_heads_with(|map, head, _| {
 9552                (movement::next_subword_end(map, head), SelectionGoal::None)
 9553            });
 9554        })
 9555    }
 9556
 9557    pub fn delete_to_next_word_end(
 9558        &mut self,
 9559        action: &DeleteToNextWordEnd,
 9560        window: &mut Window,
 9561        cx: &mut Context<Self>,
 9562    ) {
 9563        self.transact(window, cx, |this, window, cx| {
 9564            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9565                let line_mode = s.line_mode;
 9566                s.move_with(|map, selection| {
 9567                    if selection.is_empty() && !line_mode {
 9568                        let cursor = if action.ignore_newlines {
 9569                            movement::next_word_end(map, selection.head())
 9570                        } else {
 9571                            movement::next_word_end_or_newline(map, selection.head())
 9572                        };
 9573                        selection.set_head(cursor, SelectionGoal::None);
 9574                    }
 9575                });
 9576            });
 9577            this.insert("", window, cx);
 9578        });
 9579    }
 9580
 9581    pub fn delete_to_next_subword_end(
 9582        &mut self,
 9583        _: &DeleteToNextSubwordEnd,
 9584        window: &mut Window,
 9585        cx: &mut Context<Self>,
 9586    ) {
 9587        self.transact(window, cx, |this, window, cx| {
 9588            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9589                s.move_with(|map, selection| {
 9590                    if selection.is_empty() {
 9591                        let cursor = movement::next_subword_end(map, selection.head());
 9592                        selection.set_head(cursor, SelectionGoal::None);
 9593                    }
 9594                });
 9595            });
 9596            this.insert("", window, cx);
 9597        });
 9598    }
 9599
 9600    pub fn move_to_beginning_of_line(
 9601        &mut self,
 9602        action: &MoveToBeginningOfLine,
 9603        window: &mut Window,
 9604        cx: &mut Context<Self>,
 9605    ) {
 9606        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9607            s.move_cursors_with(|map, head, _| {
 9608                (
 9609                    movement::indented_line_beginning(
 9610                        map,
 9611                        head,
 9612                        action.stop_at_soft_wraps,
 9613                        action.stop_at_indent,
 9614                    ),
 9615                    SelectionGoal::None,
 9616                )
 9617            });
 9618        })
 9619    }
 9620
 9621    pub fn select_to_beginning_of_line(
 9622        &mut self,
 9623        action: &SelectToBeginningOfLine,
 9624        window: &mut Window,
 9625        cx: &mut Context<Self>,
 9626    ) {
 9627        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9628            s.move_heads_with(|map, head, _| {
 9629                (
 9630                    movement::indented_line_beginning(
 9631                        map,
 9632                        head,
 9633                        action.stop_at_soft_wraps,
 9634                        action.stop_at_indent,
 9635                    ),
 9636                    SelectionGoal::None,
 9637                )
 9638            });
 9639        });
 9640    }
 9641
 9642    pub fn delete_to_beginning_of_line(
 9643        &mut self,
 9644        action: &DeleteToBeginningOfLine,
 9645        window: &mut Window,
 9646        cx: &mut Context<Self>,
 9647    ) {
 9648        self.transact(window, cx, |this, window, cx| {
 9649            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9650                s.move_with(|_, selection| {
 9651                    selection.reversed = true;
 9652                });
 9653            });
 9654
 9655            this.select_to_beginning_of_line(
 9656                &SelectToBeginningOfLine {
 9657                    stop_at_soft_wraps: false,
 9658                    stop_at_indent: action.stop_at_indent,
 9659                },
 9660                window,
 9661                cx,
 9662            );
 9663            this.backspace(&Backspace, window, cx);
 9664        });
 9665    }
 9666
 9667    pub fn move_to_end_of_line(
 9668        &mut self,
 9669        action: &MoveToEndOfLine,
 9670        window: &mut Window,
 9671        cx: &mut Context<Self>,
 9672    ) {
 9673        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9674            s.move_cursors_with(|map, head, _| {
 9675                (
 9676                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9677                    SelectionGoal::None,
 9678                )
 9679            });
 9680        })
 9681    }
 9682
 9683    pub fn select_to_end_of_line(
 9684        &mut self,
 9685        action: &SelectToEndOfLine,
 9686        window: &mut Window,
 9687        cx: &mut Context<Self>,
 9688    ) {
 9689        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9690            s.move_heads_with(|map, head, _| {
 9691                (
 9692                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9693                    SelectionGoal::None,
 9694                )
 9695            });
 9696        })
 9697    }
 9698
 9699    pub fn delete_to_end_of_line(
 9700        &mut self,
 9701        _: &DeleteToEndOfLine,
 9702        window: &mut Window,
 9703        cx: &mut Context<Self>,
 9704    ) {
 9705        self.transact(window, cx, |this, window, cx| {
 9706            this.select_to_end_of_line(
 9707                &SelectToEndOfLine {
 9708                    stop_at_soft_wraps: false,
 9709                },
 9710                window,
 9711                cx,
 9712            );
 9713            this.delete(&Delete, window, cx);
 9714        });
 9715    }
 9716
 9717    pub fn cut_to_end_of_line(
 9718        &mut self,
 9719        _: &CutToEndOfLine,
 9720        window: &mut Window,
 9721        cx: &mut Context<Self>,
 9722    ) {
 9723        self.transact(window, cx, |this, window, cx| {
 9724            this.select_to_end_of_line(
 9725                &SelectToEndOfLine {
 9726                    stop_at_soft_wraps: false,
 9727                },
 9728                window,
 9729                cx,
 9730            );
 9731            this.cut(&Cut, window, cx);
 9732        });
 9733    }
 9734
 9735    pub fn move_to_start_of_paragraph(
 9736        &mut self,
 9737        _: &MoveToStartOfParagraph,
 9738        window: &mut Window,
 9739        cx: &mut Context<Self>,
 9740    ) {
 9741        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9742            cx.propagate();
 9743            return;
 9744        }
 9745
 9746        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9747            s.move_with(|map, selection| {
 9748                selection.collapse_to(
 9749                    movement::start_of_paragraph(map, selection.head(), 1),
 9750                    SelectionGoal::None,
 9751                )
 9752            });
 9753        })
 9754    }
 9755
 9756    pub fn move_to_end_of_paragraph(
 9757        &mut self,
 9758        _: &MoveToEndOfParagraph,
 9759        window: &mut Window,
 9760        cx: &mut Context<Self>,
 9761    ) {
 9762        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9763            cx.propagate();
 9764            return;
 9765        }
 9766
 9767        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9768            s.move_with(|map, selection| {
 9769                selection.collapse_to(
 9770                    movement::end_of_paragraph(map, selection.head(), 1),
 9771                    SelectionGoal::None,
 9772                )
 9773            });
 9774        })
 9775    }
 9776
 9777    pub fn select_to_start_of_paragraph(
 9778        &mut self,
 9779        _: &SelectToStartOfParagraph,
 9780        window: &mut Window,
 9781        cx: &mut Context<Self>,
 9782    ) {
 9783        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9784            cx.propagate();
 9785            return;
 9786        }
 9787
 9788        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9789            s.move_heads_with(|map, head, _| {
 9790                (
 9791                    movement::start_of_paragraph(map, head, 1),
 9792                    SelectionGoal::None,
 9793                )
 9794            });
 9795        })
 9796    }
 9797
 9798    pub fn select_to_end_of_paragraph(
 9799        &mut self,
 9800        _: &SelectToEndOfParagraph,
 9801        window: &mut Window,
 9802        cx: &mut Context<Self>,
 9803    ) {
 9804        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9805            cx.propagate();
 9806            return;
 9807        }
 9808
 9809        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9810            s.move_heads_with(|map, head, _| {
 9811                (
 9812                    movement::end_of_paragraph(map, head, 1),
 9813                    SelectionGoal::None,
 9814                )
 9815            });
 9816        })
 9817    }
 9818
 9819    pub fn move_to_start_of_excerpt(
 9820        &mut self,
 9821        _: &MoveToStartOfExcerpt,
 9822        window: &mut Window,
 9823        cx: &mut Context<Self>,
 9824    ) {
 9825        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9826            cx.propagate();
 9827            return;
 9828        }
 9829
 9830        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9831            s.move_with(|map, selection| {
 9832                selection.collapse_to(
 9833                    movement::start_of_excerpt(
 9834                        map,
 9835                        selection.head(),
 9836                        workspace::searchable::Direction::Prev,
 9837                    ),
 9838                    SelectionGoal::None,
 9839                )
 9840            });
 9841        })
 9842    }
 9843
 9844    pub fn move_to_start_of_next_excerpt(
 9845        &mut self,
 9846        _: &MoveToStartOfNextExcerpt,
 9847        window: &mut Window,
 9848        cx: &mut Context<Self>,
 9849    ) {
 9850        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9851            cx.propagate();
 9852            return;
 9853        }
 9854
 9855        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9856            s.move_with(|map, selection| {
 9857                selection.collapse_to(
 9858                    movement::start_of_excerpt(
 9859                        map,
 9860                        selection.head(),
 9861                        workspace::searchable::Direction::Next,
 9862                    ),
 9863                    SelectionGoal::None,
 9864                )
 9865            });
 9866        })
 9867    }
 9868
 9869    pub fn move_to_end_of_excerpt(
 9870        &mut self,
 9871        _: &MoveToEndOfExcerpt,
 9872        window: &mut Window,
 9873        cx: &mut Context<Self>,
 9874    ) {
 9875        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9876            cx.propagate();
 9877            return;
 9878        }
 9879
 9880        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9881            s.move_with(|map, selection| {
 9882                selection.collapse_to(
 9883                    movement::end_of_excerpt(
 9884                        map,
 9885                        selection.head(),
 9886                        workspace::searchable::Direction::Next,
 9887                    ),
 9888                    SelectionGoal::None,
 9889                )
 9890            });
 9891        })
 9892    }
 9893
 9894    pub fn move_to_end_of_previous_excerpt(
 9895        &mut self,
 9896        _: &MoveToEndOfPreviousExcerpt,
 9897        window: &mut Window,
 9898        cx: &mut Context<Self>,
 9899    ) {
 9900        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9901            cx.propagate();
 9902            return;
 9903        }
 9904
 9905        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9906            s.move_with(|map, selection| {
 9907                selection.collapse_to(
 9908                    movement::end_of_excerpt(
 9909                        map,
 9910                        selection.head(),
 9911                        workspace::searchable::Direction::Prev,
 9912                    ),
 9913                    SelectionGoal::None,
 9914                )
 9915            });
 9916        })
 9917    }
 9918
 9919    pub fn select_to_start_of_excerpt(
 9920        &mut self,
 9921        _: &SelectToStartOfExcerpt,
 9922        window: &mut Window,
 9923        cx: &mut Context<Self>,
 9924    ) {
 9925        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9926            cx.propagate();
 9927            return;
 9928        }
 9929
 9930        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9931            s.move_heads_with(|map, head, _| {
 9932                (
 9933                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
 9934                    SelectionGoal::None,
 9935                )
 9936            });
 9937        })
 9938    }
 9939
 9940    pub fn select_to_start_of_next_excerpt(
 9941        &mut self,
 9942        _: &SelectToStartOfNextExcerpt,
 9943        window: &mut Window,
 9944        cx: &mut Context<Self>,
 9945    ) {
 9946        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9947            cx.propagate();
 9948            return;
 9949        }
 9950
 9951        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9952            s.move_heads_with(|map, head, _| {
 9953                (
 9954                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
 9955                    SelectionGoal::None,
 9956                )
 9957            });
 9958        })
 9959    }
 9960
 9961    pub fn select_to_end_of_excerpt(
 9962        &mut self,
 9963        _: &SelectToEndOfExcerpt,
 9964        window: &mut Window,
 9965        cx: &mut Context<Self>,
 9966    ) {
 9967        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9968            cx.propagate();
 9969            return;
 9970        }
 9971
 9972        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9973            s.move_heads_with(|map, head, _| {
 9974                (
 9975                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
 9976                    SelectionGoal::None,
 9977                )
 9978            });
 9979        })
 9980    }
 9981
 9982    pub fn select_to_end_of_previous_excerpt(
 9983        &mut self,
 9984        _: &SelectToEndOfPreviousExcerpt,
 9985        window: &mut Window,
 9986        cx: &mut Context<Self>,
 9987    ) {
 9988        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9989            cx.propagate();
 9990            return;
 9991        }
 9992
 9993        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9994            s.move_heads_with(|map, head, _| {
 9995                (
 9996                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
 9997                    SelectionGoal::None,
 9998                )
 9999            });
10000        })
10001    }
10002
10003    pub fn move_to_beginning(
10004        &mut self,
10005        _: &MoveToBeginning,
10006        window: &mut Window,
10007        cx: &mut Context<Self>,
10008    ) {
10009        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10010            cx.propagate();
10011            return;
10012        }
10013
10014        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10015            s.select_ranges(vec![0..0]);
10016        });
10017    }
10018
10019    pub fn select_to_beginning(
10020        &mut self,
10021        _: &SelectToBeginning,
10022        window: &mut Window,
10023        cx: &mut Context<Self>,
10024    ) {
10025        let mut selection = self.selections.last::<Point>(cx);
10026        selection.set_head(Point::zero(), SelectionGoal::None);
10027
10028        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10029            s.select(vec![selection]);
10030        });
10031    }
10032
10033    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
10034        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10035            cx.propagate();
10036            return;
10037        }
10038
10039        let cursor = self.buffer.read(cx).read(cx).len();
10040        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10041            s.select_ranges(vec![cursor..cursor])
10042        });
10043    }
10044
10045    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
10046        self.nav_history = nav_history;
10047    }
10048
10049    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
10050        self.nav_history.as_ref()
10051    }
10052
10053    fn push_to_nav_history(
10054        &mut self,
10055        cursor_anchor: Anchor,
10056        new_position: Option<Point>,
10057        cx: &mut Context<Self>,
10058    ) {
10059        if let Some(nav_history) = self.nav_history.as_mut() {
10060            let buffer = self.buffer.read(cx).read(cx);
10061            let cursor_position = cursor_anchor.to_point(&buffer);
10062            let scroll_state = self.scroll_manager.anchor();
10063            let scroll_top_row = scroll_state.top_row(&buffer);
10064            drop(buffer);
10065
10066            if let Some(new_position) = new_position {
10067                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
10068                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
10069                    return;
10070                }
10071            }
10072
10073            nav_history.push(
10074                Some(NavigationData {
10075                    cursor_anchor,
10076                    cursor_position,
10077                    scroll_anchor: scroll_state,
10078                    scroll_top_row,
10079                }),
10080                cx,
10081            );
10082        }
10083    }
10084
10085    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
10086        let buffer = self.buffer.read(cx).snapshot(cx);
10087        let mut selection = self.selections.first::<usize>(cx);
10088        selection.set_head(buffer.len(), SelectionGoal::None);
10089        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10090            s.select(vec![selection]);
10091        });
10092    }
10093
10094    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
10095        let end = self.buffer.read(cx).read(cx).len();
10096        self.change_selections(None, window, cx, |s| {
10097            s.select_ranges(vec![0..end]);
10098        });
10099    }
10100
10101    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
10102        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10103        let mut selections = self.selections.all::<Point>(cx);
10104        let max_point = display_map.buffer_snapshot.max_point();
10105        for selection in &mut selections {
10106            let rows = selection.spanned_rows(true, &display_map);
10107            selection.start = Point::new(rows.start.0, 0);
10108            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
10109            selection.reversed = false;
10110        }
10111        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10112            s.select(selections);
10113        });
10114    }
10115
10116    pub fn split_selection_into_lines(
10117        &mut self,
10118        _: &SplitSelectionIntoLines,
10119        window: &mut Window,
10120        cx: &mut Context<Self>,
10121    ) {
10122        let selections = self
10123            .selections
10124            .all::<Point>(cx)
10125            .into_iter()
10126            .map(|selection| selection.start..selection.end)
10127            .collect::<Vec<_>>();
10128        self.unfold_ranges(&selections, true, true, cx);
10129
10130        let mut new_selection_ranges = Vec::new();
10131        {
10132            let buffer = self.buffer.read(cx).read(cx);
10133            for selection in selections {
10134                for row in selection.start.row..selection.end.row {
10135                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
10136                    new_selection_ranges.push(cursor..cursor);
10137                }
10138
10139                let is_multiline_selection = selection.start.row != selection.end.row;
10140                // Don't insert last one if it's a multi-line selection ending at the start of a line,
10141                // so this action feels more ergonomic when paired with other selection operations
10142                let should_skip_last = is_multiline_selection && selection.end.column == 0;
10143                if !should_skip_last {
10144                    new_selection_ranges.push(selection.end..selection.end);
10145                }
10146            }
10147        }
10148        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10149            s.select_ranges(new_selection_ranges);
10150        });
10151    }
10152
10153    pub fn add_selection_above(
10154        &mut self,
10155        _: &AddSelectionAbove,
10156        window: &mut Window,
10157        cx: &mut Context<Self>,
10158    ) {
10159        self.add_selection(true, window, cx);
10160    }
10161
10162    pub fn add_selection_below(
10163        &mut self,
10164        _: &AddSelectionBelow,
10165        window: &mut Window,
10166        cx: &mut Context<Self>,
10167    ) {
10168        self.add_selection(false, window, cx);
10169    }
10170
10171    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
10172        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10173        let mut selections = self.selections.all::<Point>(cx);
10174        let text_layout_details = self.text_layout_details(window);
10175        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10176            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10177            let range = oldest_selection.display_range(&display_map).sorted();
10178
10179            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10180            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10181            let positions = start_x.min(end_x)..start_x.max(end_x);
10182
10183            selections.clear();
10184            let mut stack = Vec::new();
10185            for row in range.start.row().0..=range.end.row().0 {
10186                if let Some(selection) = self.selections.build_columnar_selection(
10187                    &display_map,
10188                    DisplayRow(row),
10189                    &positions,
10190                    oldest_selection.reversed,
10191                    &text_layout_details,
10192                ) {
10193                    stack.push(selection.id);
10194                    selections.push(selection);
10195                }
10196            }
10197
10198            if above {
10199                stack.reverse();
10200            }
10201
10202            AddSelectionsState { above, stack }
10203        });
10204
10205        let last_added_selection = *state.stack.last().unwrap();
10206        let mut new_selections = Vec::new();
10207        if above == state.above {
10208            let end_row = if above {
10209                DisplayRow(0)
10210            } else {
10211                display_map.max_point().row()
10212            };
10213
10214            'outer: for selection in selections {
10215                if selection.id == last_added_selection {
10216                    let range = selection.display_range(&display_map).sorted();
10217                    debug_assert_eq!(range.start.row(), range.end.row());
10218                    let mut row = range.start.row();
10219                    let positions =
10220                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10221                            px(start)..px(end)
10222                        } else {
10223                            let start_x =
10224                                display_map.x_for_display_point(range.start, &text_layout_details);
10225                            let end_x =
10226                                display_map.x_for_display_point(range.end, &text_layout_details);
10227                            start_x.min(end_x)..start_x.max(end_x)
10228                        };
10229
10230                    while row != end_row {
10231                        if above {
10232                            row.0 -= 1;
10233                        } else {
10234                            row.0 += 1;
10235                        }
10236
10237                        if let Some(new_selection) = self.selections.build_columnar_selection(
10238                            &display_map,
10239                            row,
10240                            &positions,
10241                            selection.reversed,
10242                            &text_layout_details,
10243                        ) {
10244                            state.stack.push(new_selection.id);
10245                            if above {
10246                                new_selections.push(new_selection);
10247                                new_selections.push(selection);
10248                            } else {
10249                                new_selections.push(selection);
10250                                new_selections.push(new_selection);
10251                            }
10252
10253                            continue 'outer;
10254                        }
10255                    }
10256                }
10257
10258                new_selections.push(selection);
10259            }
10260        } else {
10261            new_selections = selections;
10262            new_selections.retain(|s| s.id != last_added_selection);
10263            state.stack.pop();
10264        }
10265
10266        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10267            s.select(new_selections);
10268        });
10269        if state.stack.len() > 1 {
10270            self.add_selections_state = Some(state);
10271        }
10272    }
10273
10274    pub fn select_next_match_internal(
10275        &mut self,
10276        display_map: &DisplaySnapshot,
10277        replace_newest: bool,
10278        autoscroll: Option<Autoscroll>,
10279        window: &mut Window,
10280        cx: &mut Context<Self>,
10281    ) -> Result<()> {
10282        fn select_next_match_ranges(
10283            this: &mut Editor,
10284            range: Range<usize>,
10285            replace_newest: bool,
10286            auto_scroll: Option<Autoscroll>,
10287            window: &mut Window,
10288            cx: &mut Context<Editor>,
10289        ) {
10290            this.unfold_ranges(&[range.clone()], false, true, cx);
10291            this.change_selections(auto_scroll, window, cx, |s| {
10292                if replace_newest {
10293                    s.delete(s.newest_anchor().id);
10294                }
10295                s.insert_range(range.clone());
10296            });
10297        }
10298
10299        let buffer = &display_map.buffer_snapshot;
10300        let mut selections = self.selections.all::<usize>(cx);
10301        if let Some(mut select_next_state) = self.select_next_state.take() {
10302            let query = &select_next_state.query;
10303            if !select_next_state.done {
10304                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10305                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10306                let mut next_selected_range = None;
10307
10308                let bytes_after_last_selection =
10309                    buffer.bytes_in_range(last_selection.end..buffer.len());
10310                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10311                let query_matches = query
10312                    .stream_find_iter(bytes_after_last_selection)
10313                    .map(|result| (last_selection.end, result))
10314                    .chain(
10315                        query
10316                            .stream_find_iter(bytes_before_first_selection)
10317                            .map(|result| (0, result)),
10318                    );
10319
10320                for (start_offset, query_match) in query_matches {
10321                    let query_match = query_match.unwrap(); // can only fail due to I/O
10322                    let offset_range =
10323                        start_offset + query_match.start()..start_offset + query_match.end();
10324                    let display_range = offset_range.start.to_display_point(display_map)
10325                        ..offset_range.end.to_display_point(display_map);
10326
10327                    if !select_next_state.wordwise
10328                        || (!movement::is_inside_word(display_map, display_range.start)
10329                            && !movement::is_inside_word(display_map, display_range.end))
10330                    {
10331                        // TODO: This is n^2, because we might check all the selections
10332                        if !selections
10333                            .iter()
10334                            .any(|selection| selection.range().overlaps(&offset_range))
10335                        {
10336                            next_selected_range = Some(offset_range);
10337                            break;
10338                        }
10339                    }
10340                }
10341
10342                if let Some(next_selected_range) = next_selected_range {
10343                    select_next_match_ranges(
10344                        self,
10345                        next_selected_range,
10346                        replace_newest,
10347                        autoscroll,
10348                        window,
10349                        cx,
10350                    );
10351                } else {
10352                    select_next_state.done = true;
10353                }
10354            }
10355
10356            self.select_next_state = Some(select_next_state);
10357        } else {
10358            let mut only_carets = true;
10359            let mut same_text_selected = true;
10360            let mut selected_text = None;
10361
10362            let mut selections_iter = selections.iter().peekable();
10363            while let Some(selection) = selections_iter.next() {
10364                if selection.start != selection.end {
10365                    only_carets = false;
10366                }
10367
10368                if same_text_selected {
10369                    if selected_text.is_none() {
10370                        selected_text =
10371                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10372                    }
10373
10374                    if let Some(next_selection) = selections_iter.peek() {
10375                        if next_selection.range().len() == selection.range().len() {
10376                            let next_selected_text = buffer
10377                                .text_for_range(next_selection.range())
10378                                .collect::<String>();
10379                            if Some(next_selected_text) != selected_text {
10380                                same_text_selected = false;
10381                                selected_text = None;
10382                            }
10383                        } else {
10384                            same_text_selected = false;
10385                            selected_text = None;
10386                        }
10387                    }
10388                }
10389            }
10390
10391            if only_carets {
10392                for selection in &mut selections {
10393                    let word_range = movement::surrounding_word(
10394                        display_map,
10395                        selection.start.to_display_point(display_map),
10396                    );
10397                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
10398                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
10399                    selection.goal = SelectionGoal::None;
10400                    selection.reversed = false;
10401                    select_next_match_ranges(
10402                        self,
10403                        selection.start..selection.end,
10404                        replace_newest,
10405                        autoscroll,
10406                        window,
10407                        cx,
10408                    );
10409                }
10410
10411                if selections.len() == 1 {
10412                    let selection = selections
10413                        .last()
10414                        .expect("ensured that there's only one selection");
10415                    let query = buffer
10416                        .text_for_range(selection.start..selection.end)
10417                        .collect::<String>();
10418                    let is_empty = query.is_empty();
10419                    let select_state = SelectNextState {
10420                        query: AhoCorasick::new(&[query])?,
10421                        wordwise: true,
10422                        done: is_empty,
10423                    };
10424                    self.select_next_state = Some(select_state);
10425                } else {
10426                    self.select_next_state = None;
10427                }
10428            } else if let Some(selected_text) = selected_text {
10429                self.select_next_state = Some(SelectNextState {
10430                    query: AhoCorasick::new(&[selected_text])?,
10431                    wordwise: false,
10432                    done: false,
10433                });
10434                self.select_next_match_internal(
10435                    display_map,
10436                    replace_newest,
10437                    autoscroll,
10438                    window,
10439                    cx,
10440                )?;
10441            }
10442        }
10443        Ok(())
10444    }
10445
10446    pub fn select_all_matches(
10447        &mut self,
10448        _action: &SelectAllMatches,
10449        window: &mut Window,
10450        cx: &mut Context<Self>,
10451    ) -> Result<()> {
10452        self.push_to_selection_history();
10453        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10454
10455        self.select_next_match_internal(&display_map, false, None, window, cx)?;
10456        let Some(select_next_state) = self.select_next_state.as_mut() else {
10457            return Ok(());
10458        };
10459        if select_next_state.done {
10460            return Ok(());
10461        }
10462
10463        let mut new_selections = self.selections.all::<usize>(cx);
10464
10465        let buffer = &display_map.buffer_snapshot;
10466        let query_matches = select_next_state
10467            .query
10468            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10469
10470        for query_match in query_matches {
10471            let query_match = query_match.unwrap(); // can only fail due to I/O
10472            let offset_range = query_match.start()..query_match.end();
10473            let display_range = offset_range.start.to_display_point(&display_map)
10474                ..offset_range.end.to_display_point(&display_map);
10475
10476            if !select_next_state.wordwise
10477                || (!movement::is_inside_word(&display_map, display_range.start)
10478                    && !movement::is_inside_word(&display_map, display_range.end))
10479            {
10480                self.selections.change_with(cx, |selections| {
10481                    new_selections.push(Selection {
10482                        id: selections.new_selection_id(),
10483                        start: offset_range.start,
10484                        end: offset_range.end,
10485                        reversed: false,
10486                        goal: SelectionGoal::None,
10487                    });
10488                });
10489            }
10490        }
10491
10492        new_selections.sort_by_key(|selection| selection.start);
10493        let mut ix = 0;
10494        while ix + 1 < new_selections.len() {
10495            let current_selection = &new_selections[ix];
10496            let next_selection = &new_selections[ix + 1];
10497            if current_selection.range().overlaps(&next_selection.range()) {
10498                if current_selection.id < next_selection.id {
10499                    new_selections.remove(ix + 1);
10500                } else {
10501                    new_selections.remove(ix);
10502                }
10503            } else {
10504                ix += 1;
10505            }
10506        }
10507
10508        let reversed = self.selections.oldest::<usize>(cx).reversed;
10509
10510        for selection in new_selections.iter_mut() {
10511            selection.reversed = reversed;
10512        }
10513
10514        select_next_state.done = true;
10515        self.unfold_ranges(
10516            &new_selections
10517                .iter()
10518                .map(|selection| selection.range())
10519                .collect::<Vec<_>>(),
10520            false,
10521            false,
10522            cx,
10523        );
10524        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10525            selections.select(new_selections)
10526        });
10527
10528        Ok(())
10529    }
10530
10531    pub fn select_next(
10532        &mut self,
10533        action: &SelectNext,
10534        window: &mut Window,
10535        cx: &mut Context<Self>,
10536    ) -> Result<()> {
10537        self.push_to_selection_history();
10538        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10539        self.select_next_match_internal(
10540            &display_map,
10541            action.replace_newest,
10542            Some(Autoscroll::newest()),
10543            window,
10544            cx,
10545        )?;
10546        Ok(())
10547    }
10548
10549    pub fn select_previous(
10550        &mut self,
10551        action: &SelectPrevious,
10552        window: &mut Window,
10553        cx: &mut Context<Self>,
10554    ) -> Result<()> {
10555        self.push_to_selection_history();
10556        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10557        let buffer = &display_map.buffer_snapshot;
10558        let mut selections = self.selections.all::<usize>(cx);
10559        if let Some(mut select_prev_state) = self.select_prev_state.take() {
10560            let query = &select_prev_state.query;
10561            if !select_prev_state.done {
10562                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10563                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10564                let mut next_selected_range = None;
10565                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10566                let bytes_before_last_selection =
10567                    buffer.reversed_bytes_in_range(0..last_selection.start);
10568                let bytes_after_first_selection =
10569                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10570                let query_matches = query
10571                    .stream_find_iter(bytes_before_last_selection)
10572                    .map(|result| (last_selection.start, result))
10573                    .chain(
10574                        query
10575                            .stream_find_iter(bytes_after_first_selection)
10576                            .map(|result| (buffer.len(), result)),
10577                    );
10578                for (end_offset, query_match) in query_matches {
10579                    let query_match = query_match.unwrap(); // can only fail due to I/O
10580                    let offset_range =
10581                        end_offset - query_match.end()..end_offset - query_match.start();
10582                    let display_range = offset_range.start.to_display_point(&display_map)
10583                        ..offset_range.end.to_display_point(&display_map);
10584
10585                    if !select_prev_state.wordwise
10586                        || (!movement::is_inside_word(&display_map, display_range.start)
10587                            && !movement::is_inside_word(&display_map, display_range.end))
10588                    {
10589                        next_selected_range = Some(offset_range);
10590                        break;
10591                    }
10592                }
10593
10594                if let Some(next_selected_range) = next_selected_range {
10595                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10596                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10597                        if action.replace_newest {
10598                            s.delete(s.newest_anchor().id);
10599                        }
10600                        s.insert_range(next_selected_range);
10601                    });
10602                } else {
10603                    select_prev_state.done = true;
10604                }
10605            }
10606
10607            self.select_prev_state = Some(select_prev_state);
10608        } else {
10609            let mut only_carets = true;
10610            let mut same_text_selected = true;
10611            let mut selected_text = None;
10612
10613            let mut selections_iter = selections.iter().peekable();
10614            while let Some(selection) = selections_iter.next() {
10615                if selection.start != selection.end {
10616                    only_carets = false;
10617                }
10618
10619                if same_text_selected {
10620                    if selected_text.is_none() {
10621                        selected_text =
10622                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10623                    }
10624
10625                    if let Some(next_selection) = selections_iter.peek() {
10626                        if next_selection.range().len() == selection.range().len() {
10627                            let next_selected_text = buffer
10628                                .text_for_range(next_selection.range())
10629                                .collect::<String>();
10630                            if Some(next_selected_text) != selected_text {
10631                                same_text_selected = false;
10632                                selected_text = None;
10633                            }
10634                        } else {
10635                            same_text_selected = false;
10636                            selected_text = None;
10637                        }
10638                    }
10639                }
10640            }
10641
10642            if only_carets {
10643                for selection in &mut selections {
10644                    let word_range = movement::surrounding_word(
10645                        &display_map,
10646                        selection.start.to_display_point(&display_map),
10647                    );
10648                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10649                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10650                    selection.goal = SelectionGoal::None;
10651                    selection.reversed = false;
10652                }
10653                if selections.len() == 1 {
10654                    let selection = selections
10655                        .last()
10656                        .expect("ensured that there's only one selection");
10657                    let query = buffer
10658                        .text_for_range(selection.start..selection.end)
10659                        .collect::<String>();
10660                    let is_empty = query.is_empty();
10661                    let select_state = SelectNextState {
10662                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10663                        wordwise: true,
10664                        done: is_empty,
10665                    };
10666                    self.select_prev_state = Some(select_state);
10667                } else {
10668                    self.select_prev_state = None;
10669                }
10670
10671                self.unfold_ranges(
10672                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10673                    false,
10674                    true,
10675                    cx,
10676                );
10677                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10678                    s.select(selections);
10679                });
10680            } else if let Some(selected_text) = selected_text {
10681                self.select_prev_state = Some(SelectNextState {
10682                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10683                    wordwise: false,
10684                    done: false,
10685                });
10686                self.select_previous(action, window, cx)?;
10687            }
10688        }
10689        Ok(())
10690    }
10691
10692    pub fn toggle_comments(
10693        &mut self,
10694        action: &ToggleComments,
10695        window: &mut Window,
10696        cx: &mut Context<Self>,
10697    ) {
10698        if self.read_only(cx) {
10699            return;
10700        }
10701        let text_layout_details = &self.text_layout_details(window);
10702        self.transact(window, cx, |this, window, cx| {
10703            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10704            let mut edits = Vec::new();
10705            let mut selection_edit_ranges = Vec::new();
10706            let mut last_toggled_row = None;
10707            let snapshot = this.buffer.read(cx).read(cx);
10708            let empty_str: Arc<str> = Arc::default();
10709            let mut suffixes_inserted = Vec::new();
10710            let ignore_indent = action.ignore_indent;
10711
10712            fn comment_prefix_range(
10713                snapshot: &MultiBufferSnapshot,
10714                row: MultiBufferRow,
10715                comment_prefix: &str,
10716                comment_prefix_whitespace: &str,
10717                ignore_indent: bool,
10718            ) -> Range<Point> {
10719                let indent_size = if ignore_indent {
10720                    0
10721                } else {
10722                    snapshot.indent_size_for_line(row).len
10723                };
10724
10725                let start = Point::new(row.0, indent_size);
10726
10727                let mut line_bytes = snapshot
10728                    .bytes_in_range(start..snapshot.max_point())
10729                    .flatten()
10730                    .copied();
10731
10732                // If this line currently begins with the line comment prefix, then record
10733                // the range containing the prefix.
10734                if line_bytes
10735                    .by_ref()
10736                    .take(comment_prefix.len())
10737                    .eq(comment_prefix.bytes())
10738                {
10739                    // Include any whitespace that matches the comment prefix.
10740                    let matching_whitespace_len = line_bytes
10741                        .zip(comment_prefix_whitespace.bytes())
10742                        .take_while(|(a, b)| a == b)
10743                        .count() as u32;
10744                    let end = Point::new(
10745                        start.row,
10746                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10747                    );
10748                    start..end
10749                } else {
10750                    start..start
10751                }
10752            }
10753
10754            fn comment_suffix_range(
10755                snapshot: &MultiBufferSnapshot,
10756                row: MultiBufferRow,
10757                comment_suffix: &str,
10758                comment_suffix_has_leading_space: bool,
10759            ) -> Range<Point> {
10760                let end = Point::new(row.0, snapshot.line_len(row));
10761                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10762
10763                let mut line_end_bytes = snapshot
10764                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10765                    .flatten()
10766                    .copied();
10767
10768                let leading_space_len = if suffix_start_column > 0
10769                    && line_end_bytes.next() == Some(b' ')
10770                    && comment_suffix_has_leading_space
10771                {
10772                    1
10773                } else {
10774                    0
10775                };
10776
10777                // If this line currently begins with the line comment prefix, then record
10778                // the range containing the prefix.
10779                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10780                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
10781                    start..end
10782                } else {
10783                    end..end
10784                }
10785            }
10786
10787            // TODO: Handle selections that cross excerpts
10788            for selection in &mut selections {
10789                let start_column = snapshot
10790                    .indent_size_for_line(MultiBufferRow(selection.start.row))
10791                    .len;
10792                let language = if let Some(language) =
10793                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10794                {
10795                    language
10796                } else {
10797                    continue;
10798                };
10799
10800                selection_edit_ranges.clear();
10801
10802                // If multiple selections contain a given row, avoid processing that
10803                // row more than once.
10804                let mut start_row = MultiBufferRow(selection.start.row);
10805                if last_toggled_row == Some(start_row) {
10806                    start_row = start_row.next_row();
10807                }
10808                let end_row =
10809                    if selection.end.row > selection.start.row && selection.end.column == 0 {
10810                        MultiBufferRow(selection.end.row - 1)
10811                    } else {
10812                        MultiBufferRow(selection.end.row)
10813                    };
10814                last_toggled_row = Some(end_row);
10815
10816                if start_row > end_row {
10817                    continue;
10818                }
10819
10820                // If the language has line comments, toggle those.
10821                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10822
10823                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10824                if ignore_indent {
10825                    full_comment_prefixes = full_comment_prefixes
10826                        .into_iter()
10827                        .map(|s| Arc::from(s.trim_end()))
10828                        .collect();
10829                }
10830
10831                if !full_comment_prefixes.is_empty() {
10832                    let first_prefix = full_comment_prefixes
10833                        .first()
10834                        .expect("prefixes is non-empty");
10835                    let prefix_trimmed_lengths = full_comment_prefixes
10836                        .iter()
10837                        .map(|p| p.trim_end_matches(' ').len())
10838                        .collect::<SmallVec<[usize; 4]>>();
10839
10840                    let mut all_selection_lines_are_comments = true;
10841
10842                    for row in start_row.0..=end_row.0 {
10843                        let row = MultiBufferRow(row);
10844                        if start_row < end_row && snapshot.is_line_blank(row) {
10845                            continue;
10846                        }
10847
10848                        let prefix_range = full_comment_prefixes
10849                            .iter()
10850                            .zip(prefix_trimmed_lengths.iter().copied())
10851                            .map(|(prefix, trimmed_prefix_len)| {
10852                                comment_prefix_range(
10853                                    snapshot.deref(),
10854                                    row,
10855                                    &prefix[..trimmed_prefix_len],
10856                                    &prefix[trimmed_prefix_len..],
10857                                    ignore_indent,
10858                                )
10859                            })
10860                            .max_by_key(|range| range.end.column - range.start.column)
10861                            .expect("prefixes is non-empty");
10862
10863                        if prefix_range.is_empty() {
10864                            all_selection_lines_are_comments = false;
10865                        }
10866
10867                        selection_edit_ranges.push(prefix_range);
10868                    }
10869
10870                    if all_selection_lines_are_comments {
10871                        edits.extend(
10872                            selection_edit_ranges
10873                                .iter()
10874                                .cloned()
10875                                .map(|range| (range, empty_str.clone())),
10876                        );
10877                    } else {
10878                        let min_column = selection_edit_ranges
10879                            .iter()
10880                            .map(|range| range.start.column)
10881                            .min()
10882                            .unwrap_or(0);
10883                        edits.extend(selection_edit_ranges.iter().map(|range| {
10884                            let position = Point::new(range.start.row, min_column);
10885                            (position..position, first_prefix.clone())
10886                        }));
10887                    }
10888                } else if let Some((full_comment_prefix, comment_suffix)) =
10889                    language.block_comment_delimiters()
10890                {
10891                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10892                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10893                    let prefix_range = comment_prefix_range(
10894                        snapshot.deref(),
10895                        start_row,
10896                        comment_prefix,
10897                        comment_prefix_whitespace,
10898                        ignore_indent,
10899                    );
10900                    let suffix_range = comment_suffix_range(
10901                        snapshot.deref(),
10902                        end_row,
10903                        comment_suffix.trim_start_matches(' '),
10904                        comment_suffix.starts_with(' '),
10905                    );
10906
10907                    if prefix_range.is_empty() || suffix_range.is_empty() {
10908                        edits.push((
10909                            prefix_range.start..prefix_range.start,
10910                            full_comment_prefix.clone(),
10911                        ));
10912                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10913                        suffixes_inserted.push((end_row, comment_suffix.len()));
10914                    } else {
10915                        edits.push((prefix_range, empty_str.clone()));
10916                        edits.push((suffix_range, empty_str.clone()));
10917                    }
10918                } else {
10919                    continue;
10920                }
10921            }
10922
10923            drop(snapshot);
10924            this.buffer.update(cx, |buffer, cx| {
10925                buffer.edit(edits, None, cx);
10926            });
10927
10928            // Adjust selections so that they end before any comment suffixes that
10929            // were inserted.
10930            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10931            let mut selections = this.selections.all::<Point>(cx);
10932            let snapshot = this.buffer.read(cx).read(cx);
10933            for selection in &mut selections {
10934                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10935                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10936                        Ordering::Less => {
10937                            suffixes_inserted.next();
10938                            continue;
10939                        }
10940                        Ordering::Greater => break,
10941                        Ordering::Equal => {
10942                            if selection.end.column == snapshot.line_len(row) {
10943                                if selection.is_empty() {
10944                                    selection.start.column -= suffix_len as u32;
10945                                }
10946                                selection.end.column -= suffix_len as u32;
10947                            }
10948                            break;
10949                        }
10950                    }
10951                }
10952            }
10953
10954            drop(snapshot);
10955            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10956                s.select(selections)
10957            });
10958
10959            let selections = this.selections.all::<Point>(cx);
10960            let selections_on_single_row = selections.windows(2).all(|selections| {
10961                selections[0].start.row == selections[1].start.row
10962                    && selections[0].end.row == selections[1].end.row
10963                    && selections[0].start.row == selections[0].end.row
10964            });
10965            let selections_selecting = selections
10966                .iter()
10967                .any(|selection| selection.start != selection.end);
10968            let advance_downwards = action.advance_downwards
10969                && selections_on_single_row
10970                && !selections_selecting
10971                && !matches!(this.mode, EditorMode::SingleLine { .. });
10972
10973            if advance_downwards {
10974                let snapshot = this.buffer.read(cx).snapshot(cx);
10975
10976                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10977                    s.move_cursors_with(|display_snapshot, display_point, _| {
10978                        let mut point = display_point.to_point(display_snapshot);
10979                        point.row += 1;
10980                        point = snapshot.clip_point(point, Bias::Left);
10981                        let display_point = point.to_display_point(display_snapshot);
10982                        let goal = SelectionGoal::HorizontalPosition(
10983                            display_snapshot
10984                                .x_for_display_point(display_point, text_layout_details)
10985                                .into(),
10986                        );
10987                        (display_point, goal)
10988                    })
10989                });
10990            }
10991        });
10992    }
10993
10994    pub fn select_enclosing_symbol(
10995        &mut self,
10996        _: &SelectEnclosingSymbol,
10997        window: &mut Window,
10998        cx: &mut Context<Self>,
10999    ) {
11000        let buffer = self.buffer.read(cx).snapshot(cx);
11001        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11002
11003        fn update_selection(
11004            selection: &Selection<usize>,
11005            buffer_snap: &MultiBufferSnapshot,
11006        ) -> Option<Selection<usize>> {
11007            let cursor = selection.head();
11008            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
11009            for symbol in symbols.iter().rev() {
11010                let start = symbol.range.start.to_offset(buffer_snap);
11011                let end = symbol.range.end.to_offset(buffer_snap);
11012                let new_range = start..end;
11013                if start < selection.start || end > selection.end {
11014                    return Some(Selection {
11015                        id: selection.id,
11016                        start: new_range.start,
11017                        end: new_range.end,
11018                        goal: SelectionGoal::None,
11019                        reversed: selection.reversed,
11020                    });
11021                }
11022            }
11023            None
11024        }
11025
11026        let mut selected_larger_symbol = false;
11027        let new_selections = old_selections
11028            .iter()
11029            .map(|selection| match update_selection(selection, &buffer) {
11030                Some(new_selection) => {
11031                    if new_selection.range() != selection.range() {
11032                        selected_larger_symbol = true;
11033                    }
11034                    new_selection
11035                }
11036                None => selection.clone(),
11037            })
11038            .collect::<Vec<_>>();
11039
11040        if selected_larger_symbol {
11041            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11042                s.select(new_selections);
11043            });
11044        }
11045    }
11046
11047    pub fn select_larger_syntax_node(
11048        &mut self,
11049        _: &SelectLargerSyntaxNode,
11050        window: &mut Window,
11051        cx: &mut Context<Self>,
11052    ) {
11053        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11054        let buffer = self.buffer.read(cx).snapshot(cx);
11055        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11056
11057        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11058        let mut selected_larger_node = false;
11059        let new_selections = old_selections
11060            .iter()
11061            .map(|selection| {
11062                let old_range = selection.start..selection.end;
11063                let mut new_range = old_range.clone();
11064                let mut new_node = None;
11065                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
11066                {
11067                    new_node = Some(node);
11068                    new_range = match containing_range {
11069                        MultiOrSingleBufferOffsetRange::Single(_) => break,
11070                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
11071                    };
11072                    if !display_map.intersects_fold(new_range.start)
11073                        && !display_map.intersects_fold(new_range.end)
11074                    {
11075                        break;
11076                    }
11077                }
11078
11079                if let Some(node) = new_node {
11080                    // Log the ancestor, to support using this action as a way to explore TreeSitter
11081                    // nodes. Parent and grandparent are also logged because this operation will not
11082                    // visit nodes that have the same range as their parent.
11083                    log::info!("Node: {node:?}");
11084                    let parent = node.parent();
11085                    log::info!("Parent: {parent:?}");
11086                    let grandparent = parent.and_then(|x| x.parent());
11087                    log::info!("Grandparent: {grandparent:?}");
11088                }
11089
11090                selected_larger_node |= new_range != old_range;
11091                Selection {
11092                    id: selection.id,
11093                    start: new_range.start,
11094                    end: new_range.end,
11095                    goal: SelectionGoal::None,
11096                    reversed: selection.reversed,
11097                }
11098            })
11099            .collect::<Vec<_>>();
11100
11101        if selected_larger_node {
11102            stack.push(old_selections);
11103            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11104                s.select(new_selections);
11105            });
11106        }
11107        self.select_larger_syntax_node_stack = stack;
11108    }
11109
11110    pub fn select_smaller_syntax_node(
11111        &mut self,
11112        _: &SelectSmallerSyntaxNode,
11113        window: &mut Window,
11114        cx: &mut Context<Self>,
11115    ) {
11116        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11117        if let Some(selections) = stack.pop() {
11118            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11119                s.select(selections.to_vec());
11120            });
11121        }
11122        self.select_larger_syntax_node_stack = stack;
11123    }
11124
11125    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
11126        if !EditorSettings::get_global(cx).gutter.runnables {
11127            self.clear_tasks();
11128            return Task::ready(());
11129        }
11130        let project = self.project.as_ref().map(Entity::downgrade);
11131        cx.spawn_in(window, |this, mut cx| async move {
11132            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
11133            let Some(project) = project.and_then(|p| p.upgrade()) else {
11134                return;
11135            };
11136            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
11137                this.display_map.update(cx, |map, cx| map.snapshot(cx))
11138            }) else {
11139                return;
11140            };
11141
11142            let hide_runnables = project
11143                .update(&mut cx, |project, cx| {
11144                    // Do not display any test indicators in non-dev server remote projects.
11145                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
11146                })
11147                .unwrap_or(true);
11148            if hide_runnables {
11149                return;
11150            }
11151            let new_rows =
11152                cx.background_spawn({
11153                    let snapshot = display_snapshot.clone();
11154                    async move {
11155                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
11156                    }
11157                })
11158                    .await;
11159
11160            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
11161            this.update(&mut cx, |this, _| {
11162                this.clear_tasks();
11163                for (key, value) in rows {
11164                    this.insert_tasks(key, value);
11165                }
11166            })
11167            .ok();
11168        })
11169    }
11170    fn fetch_runnable_ranges(
11171        snapshot: &DisplaySnapshot,
11172        range: Range<Anchor>,
11173    ) -> Vec<language::RunnableRange> {
11174        snapshot.buffer_snapshot.runnable_ranges(range).collect()
11175    }
11176
11177    fn runnable_rows(
11178        project: Entity<Project>,
11179        snapshot: DisplaySnapshot,
11180        runnable_ranges: Vec<RunnableRange>,
11181        mut cx: AsyncWindowContext,
11182    ) -> Vec<((BufferId, u32), RunnableTasks)> {
11183        runnable_ranges
11184            .into_iter()
11185            .filter_map(|mut runnable| {
11186                let tasks = cx
11187                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11188                    .ok()?;
11189                if tasks.is_empty() {
11190                    return None;
11191                }
11192
11193                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11194
11195                let row = snapshot
11196                    .buffer_snapshot
11197                    .buffer_line_for_row(MultiBufferRow(point.row))?
11198                    .1
11199                    .start
11200                    .row;
11201
11202                let context_range =
11203                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11204                Some((
11205                    (runnable.buffer_id, row),
11206                    RunnableTasks {
11207                        templates: tasks,
11208                        offset: snapshot
11209                            .buffer_snapshot
11210                            .anchor_before(runnable.run_range.start),
11211                        context_range,
11212                        column: point.column,
11213                        extra_variables: runnable.extra_captures,
11214                    },
11215                ))
11216            })
11217            .collect()
11218    }
11219
11220    fn templates_with_tags(
11221        project: &Entity<Project>,
11222        runnable: &mut Runnable,
11223        cx: &mut App,
11224    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11225        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11226            let (worktree_id, file) = project
11227                .buffer_for_id(runnable.buffer, cx)
11228                .and_then(|buffer| buffer.read(cx).file())
11229                .map(|file| (file.worktree_id(cx), file.clone()))
11230                .unzip();
11231
11232            (
11233                project.task_store().read(cx).task_inventory().cloned(),
11234                worktree_id,
11235                file,
11236            )
11237        });
11238
11239        let tags = mem::take(&mut runnable.tags);
11240        let mut tags: Vec<_> = tags
11241            .into_iter()
11242            .flat_map(|tag| {
11243                let tag = tag.0.clone();
11244                inventory
11245                    .as_ref()
11246                    .into_iter()
11247                    .flat_map(|inventory| {
11248                        inventory.read(cx).list_tasks(
11249                            file.clone(),
11250                            Some(runnable.language.clone()),
11251                            worktree_id,
11252                            cx,
11253                        )
11254                    })
11255                    .filter(move |(_, template)| {
11256                        template.tags.iter().any(|source_tag| source_tag == &tag)
11257                    })
11258            })
11259            .sorted_by_key(|(kind, _)| kind.to_owned())
11260            .collect();
11261        if let Some((leading_tag_source, _)) = tags.first() {
11262            // Strongest source wins; if we have worktree tag binding, prefer that to
11263            // global and language bindings;
11264            // if we have a global binding, prefer that to language binding.
11265            let first_mismatch = tags
11266                .iter()
11267                .position(|(tag_source, _)| tag_source != leading_tag_source);
11268            if let Some(index) = first_mismatch {
11269                tags.truncate(index);
11270            }
11271        }
11272
11273        tags
11274    }
11275
11276    pub fn move_to_enclosing_bracket(
11277        &mut self,
11278        _: &MoveToEnclosingBracket,
11279        window: &mut Window,
11280        cx: &mut Context<Self>,
11281    ) {
11282        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11283            s.move_offsets_with(|snapshot, selection| {
11284                let Some(enclosing_bracket_ranges) =
11285                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11286                else {
11287                    return;
11288                };
11289
11290                let mut best_length = usize::MAX;
11291                let mut best_inside = false;
11292                let mut best_in_bracket_range = false;
11293                let mut best_destination = None;
11294                for (open, close) in enclosing_bracket_ranges {
11295                    let close = close.to_inclusive();
11296                    let length = close.end() - open.start;
11297                    let inside = selection.start >= open.end && selection.end <= *close.start();
11298                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
11299                        || close.contains(&selection.head());
11300
11301                    // If best is next to a bracket and current isn't, skip
11302                    if !in_bracket_range && best_in_bracket_range {
11303                        continue;
11304                    }
11305
11306                    // Prefer smaller lengths unless best is inside and current isn't
11307                    if length > best_length && (best_inside || !inside) {
11308                        continue;
11309                    }
11310
11311                    best_length = length;
11312                    best_inside = inside;
11313                    best_in_bracket_range = in_bracket_range;
11314                    best_destination = Some(
11315                        if close.contains(&selection.start) && close.contains(&selection.end) {
11316                            if inside {
11317                                open.end
11318                            } else {
11319                                open.start
11320                            }
11321                        } else if inside {
11322                            *close.start()
11323                        } else {
11324                            *close.end()
11325                        },
11326                    );
11327                }
11328
11329                if let Some(destination) = best_destination {
11330                    selection.collapse_to(destination, SelectionGoal::None);
11331                }
11332            })
11333        });
11334    }
11335
11336    pub fn undo_selection(
11337        &mut self,
11338        _: &UndoSelection,
11339        window: &mut Window,
11340        cx: &mut Context<Self>,
11341    ) {
11342        self.end_selection(window, cx);
11343        self.selection_history.mode = SelectionHistoryMode::Undoing;
11344        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11345            self.change_selections(None, window, cx, |s| {
11346                s.select_anchors(entry.selections.to_vec())
11347            });
11348            self.select_next_state = entry.select_next_state;
11349            self.select_prev_state = entry.select_prev_state;
11350            self.add_selections_state = entry.add_selections_state;
11351            self.request_autoscroll(Autoscroll::newest(), cx);
11352        }
11353        self.selection_history.mode = SelectionHistoryMode::Normal;
11354    }
11355
11356    pub fn redo_selection(
11357        &mut self,
11358        _: &RedoSelection,
11359        window: &mut Window,
11360        cx: &mut Context<Self>,
11361    ) {
11362        self.end_selection(window, cx);
11363        self.selection_history.mode = SelectionHistoryMode::Redoing;
11364        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11365            self.change_selections(None, window, cx, |s| {
11366                s.select_anchors(entry.selections.to_vec())
11367            });
11368            self.select_next_state = entry.select_next_state;
11369            self.select_prev_state = entry.select_prev_state;
11370            self.add_selections_state = entry.add_selections_state;
11371            self.request_autoscroll(Autoscroll::newest(), cx);
11372        }
11373        self.selection_history.mode = SelectionHistoryMode::Normal;
11374    }
11375
11376    pub fn expand_excerpts(
11377        &mut self,
11378        action: &ExpandExcerpts,
11379        _: &mut Window,
11380        cx: &mut Context<Self>,
11381    ) {
11382        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11383    }
11384
11385    pub fn expand_excerpts_down(
11386        &mut self,
11387        action: &ExpandExcerptsDown,
11388        _: &mut Window,
11389        cx: &mut Context<Self>,
11390    ) {
11391        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11392    }
11393
11394    pub fn expand_excerpts_up(
11395        &mut self,
11396        action: &ExpandExcerptsUp,
11397        _: &mut Window,
11398        cx: &mut Context<Self>,
11399    ) {
11400        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11401    }
11402
11403    pub fn expand_excerpts_for_direction(
11404        &mut self,
11405        lines: u32,
11406        direction: ExpandExcerptDirection,
11407
11408        cx: &mut Context<Self>,
11409    ) {
11410        let selections = self.selections.disjoint_anchors();
11411
11412        let lines = if lines == 0 {
11413            EditorSettings::get_global(cx).expand_excerpt_lines
11414        } else {
11415            lines
11416        };
11417
11418        self.buffer.update(cx, |buffer, cx| {
11419            let snapshot = buffer.snapshot(cx);
11420            let mut excerpt_ids = selections
11421                .iter()
11422                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11423                .collect::<Vec<_>>();
11424            excerpt_ids.sort();
11425            excerpt_ids.dedup();
11426            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11427        })
11428    }
11429
11430    pub fn expand_excerpt(
11431        &mut self,
11432        excerpt: ExcerptId,
11433        direction: ExpandExcerptDirection,
11434        cx: &mut Context<Self>,
11435    ) {
11436        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11437        self.buffer.update(cx, |buffer, cx| {
11438            buffer.expand_excerpts([excerpt], lines, direction, cx)
11439        })
11440    }
11441
11442    pub fn go_to_singleton_buffer_point(
11443        &mut self,
11444        point: Point,
11445        window: &mut Window,
11446        cx: &mut Context<Self>,
11447    ) {
11448        self.go_to_singleton_buffer_range(point..point, window, cx);
11449    }
11450
11451    pub fn go_to_singleton_buffer_range(
11452        &mut self,
11453        range: Range<Point>,
11454        window: &mut Window,
11455        cx: &mut Context<Self>,
11456    ) {
11457        let multibuffer = self.buffer().read(cx);
11458        let Some(buffer) = multibuffer.as_singleton() else {
11459            return;
11460        };
11461        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11462            return;
11463        };
11464        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11465            return;
11466        };
11467        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11468            s.select_anchor_ranges([start..end])
11469        });
11470    }
11471
11472    fn go_to_diagnostic(
11473        &mut self,
11474        _: &GoToDiagnostic,
11475        window: &mut Window,
11476        cx: &mut Context<Self>,
11477    ) {
11478        self.go_to_diagnostic_impl(Direction::Next, window, cx)
11479    }
11480
11481    fn go_to_prev_diagnostic(
11482        &mut self,
11483        _: &GoToPreviousDiagnostic,
11484        window: &mut Window,
11485        cx: &mut Context<Self>,
11486    ) {
11487        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11488    }
11489
11490    pub fn go_to_diagnostic_impl(
11491        &mut self,
11492        direction: Direction,
11493        window: &mut Window,
11494        cx: &mut Context<Self>,
11495    ) {
11496        let buffer = self.buffer.read(cx).snapshot(cx);
11497        let selection = self.selections.newest::<usize>(cx);
11498
11499        // If there is an active Diagnostic Popover jump to its diagnostic instead.
11500        if direction == Direction::Next {
11501            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11502                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11503                    return;
11504                };
11505                self.activate_diagnostics(
11506                    buffer_id,
11507                    popover.local_diagnostic.diagnostic.group_id,
11508                    window,
11509                    cx,
11510                );
11511                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11512                    let primary_range_start = active_diagnostics.primary_range.start;
11513                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11514                        let mut new_selection = s.newest_anchor().clone();
11515                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11516                        s.select_anchors(vec![new_selection.clone()]);
11517                    });
11518                    self.refresh_inline_completion(false, true, window, cx);
11519                }
11520                return;
11521            }
11522        }
11523
11524        let active_group_id = self
11525            .active_diagnostics
11526            .as_ref()
11527            .map(|active_group| active_group.group_id);
11528        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11529            active_diagnostics
11530                .primary_range
11531                .to_offset(&buffer)
11532                .to_inclusive()
11533        });
11534        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11535            if active_primary_range.contains(&selection.head()) {
11536                *active_primary_range.start()
11537            } else {
11538                selection.head()
11539            }
11540        } else {
11541            selection.head()
11542        };
11543
11544        let snapshot = self.snapshot(window, cx);
11545        let primary_diagnostics_before = buffer
11546            .diagnostics_in_range::<usize>(0..search_start)
11547            .filter(|entry| entry.diagnostic.is_primary)
11548            .filter(|entry| entry.range.start != entry.range.end)
11549            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11550            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11551            .collect::<Vec<_>>();
11552        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11553            primary_diagnostics_before
11554                .iter()
11555                .position(|entry| entry.diagnostic.group_id == active_group_id)
11556        });
11557
11558        let primary_diagnostics_after = buffer
11559            .diagnostics_in_range::<usize>(search_start..buffer.len())
11560            .filter(|entry| entry.diagnostic.is_primary)
11561            .filter(|entry| entry.range.start != entry.range.end)
11562            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11563            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11564            .collect::<Vec<_>>();
11565        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11566            primary_diagnostics_after
11567                .iter()
11568                .enumerate()
11569                .rev()
11570                .find_map(|(i, entry)| {
11571                    if entry.diagnostic.group_id == active_group_id {
11572                        Some(i)
11573                    } else {
11574                        None
11575                    }
11576                })
11577        });
11578
11579        let next_primary_diagnostic = match direction {
11580            Direction::Prev => primary_diagnostics_before
11581                .iter()
11582                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11583                .rev()
11584                .next(),
11585            Direction::Next => primary_diagnostics_after
11586                .iter()
11587                .skip(
11588                    last_same_group_diagnostic_after
11589                        .map(|index| index + 1)
11590                        .unwrap_or(0),
11591                )
11592                .next(),
11593        };
11594
11595        // Cycle around to the start of the buffer, potentially moving back to the start of
11596        // the currently active diagnostic.
11597        let cycle_around = || match direction {
11598            Direction::Prev => primary_diagnostics_after
11599                .iter()
11600                .rev()
11601                .chain(primary_diagnostics_before.iter().rev())
11602                .next(),
11603            Direction::Next => primary_diagnostics_before
11604                .iter()
11605                .chain(primary_diagnostics_after.iter())
11606                .next(),
11607        };
11608
11609        if let Some((primary_range, group_id)) = next_primary_diagnostic
11610            .or_else(cycle_around)
11611            .map(|entry| (&entry.range, entry.diagnostic.group_id))
11612        {
11613            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11614                return;
11615            };
11616            self.activate_diagnostics(buffer_id, group_id, window, cx);
11617            if self.active_diagnostics.is_some() {
11618                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11619                    s.select(vec![Selection {
11620                        id: selection.id,
11621                        start: primary_range.start,
11622                        end: primary_range.start,
11623                        reversed: false,
11624                        goal: SelectionGoal::None,
11625                    }]);
11626                });
11627                self.refresh_inline_completion(false, true, window, cx);
11628            }
11629        }
11630    }
11631
11632    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11633        let snapshot = self.snapshot(window, cx);
11634        let selection = self.selections.newest::<Point>(cx);
11635        self.go_to_hunk_before_or_after_position(
11636            &snapshot,
11637            selection.head(),
11638            Direction::Next,
11639            window,
11640            cx,
11641        );
11642    }
11643
11644    fn go_to_hunk_before_or_after_position(
11645        &mut self,
11646        snapshot: &EditorSnapshot,
11647        position: Point,
11648        direction: Direction,
11649        window: &mut Window,
11650        cx: &mut Context<Editor>,
11651    ) {
11652        let row = if direction == Direction::Next {
11653            self.hunk_after_position(snapshot, position)
11654                .map(|hunk| hunk.row_range.start)
11655        } else {
11656            self.hunk_before_position(snapshot, position)
11657        };
11658
11659        if let Some(row) = row {
11660            let destination = Point::new(row.0, 0);
11661            let autoscroll = Autoscroll::center();
11662
11663            self.unfold_ranges(&[destination..destination], false, false, cx);
11664            self.change_selections(Some(autoscroll), window, cx, |s| {
11665                s.select_ranges([destination..destination]);
11666            });
11667        }
11668    }
11669
11670    fn hunk_after_position(
11671        &mut self,
11672        snapshot: &EditorSnapshot,
11673        position: Point,
11674    ) -> Option<MultiBufferDiffHunk> {
11675        snapshot
11676            .buffer_snapshot
11677            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11678            .find(|hunk| hunk.row_range.start.0 > position.row)
11679            .or_else(|| {
11680                snapshot
11681                    .buffer_snapshot
11682                    .diff_hunks_in_range(Point::zero()..position)
11683                    .find(|hunk| hunk.row_range.end.0 < position.row)
11684            })
11685    }
11686
11687    fn go_to_prev_hunk(
11688        &mut self,
11689        _: &GoToPreviousHunk,
11690        window: &mut Window,
11691        cx: &mut Context<Self>,
11692    ) {
11693        let snapshot = self.snapshot(window, cx);
11694        let selection = self.selections.newest::<Point>(cx);
11695        self.go_to_hunk_before_or_after_position(
11696            &snapshot,
11697            selection.head(),
11698            Direction::Prev,
11699            window,
11700            cx,
11701        );
11702    }
11703
11704    fn hunk_before_position(
11705        &mut self,
11706        snapshot: &EditorSnapshot,
11707        position: Point,
11708    ) -> Option<MultiBufferRow> {
11709        snapshot
11710            .buffer_snapshot
11711            .diff_hunk_before(position)
11712            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11713    }
11714
11715    pub fn go_to_definition(
11716        &mut self,
11717        _: &GoToDefinition,
11718        window: &mut Window,
11719        cx: &mut Context<Self>,
11720    ) -> Task<Result<Navigated>> {
11721        let definition =
11722            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11723        cx.spawn_in(window, |editor, mut cx| async move {
11724            if definition.await? == Navigated::Yes {
11725                return Ok(Navigated::Yes);
11726            }
11727            match editor.update_in(&mut cx, |editor, window, cx| {
11728                editor.find_all_references(&FindAllReferences, window, cx)
11729            })? {
11730                Some(references) => references.await,
11731                None => Ok(Navigated::No),
11732            }
11733        })
11734    }
11735
11736    pub fn go_to_declaration(
11737        &mut self,
11738        _: &GoToDeclaration,
11739        window: &mut Window,
11740        cx: &mut Context<Self>,
11741    ) -> Task<Result<Navigated>> {
11742        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11743    }
11744
11745    pub fn go_to_declaration_split(
11746        &mut self,
11747        _: &GoToDeclaration,
11748        window: &mut Window,
11749        cx: &mut Context<Self>,
11750    ) -> Task<Result<Navigated>> {
11751        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11752    }
11753
11754    pub fn go_to_implementation(
11755        &mut self,
11756        _: &GoToImplementation,
11757        window: &mut Window,
11758        cx: &mut Context<Self>,
11759    ) -> Task<Result<Navigated>> {
11760        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11761    }
11762
11763    pub fn go_to_implementation_split(
11764        &mut self,
11765        _: &GoToImplementationSplit,
11766        window: &mut Window,
11767        cx: &mut Context<Self>,
11768    ) -> Task<Result<Navigated>> {
11769        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11770    }
11771
11772    pub fn go_to_type_definition(
11773        &mut self,
11774        _: &GoToTypeDefinition,
11775        window: &mut Window,
11776        cx: &mut Context<Self>,
11777    ) -> Task<Result<Navigated>> {
11778        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11779    }
11780
11781    pub fn go_to_definition_split(
11782        &mut self,
11783        _: &GoToDefinitionSplit,
11784        window: &mut Window,
11785        cx: &mut Context<Self>,
11786    ) -> Task<Result<Navigated>> {
11787        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11788    }
11789
11790    pub fn go_to_type_definition_split(
11791        &mut self,
11792        _: &GoToTypeDefinitionSplit,
11793        window: &mut Window,
11794        cx: &mut Context<Self>,
11795    ) -> Task<Result<Navigated>> {
11796        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11797    }
11798
11799    fn go_to_definition_of_kind(
11800        &mut self,
11801        kind: GotoDefinitionKind,
11802        split: bool,
11803        window: &mut Window,
11804        cx: &mut Context<Self>,
11805    ) -> Task<Result<Navigated>> {
11806        let Some(provider) = self.semantics_provider.clone() else {
11807            return Task::ready(Ok(Navigated::No));
11808        };
11809        let head = self.selections.newest::<usize>(cx).head();
11810        let buffer = self.buffer.read(cx);
11811        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11812            text_anchor
11813        } else {
11814            return Task::ready(Ok(Navigated::No));
11815        };
11816
11817        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11818            return Task::ready(Ok(Navigated::No));
11819        };
11820
11821        cx.spawn_in(window, |editor, mut cx| async move {
11822            let definitions = definitions.await?;
11823            let navigated = editor
11824                .update_in(&mut cx, |editor, window, cx| {
11825                    editor.navigate_to_hover_links(
11826                        Some(kind),
11827                        definitions
11828                            .into_iter()
11829                            .filter(|location| {
11830                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11831                            })
11832                            .map(HoverLink::Text)
11833                            .collect::<Vec<_>>(),
11834                        split,
11835                        window,
11836                        cx,
11837                    )
11838                })?
11839                .await?;
11840            anyhow::Ok(navigated)
11841        })
11842    }
11843
11844    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11845        let selection = self.selections.newest_anchor();
11846        let head = selection.head();
11847        let tail = selection.tail();
11848
11849        let Some((buffer, start_position)) =
11850            self.buffer.read(cx).text_anchor_for_position(head, cx)
11851        else {
11852            return;
11853        };
11854
11855        let end_position = if head != tail {
11856            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11857                return;
11858            };
11859            Some(pos)
11860        } else {
11861            None
11862        };
11863
11864        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11865            let url = if let Some(end_pos) = end_position {
11866                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11867            } else {
11868                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11869            };
11870
11871            if let Some(url) = url {
11872                editor.update(&mut cx, |_, cx| {
11873                    cx.open_url(&url);
11874                })
11875            } else {
11876                Ok(())
11877            }
11878        });
11879
11880        url_finder.detach();
11881    }
11882
11883    pub fn open_selected_filename(
11884        &mut self,
11885        _: &OpenSelectedFilename,
11886        window: &mut Window,
11887        cx: &mut Context<Self>,
11888    ) {
11889        let Some(workspace) = self.workspace() else {
11890            return;
11891        };
11892
11893        let position = self.selections.newest_anchor().head();
11894
11895        let Some((buffer, buffer_position)) =
11896            self.buffer.read(cx).text_anchor_for_position(position, cx)
11897        else {
11898            return;
11899        };
11900
11901        let project = self.project.clone();
11902
11903        cx.spawn_in(window, |_, mut cx| async move {
11904            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11905
11906            if let Some((_, path)) = result {
11907                workspace
11908                    .update_in(&mut cx, |workspace, window, cx| {
11909                        workspace.open_resolved_path(path, window, cx)
11910                    })?
11911                    .await?;
11912            }
11913            anyhow::Ok(())
11914        })
11915        .detach();
11916    }
11917
11918    pub(crate) fn navigate_to_hover_links(
11919        &mut self,
11920        kind: Option<GotoDefinitionKind>,
11921        mut definitions: Vec<HoverLink>,
11922        split: bool,
11923        window: &mut Window,
11924        cx: &mut Context<Editor>,
11925    ) -> Task<Result<Navigated>> {
11926        // If there is one definition, just open it directly
11927        if definitions.len() == 1 {
11928            let definition = definitions.pop().unwrap();
11929
11930            enum TargetTaskResult {
11931                Location(Option<Location>),
11932                AlreadyNavigated,
11933            }
11934
11935            let target_task = match definition {
11936                HoverLink::Text(link) => {
11937                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11938                }
11939                HoverLink::InlayHint(lsp_location, server_id) => {
11940                    let computation =
11941                        self.compute_target_location(lsp_location, server_id, window, cx);
11942                    cx.background_spawn(async move {
11943                        let location = computation.await?;
11944                        Ok(TargetTaskResult::Location(location))
11945                    })
11946                }
11947                HoverLink::Url(url) => {
11948                    cx.open_url(&url);
11949                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11950                }
11951                HoverLink::File(path) => {
11952                    if let Some(workspace) = self.workspace() {
11953                        cx.spawn_in(window, |_, mut cx| async move {
11954                            workspace
11955                                .update_in(&mut cx, |workspace, window, cx| {
11956                                    workspace.open_resolved_path(path, window, cx)
11957                                })?
11958                                .await
11959                                .map(|_| TargetTaskResult::AlreadyNavigated)
11960                        })
11961                    } else {
11962                        Task::ready(Ok(TargetTaskResult::Location(None)))
11963                    }
11964                }
11965            };
11966            cx.spawn_in(window, |editor, mut cx| async move {
11967                let target = match target_task.await.context("target resolution task")? {
11968                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11969                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11970                    TargetTaskResult::Location(Some(target)) => target,
11971                };
11972
11973                editor.update_in(&mut cx, |editor, window, cx| {
11974                    let Some(workspace) = editor.workspace() else {
11975                        return Navigated::No;
11976                    };
11977                    let pane = workspace.read(cx).active_pane().clone();
11978
11979                    let range = target.range.to_point(target.buffer.read(cx));
11980                    let range = editor.range_for_match(&range);
11981                    let range = collapse_multiline_range(range);
11982
11983                    if !split
11984                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11985                    {
11986                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11987                    } else {
11988                        window.defer(cx, move |window, cx| {
11989                            let target_editor: Entity<Self> =
11990                                workspace.update(cx, |workspace, cx| {
11991                                    let pane = if split {
11992                                        workspace.adjacent_pane(window, cx)
11993                                    } else {
11994                                        workspace.active_pane().clone()
11995                                    };
11996
11997                                    workspace.open_project_item(
11998                                        pane,
11999                                        target.buffer.clone(),
12000                                        true,
12001                                        true,
12002                                        window,
12003                                        cx,
12004                                    )
12005                                });
12006                            target_editor.update(cx, |target_editor, cx| {
12007                                // When selecting a definition in a different buffer, disable the nav history
12008                                // to avoid creating a history entry at the previous cursor location.
12009                                pane.update(cx, |pane, _| pane.disable_history());
12010                                target_editor.go_to_singleton_buffer_range(range, window, cx);
12011                                pane.update(cx, |pane, _| pane.enable_history());
12012                            });
12013                        });
12014                    }
12015                    Navigated::Yes
12016                })
12017            })
12018        } else if !definitions.is_empty() {
12019            cx.spawn_in(window, |editor, mut cx| async move {
12020                let (title, location_tasks, workspace) = editor
12021                    .update_in(&mut cx, |editor, window, cx| {
12022                        let tab_kind = match kind {
12023                            Some(GotoDefinitionKind::Implementation) => "Implementations",
12024                            _ => "Definitions",
12025                        };
12026                        let title = definitions
12027                            .iter()
12028                            .find_map(|definition| match definition {
12029                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
12030                                    let buffer = origin.buffer.read(cx);
12031                                    format!(
12032                                        "{} for {}",
12033                                        tab_kind,
12034                                        buffer
12035                                            .text_for_range(origin.range.clone())
12036                                            .collect::<String>()
12037                                    )
12038                                }),
12039                                HoverLink::InlayHint(_, _) => None,
12040                                HoverLink::Url(_) => None,
12041                                HoverLink::File(_) => None,
12042                            })
12043                            .unwrap_or(tab_kind.to_string());
12044                        let location_tasks = definitions
12045                            .into_iter()
12046                            .map(|definition| match definition {
12047                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
12048                                HoverLink::InlayHint(lsp_location, server_id) => editor
12049                                    .compute_target_location(lsp_location, server_id, window, cx),
12050                                HoverLink::Url(_) => Task::ready(Ok(None)),
12051                                HoverLink::File(_) => Task::ready(Ok(None)),
12052                            })
12053                            .collect::<Vec<_>>();
12054                        (title, location_tasks, editor.workspace().clone())
12055                    })
12056                    .context("location tasks preparation")?;
12057
12058                let locations = future::join_all(location_tasks)
12059                    .await
12060                    .into_iter()
12061                    .filter_map(|location| location.transpose())
12062                    .collect::<Result<_>>()
12063                    .context("location tasks")?;
12064
12065                let Some(workspace) = workspace else {
12066                    return Ok(Navigated::No);
12067                };
12068                let opened = workspace
12069                    .update_in(&mut cx, |workspace, window, cx| {
12070                        Self::open_locations_in_multibuffer(
12071                            workspace,
12072                            locations,
12073                            title,
12074                            split,
12075                            MultibufferSelectionMode::First,
12076                            window,
12077                            cx,
12078                        )
12079                    })
12080                    .ok();
12081
12082                anyhow::Ok(Navigated::from_bool(opened.is_some()))
12083            })
12084        } else {
12085            Task::ready(Ok(Navigated::No))
12086        }
12087    }
12088
12089    fn compute_target_location(
12090        &self,
12091        lsp_location: lsp::Location,
12092        server_id: LanguageServerId,
12093        window: &mut Window,
12094        cx: &mut Context<Self>,
12095    ) -> Task<anyhow::Result<Option<Location>>> {
12096        let Some(project) = self.project.clone() else {
12097            return Task::ready(Ok(None));
12098        };
12099
12100        cx.spawn_in(window, move |editor, mut cx| async move {
12101            let location_task = editor.update(&mut cx, |_, cx| {
12102                project.update(cx, |project, cx| {
12103                    let language_server_name = project
12104                        .language_server_statuses(cx)
12105                        .find(|(id, _)| server_id == *id)
12106                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
12107                    language_server_name.map(|language_server_name| {
12108                        project.open_local_buffer_via_lsp(
12109                            lsp_location.uri.clone(),
12110                            server_id,
12111                            language_server_name,
12112                            cx,
12113                        )
12114                    })
12115                })
12116            })?;
12117            let location = match location_task {
12118                Some(task) => Some({
12119                    let target_buffer_handle = task.await.context("open local buffer")?;
12120                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
12121                        let target_start = target_buffer
12122                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
12123                        let target_end = target_buffer
12124                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
12125                        target_buffer.anchor_after(target_start)
12126                            ..target_buffer.anchor_before(target_end)
12127                    })?;
12128                    Location {
12129                        buffer: target_buffer_handle,
12130                        range,
12131                    }
12132                }),
12133                None => None,
12134            };
12135            Ok(location)
12136        })
12137    }
12138
12139    pub fn find_all_references(
12140        &mut self,
12141        _: &FindAllReferences,
12142        window: &mut Window,
12143        cx: &mut Context<Self>,
12144    ) -> Option<Task<Result<Navigated>>> {
12145        let selection = self.selections.newest::<usize>(cx);
12146        let multi_buffer = self.buffer.read(cx);
12147        let head = selection.head();
12148
12149        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12150        let head_anchor = multi_buffer_snapshot.anchor_at(
12151            head,
12152            if head < selection.tail() {
12153                Bias::Right
12154            } else {
12155                Bias::Left
12156            },
12157        );
12158
12159        match self
12160            .find_all_references_task_sources
12161            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12162        {
12163            Ok(_) => {
12164                log::info!(
12165                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
12166                );
12167                return None;
12168            }
12169            Err(i) => {
12170                self.find_all_references_task_sources.insert(i, head_anchor);
12171            }
12172        }
12173
12174        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12175        let workspace = self.workspace()?;
12176        let project = workspace.read(cx).project().clone();
12177        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12178        Some(cx.spawn_in(window, |editor, mut cx| async move {
12179            let _cleanup = defer({
12180                let mut cx = cx.clone();
12181                move || {
12182                    let _ = editor.update(&mut cx, |editor, _| {
12183                        if let Ok(i) =
12184                            editor
12185                                .find_all_references_task_sources
12186                                .binary_search_by(|anchor| {
12187                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
12188                                })
12189                        {
12190                            editor.find_all_references_task_sources.remove(i);
12191                        }
12192                    });
12193                }
12194            });
12195
12196            let locations = references.await?;
12197            if locations.is_empty() {
12198                return anyhow::Ok(Navigated::No);
12199            }
12200
12201            workspace.update_in(&mut cx, |workspace, window, cx| {
12202                let title = locations
12203                    .first()
12204                    .as_ref()
12205                    .map(|location| {
12206                        let buffer = location.buffer.read(cx);
12207                        format!(
12208                            "References to `{}`",
12209                            buffer
12210                                .text_for_range(location.range.clone())
12211                                .collect::<String>()
12212                        )
12213                    })
12214                    .unwrap();
12215                Self::open_locations_in_multibuffer(
12216                    workspace,
12217                    locations,
12218                    title,
12219                    false,
12220                    MultibufferSelectionMode::First,
12221                    window,
12222                    cx,
12223                );
12224                Navigated::Yes
12225            })
12226        }))
12227    }
12228
12229    /// Opens a multibuffer with the given project locations in it
12230    pub fn open_locations_in_multibuffer(
12231        workspace: &mut Workspace,
12232        mut locations: Vec<Location>,
12233        title: String,
12234        split: bool,
12235        multibuffer_selection_mode: MultibufferSelectionMode,
12236        window: &mut Window,
12237        cx: &mut Context<Workspace>,
12238    ) {
12239        // If there are multiple definitions, open them in a multibuffer
12240        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12241        let mut locations = locations.into_iter().peekable();
12242        let mut ranges = Vec::new();
12243        let capability = workspace.project().read(cx).capability();
12244
12245        let excerpt_buffer = cx.new(|cx| {
12246            let mut multibuffer = MultiBuffer::new(capability);
12247            while let Some(location) = locations.next() {
12248                let buffer = location.buffer.read(cx);
12249                let mut ranges_for_buffer = Vec::new();
12250                let range = location.range.to_offset(buffer);
12251                ranges_for_buffer.push(range.clone());
12252
12253                while let Some(next_location) = locations.peek() {
12254                    if next_location.buffer == location.buffer {
12255                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
12256                        locations.next();
12257                    } else {
12258                        break;
12259                    }
12260                }
12261
12262                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12263                ranges.extend(multibuffer.push_excerpts_with_context_lines(
12264                    location.buffer.clone(),
12265                    ranges_for_buffer,
12266                    DEFAULT_MULTIBUFFER_CONTEXT,
12267                    cx,
12268                ))
12269            }
12270
12271            multibuffer.with_title(title)
12272        });
12273
12274        let editor = cx.new(|cx| {
12275            Editor::for_multibuffer(
12276                excerpt_buffer,
12277                Some(workspace.project().clone()),
12278                true,
12279                window,
12280                cx,
12281            )
12282        });
12283        editor.update(cx, |editor, cx| {
12284            match multibuffer_selection_mode {
12285                MultibufferSelectionMode::First => {
12286                    if let Some(first_range) = ranges.first() {
12287                        editor.change_selections(None, window, cx, |selections| {
12288                            selections.clear_disjoint();
12289                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12290                        });
12291                    }
12292                    editor.highlight_background::<Self>(
12293                        &ranges,
12294                        |theme| theme.editor_highlighted_line_background,
12295                        cx,
12296                    );
12297                }
12298                MultibufferSelectionMode::All => {
12299                    editor.change_selections(None, window, cx, |selections| {
12300                        selections.clear_disjoint();
12301                        selections.select_anchor_ranges(ranges);
12302                    });
12303                }
12304            }
12305            editor.register_buffers_with_language_servers(cx);
12306        });
12307
12308        let item = Box::new(editor);
12309        let item_id = item.item_id();
12310
12311        if split {
12312            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12313        } else {
12314            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12315                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12316                    pane.close_current_preview_item(window, cx)
12317                } else {
12318                    None
12319                }
12320            });
12321            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12322        }
12323        workspace.active_pane().update(cx, |pane, cx| {
12324            pane.set_preview_item_id(Some(item_id), cx);
12325        });
12326    }
12327
12328    pub fn rename(
12329        &mut self,
12330        _: &Rename,
12331        window: &mut Window,
12332        cx: &mut Context<Self>,
12333    ) -> Option<Task<Result<()>>> {
12334        use language::ToOffset as _;
12335
12336        let provider = self.semantics_provider.clone()?;
12337        let selection = self.selections.newest_anchor().clone();
12338        let (cursor_buffer, cursor_buffer_position) = self
12339            .buffer
12340            .read(cx)
12341            .text_anchor_for_position(selection.head(), cx)?;
12342        let (tail_buffer, cursor_buffer_position_end) = self
12343            .buffer
12344            .read(cx)
12345            .text_anchor_for_position(selection.tail(), cx)?;
12346        if tail_buffer != cursor_buffer {
12347            return None;
12348        }
12349
12350        let snapshot = cursor_buffer.read(cx).snapshot();
12351        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12352        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12353        let prepare_rename = provider
12354            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12355            .unwrap_or_else(|| Task::ready(Ok(None)));
12356        drop(snapshot);
12357
12358        Some(cx.spawn_in(window, |this, mut cx| async move {
12359            let rename_range = if let Some(range) = prepare_rename.await? {
12360                Some(range)
12361            } else {
12362                this.update(&mut cx, |this, cx| {
12363                    let buffer = this.buffer.read(cx).snapshot(cx);
12364                    let mut buffer_highlights = this
12365                        .document_highlights_for_position(selection.head(), &buffer)
12366                        .filter(|highlight| {
12367                            highlight.start.excerpt_id == selection.head().excerpt_id
12368                                && highlight.end.excerpt_id == selection.head().excerpt_id
12369                        });
12370                    buffer_highlights
12371                        .next()
12372                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12373                })?
12374            };
12375            if let Some(rename_range) = rename_range {
12376                this.update_in(&mut cx, |this, window, cx| {
12377                    let snapshot = cursor_buffer.read(cx).snapshot();
12378                    let rename_buffer_range = rename_range.to_offset(&snapshot);
12379                    let cursor_offset_in_rename_range =
12380                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12381                    let cursor_offset_in_rename_range_end =
12382                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12383
12384                    this.take_rename(false, window, cx);
12385                    let buffer = this.buffer.read(cx).read(cx);
12386                    let cursor_offset = selection.head().to_offset(&buffer);
12387                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12388                    let rename_end = rename_start + rename_buffer_range.len();
12389                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12390                    let mut old_highlight_id = None;
12391                    let old_name: Arc<str> = buffer
12392                        .chunks(rename_start..rename_end, true)
12393                        .map(|chunk| {
12394                            if old_highlight_id.is_none() {
12395                                old_highlight_id = chunk.syntax_highlight_id;
12396                            }
12397                            chunk.text
12398                        })
12399                        .collect::<String>()
12400                        .into();
12401
12402                    drop(buffer);
12403
12404                    // Position the selection in the rename editor so that it matches the current selection.
12405                    this.show_local_selections = false;
12406                    let rename_editor = cx.new(|cx| {
12407                        let mut editor = Editor::single_line(window, cx);
12408                        editor.buffer.update(cx, |buffer, cx| {
12409                            buffer.edit([(0..0, old_name.clone())], None, cx)
12410                        });
12411                        let rename_selection_range = match cursor_offset_in_rename_range
12412                            .cmp(&cursor_offset_in_rename_range_end)
12413                        {
12414                            Ordering::Equal => {
12415                                editor.select_all(&SelectAll, window, cx);
12416                                return editor;
12417                            }
12418                            Ordering::Less => {
12419                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12420                            }
12421                            Ordering::Greater => {
12422                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12423                            }
12424                        };
12425                        if rename_selection_range.end > old_name.len() {
12426                            editor.select_all(&SelectAll, window, cx);
12427                        } else {
12428                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12429                                s.select_ranges([rename_selection_range]);
12430                            });
12431                        }
12432                        editor
12433                    });
12434                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12435                        if e == &EditorEvent::Focused {
12436                            cx.emit(EditorEvent::FocusedIn)
12437                        }
12438                    })
12439                    .detach();
12440
12441                    let write_highlights =
12442                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12443                    let read_highlights =
12444                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
12445                    let ranges = write_highlights
12446                        .iter()
12447                        .flat_map(|(_, ranges)| ranges.iter())
12448                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12449                        .cloned()
12450                        .collect();
12451
12452                    this.highlight_text::<Rename>(
12453                        ranges,
12454                        HighlightStyle {
12455                            fade_out: Some(0.6),
12456                            ..Default::default()
12457                        },
12458                        cx,
12459                    );
12460                    let rename_focus_handle = rename_editor.focus_handle(cx);
12461                    window.focus(&rename_focus_handle);
12462                    let block_id = this.insert_blocks(
12463                        [BlockProperties {
12464                            style: BlockStyle::Flex,
12465                            placement: BlockPlacement::Below(range.start),
12466                            height: 1,
12467                            render: Arc::new({
12468                                let rename_editor = rename_editor.clone();
12469                                move |cx: &mut BlockContext| {
12470                                    let mut text_style = cx.editor_style.text.clone();
12471                                    if let Some(highlight_style) = old_highlight_id
12472                                        .and_then(|h| h.style(&cx.editor_style.syntax))
12473                                    {
12474                                        text_style = text_style.highlight(highlight_style);
12475                                    }
12476                                    div()
12477                                        .block_mouse_down()
12478                                        .pl(cx.anchor_x)
12479                                        .child(EditorElement::new(
12480                                            &rename_editor,
12481                                            EditorStyle {
12482                                                background: cx.theme().system().transparent,
12483                                                local_player: cx.editor_style.local_player,
12484                                                text: text_style,
12485                                                scrollbar_width: cx.editor_style.scrollbar_width,
12486                                                syntax: cx.editor_style.syntax.clone(),
12487                                                status: cx.editor_style.status.clone(),
12488                                                inlay_hints_style: HighlightStyle {
12489                                                    font_weight: Some(FontWeight::BOLD),
12490                                                    ..make_inlay_hints_style(cx.app)
12491                                                },
12492                                                inline_completion_styles: make_suggestion_styles(
12493                                                    cx.app,
12494                                                ),
12495                                                ..EditorStyle::default()
12496                                            },
12497                                        ))
12498                                        .into_any_element()
12499                                }
12500                            }),
12501                            priority: 0,
12502                        }],
12503                        Some(Autoscroll::fit()),
12504                        cx,
12505                    )[0];
12506                    this.pending_rename = Some(RenameState {
12507                        range,
12508                        old_name,
12509                        editor: rename_editor,
12510                        block_id,
12511                    });
12512                })?;
12513            }
12514
12515            Ok(())
12516        }))
12517    }
12518
12519    pub fn confirm_rename(
12520        &mut self,
12521        _: &ConfirmRename,
12522        window: &mut Window,
12523        cx: &mut Context<Self>,
12524    ) -> Option<Task<Result<()>>> {
12525        let rename = self.take_rename(false, window, cx)?;
12526        let workspace = self.workspace()?.downgrade();
12527        let (buffer, start) = self
12528            .buffer
12529            .read(cx)
12530            .text_anchor_for_position(rename.range.start, cx)?;
12531        let (end_buffer, _) = self
12532            .buffer
12533            .read(cx)
12534            .text_anchor_for_position(rename.range.end, cx)?;
12535        if buffer != end_buffer {
12536            return None;
12537        }
12538
12539        let old_name = rename.old_name;
12540        let new_name = rename.editor.read(cx).text(cx);
12541
12542        let rename = self.semantics_provider.as_ref()?.perform_rename(
12543            &buffer,
12544            start,
12545            new_name.clone(),
12546            cx,
12547        )?;
12548
12549        Some(cx.spawn_in(window, |editor, mut cx| async move {
12550            let project_transaction = rename.await?;
12551            Self::open_project_transaction(
12552                &editor,
12553                workspace,
12554                project_transaction,
12555                format!("Rename: {}{}", old_name, new_name),
12556                cx.clone(),
12557            )
12558            .await?;
12559
12560            editor.update(&mut cx, |editor, cx| {
12561                editor.refresh_document_highlights(cx);
12562            })?;
12563            Ok(())
12564        }))
12565    }
12566
12567    fn take_rename(
12568        &mut self,
12569        moving_cursor: bool,
12570        window: &mut Window,
12571        cx: &mut Context<Self>,
12572    ) -> Option<RenameState> {
12573        let rename = self.pending_rename.take()?;
12574        if rename.editor.focus_handle(cx).is_focused(window) {
12575            window.focus(&self.focus_handle);
12576        }
12577
12578        self.remove_blocks(
12579            [rename.block_id].into_iter().collect(),
12580            Some(Autoscroll::fit()),
12581            cx,
12582        );
12583        self.clear_highlights::<Rename>(cx);
12584        self.show_local_selections = true;
12585
12586        if moving_cursor {
12587            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12588                editor.selections.newest::<usize>(cx).head()
12589            });
12590
12591            // Update the selection to match the position of the selection inside
12592            // the rename editor.
12593            let snapshot = self.buffer.read(cx).read(cx);
12594            let rename_range = rename.range.to_offset(&snapshot);
12595            let cursor_in_editor = snapshot
12596                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12597                .min(rename_range.end);
12598            drop(snapshot);
12599
12600            self.change_selections(None, window, cx, |s| {
12601                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12602            });
12603        } else {
12604            self.refresh_document_highlights(cx);
12605        }
12606
12607        Some(rename)
12608    }
12609
12610    pub fn pending_rename(&self) -> Option<&RenameState> {
12611        self.pending_rename.as_ref()
12612    }
12613
12614    fn format(
12615        &mut self,
12616        _: &Format,
12617        window: &mut Window,
12618        cx: &mut Context<Self>,
12619    ) -> Option<Task<Result<()>>> {
12620        let project = match &self.project {
12621            Some(project) => project.clone(),
12622            None => return None,
12623        };
12624
12625        Some(self.perform_format(
12626            project,
12627            FormatTrigger::Manual,
12628            FormatTarget::Buffers,
12629            window,
12630            cx,
12631        ))
12632    }
12633
12634    fn format_selections(
12635        &mut self,
12636        _: &FormatSelections,
12637        window: &mut Window,
12638        cx: &mut Context<Self>,
12639    ) -> Option<Task<Result<()>>> {
12640        let project = match &self.project {
12641            Some(project) => project.clone(),
12642            None => return None,
12643        };
12644
12645        let ranges = self
12646            .selections
12647            .all_adjusted(cx)
12648            .into_iter()
12649            .map(|selection| selection.range())
12650            .collect_vec();
12651
12652        Some(self.perform_format(
12653            project,
12654            FormatTrigger::Manual,
12655            FormatTarget::Ranges(ranges),
12656            window,
12657            cx,
12658        ))
12659    }
12660
12661    fn perform_format(
12662        &mut self,
12663        project: Entity<Project>,
12664        trigger: FormatTrigger,
12665        target: FormatTarget,
12666        window: &mut Window,
12667        cx: &mut Context<Self>,
12668    ) -> Task<Result<()>> {
12669        let buffer = self.buffer.clone();
12670        let (buffers, target) = match target {
12671            FormatTarget::Buffers => {
12672                let mut buffers = buffer.read(cx).all_buffers();
12673                if trigger == FormatTrigger::Save {
12674                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
12675                }
12676                (buffers, LspFormatTarget::Buffers)
12677            }
12678            FormatTarget::Ranges(selection_ranges) => {
12679                let multi_buffer = buffer.read(cx);
12680                let snapshot = multi_buffer.read(cx);
12681                let mut buffers = HashSet::default();
12682                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12683                    BTreeMap::new();
12684                for selection_range in selection_ranges {
12685                    for (buffer, buffer_range, _) in
12686                        snapshot.range_to_buffer_ranges(selection_range)
12687                    {
12688                        let buffer_id = buffer.remote_id();
12689                        let start = buffer.anchor_before(buffer_range.start);
12690                        let end = buffer.anchor_after(buffer_range.end);
12691                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12692                        buffer_id_to_ranges
12693                            .entry(buffer_id)
12694                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12695                            .or_insert_with(|| vec![start..end]);
12696                    }
12697                }
12698                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12699            }
12700        };
12701
12702        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12703        let format = project.update(cx, |project, cx| {
12704            project.format(buffers, target, true, trigger, cx)
12705        });
12706
12707        cx.spawn_in(window, |_, mut cx| async move {
12708            let transaction = futures::select_biased! {
12709                () = timeout => {
12710                    log::warn!("timed out waiting for formatting");
12711                    None
12712                }
12713                transaction = format.log_err().fuse() => transaction,
12714            };
12715
12716            buffer
12717                .update(&mut cx, |buffer, cx| {
12718                    if let Some(transaction) = transaction {
12719                        if !buffer.is_singleton() {
12720                            buffer.push_transaction(&transaction.0, cx);
12721                        }
12722                    }
12723                    cx.notify();
12724                })
12725                .ok();
12726
12727            Ok(())
12728        })
12729    }
12730
12731    fn organize_imports(
12732        &mut self,
12733        _: &OrganizeImports,
12734        window: &mut Window,
12735        cx: &mut Context<Self>,
12736    ) -> Option<Task<Result<()>>> {
12737        let project = match &self.project {
12738            Some(project) => project.clone(),
12739            None => return None,
12740        };
12741        Some(self.perform_code_action_kind(
12742            project,
12743            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12744            window,
12745            cx,
12746        ))
12747    }
12748
12749    fn perform_code_action_kind(
12750        &mut self,
12751        project: Entity<Project>,
12752        kind: CodeActionKind,
12753        window: &mut Window,
12754        cx: &mut Context<Self>,
12755    ) -> Task<Result<()>> {
12756        let buffer = self.buffer.clone();
12757        let buffers = buffer.read(cx).all_buffers();
12758        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12759        let apply_action = project.update(cx, |project, cx| {
12760            project.apply_code_action_kind(buffers, kind, true, cx)
12761        });
12762        cx.spawn_in(window, |_, mut cx| async move {
12763            let transaction = futures::select_biased! {
12764                () = timeout => {
12765                    log::warn!("timed out waiting for executing code action");
12766                    None
12767                }
12768                transaction = apply_action.log_err().fuse() => transaction,
12769            };
12770            buffer
12771                .update(&mut cx, |buffer, cx| {
12772                    // check if we need this
12773                    if let Some(transaction) = transaction {
12774                        if !buffer.is_singleton() {
12775                            buffer.push_transaction(&transaction.0, cx);
12776                        }
12777                    }
12778                    cx.notify();
12779                })
12780                .ok();
12781            Ok(())
12782        })
12783    }
12784
12785    fn restart_language_server(
12786        &mut self,
12787        _: &RestartLanguageServer,
12788        _: &mut Window,
12789        cx: &mut Context<Self>,
12790    ) {
12791        if let Some(project) = self.project.clone() {
12792            self.buffer.update(cx, |multi_buffer, cx| {
12793                project.update(cx, |project, cx| {
12794                    project.restart_language_servers_for_buffers(
12795                        multi_buffer.all_buffers().into_iter().collect(),
12796                        cx,
12797                    );
12798                });
12799            })
12800        }
12801    }
12802
12803    fn cancel_language_server_work(
12804        workspace: &mut Workspace,
12805        _: &actions::CancelLanguageServerWork,
12806        _: &mut Window,
12807        cx: &mut Context<Workspace>,
12808    ) {
12809        let project = workspace.project();
12810        let buffers = workspace
12811            .active_item(cx)
12812            .and_then(|item| item.act_as::<Editor>(cx))
12813            .map_or(HashSet::default(), |editor| {
12814                editor.read(cx).buffer.read(cx).all_buffers()
12815            });
12816        project.update(cx, |project, cx| {
12817            project.cancel_language_server_work_for_buffers(buffers, cx);
12818        });
12819    }
12820
12821    fn show_character_palette(
12822        &mut self,
12823        _: &ShowCharacterPalette,
12824        window: &mut Window,
12825        _: &mut Context<Self>,
12826    ) {
12827        window.show_character_palette();
12828    }
12829
12830    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12831        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12832            let buffer = self.buffer.read(cx).snapshot(cx);
12833            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12834            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12835            let is_valid = buffer
12836                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12837                .any(|entry| {
12838                    entry.diagnostic.is_primary
12839                        && !entry.range.is_empty()
12840                        && entry.range.start == primary_range_start
12841                        && entry.diagnostic.message == active_diagnostics.primary_message
12842                });
12843
12844            if is_valid != active_diagnostics.is_valid {
12845                active_diagnostics.is_valid = is_valid;
12846                if is_valid {
12847                    let mut new_styles = HashMap::default();
12848                    for (block_id, diagnostic) in &active_diagnostics.blocks {
12849                        new_styles.insert(
12850                            *block_id,
12851                            diagnostic_block_renderer(diagnostic.clone(), None, true),
12852                        );
12853                    }
12854                    self.display_map.update(cx, |display_map, _cx| {
12855                        display_map.replace_blocks(new_styles);
12856                    });
12857                } else {
12858                    self.dismiss_diagnostics(cx);
12859                }
12860            }
12861        }
12862    }
12863
12864    fn activate_diagnostics(
12865        &mut self,
12866        buffer_id: BufferId,
12867        group_id: usize,
12868        window: &mut Window,
12869        cx: &mut Context<Self>,
12870    ) {
12871        self.dismiss_diagnostics(cx);
12872        let snapshot = self.snapshot(window, cx);
12873        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12874            let buffer = self.buffer.read(cx).snapshot(cx);
12875
12876            let mut primary_range = None;
12877            let mut primary_message = None;
12878            let diagnostic_group = buffer
12879                .diagnostic_group(buffer_id, group_id)
12880                .filter_map(|entry| {
12881                    let start = entry.range.start;
12882                    let end = entry.range.end;
12883                    if snapshot.is_line_folded(MultiBufferRow(start.row))
12884                        && (start.row == end.row
12885                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
12886                    {
12887                        return None;
12888                    }
12889                    if entry.diagnostic.is_primary {
12890                        primary_range = Some(entry.range.clone());
12891                        primary_message = Some(entry.diagnostic.message.clone());
12892                    }
12893                    Some(entry)
12894                })
12895                .collect::<Vec<_>>();
12896            let primary_range = primary_range?;
12897            let primary_message = primary_message?;
12898
12899            let blocks = display_map
12900                .insert_blocks(
12901                    diagnostic_group.iter().map(|entry| {
12902                        let diagnostic = entry.diagnostic.clone();
12903                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12904                        BlockProperties {
12905                            style: BlockStyle::Fixed,
12906                            placement: BlockPlacement::Below(
12907                                buffer.anchor_after(entry.range.start),
12908                            ),
12909                            height: message_height,
12910                            render: diagnostic_block_renderer(diagnostic, None, true),
12911                            priority: 0,
12912                        }
12913                    }),
12914                    cx,
12915                )
12916                .into_iter()
12917                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12918                .collect();
12919
12920            Some(ActiveDiagnosticGroup {
12921                primary_range: buffer.anchor_before(primary_range.start)
12922                    ..buffer.anchor_after(primary_range.end),
12923                primary_message,
12924                group_id,
12925                blocks,
12926                is_valid: true,
12927            })
12928        });
12929    }
12930
12931    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12932        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12933            self.display_map.update(cx, |display_map, cx| {
12934                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12935            });
12936            cx.notify();
12937        }
12938    }
12939
12940    /// Disable inline diagnostics rendering for this editor.
12941    pub fn disable_inline_diagnostics(&mut self) {
12942        self.inline_diagnostics_enabled = false;
12943        self.inline_diagnostics_update = Task::ready(());
12944        self.inline_diagnostics.clear();
12945    }
12946
12947    pub fn inline_diagnostics_enabled(&self) -> bool {
12948        self.inline_diagnostics_enabled
12949    }
12950
12951    pub fn show_inline_diagnostics(&self) -> bool {
12952        self.show_inline_diagnostics
12953    }
12954
12955    pub fn toggle_inline_diagnostics(
12956        &mut self,
12957        _: &ToggleInlineDiagnostics,
12958        window: &mut Window,
12959        cx: &mut Context<'_, Editor>,
12960    ) {
12961        self.show_inline_diagnostics = !self.show_inline_diagnostics;
12962        self.refresh_inline_diagnostics(false, window, cx);
12963    }
12964
12965    fn refresh_inline_diagnostics(
12966        &mut self,
12967        debounce: bool,
12968        window: &mut Window,
12969        cx: &mut Context<Self>,
12970    ) {
12971        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12972            self.inline_diagnostics_update = Task::ready(());
12973            self.inline_diagnostics.clear();
12974            return;
12975        }
12976
12977        let debounce_ms = ProjectSettings::get_global(cx)
12978            .diagnostics
12979            .inline
12980            .update_debounce_ms;
12981        let debounce = if debounce && debounce_ms > 0 {
12982            Some(Duration::from_millis(debounce_ms))
12983        } else {
12984            None
12985        };
12986        self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12987            if let Some(debounce) = debounce {
12988                cx.background_executor().timer(debounce).await;
12989            }
12990            let Some(snapshot) = editor
12991                .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12992                .ok()
12993            else {
12994                return;
12995            };
12996
12997            let new_inline_diagnostics = cx
12998                .background_spawn(async move {
12999                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
13000                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
13001                        let message = diagnostic_entry
13002                            .diagnostic
13003                            .message
13004                            .split_once('\n')
13005                            .map(|(line, _)| line)
13006                            .map(SharedString::new)
13007                            .unwrap_or_else(|| {
13008                                SharedString::from(diagnostic_entry.diagnostic.message)
13009                            });
13010                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
13011                        let (Ok(i) | Err(i)) = inline_diagnostics
13012                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
13013                        inline_diagnostics.insert(
13014                            i,
13015                            (
13016                                start_anchor,
13017                                InlineDiagnostic {
13018                                    message,
13019                                    group_id: diagnostic_entry.diagnostic.group_id,
13020                                    start: diagnostic_entry.range.start.to_point(&snapshot),
13021                                    is_primary: diagnostic_entry.diagnostic.is_primary,
13022                                    severity: diagnostic_entry.diagnostic.severity,
13023                                },
13024                            ),
13025                        );
13026                    }
13027                    inline_diagnostics
13028                })
13029                .await;
13030
13031            editor
13032                .update(&mut cx, |editor, cx| {
13033                    editor.inline_diagnostics = new_inline_diagnostics;
13034                    cx.notify();
13035                })
13036                .ok();
13037        });
13038    }
13039
13040    pub fn set_selections_from_remote(
13041        &mut self,
13042        selections: Vec<Selection<Anchor>>,
13043        pending_selection: Option<Selection<Anchor>>,
13044        window: &mut Window,
13045        cx: &mut Context<Self>,
13046    ) {
13047        let old_cursor_position = self.selections.newest_anchor().head();
13048        self.selections.change_with(cx, |s| {
13049            s.select_anchors(selections);
13050            if let Some(pending_selection) = pending_selection {
13051                s.set_pending(pending_selection, SelectMode::Character);
13052            } else {
13053                s.clear_pending();
13054            }
13055        });
13056        self.selections_did_change(false, &old_cursor_position, true, window, cx);
13057    }
13058
13059    fn push_to_selection_history(&mut self) {
13060        self.selection_history.push(SelectionHistoryEntry {
13061            selections: self.selections.disjoint_anchors(),
13062            select_next_state: self.select_next_state.clone(),
13063            select_prev_state: self.select_prev_state.clone(),
13064            add_selections_state: self.add_selections_state.clone(),
13065        });
13066    }
13067
13068    pub fn transact(
13069        &mut self,
13070        window: &mut Window,
13071        cx: &mut Context<Self>,
13072        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
13073    ) -> Option<TransactionId> {
13074        self.start_transaction_at(Instant::now(), window, cx);
13075        update(self, window, cx);
13076        self.end_transaction_at(Instant::now(), cx)
13077    }
13078
13079    pub fn start_transaction_at(
13080        &mut self,
13081        now: Instant,
13082        window: &mut Window,
13083        cx: &mut Context<Self>,
13084    ) {
13085        self.end_selection(window, cx);
13086        if let Some(tx_id) = self
13087            .buffer
13088            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
13089        {
13090            self.selection_history
13091                .insert_transaction(tx_id, self.selections.disjoint_anchors());
13092            cx.emit(EditorEvent::TransactionBegun {
13093                transaction_id: tx_id,
13094            })
13095        }
13096    }
13097
13098    pub fn end_transaction_at(
13099        &mut self,
13100        now: Instant,
13101        cx: &mut Context<Self>,
13102    ) -> Option<TransactionId> {
13103        if let Some(transaction_id) = self
13104            .buffer
13105            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
13106        {
13107            if let Some((_, end_selections)) =
13108                self.selection_history.transaction_mut(transaction_id)
13109            {
13110                *end_selections = Some(self.selections.disjoint_anchors());
13111            } else {
13112                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
13113            }
13114
13115            cx.emit(EditorEvent::Edited { transaction_id });
13116            Some(transaction_id)
13117        } else {
13118            None
13119        }
13120    }
13121
13122    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
13123        if self.selection_mark_mode {
13124            self.change_selections(None, window, cx, |s| {
13125                s.move_with(|_, sel| {
13126                    sel.collapse_to(sel.head(), SelectionGoal::None);
13127                });
13128            })
13129        }
13130        self.selection_mark_mode = true;
13131        cx.notify();
13132    }
13133
13134    pub fn swap_selection_ends(
13135        &mut self,
13136        _: &actions::SwapSelectionEnds,
13137        window: &mut Window,
13138        cx: &mut Context<Self>,
13139    ) {
13140        self.change_selections(None, window, cx, |s| {
13141            s.move_with(|_, sel| {
13142                if sel.start != sel.end {
13143                    sel.reversed = !sel.reversed
13144                }
13145            });
13146        });
13147        self.request_autoscroll(Autoscroll::newest(), cx);
13148        cx.notify();
13149    }
13150
13151    pub fn toggle_fold(
13152        &mut self,
13153        _: &actions::ToggleFold,
13154        window: &mut Window,
13155        cx: &mut Context<Self>,
13156    ) {
13157        if self.is_singleton(cx) {
13158            let selection = self.selections.newest::<Point>(cx);
13159
13160            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13161            let range = if selection.is_empty() {
13162                let point = selection.head().to_display_point(&display_map);
13163                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13164                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13165                    .to_point(&display_map);
13166                start..end
13167            } else {
13168                selection.range()
13169            };
13170            if display_map.folds_in_range(range).next().is_some() {
13171                self.unfold_lines(&Default::default(), window, cx)
13172            } else {
13173                self.fold(&Default::default(), window, cx)
13174            }
13175        } else {
13176            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13177            let buffer_ids: HashSet<_> = self
13178                .selections
13179                .disjoint_anchor_ranges()
13180                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13181                .collect();
13182
13183            let should_unfold = buffer_ids
13184                .iter()
13185                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13186
13187            for buffer_id in buffer_ids {
13188                if should_unfold {
13189                    self.unfold_buffer(buffer_id, cx);
13190                } else {
13191                    self.fold_buffer(buffer_id, cx);
13192                }
13193            }
13194        }
13195    }
13196
13197    pub fn toggle_fold_recursive(
13198        &mut self,
13199        _: &actions::ToggleFoldRecursive,
13200        window: &mut Window,
13201        cx: &mut Context<Self>,
13202    ) {
13203        let selection = self.selections.newest::<Point>(cx);
13204
13205        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13206        let range = if selection.is_empty() {
13207            let point = selection.head().to_display_point(&display_map);
13208            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13209            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13210                .to_point(&display_map);
13211            start..end
13212        } else {
13213            selection.range()
13214        };
13215        if display_map.folds_in_range(range).next().is_some() {
13216            self.unfold_recursive(&Default::default(), window, cx)
13217        } else {
13218            self.fold_recursive(&Default::default(), window, cx)
13219        }
13220    }
13221
13222    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13223        if self.is_singleton(cx) {
13224            let mut to_fold = Vec::new();
13225            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13226            let selections = self.selections.all_adjusted(cx);
13227
13228            for selection in selections {
13229                let range = selection.range().sorted();
13230                let buffer_start_row = range.start.row;
13231
13232                if range.start.row != range.end.row {
13233                    let mut found = false;
13234                    let mut row = range.start.row;
13235                    while row <= range.end.row {
13236                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13237                        {
13238                            found = true;
13239                            row = crease.range().end.row + 1;
13240                            to_fold.push(crease);
13241                        } else {
13242                            row += 1
13243                        }
13244                    }
13245                    if found {
13246                        continue;
13247                    }
13248                }
13249
13250                for row in (0..=range.start.row).rev() {
13251                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13252                        if crease.range().end.row >= buffer_start_row {
13253                            to_fold.push(crease);
13254                            if row <= range.start.row {
13255                                break;
13256                            }
13257                        }
13258                    }
13259                }
13260            }
13261
13262            self.fold_creases(to_fold, true, window, cx);
13263        } else {
13264            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13265            let buffer_ids = self
13266                .selections
13267                .disjoint_anchor_ranges()
13268                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13269                .collect::<HashSet<_>>();
13270            for buffer_id in buffer_ids {
13271                self.fold_buffer(buffer_id, cx);
13272            }
13273        }
13274    }
13275
13276    fn fold_at_level(
13277        &mut self,
13278        fold_at: &FoldAtLevel,
13279        window: &mut Window,
13280        cx: &mut Context<Self>,
13281    ) {
13282        if !self.buffer.read(cx).is_singleton() {
13283            return;
13284        }
13285
13286        let fold_at_level = fold_at.0;
13287        let snapshot = self.buffer.read(cx).snapshot(cx);
13288        let mut to_fold = Vec::new();
13289        let mut stack = vec![(0, snapshot.max_row().0, 1)];
13290
13291        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13292            while start_row < end_row {
13293                match self
13294                    .snapshot(window, cx)
13295                    .crease_for_buffer_row(MultiBufferRow(start_row))
13296                {
13297                    Some(crease) => {
13298                        let nested_start_row = crease.range().start.row + 1;
13299                        let nested_end_row = crease.range().end.row;
13300
13301                        if current_level < fold_at_level {
13302                            stack.push((nested_start_row, nested_end_row, current_level + 1));
13303                        } else if current_level == fold_at_level {
13304                            to_fold.push(crease);
13305                        }
13306
13307                        start_row = nested_end_row + 1;
13308                    }
13309                    None => start_row += 1,
13310                }
13311            }
13312        }
13313
13314        self.fold_creases(to_fold, true, window, cx);
13315    }
13316
13317    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13318        if self.buffer.read(cx).is_singleton() {
13319            let mut fold_ranges = Vec::new();
13320            let snapshot = self.buffer.read(cx).snapshot(cx);
13321
13322            for row in 0..snapshot.max_row().0 {
13323                if let Some(foldable_range) = self
13324                    .snapshot(window, cx)
13325                    .crease_for_buffer_row(MultiBufferRow(row))
13326                {
13327                    fold_ranges.push(foldable_range);
13328                }
13329            }
13330
13331            self.fold_creases(fold_ranges, true, window, cx);
13332        } else {
13333            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13334                editor
13335                    .update_in(&mut cx, |editor, _, cx| {
13336                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13337                            editor.fold_buffer(buffer_id, cx);
13338                        }
13339                    })
13340                    .ok();
13341            });
13342        }
13343    }
13344
13345    pub fn fold_function_bodies(
13346        &mut self,
13347        _: &actions::FoldFunctionBodies,
13348        window: &mut Window,
13349        cx: &mut Context<Self>,
13350    ) {
13351        let snapshot = self.buffer.read(cx).snapshot(cx);
13352
13353        let ranges = snapshot
13354            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13355            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13356            .collect::<Vec<_>>();
13357
13358        let creases = ranges
13359            .into_iter()
13360            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13361            .collect();
13362
13363        self.fold_creases(creases, true, window, cx);
13364    }
13365
13366    pub fn fold_recursive(
13367        &mut self,
13368        _: &actions::FoldRecursive,
13369        window: &mut Window,
13370        cx: &mut Context<Self>,
13371    ) {
13372        let mut to_fold = Vec::new();
13373        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13374        let selections = self.selections.all_adjusted(cx);
13375
13376        for selection in selections {
13377            let range = selection.range().sorted();
13378            let buffer_start_row = range.start.row;
13379
13380            if range.start.row != range.end.row {
13381                let mut found = false;
13382                for row in range.start.row..=range.end.row {
13383                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13384                        found = true;
13385                        to_fold.push(crease);
13386                    }
13387                }
13388                if found {
13389                    continue;
13390                }
13391            }
13392
13393            for row in (0..=range.start.row).rev() {
13394                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13395                    if crease.range().end.row >= buffer_start_row {
13396                        to_fold.push(crease);
13397                    } else {
13398                        break;
13399                    }
13400                }
13401            }
13402        }
13403
13404        self.fold_creases(to_fold, true, window, cx);
13405    }
13406
13407    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13408        let buffer_row = fold_at.buffer_row;
13409        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13410
13411        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13412            let autoscroll = self
13413                .selections
13414                .all::<Point>(cx)
13415                .iter()
13416                .any(|selection| crease.range().overlaps(&selection.range()));
13417
13418            self.fold_creases(vec![crease], autoscroll, window, cx);
13419        }
13420    }
13421
13422    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13423        if self.is_singleton(cx) {
13424            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13425            let buffer = &display_map.buffer_snapshot;
13426            let selections = self.selections.all::<Point>(cx);
13427            let ranges = selections
13428                .iter()
13429                .map(|s| {
13430                    let range = s.display_range(&display_map).sorted();
13431                    let mut start = range.start.to_point(&display_map);
13432                    let mut end = range.end.to_point(&display_map);
13433                    start.column = 0;
13434                    end.column = buffer.line_len(MultiBufferRow(end.row));
13435                    start..end
13436                })
13437                .collect::<Vec<_>>();
13438
13439            self.unfold_ranges(&ranges, true, true, cx);
13440        } else {
13441            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13442            let buffer_ids = self
13443                .selections
13444                .disjoint_anchor_ranges()
13445                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13446                .collect::<HashSet<_>>();
13447            for buffer_id in buffer_ids {
13448                self.unfold_buffer(buffer_id, cx);
13449            }
13450        }
13451    }
13452
13453    pub fn unfold_recursive(
13454        &mut self,
13455        _: &UnfoldRecursive,
13456        _window: &mut Window,
13457        cx: &mut Context<Self>,
13458    ) {
13459        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13460        let selections = self.selections.all::<Point>(cx);
13461        let ranges = selections
13462            .iter()
13463            .map(|s| {
13464                let mut range = s.display_range(&display_map).sorted();
13465                *range.start.column_mut() = 0;
13466                *range.end.column_mut() = display_map.line_len(range.end.row());
13467                let start = range.start.to_point(&display_map);
13468                let end = range.end.to_point(&display_map);
13469                start..end
13470            })
13471            .collect::<Vec<_>>();
13472
13473        self.unfold_ranges(&ranges, true, true, cx);
13474    }
13475
13476    pub fn unfold_at(
13477        &mut self,
13478        unfold_at: &UnfoldAt,
13479        _window: &mut Window,
13480        cx: &mut Context<Self>,
13481    ) {
13482        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13483
13484        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13485            ..Point::new(
13486                unfold_at.buffer_row.0,
13487                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13488            );
13489
13490        let autoscroll = self
13491            .selections
13492            .all::<Point>(cx)
13493            .iter()
13494            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13495
13496        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13497    }
13498
13499    pub fn unfold_all(
13500        &mut self,
13501        _: &actions::UnfoldAll,
13502        _window: &mut Window,
13503        cx: &mut Context<Self>,
13504    ) {
13505        if self.buffer.read(cx).is_singleton() {
13506            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13507            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13508        } else {
13509            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13510                editor
13511                    .update(&mut cx, |editor, cx| {
13512                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13513                            editor.unfold_buffer(buffer_id, cx);
13514                        }
13515                    })
13516                    .ok();
13517            });
13518        }
13519    }
13520
13521    pub fn fold_selected_ranges(
13522        &mut self,
13523        _: &FoldSelectedRanges,
13524        window: &mut Window,
13525        cx: &mut Context<Self>,
13526    ) {
13527        let selections = self.selections.all::<Point>(cx);
13528        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13529        let line_mode = self.selections.line_mode;
13530        let ranges = selections
13531            .into_iter()
13532            .map(|s| {
13533                if line_mode {
13534                    let start = Point::new(s.start.row, 0);
13535                    let end = Point::new(
13536                        s.end.row,
13537                        display_map
13538                            .buffer_snapshot
13539                            .line_len(MultiBufferRow(s.end.row)),
13540                    );
13541                    Crease::simple(start..end, display_map.fold_placeholder.clone())
13542                } else {
13543                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13544                }
13545            })
13546            .collect::<Vec<_>>();
13547        self.fold_creases(ranges, true, window, cx);
13548    }
13549
13550    pub fn fold_ranges<T: ToOffset + Clone>(
13551        &mut self,
13552        ranges: Vec<Range<T>>,
13553        auto_scroll: bool,
13554        window: &mut Window,
13555        cx: &mut Context<Self>,
13556    ) {
13557        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13558        let ranges = ranges
13559            .into_iter()
13560            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13561            .collect::<Vec<_>>();
13562        self.fold_creases(ranges, auto_scroll, window, cx);
13563    }
13564
13565    pub fn fold_creases<T: ToOffset + Clone>(
13566        &mut self,
13567        creases: Vec<Crease<T>>,
13568        auto_scroll: bool,
13569        window: &mut Window,
13570        cx: &mut Context<Self>,
13571    ) {
13572        if creases.is_empty() {
13573            return;
13574        }
13575
13576        let mut buffers_affected = HashSet::default();
13577        let multi_buffer = self.buffer().read(cx);
13578        for crease in &creases {
13579            if let Some((_, buffer, _)) =
13580                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13581            {
13582                buffers_affected.insert(buffer.read(cx).remote_id());
13583            };
13584        }
13585
13586        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13587
13588        if auto_scroll {
13589            self.request_autoscroll(Autoscroll::fit(), cx);
13590        }
13591
13592        cx.notify();
13593
13594        if let Some(active_diagnostics) = self.active_diagnostics.take() {
13595            // Clear diagnostics block when folding a range that contains it.
13596            let snapshot = self.snapshot(window, cx);
13597            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13598                drop(snapshot);
13599                self.active_diagnostics = Some(active_diagnostics);
13600                self.dismiss_diagnostics(cx);
13601            } else {
13602                self.active_diagnostics = Some(active_diagnostics);
13603            }
13604        }
13605
13606        self.scrollbar_marker_state.dirty = true;
13607    }
13608
13609    /// Removes any folds whose ranges intersect any of the given ranges.
13610    pub fn unfold_ranges<T: ToOffset + Clone>(
13611        &mut self,
13612        ranges: &[Range<T>],
13613        inclusive: bool,
13614        auto_scroll: bool,
13615        cx: &mut Context<Self>,
13616    ) {
13617        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13618            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13619        });
13620    }
13621
13622    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13623        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13624            return;
13625        }
13626        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13627        self.display_map.update(cx, |display_map, cx| {
13628            display_map.fold_buffers([buffer_id], cx)
13629        });
13630        cx.emit(EditorEvent::BufferFoldToggled {
13631            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13632            folded: true,
13633        });
13634        cx.notify();
13635    }
13636
13637    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13638        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13639            return;
13640        }
13641        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13642        self.display_map.update(cx, |display_map, cx| {
13643            display_map.unfold_buffers([buffer_id], cx);
13644        });
13645        cx.emit(EditorEvent::BufferFoldToggled {
13646            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13647            folded: false,
13648        });
13649        cx.notify();
13650    }
13651
13652    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13653        self.display_map.read(cx).is_buffer_folded(buffer)
13654    }
13655
13656    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13657        self.display_map.read(cx).folded_buffers()
13658    }
13659
13660    /// Removes any folds with the given ranges.
13661    pub fn remove_folds_with_type<T: ToOffset + Clone>(
13662        &mut self,
13663        ranges: &[Range<T>],
13664        type_id: TypeId,
13665        auto_scroll: bool,
13666        cx: &mut Context<Self>,
13667    ) {
13668        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13669            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13670        });
13671    }
13672
13673    fn remove_folds_with<T: ToOffset + Clone>(
13674        &mut self,
13675        ranges: &[Range<T>],
13676        auto_scroll: bool,
13677        cx: &mut Context<Self>,
13678        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13679    ) {
13680        if ranges.is_empty() {
13681            return;
13682        }
13683
13684        let mut buffers_affected = HashSet::default();
13685        let multi_buffer = self.buffer().read(cx);
13686        for range in ranges {
13687            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13688                buffers_affected.insert(buffer.read(cx).remote_id());
13689            };
13690        }
13691
13692        self.display_map.update(cx, update);
13693
13694        if auto_scroll {
13695            self.request_autoscroll(Autoscroll::fit(), cx);
13696        }
13697
13698        cx.notify();
13699        self.scrollbar_marker_state.dirty = true;
13700        self.active_indent_guides_state.dirty = true;
13701    }
13702
13703    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13704        self.display_map.read(cx).fold_placeholder.clone()
13705    }
13706
13707    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13708        self.buffer.update(cx, |buffer, cx| {
13709            buffer.set_all_diff_hunks_expanded(cx);
13710        });
13711    }
13712
13713    pub fn expand_all_diff_hunks(
13714        &mut self,
13715        _: &ExpandAllDiffHunks,
13716        _window: &mut Window,
13717        cx: &mut Context<Self>,
13718    ) {
13719        self.buffer.update(cx, |buffer, cx| {
13720            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13721        });
13722    }
13723
13724    pub fn toggle_selected_diff_hunks(
13725        &mut self,
13726        _: &ToggleSelectedDiffHunks,
13727        _window: &mut Window,
13728        cx: &mut Context<Self>,
13729    ) {
13730        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13731        self.toggle_diff_hunks_in_ranges(ranges, cx);
13732    }
13733
13734    pub fn diff_hunks_in_ranges<'a>(
13735        &'a self,
13736        ranges: &'a [Range<Anchor>],
13737        buffer: &'a MultiBufferSnapshot,
13738    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13739        ranges.iter().flat_map(move |range| {
13740            let end_excerpt_id = range.end.excerpt_id;
13741            let range = range.to_point(buffer);
13742            let mut peek_end = range.end;
13743            if range.end.row < buffer.max_row().0 {
13744                peek_end = Point::new(range.end.row + 1, 0);
13745            }
13746            buffer
13747                .diff_hunks_in_range(range.start..peek_end)
13748                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13749        })
13750    }
13751
13752    pub fn has_stageable_diff_hunks_in_ranges(
13753        &self,
13754        ranges: &[Range<Anchor>],
13755        snapshot: &MultiBufferSnapshot,
13756    ) -> bool {
13757        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13758        hunks.any(|hunk| hunk.status().has_secondary_hunk())
13759    }
13760
13761    pub fn toggle_staged_selected_diff_hunks(
13762        &mut self,
13763        _: &::git::ToggleStaged,
13764        _: &mut Window,
13765        cx: &mut Context<Self>,
13766    ) {
13767        let snapshot = self.buffer.read(cx).snapshot(cx);
13768        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13769        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13770        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13771    }
13772
13773    pub fn stage_and_next(
13774        &mut self,
13775        _: &::git::StageAndNext,
13776        window: &mut Window,
13777        cx: &mut Context<Self>,
13778    ) {
13779        self.do_stage_or_unstage_and_next(true, window, cx);
13780    }
13781
13782    pub fn unstage_and_next(
13783        &mut self,
13784        _: &::git::UnstageAndNext,
13785        window: &mut Window,
13786        cx: &mut Context<Self>,
13787    ) {
13788        self.do_stage_or_unstage_and_next(false, window, cx);
13789    }
13790
13791    pub fn stage_or_unstage_diff_hunks(
13792        &mut self,
13793        stage: bool,
13794        ranges: Vec<Range<Anchor>>,
13795        cx: &mut Context<Self>,
13796    ) {
13797        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
13798        cx.spawn(|this, mut cx| async move {
13799            task.await?;
13800            this.update(&mut cx, |this, cx| {
13801                let snapshot = this.buffer.read(cx).snapshot(cx);
13802                let chunk_by = this
13803                    .diff_hunks_in_ranges(&ranges, &snapshot)
13804                    .chunk_by(|hunk| hunk.buffer_id);
13805                for (buffer_id, hunks) in &chunk_by {
13806                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
13807                }
13808            })
13809        })
13810        .detach_and_log_err(cx);
13811    }
13812
13813    fn save_buffers_for_ranges_if_needed(
13814        &mut self,
13815        ranges: &[Range<Anchor>],
13816        cx: &mut Context<'_, Editor>,
13817    ) -> Task<Result<()>> {
13818        let multibuffer = self.buffer.read(cx);
13819        let snapshot = multibuffer.read(cx);
13820        let buffer_ids: HashSet<_> = ranges
13821            .iter()
13822            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
13823            .collect();
13824        drop(snapshot);
13825
13826        let mut buffers = HashSet::default();
13827        for buffer_id in buffer_ids {
13828            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
13829                let buffer = buffer_entity.read(cx);
13830                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
13831                {
13832                    buffers.insert(buffer_entity);
13833                }
13834            }
13835        }
13836
13837        if let Some(project) = &self.project {
13838            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
13839        } else {
13840            Task::ready(Ok(()))
13841        }
13842    }
13843
13844    fn do_stage_or_unstage_and_next(
13845        &mut self,
13846        stage: bool,
13847        window: &mut Window,
13848        cx: &mut Context<Self>,
13849    ) {
13850        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13851
13852        if ranges.iter().any(|range| range.start != range.end) {
13853            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13854            return;
13855        }
13856
13857        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13858        let snapshot = self.snapshot(window, cx);
13859        let position = self.selections.newest::<Point>(cx).head();
13860        let mut row = snapshot
13861            .buffer_snapshot
13862            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13863            .find(|hunk| hunk.row_range.start.0 > position.row)
13864            .map(|hunk| hunk.row_range.start);
13865
13866        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
13867        // Outside of the project diff editor, wrap around to the beginning.
13868        if !all_diff_hunks_expanded {
13869            row = row.or_else(|| {
13870                snapshot
13871                    .buffer_snapshot
13872                    .diff_hunks_in_range(Point::zero()..position)
13873                    .find(|hunk| hunk.row_range.end.0 < position.row)
13874                    .map(|hunk| hunk.row_range.start)
13875            });
13876        }
13877
13878        if let Some(row) = row {
13879            let destination = Point::new(row.0, 0);
13880            let autoscroll = Autoscroll::center();
13881
13882            self.unfold_ranges(&[destination..destination], false, false, cx);
13883            self.change_selections(Some(autoscroll), window, cx, |s| {
13884                s.select_ranges([destination..destination]);
13885            });
13886        } else if all_diff_hunks_expanded {
13887            window.dispatch_action(::git::ExpandCommitEditor.boxed_clone(), cx);
13888        }
13889    }
13890
13891    fn do_stage_or_unstage(
13892        &self,
13893        stage: bool,
13894        buffer_id: BufferId,
13895        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13896        cx: &mut App,
13897    ) -> Option<()> {
13898        let project = self.project.as_ref()?;
13899        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
13900        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
13901        let buffer_snapshot = buffer.read(cx).snapshot();
13902        let file_exists = buffer_snapshot
13903            .file()
13904            .is_some_and(|file| file.disk_state().exists());
13905        diff.update(cx, |diff, cx| {
13906            diff.stage_or_unstage_hunks(
13907                stage,
13908                &hunks
13909                    .map(|hunk| buffer_diff::DiffHunk {
13910                        buffer_range: hunk.buffer_range,
13911                        diff_base_byte_range: hunk.diff_base_byte_range,
13912                        secondary_status: hunk.secondary_status,
13913                        range: Point::zero()..Point::zero(), // unused
13914                    })
13915                    .collect::<Vec<_>>(),
13916                &buffer_snapshot,
13917                file_exists,
13918                cx,
13919            )
13920        });
13921        None
13922    }
13923
13924    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13925        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13926        self.buffer
13927            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13928    }
13929
13930    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13931        self.buffer.update(cx, |buffer, cx| {
13932            let ranges = vec![Anchor::min()..Anchor::max()];
13933            if !buffer.all_diff_hunks_expanded()
13934                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13935            {
13936                buffer.collapse_diff_hunks(ranges, cx);
13937                true
13938            } else {
13939                false
13940            }
13941        })
13942    }
13943
13944    fn toggle_diff_hunks_in_ranges(
13945        &mut self,
13946        ranges: Vec<Range<Anchor>>,
13947        cx: &mut Context<'_, Editor>,
13948    ) {
13949        self.buffer.update(cx, |buffer, cx| {
13950            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13951            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13952        })
13953    }
13954
13955    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13956        self.buffer.update(cx, |buffer, cx| {
13957            let snapshot = buffer.snapshot(cx);
13958            let excerpt_id = range.end.excerpt_id;
13959            let point_range = range.to_point(&snapshot);
13960            let expand = !buffer.single_hunk_is_expanded(range, cx);
13961            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13962        })
13963    }
13964
13965    pub(crate) fn apply_all_diff_hunks(
13966        &mut self,
13967        _: &ApplyAllDiffHunks,
13968        window: &mut Window,
13969        cx: &mut Context<Self>,
13970    ) {
13971        let buffers = self.buffer.read(cx).all_buffers();
13972        for branch_buffer in buffers {
13973            branch_buffer.update(cx, |branch_buffer, cx| {
13974                branch_buffer.merge_into_base(Vec::new(), cx);
13975            });
13976        }
13977
13978        if let Some(project) = self.project.clone() {
13979            self.save(true, project, window, cx).detach_and_log_err(cx);
13980        }
13981    }
13982
13983    pub(crate) fn apply_selected_diff_hunks(
13984        &mut self,
13985        _: &ApplyDiffHunk,
13986        window: &mut Window,
13987        cx: &mut Context<Self>,
13988    ) {
13989        let snapshot = self.snapshot(window, cx);
13990        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
13991        let mut ranges_by_buffer = HashMap::default();
13992        self.transact(window, cx, |editor, _window, cx| {
13993            for hunk in hunks {
13994                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13995                    ranges_by_buffer
13996                        .entry(buffer.clone())
13997                        .or_insert_with(Vec::new)
13998                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13999                }
14000            }
14001
14002            for (buffer, ranges) in ranges_by_buffer {
14003                buffer.update(cx, |buffer, cx| {
14004                    buffer.merge_into_base(ranges, cx);
14005                });
14006            }
14007        });
14008
14009        if let Some(project) = self.project.clone() {
14010            self.save(true, project, window, cx).detach_and_log_err(cx);
14011        }
14012    }
14013
14014    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
14015        if hovered != self.gutter_hovered {
14016            self.gutter_hovered = hovered;
14017            cx.notify();
14018        }
14019    }
14020
14021    pub fn insert_blocks(
14022        &mut self,
14023        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
14024        autoscroll: Option<Autoscroll>,
14025        cx: &mut Context<Self>,
14026    ) -> Vec<CustomBlockId> {
14027        let blocks = self
14028            .display_map
14029            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
14030        if let Some(autoscroll) = autoscroll {
14031            self.request_autoscroll(autoscroll, cx);
14032        }
14033        cx.notify();
14034        blocks
14035    }
14036
14037    pub fn resize_blocks(
14038        &mut self,
14039        heights: HashMap<CustomBlockId, u32>,
14040        autoscroll: Option<Autoscroll>,
14041        cx: &mut Context<Self>,
14042    ) {
14043        self.display_map
14044            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
14045        if let Some(autoscroll) = autoscroll {
14046            self.request_autoscroll(autoscroll, cx);
14047        }
14048        cx.notify();
14049    }
14050
14051    pub fn replace_blocks(
14052        &mut self,
14053        renderers: HashMap<CustomBlockId, RenderBlock>,
14054        autoscroll: Option<Autoscroll>,
14055        cx: &mut Context<Self>,
14056    ) {
14057        self.display_map
14058            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
14059        if let Some(autoscroll) = autoscroll {
14060            self.request_autoscroll(autoscroll, cx);
14061        }
14062        cx.notify();
14063    }
14064
14065    pub fn remove_blocks(
14066        &mut self,
14067        block_ids: HashSet<CustomBlockId>,
14068        autoscroll: Option<Autoscroll>,
14069        cx: &mut Context<Self>,
14070    ) {
14071        self.display_map.update(cx, |display_map, cx| {
14072            display_map.remove_blocks(block_ids, cx)
14073        });
14074        if let Some(autoscroll) = autoscroll {
14075            self.request_autoscroll(autoscroll, cx);
14076        }
14077        cx.notify();
14078    }
14079
14080    pub fn row_for_block(
14081        &self,
14082        block_id: CustomBlockId,
14083        cx: &mut Context<Self>,
14084    ) -> Option<DisplayRow> {
14085        self.display_map
14086            .update(cx, |map, cx| map.row_for_block(block_id, cx))
14087    }
14088
14089    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
14090        self.focused_block = Some(focused_block);
14091    }
14092
14093    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
14094        self.focused_block.take()
14095    }
14096
14097    pub fn insert_creases(
14098        &mut self,
14099        creases: impl IntoIterator<Item = Crease<Anchor>>,
14100        cx: &mut Context<Self>,
14101    ) -> Vec<CreaseId> {
14102        self.display_map
14103            .update(cx, |map, cx| map.insert_creases(creases, cx))
14104    }
14105
14106    pub fn remove_creases(
14107        &mut self,
14108        ids: impl IntoIterator<Item = CreaseId>,
14109        cx: &mut Context<Self>,
14110    ) {
14111        self.display_map
14112            .update(cx, |map, cx| map.remove_creases(ids, cx));
14113    }
14114
14115    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
14116        self.display_map
14117            .update(cx, |map, cx| map.snapshot(cx))
14118            .longest_row()
14119    }
14120
14121    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
14122        self.display_map
14123            .update(cx, |map, cx| map.snapshot(cx))
14124            .max_point()
14125    }
14126
14127    pub fn text(&self, cx: &App) -> String {
14128        self.buffer.read(cx).read(cx).text()
14129    }
14130
14131    pub fn is_empty(&self, cx: &App) -> bool {
14132        self.buffer.read(cx).read(cx).is_empty()
14133    }
14134
14135    pub fn text_option(&self, cx: &App) -> Option<String> {
14136        let text = self.text(cx);
14137        let text = text.trim();
14138
14139        if text.is_empty() {
14140            return None;
14141        }
14142
14143        Some(text.to_string())
14144    }
14145
14146    pub fn set_text(
14147        &mut self,
14148        text: impl Into<Arc<str>>,
14149        window: &mut Window,
14150        cx: &mut Context<Self>,
14151    ) {
14152        self.transact(window, cx, |this, _, cx| {
14153            this.buffer
14154                .read(cx)
14155                .as_singleton()
14156                .expect("you can only call set_text on editors for singleton buffers")
14157                .update(cx, |buffer, cx| buffer.set_text(text, cx));
14158        });
14159    }
14160
14161    pub fn display_text(&self, cx: &mut App) -> String {
14162        self.display_map
14163            .update(cx, |map, cx| map.snapshot(cx))
14164            .text()
14165    }
14166
14167    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
14168        let mut wrap_guides = smallvec::smallvec![];
14169
14170        if self.show_wrap_guides == Some(false) {
14171            return wrap_guides;
14172        }
14173
14174        let settings = self.buffer.read(cx).language_settings(cx);
14175        if settings.show_wrap_guides {
14176            match self.soft_wrap_mode(cx) {
14177                SoftWrap::Column(soft_wrap) => {
14178                    wrap_guides.push((soft_wrap as usize, true));
14179                }
14180                SoftWrap::Bounded(soft_wrap) => {
14181                    wrap_guides.push((soft_wrap as usize, true));
14182                }
14183                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
14184            }
14185            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14186        }
14187
14188        wrap_guides
14189    }
14190
14191    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14192        let settings = self.buffer.read(cx).language_settings(cx);
14193        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14194        match mode {
14195            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14196                SoftWrap::None
14197            }
14198            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14199            language_settings::SoftWrap::PreferredLineLength => {
14200                SoftWrap::Column(settings.preferred_line_length)
14201            }
14202            language_settings::SoftWrap::Bounded => {
14203                SoftWrap::Bounded(settings.preferred_line_length)
14204            }
14205        }
14206    }
14207
14208    pub fn set_soft_wrap_mode(
14209        &mut self,
14210        mode: language_settings::SoftWrap,
14211
14212        cx: &mut Context<Self>,
14213    ) {
14214        self.soft_wrap_mode_override = Some(mode);
14215        cx.notify();
14216    }
14217
14218    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14219        self.text_style_refinement = Some(style);
14220    }
14221
14222    /// called by the Element so we know what style we were most recently rendered with.
14223    pub(crate) fn set_style(
14224        &mut self,
14225        style: EditorStyle,
14226        window: &mut Window,
14227        cx: &mut Context<Self>,
14228    ) {
14229        let rem_size = window.rem_size();
14230        self.display_map.update(cx, |map, cx| {
14231            map.set_font(
14232                style.text.font(),
14233                style.text.font_size.to_pixels(rem_size),
14234                cx,
14235            )
14236        });
14237        self.style = Some(style);
14238    }
14239
14240    pub fn style(&self) -> Option<&EditorStyle> {
14241        self.style.as_ref()
14242    }
14243
14244    // Called by the element. This method is not designed to be called outside of the editor
14245    // element's layout code because it does not notify when rewrapping is computed synchronously.
14246    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14247        self.display_map
14248            .update(cx, |map, cx| map.set_wrap_width(width, cx))
14249    }
14250
14251    pub fn set_soft_wrap(&mut self) {
14252        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14253    }
14254
14255    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14256        if self.soft_wrap_mode_override.is_some() {
14257            self.soft_wrap_mode_override.take();
14258        } else {
14259            let soft_wrap = match self.soft_wrap_mode(cx) {
14260                SoftWrap::GitDiff => return,
14261                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14262                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14263                    language_settings::SoftWrap::None
14264                }
14265            };
14266            self.soft_wrap_mode_override = Some(soft_wrap);
14267        }
14268        cx.notify();
14269    }
14270
14271    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14272        let Some(workspace) = self.workspace() else {
14273            return;
14274        };
14275        let fs = workspace.read(cx).app_state().fs.clone();
14276        let current_show = TabBarSettings::get_global(cx).show;
14277        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14278            setting.show = Some(!current_show);
14279        });
14280    }
14281
14282    pub fn toggle_indent_guides(
14283        &mut self,
14284        _: &ToggleIndentGuides,
14285        _: &mut Window,
14286        cx: &mut Context<Self>,
14287    ) {
14288        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14289            self.buffer
14290                .read(cx)
14291                .language_settings(cx)
14292                .indent_guides
14293                .enabled
14294        });
14295        self.show_indent_guides = Some(!currently_enabled);
14296        cx.notify();
14297    }
14298
14299    fn should_show_indent_guides(&self) -> Option<bool> {
14300        self.show_indent_guides
14301    }
14302
14303    pub fn toggle_line_numbers(
14304        &mut self,
14305        _: &ToggleLineNumbers,
14306        _: &mut Window,
14307        cx: &mut Context<Self>,
14308    ) {
14309        let mut editor_settings = EditorSettings::get_global(cx).clone();
14310        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14311        EditorSettings::override_global(editor_settings, cx);
14312    }
14313
14314    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
14315        if let Some(show_line_numbers) = self.show_line_numbers {
14316            return show_line_numbers;
14317        }
14318        EditorSettings::get_global(cx).gutter.line_numbers
14319    }
14320
14321    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14322        self.use_relative_line_numbers
14323            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14324    }
14325
14326    pub fn toggle_relative_line_numbers(
14327        &mut self,
14328        _: &ToggleRelativeLineNumbers,
14329        _: &mut Window,
14330        cx: &mut Context<Self>,
14331    ) {
14332        let is_relative = self.should_use_relative_line_numbers(cx);
14333        self.set_relative_line_number(Some(!is_relative), cx)
14334    }
14335
14336    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14337        self.use_relative_line_numbers = is_relative;
14338        cx.notify();
14339    }
14340
14341    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14342        self.show_gutter = show_gutter;
14343        cx.notify();
14344    }
14345
14346    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14347        self.show_scrollbars = show_scrollbars;
14348        cx.notify();
14349    }
14350
14351    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14352        self.show_line_numbers = Some(show_line_numbers);
14353        cx.notify();
14354    }
14355
14356    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14357        self.show_git_diff_gutter = Some(show_git_diff_gutter);
14358        cx.notify();
14359    }
14360
14361    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14362        self.show_code_actions = Some(show_code_actions);
14363        cx.notify();
14364    }
14365
14366    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14367        self.show_runnables = Some(show_runnables);
14368        cx.notify();
14369    }
14370
14371    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14372        if self.display_map.read(cx).masked != masked {
14373            self.display_map.update(cx, |map, _| map.masked = masked);
14374        }
14375        cx.notify()
14376    }
14377
14378    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14379        self.show_wrap_guides = Some(show_wrap_guides);
14380        cx.notify();
14381    }
14382
14383    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14384        self.show_indent_guides = Some(show_indent_guides);
14385        cx.notify();
14386    }
14387
14388    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14389        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14390            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14391                if let Some(dir) = file.abs_path(cx).parent() {
14392                    return Some(dir.to_owned());
14393                }
14394            }
14395
14396            if let Some(project_path) = buffer.read(cx).project_path(cx) {
14397                return Some(project_path.path.to_path_buf());
14398            }
14399        }
14400
14401        None
14402    }
14403
14404    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14405        self.active_excerpt(cx)?
14406            .1
14407            .read(cx)
14408            .file()
14409            .and_then(|f| f.as_local())
14410    }
14411
14412    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14413        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14414            let buffer = buffer.read(cx);
14415            if let Some(project_path) = buffer.project_path(cx) {
14416                let project = self.project.as_ref()?.read(cx);
14417                project.absolute_path(&project_path, cx)
14418            } else {
14419                buffer
14420                    .file()
14421                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14422            }
14423        })
14424    }
14425
14426    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14427        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14428            let project_path = buffer.read(cx).project_path(cx)?;
14429            let project = self.project.as_ref()?.read(cx);
14430            let entry = project.entry_for_path(&project_path, cx)?;
14431            let path = entry.path.to_path_buf();
14432            Some(path)
14433        })
14434    }
14435
14436    pub fn reveal_in_finder(
14437        &mut self,
14438        _: &RevealInFileManager,
14439        _window: &mut Window,
14440        cx: &mut Context<Self>,
14441    ) {
14442        if let Some(target) = self.target_file(cx) {
14443            cx.reveal_path(&target.abs_path(cx));
14444        }
14445    }
14446
14447    pub fn copy_path(
14448        &mut self,
14449        _: &zed_actions::workspace::CopyPath,
14450        _window: &mut Window,
14451        cx: &mut Context<Self>,
14452    ) {
14453        if let Some(path) = self.target_file_abs_path(cx) {
14454            if let Some(path) = path.to_str() {
14455                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14456            }
14457        }
14458    }
14459
14460    pub fn copy_relative_path(
14461        &mut self,
14462        _: &zed_actions::workspace::CopyRelativePath,
14463        _window: &mut Window,
14464        cx: &mut Context<Self>,
14465    ) {
14466        if let Some(path) = self.target_file_path(cx) {
14467            if let Some(path) = path.to_str() {
14468                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14469            }
14470        }
14471    }
14472
14473    pub fn copy_file_name_without_extension(
14474        &mut self,
14475        _: &CopyFileNameWithoutExtension,
14476        _: &mut Window,
14477        cx: &mut Context<Self>,
14478    ) {
14479        if let Some(file) = self.target_file(cx) {
14480            if let Some(file_stem) = file.path().file_stem() {
14481                if let Some(name) = file_stem.to_str() {
14482                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14483                }
14484            }
14485        }
14486    }
14487
14488    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14489        if let Some(file) = self.target_file(cx) {
14490            if let Some(file_name) = file.path().file_name() {
14491                if let Some(name) = file_name.to_str() {
14492                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14493                }
14494            }
14495        }
14496    }
14497
14498    pub fn toggle_git_blame(
14499        &mut self,
14500        _: &ToggleGitBlame,
14501        window: &mut Window,
14502        cx: &mut Context<Self>,
14503    ) {
14504        self.show_git_blame_gutter = !self.show_git_blame_gutter;
14505
14506        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14507            self.start_git_blame(true, window, cx);
14508        }
14509
14510        cx.notify();
14511    }
14512
14513    pub fn toggle_git_blame_inline(
14514        &mut self,
14515        _: &ToggleGitBlameInline,
14516        window: &mut Window,
14517        cx: &mut Context<Self>,
14518    ) {
14519        self.toggle_git_blame_inline_internal(true, window, cx);
14520        cx.notify();
14521    }
14522
14523    pub fn git_blame_inline_enabled(&self) -> bool {
14524        self.git_blame_inline_enabled
14525    }
14526
14527    pub fn toggle_selection_menu(
14528        &mut self,
14529        _: &ToggleSelectionMenu,
14530        _: &mut Window,
14531        cx: &mut Context<Self>,
14532    ) {
14533        self.show_selection_menu = self
14534            .show_selection_menu
14535            .map(|show_selections_menu| !show_selections_menu)
14536            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14537
14538        cx.notify();
14539    }
14540
14541    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14542        self.show_selection_menu
14543            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14544    }
14545
14546    fn start_git_blame(
14547        &mut self,
14548        user_triggered: bool,
14549        window: &mut Window,
14550        cx: &mut Context<Self>,
14551    ) {
14552        if let Some(project) = self.project.as_ref() {
14553            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14554                return;
14555            };
14556
14557            if buffer.read(cx).file().is_none() {
14558                return;
14559            }
14560
14561            let focused = self.focus_handle(cx).contains_focused(window, cx);
14562
14563            let project = project.clone();
14564            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14565            self.blame_subscription =
14566                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14567            self.blame = Some(blame);
14568        }
14569    }
14570
14571    fn toggle_git_blame_inline_internal(
14572        &mut self,
14573        user_triggered: bool,
14574        window: &mut Window,
14575        cx: &mut Context<Self>,
14576    ) {
14577        if self.git_blame_inline_enabled {
14578            self.git_blame_inline_enabled = false;
14579            self.show_git_blame_inline = false;
14580            self.show_git_blame_inline_delay_task.take();
14581        } else {
14582            self.git_blame_inline_enabled = true;
14583            self.start_git_blame_inline(user_triggered, window, cx);
14584        }
14585
14586        cx.notify();
14587    }
14588
14589    fn start_git_blame_inline(
14590        &mut self,
14591        user_triggered: bool,
14592        window: &mut Window,
14593        cx: &mut Context<Self>,
14594    ) {
14595        self.start_git_blame(user_triggered, window, cx);
14596
14597        if ProjectSettings::get_global(cx)
14598            .git
14599            .inline_blame_delay()
14600            .is_some()
14601        {
14602            self.start_inline_blame_timer(window, cx);
14603        } else {
14604            self.show_git_blame_inline = true
14605        }
14606    }
14607
14608    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14609        self.blame.as_ref()
14610    }
14611
14612    pub fn show_git_blame_gutter(&self) -> bool {
14613        self.show_git_blame_gutter
14614    }
14615
14616    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14617        self.show_git_blame_gutter && self.has_blame_entries(cx)
14618    }
14619
14620    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14621        self.show_git_blame_inline
14622            && (self.focus_handle.is_focused(window)
14623                || self
14624                    .git_blame_inline_tooltip
14625                    .as_ref()
14626                    .and_then(|t| t.upgrade())
14627                    .is_some())
14628            && !self.newest_selection_head_on_empty_line(cx)
14629            && self.has_blame_entries(cx)
14630    }
14631
14632    fn has_blame_entries(&self, cx: &App) -> bool {
14633        self.blame()
14634            .map_or(false, |blame| blame.read(cx).has_generated_entries())
14635    }
14636
14637    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14638        let cursor_anchor = self.selections.newest_anchor().head();
14639
14640        let snapshot = self.buffer.read(cx).snapshot(cx);
14641        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14642
14643        snapshot.line_len(buffer_row) == 0
14644    }
14645
14646    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14647        let buffer_and_selection = maybe!({
14648            let selection = self.selections.newest::<Point>(cx);
14649            let selection_range = selection.range();
14650
14651            let multi_buffer = self.buffer().read(cx);
14652            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14653            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14654
14655            let (buffer, range, _) = if selection.reversed {
14656                buffer_ranges.first()
14657            } else {
14658                buffer_ranges.last()
14659            }?;
14660
14661            let selection = text::ToPoint::to_point(&range.start, &buffer).row
14662                ..text::ToPoint::to_point(&range.end, &buffer).row;
14663            Some((
14664                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14665                selection,
14666            ))
14667        });
14668
14669        let Some((buffer, selection)) = buffer_and_selection else {
14670            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14671        };
14672
14673        let Some(project) = self.project.as_ref() else {
14674            return Task::ready(Err(anyhow!("editor does not have project")));
14675        };
14676
14677        project.update(cx, |project, cx| {
14678            project.get_permalink_to_line(&buffer, selection, cx)
14679        })
14680    }
14681
14682    pub fn copy_permalink_to_line(
14683        &mut self,
14684        _: &CopyPermalinkToLine,
14685        window: &mut Window,
14686        cx: &mut Context<Self>,
14687    ) {
14688        let permalink_task = self.get_permalink_to_line(cx);
14689        let workspace = self.workspace();
14690
14691        cx.spawn_in(window, |_, mut cx| async move {
14692            match permalink_task.await {
14693                Ok(permalink) => {
14694                    cx.update(|_, cx| {
14695                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14696                    })
14697                    .ok();
14698                }
14699                Err(err) => {
14700                    let message = format!("Failed to copy permalink: {err}");
14701
14702                    Err::<(), anyhow::Error>(err).log_err();
14703
14704                    if let Some(workspace) = workspace {
14705                        workspace
14706                            .update_in(&mut cx, |workspace, _, cx| {
14707                                struct CopyPermalinkToLine;
14708
14709                                workspace.show_toast(
14710                                    Toast::new(
14711                                        NotificationId::unique::<CopyPermalinkToLine>(),
14712                                        message,
14713                                    ),
14714                                    cx,
14715                                )
14716                            })
14717                            .ok();
14718                    }
14719                }
14720            }
14721        })
14722        .detach();
14723    }
14724
14725    pub fn copy_file_location(
14726        &mut self,
14727        _: &CopyFileLocation,
14728        _: &mut Window,
14729        cx: &mut Context<Self>,
14730    ) {
14731        let selection = self.selections.newest::<Point>(cx).start.row + 1;
14732        if let Some(file) = self.target_file(cx) {
14733            if let Some(path) = file.path().to_str() {
14734                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14735            }
14736        }
14737    }
14738
14739    pub fn open_permalink_to_line(
14740        &mut self,
14741        _: &OpenPermalinkToLine,
14742        window: &mut Window,
14743        cx: &mut Context<Self>,
14744    ) {
14745        let permalink_task = self.get_permalink_to_line(cx);
14746        let workspace = self.workspace();
14747
14748        cx.spawn_in(window, |_, mut cx| async move {
14749            match permalink_task.await {
14750                Ok(permalink) => {
14751                    cx.update(|_, cx| {
14752                        cx.open_url(permalink.as_ref());
14753                    })
14754                    .ok();
14755                }
14756                Err(err) => {
14757                    let message = format!("Failed to open permalink: {err}");
14758
14759                    Err::<(), anyhow::Error>(err).log_err();
14760
14761                    if let Some(workspace) = workspace {
14762                        workspace
14763                            .update(&mut cx, |workspace, cx| {
14764                                struct OpenPermalinkToLine;
14765
14766                                workspace.show_toast(
14767                                    Toast::new(
14768                                        NotificationId::unique::<OpenPermalinkToLine>(),
14769                                        message,
14770                                    ),
14771                                    cx,
14772                                )
14773                            })
14774                            .ok();
14775                    }
14776                }
14777            }
14778        })
14779        .detach();
14780    }
14781
14782    pub fn insert_uuid_v4(
14783        &mut self,
14784        _: &InsertUuidV4,
14785        window: &mut Window,
14786        cx: &mut Context<Self>,
14787    ) {
14788        self.insert_uuid(UuidVersion::V4, window, cx);
14789    }
14790
14791    pub fn insert_uuid_v7(
14792        &mut self,
14793        _: &InsertUuidV7,
14794        window: &mut Window,
14795        cx: &mut Context<Self>,
14796    ) {
14797        self.insert_uuid(UuidVersion::V7, window, cx);
14798    }
14799
14800    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14801        self.transact(window, cx, |this, window, cx| {
14802            let edits = this
14803                .selections
14804                .all::<Point>(cx)
14805                .into_iter()
14806                .map(|selection| {
14807                    let uuid = match version {
14808                        UuidVersion::V4 => uuid::Uuid::new_v4(),
14809                        UuidVersion::V7 => uuid::Uuid::now_v7(),
14810                    };
14811
14812                    (selection.range(), uuid.to_string())
14813                });
14814            this.edit(edits, cx);
14815            this.refresh_inline_completion(true, false, window, cx);
14816        });
14817    }
14818
14819    pub fn open_selections_in_multibuffer(
14820        &mut self,
14821        _: &OpenSelectionsInMultibuffer,
14822        window: &mut Window,
14823        cx: &mut Context<Self>,
14824    ) {
14825        let multibuffer = self.buffer.read(cx);
14826
14827        let Some(buffer) = multibuffer.as_singleton() else {
14828            return;
14829        };
14830
14831        let Some(workspace) = self.workspace() else {
14832            return;
14833        };
14834
14835        let locations = self
14836            .selections
14837            .disjoint_anchors()
14838            .iter()
14839            .map(|range| Location {
14840                buffer: buffer.clone(),
14841                range: range.start.text_anchor..range.end.text_anchor,
14842            })
14843            .collect::<Vec<_>>();
14844
14845        let title = multibuffer.title(cx).to_string();
14846
14847        cx.spawn_in(window, |_, mut cx| async move {
14848            workspace.update_in(&mut cx, |workspace, window, cx| {
14849                Self::open_locations_in_multibuffer(
14850                    workspace,
14851                    locations,
14852                    format!("Selections for '{title}'"),
14853                    false,
14854                    MultibufferSelectionMode::All,
14855                    window,
14856                    cx,
14857                );
14858            })
14859        })
14860        .detach();
14861    }
14862
14863    /// Adds a row highlight for the given range. If a row has multiple highlights, the
14864    /// last highlight added will be used.
14865    ///
14866    /// If the range ends at the beginning of a line, then that line will not be highlighted.
14867    pub fn highlight_rows<T: 'static>(
14868        &mut self,
14869        range: Range<Anchor>,
14870        color: Hsla,
14871        should_autoscroll: bool,
14872        cx: &mut Context<Self>,
14873    ) {
14874        let snapshot = self.buffer().read(cx).snapshot(cx);
14875        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14876        let ix = row_highlights.binary_search_by(|highlight| {
14877            Ordering::Equal
14878                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14879                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14880        });
14881
14882        if let Err(mut ix) = ix {
14883            let index = post_inc(&mut self.highlight_order);
14884
14885            // If this range intersects with the preceding highlight, then merge it with
14886            // the preceding highlight. Otherwise insert a new highlight.
14887            let mut merged = false;
14888            if ix > 0 {
14889                let prev_highlight = &mut row_highlights[ix - 1];
14890                if prev_highlight
14891                    .range
14892                    .end
14893                    .cmp(&range.start, &snapshot)
14894                    .is_ge()
14895                {
14896                    ix -= 1;
14897                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14898                        prev_highlight.range.end = range.end;
14899                    }
14900                    merged = true;
14901                    prev_highlight.index = index;
14902                    prev_highlight.color = color;
14903                    prev_highlight.should_autoscroll = should_autoscroll;
14904                }
14905            }
14906
14907            if !merged {
14908                row_highlights.insert(
14909                    ix,
14910                    RowHighlight {
14911                        range: range.clone(),
14912                        index,
14913                        color,
14914                        should_autoscroll,
14915                    },
14916                );
14917            }
14918
14919            // If any of the following highlights intersect with this one, merge them.
14920            while let Some(next_highlight) = row_highlights.get(ix + 1) {
14921                let highlight = &row_highlights[ix];
14922                if next_highlight
14923                    .range
14924                    .start
14925                    .cmp(&highlight.range.end, &snapshot)
14926                    .is_le()
14927                {
14928                    if next_highlight
14929                        .range
14930                        .end
14931                        .cmp(&highlight.range.end, &snapshot)
14932                        .is_gt()
14933                    {
14934                        row_highlights[ix].range.end = next_highlight.range.end;
14935                    }
14936                    row_highlights.remove(ix + 1);
14937                } else {
14938                    break;
14939                }
14940            }
14941        }
14942    }
14943
14944    /// Remove any highlighted row ranges of the given type that intersect the
14945    /// given ranges.
14946    pub fn remove_highlighted_rows<T: 'static>(
14947        &mut self,
14948        ranges_to_remove: Vec<Range<Anchor>>,
14949        cx: &mut Context<Self>,
14950    ) {
14951        let snapshot = self.buffer().read(cx).snapshot(cx);
14952        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14953        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14954        row_highlights.retain(|highlight| {
14955            while let Some(range_to_remove) = ranges_to_remove.peek() {
14956                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14957                    Ordering::Less | Ordering::Equal => {
14958                        ranges_to_remove.next();
14959                    }
14960                    Ordering::Greater => {
14961                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14962                            Ordering::Less | Ordering::Equal => {
14963                                return false;
14964                            }
14965                            Ordering::Greater => break,
14966                        }
14967                    }
14968                }
14969            }
14970
14971            true
14972        })
14973    }
14974
14975    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14976    pub fn clear_row_highlights<T: 'static>(&mut self) {
14977        self.highlighted_rows.remove(&TypeId::of::<T>());
14978    }
14979
14980    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14981    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14982        self.highlighted_rows
14983            .get(&TypeId::of::<T>())
14984            .map_or(&[] as &[_], |vec| vec.as_slice())
14985            .iter()
14986            .map(|highlight| (highlight.range.clone(), highlight.color))
14987    }
14988
14989    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14990    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14991    /// Allows to ignore certain kinds of highlights.
14992    pub fn highlighted_display_rows(
14993        &self,
14994        window: &mut Window,
14995        cx: &mut App,
14996    ) -> BTreeMap<DisplayRow, LineHighlight> {
14997        let snapshot = self.snapshot(window, cx);
14998        let mut used_highlight_orders = HashMap::default();
14999        self.highlighted_rows
15000            .iter()
15001            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
15002            .fold(
15003                BTreeMap::<DisplayRow, LineHighlight>::new(),
15004                |mut unique_rows, highlight| {
15005                    let start = highlight.range.start.to_display_point(&snapshot);
15006                    let end = highlight.range.end.to_display_point(&snapshot);
15007                    let start_row = start.row().0;
15008                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
15009                        && end.column() == 0
15010                    {
15011                        end.row().0.saturating_sub(1)
15012                    } else {
15013                        end.row().0
15014                    };
15015                    for row in start_row..=end_row {
15016                        let used_index =
15017                            used_highlight_orders.entry(row).or_insert(highlight.index);
15018                        if highlight.index >= *used_index {
15019                            *used_index = highlight.index;
15020                            unique_rows.insert(DisplayRow(row), highlight.color.into());
15021                        }
15022                    }
15023                    unique_rows
15024                },
15025            )
15026    }
15027
15028    pub fn highlighted_display_row_for_autoscroll(
15029        &self,
15030        snapshot: &DisplaySnapshot,
15031    ) -> Option<DisplayRow> {
15032        self.highlighted_rows
15033            .values()
15034            .flat_map(|highlighted_rows| highlighted_rows.iter())
15035            .filter_map(|highlight| {
15036                if highlight.should_autoscroll {
15037                    Some(highlight.range.start.to_display_point(snapshot).row())
15038                } else {
15039                    None
15040                }
15041            })
15042            .min()
15043    }
15044
15045    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
15046        self.highlight_background::<SearchWithinRange>(
15047            ranges,
15048            |colors| colors.editor_document_highlight_read_background,
15049            cx,
15050        )
15051    }
15052
15053    pub fn set_breadcrumb_header(&mut self, new_header: String) {
15054        self.breadcrumb_header = Some(new_header);
15055    }
15056
15057    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
15058        self.clear_background_highlights::<SearchWithinRange>(cx);
15059    }
15060
15061    pub fn highlight_background<T: 'static>(
15062        &mut self,
15063        ranges: &[Range<Anchor>],
15064        color_fetcher: fn(&ThemeColors) -> Hsla,
15065        cx: &mut Context<Self>,
15066    ) {
15067        self.background_highlights
15068            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15069        self.scrollbar_marker_state.dirty = true;
15070        cx.notify();
15071    }
15072
15073    pub fn clear_background_highlights<T: 'static>(
15074        &mut self,
15075        cx: &mut Context<Self>,
15076    ) -> Option<BackgroundHighlight> {
15077        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
15078        if !text_highlights.1.is_empty() {
15079            self.scrollbar_marker_state.dirty = true;
15080            cx.notify();
15081        }
15082        Some(text_highlights)
15083    }
15084
15085    pub fn highlight_gutter<T: 'static>(
15086        &mut self,
15087        ranges: &[Range<Anchor>],
15088        color_fetcher: fn(&App) -> Hsla,
15089        cx: &mut Context<Self>,
15090    ) {
15091        self.gutter_highlights
15092            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15093        cx.notify();
15094    }
15095
15096    pub fn clear_gutter_highlights<T: 'static>(
15097        &mut self,
15098        cx: &mut Context<Self>,
15099    ) -> Option<GutterHighlight> {
15100        cx.notify();
15101        self.gutter_highlights.remove(&TypeId::of::<T>())
15102    }
15103
15104    #[cfg(feature = "test-support")]
15105    pub fn all_text_background_highlights(
15106        &self,
15107        window: &mut Window,
15108        cx: &mut Context<Self>,
15109    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15110        let snapshot = self.snapshot(window, cx);
15111        let buffer = &snapshot.buffer_snapshot;
15112        let start = buffer.anchor_before(0);
15113        let end = buffer.anchor_after(buffer.len());
15114        let theme = cx.theme().colors();
15115        self.background_highlights_in_range(start..end, &snapshot, theme)
15116    }
15117
15118    #[cfg(feature = "test-support")]
15119    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
15120        let snapshot = self.buffer().read(cx).snapshot(cx);
15121
15122        let highlights = self
15123            .background_highlights
15124            .get(&TypeId::of::<items::BufferSearchHighlights>());
15125
15126        if let Some((_color, ranges)) = highlights {
15127            ranges
15128                .iter()
15129                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
15130                .collect_vec()
15131        } else {
15132            vec![]
15133        }
15134    }
15135
15136    fn document_highlights_for_position<'a>(
15137        &'a self,
15138        position: Anchor,
15139        buffer: &'a MultiBufferSnapshot,
15140    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
15141        let read_highlights = self
15142            .background_highlights
15143            .get(&TypeId::of::<DocumentHighlightRead>())
15144            .map(|h| &h.1);
15145        let write_highlights = self
15146            .background_highlights
15147            .get(&TypeId::of::<DocumentHighlightWrite>())
15148            .map(|h| &h.1);
15149        let left_position = position.bias_left(buffer);
15150        let right_position = position.bias_right(buffer);
15151        read_highlights
15152            .into_iter()
15153            .chain(write_highlights)
15154            .flat_map(move |ranges| {
15155                let start_ix = match ranges.binary_search_by(|probe| {
15156                    let cmp = probe.end.cmp(&left_position, buffer);
15157                    if cmp.is_ge() {
15158                        Ordering::Greater
15159                    } else {
15160                        Ordering::Less
15161                    }
15162                }) {
15163                    Ok(i) | Err(i) => i,
15164                };
15165
15166                ranges[start_ix..]
15167                    .iter()
15168                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
15169            })
15170    }
15171
15172    pub fn has_background_highlights<T: 'static>(&self) -> bool {
15173        self.background_highlights
15174            .get(&TypeId::of::<T>())
15175            .map_or(false, |(_, highlights)| !highlights.is_empty())
15176    }
15177
15178    pub fn background_highlights_in_range(
15179        &self,
15180        search_range: Range<Anchor>,
15181        display_snapshot: &DisplaySnapshot,
15182        theme: &ThemeColors,
15183    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15184        let mut results = Vec::new();
15185        for (color_fetcher, ranges) in self.background_highlights.values() {
15186            let color = color_fetcher(theme);
15187            let start_ix = match ranges.binary_search_by(|probe| {
15188                let cmp = probe
15189                    .end
15190                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15191                if cmp.is_gt() {
15192                    Ordering::Greater
15193                } else {
15194                    Ordering::Less
15195                }
15196            }) {
15197                Ok(i) | Err(i) => i,
15198            };
15199            for range in &ranges[start_ix..] {
15200                if range
15201                    .start
15202                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15203                    .is_ge()
15204                {
15205                    break;
15206                }
15207
15208                let start = range.start.to_display_point(display_snapshot);
15209                let end = range.end.to_display_point(display_snapshot);
15210                results.push((start..end, color))
15211            }
15212        }
15213        results
15214    }
15215
15216    pub fn background_highlight_row_ranges<T: 'static>(
15217        &self,
15218        search_range: Range<Anchor>,
15219        display_snapshot: &DisplaySnapshot,
15220        count: usize,
15221    ) -> Vec<RangeInclusive<DisplayPoint>> {
15222        let mut results = Vec::new();
15223        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15224            return vec![];
15225        };
15226
15227        let start_ix = match ranges.binary_search_by(|probe| {
15228            let cmp = probe
15229                .end
15230                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15231            if cmp.is_gt() {
15232                Ordering::Greater
15233            } else {
15234                Ordering::Less
15235            }
15236        }) {
15237            Ok(i) | Err(i) => i,
15238        };
15239        let mut push_region = |start: Option<Point>, end: Option<Point>| {
15240            if let (Some(start_display), Some(end_display)) = (start, end) {
15241                results.push(
15242                    start_display.to_display_point(display_snapshot)
15243                        ..=end_display.to_display_point(display_snapshot),
15244                );
15245            }
15246        };
15247        let mut start_row: Option<Point> = None;
15248        let mut end_row: Option<Point> = None;
15249        if ranges.len() > count {
15250            return Vec::new();
15251        }
15252        for range in &ranges[start_ix..] {
15253            if range
15254                .start
15255                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15256                .is_ge()
15257            {
15258                break;
15259            }
15260            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15261            if let Some(current_row) = &end_row {
15262                if end.row == current_row.row {
15263                    continue;
15264                }
15265            }
15266            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15267            if start_row.is_none() {
15268                assert_eq!(end_row, None);
15269                start_row = Some(start);
15270                end_row = Some(end);
15271                continue;
15272            }
15273            if let Some(current_end) = end_row.as_mut() {
15274                if start.row > current_end.row + 1 {
15275                    push_region(start_row, end_row);
15276                    start_row = Some(start);
15277                    end_row = Some(end);
15278                } else {
15279                    // Merge two hunks.
15280                    *current_end = end;
15281                }
15282            } else {
15283                unreachable!();
15284            }
15285        }
15286        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15287        push_region(start_row, end_row);
15288        results
15289    }
15290
15291    pub fn gutter_highlights_in_range(
15292        &self,
15293        search_range: Range<Anchor>,
15294        display_snapshot: &DisplaySnapshot,
15295        cx: &App,
15296    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15297        let mut results = Vec::new();
15298        for (color_fetcher, ranges) in self.gutter_highlights.values() {
15299            let color = color_fetcher(cx);
15300            let start_ix = match ranges.binary_search_by(|probe| {
15301                let cmp = probe
15302                    .end
15303                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15304                if cmp.is_gt() {
15305                    Ordering::Greater
15306                } else {
15307                    Ordering::Less
15308                }
15309            }) {
15310                Ok(i) | Err(i) => i,
15311            };
15312            for range in &ranges[start_ix..] {
15313                if range
15314                    .start
15315                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15316                    .is_ge()
15317                {
15318                    break;
15319                }
15320
15321                let start = range.start.to_display_point(display_snapshot);
15322                let end = range.end.to_display_point(display_snapshot);
15323                results.push((start..end, color))
15324            }
15325        }
15326        results
15327    }
15328
15329    /// Get the text ranges corresponding to the redaction query
15330    pub fn redacted_ranges(
15331        &self,
15332        search_range: Range<Anchor>,
15333        display_snapshot: &DisplaySnapshot,
15334        cx: &App,
15335    ) -> Vec<Range<DisplayPoint>> {
15336        display_snapshot
15337            .buffer_snapshot
15338            .redacted_ranges(search_range, |file| {
15339                if let Some(file) = file {
15340                    file.is_private()
15341                        && EditorSettings::get(
15342                            Some(SettingsLocation {
15343                                worktree_id: file.worktree_id(cx),
15344                                path: file.path().as_ref(),
15345                            }),
15346                            cx,
15347                        )
15348                        .redact_private_values
15349                } else {
15350                    false
15351                }
15352            })
15353            .map(|range| {
15354                range.start.to_display_point(display_snapshot)
15355                    ..range.end.to_display_point(display_snapshot)
15356            })
15357            .collect()
15358    }
15359
15360    pub fn highlight_text<T: 'static>(
15361        &mut self,
15362        ranges: Vec<Range<Anchor>>,
15363        style: HighlightStyle,
15364        cx: &mut Context<Self>,
15365    ) {
15366        self.display_map.update(cx, |map, _| {
15367            map.highlight_text(TypeId::of::<T>(), ranges, style)
15368        });
15369        cx.notify();
15370    }
15371
15372    pub(crate) fn highlight_inlays<T: 'static>(
15373        &mut self,
15374        highlights: Vec<InlayHighlight>,
15375        style: HighlightStyle,
15376        cx: &mut Context<Self>,
15377    ) {
15378        self.display_map.update(cx, |map, _| {
15379            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15380        });
15381        cx.notify();
15382    }
15383
15384    pub fn text_highlights<'a, T: 'static>(
15385        &'a self,
15386        cx: &'a App,
15387    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15388        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15389    }
15390
15391    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15392        let cleared = self
15393            .display_map
15394            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15395        if cleared {
15396            cx.notify();
15397        }
15398    }
15399
15400    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15401        (self.read_only(cx) || self.blink_manager.read(cx).visible())
15402            && self.focus_handle.is_focused(window)
15403    }
15404
15405    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15406        self.show_cursor_when_unfocused = is_enabled;
15407        cx.notify();
15408    }
15409
15410    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15411        cx.notify();
15412    }
15413
15414    fn on_buffer_event(
15415        &mut self,
15416        multibuffer: &Entity<MultiBuffer>,
15417        event: &multi_buffer::Event,
15418        window: &mut Window,
15419        cx: &mut Context<Self>,
15420    ) {
15421        match event {
15422            multi_buffer::Event::Edited {
15423                singleton_buffer_edited,
15424                edited_buffer: buffer_edited,
15425            } => {
15426                self.scrollbar_marker_state.dirty = true;
15427                self.active_indent_guides_state.dirty = true;
15428                self.refresh_active_diagnostics(cx);
15429                self.refresh_code_actions(window, cx);
15430                if self.has_active_inline_completion() {
15431                    self.update_visible_inline_completion(window, cx);
15432                }
15433                if let Some(buffer) = buffer_edited {
15434                    let buffer_id = buffer.read(cx).remote_id();
15435                    if !self.registered_buffers.contains_key(&buffer_id) {
15436                        if let Some(project) = self.project.as_ref() {
15437                            project.update(cx, |project, cx| {
15438                                self.registered_buffers.insert(
15439                                    buffer_id,
15440                                    project.register_buffer_with_language_servers(&buffer, cx),
15441                                );
15442                            })
15443                        }
15444                    }
15445                }
15446                cx.emit(EditorEvent::BufferEdited);
15447                cx.emit(SearchEvent::MatchesInvalidated);
15448                if *singleton_buffer_edited {
15449                    if let Some(project) = &self.project {
15450                        #[allow(clippy::mutable_key_type)]
15451                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15452                            multibuffer
15453                                .all_buffers()
15454                                .into_iter()
15455                                .filter_map(|buffer| {
15456                                    buffer.update(cx, |buffer, cx| {
15457                                        let language = buffer.language()?;
15458                                        let should_discard = project.update(cx, |project, cx| {
15459                                            project.is_local()
15460                                                && !project.has_language_servers_for(buffer, cx)
15461                                        });
15462                                        should_discard.not().then_some(language.clone())
15463                                    })
15464                                })
15465                                .collect::<HashSet<_>>()
15466                        });
15467                        if !languages_affected.is_empty() {
15468                            self.refresh_inlay_hints(
15469                                InlayHintRefreshReason::BufferEdited(languages_affected),
15470                                cx,
15471                            );
15472                        }
15473                    }
15474                }
15475
15476                let Some(project) = &self.project else { return };
15477                let (telemetry, is_via_ssh) = {
15478                    let project = project.read(cx);
15479                    let telemetry = project.client().telemetry().clone();
15480                    let is_via_ssh = project.is_via_ssh();
15481                    (telemetry, is_via_ssh)
15482                };
15483                refresh_linked_ranges(self, window, cx);
15484                telemetry.log_edit_event("editor", is_via_ssh);
15485            }
15486            multi_buffer::Event::ExcerptsAdded {
15487                buffer,
15488                predecessor,
15489                excerpts,
15490            } => {
15491                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15492                let buffer_id = buffer.read(cx).remote_id();
15493                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15494                    if let Some(project) = &self.project {
15495                        get_uncommitted_diff_for_buffer(
15496                            project,
15497                            [buffer.clone()],
15498                            self.buffer.clone(),
15499                            cx,
15500                        )
15501                        .detach();
15502                    }
15503                }
15504                cx.emit(EditorEvent::ExcerptsAdded {
15505                    buffer: buffer.clone(),
15506                    predecessor: *predecessor,
15507                    excerpts: excerpts.clone(),
15508                });
15509                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15510            }
15511            multi_buffer::Event::ExcerptsRemoved { ids } => {
15512                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15513                let buffer = self.buffer.read(cx);
15514                self.registered_buffers
15515                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15516                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15517                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15518            }
15519            multi_buffer::Event::ExcerptsEdited {
15520                excerpt_ids,
15521                buffer_ids,
15522            } => {
15523                self.display_map.update(cx, |map, cx| {
15524                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
15525                });
15526                cx.emit(EditorEvent::ExcerptsEdited {
15527                    ids: excerpt_ids.clone(),
15528                })
15529            }
15530            multi_buffer::Event::ExcerptsExpanded { ids } => {
15531                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15532                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15533            }
15534            multi_buffer::Event::Reparsed(buffer_id) => {
15535                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15536                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15537
15538                cx.emit(EditorEvent::Reparsed(*buffer_id));
15539            }
15540            multi_buffer::Event::DiffHunksToggled => {
15541                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15542            }
15543            multi_buffer::Event::LanguageChanged(buffer_id) => {
15544                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15545                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15546                cx.emit(EditorEvent::Reparsed(*buffer_id));
15547                cx.notify();
15548            }
15549            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15550            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15551            multi_buffer::Event::FileHandleChanged
15552            | multi_buffer::Event::Reloaded
15553            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
15554            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15555            multi_buffer::Event::DiagnosticsUpdated => {
15556                self.refresh_active_diagnostics(cx);
15557                self.refresh_inline_diagnostics(true, window, cx);
15558                self.scrollbar_marker_state.dirty = true;
15559                cx.notify();
15560            }
15561            _ => {}
15562        };
15563    }
15564
15565    fn on_display_map_changed(
15566        &mut self,
15567        _: Entity<DisplayMap>,
15568        _: &mut Window,
15569        cx: &mut Context<Self>,
15570    ) {
15571        cx.notify();
15572    }
15573
15574    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15575        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15576        self.update_edit_prediction_settings(cx);
15577        self.refresh_inline_completion(true, false, window, cx);
15578        self.refresh_inlay_hints(
15579            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15580                self.selections.newest_anchor().head(),
15581                &self.buffer.read(cx).snapshot(cx),
15582                cx,
15583            )),
15584            cx,
15585        );
15586
15587        let old_cursor_shape = self.cursor_shape;
15588
15589        {
15590            let editor_settings = EditorSettings::get_global(cx);
15591            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15592            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15593            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15594        }
15595
15596        if old_cursor_shape != self.cursor_shape {
15597            cx.emit(EditorEvent::CursorShapeChanged);
15598        }
15599
15600        let project_settings = ProjectSettings::get_global(cx);
15601        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15602
15603        if self.mode == EditorMode::Full {
15604            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15605            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15606            if self.show_inline_diagnostics != show_inline_diagnostics {
15607                self.show_inline_diagnostics = show_inline_diagnostics;
15608                self.refresh_inline_diagnostics(false, window, cx);
15609            }
15610
15611            if self.git_blame_inline_enabled != inline_blame_enabled {
15612                self.toggle_git_blame_inline_internal(false, window, cx);
15613            }
15614        }
15615
15616        cx.notify();
15617    }
15618
15619    pub fn set_searchable(&mut self, searchable: bool) {
15620        self.searchable = searchable;
15621    }
15622
15623    pub fn searchable(&self) -> bool {
15624        self.searchable
15625    }
15626
15627    fn open_proposed_changes_editor(
15628        &mut self,
15629        _: &OpenProposedChangesEditor,
15630        window: &mut Window,
15631        cx: &mut Context<Self>,
15632    ) {
15633        let Some(workspace) = self.workspace() else {
15634            cx.propagate();
15635            return;
15636        };
15637
15638        let selections = self.selections.all::<usize>(cx);
15639        let multi_buffer = self.buffer.read(cx);
15640        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15641        let mut new_selections_by_buffer = HashMap::default();
15642        for selection in selections {
15643            for (buffer, range, _) in
15644                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15645            {
15646                let mut range = range.to_point(buffer);
15647                range.start.column = 0;
15648                range.end.column = buffer.line_len(range.end.row);
15649                new_selections_by_buffer
15650                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15651                    .or_insert(Vec::new())
15652                    .push(range)
15653            }
15654        }
15655
15656        let proposed_changes_buffers = new_selections_by_buffer
15657            .into_iter()
15658            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15659            .collect::<Vec<_>>();
15660        let proposed_changes_editor = cx.new(|cx| {
15661            ProposedChangesEditor::new(
15662                "Proposed changes",
15663                proposed_changes_buffers,
15664                self.project.clone(),
15665                window,
15666                cx,
15667            )
15668        });
15669
15670        window.defer(cx, move |window, cx| {
15671            workspace.update(cx, |workspace, cx| {
15672                workspace.active_pane().update(cx, |pane, cx| {
15673                    pane.add_item(
15674                        Box::new(proposed_changes_editor),
15675                        true,
15676                        true,
15677                        None,
15678                        window,
15679                        cx,
15680                    );
15681                });
15682            });
15683        });
15684    }
15685
15686    pub fn open_excerpts_in_split(
15687        &mut self,
15688        _: &OpenExcerptsSplit,
15689        window: &mut Window,
15690        cx: &mut Context<Self>,
15691    ) {
15692        self.open_excerpts_common(None, true, window, cx)
15693    }
15694
15695    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15696        self.open_excerpts_common(None, false, window, cx)
15697    }
15698
15699    fn open_excerpts_common(
15700        &mut self,
15701        jump_data: Option<JumpData>,
15702        split: bool,
15703        window: &mut Window,
15704        cx: &mut Context<Self>,
15705    ) {
15706        let Some(workspace) = self.workspace() else {
15707            cx.propagate();
15708            return;
15709        };
15710
15711        if self.buffer.read(cx).is_singleton() {
15712            cx.propagate();
15713            return;
15714        }
15715
15716        let mut new_selections_by_buffer = HashMap::default();
15717        match &jump_data {
15718            Some(JumpData::MultiBufferPoint {
15719                excerpt_id,
15720                position,
15721                anchor,
15722                line_offset_from_top,
15723            }) => {
15724                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15725                if let Some(buffer) = multi_buffer_snapshot
15726                    .buffer_id_for_excerpt(*excerpt_id)
15727                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15728                {
15729                    let buffer_snapshot = buffer.read(cx).snapshot();
15730                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15731                        language::ToPoint::to_point(anchor, &buffer_snapshot)
15732                    } else {
15733                        buffer_snapshot.clip_point(*position, Bias::Left)
15734                    };
15735                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15736                    new_selections_by_buffer.insert(
15737                        buffer,
15738                        (
15739                            vec![jump_to_offset..jump_to_offset],
15740                            Some(*line_offset_from_top),
15741                        ),
15742                    );
15743                }
15744            }
15745            Some(JumpData::MultiBufferRow {
15746                row,
15747                line_offset_from_top,
15748            }) => {
15749                let point = MultiBufferPoint::new(row.0, 0);
15750                if let Some((buffer, buffer_point, _)) =
15751                    self.buffer.read(cx).point_to_buffer_point(point, cx)
15752                {
15753                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15754                    new_selections_by_buffer
15755                        .entry(buffer)
15756                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
15757                        .0
15758                        .push(buffer_offset..buffer_offset)
15759                }
15760            }
15761            None => {
15762                let selections = self.selections.all::<usize>(cx);
15763                let multi_buffer = self.buffer.read(cx);
15764                for selection in selections {
15765                    for (snapshot, range, _, anchor) in multi_buffer
15766                        .snapshot(cx)
15767                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15768                    {
15769                        if let Some(anchor) = anchor {
15770                            // selection is in a deleted hunk
15771                            let Some(buffer_id) = anchor.buffer_id else {
15772                                continue;
15773                            };
15774                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15775                                continue;
15776                            };
15777                            let offset = text::ToOffset::to_offset(
15778                                &anchor.text_anchor,
15779                                &buffer_handle.read(cx).snapshot(),
15780                            );
15781                            let range = offset..offset;
15782                            new_selections_by_buffer
15783                                .entry(buffer_handle)
15784                                .or_insert((Vec::new(), None))
15785                                .0
15786                                .push(range)
15787                        } else {
15788                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15789                            else {
15790                                continue;
15791                            };
15792                            new_selections_by_buffer
15793                                .entry(buffer_handle)
15794                                .or_insert((Vec::new(), None))
15795                                .0
15796                                .push(range)
15797                        }
15798                    }
15799                }
15800            }
15801        }
15802
15803        if new_selections_by_buffer.is_empty() {
15804            return;
15805        }
15806
15807        // We defer the pane interaction because we ourselves are a workspace item
15808        // and activating a new item causes the pane to call a method on us reentrantly,
15809        // which panics if we're on the stack.
15810        window.defer(cx, move |window, cx| {
15811            workspace.update(cx, |workspace, cx| {
15812                let pane = if split {
15813                    workspace.adjacent_pane(window, cx)
15814                } else {
15815                    workspace.active_pane().clone()
15816                };
15817
15818                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15819                    let editor = buffer
15820                        .read(cx)
15821                        .file()
15822                        .is_none()
15823                        .then(|| {
15824                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15825                            // so `workspace.open_project_item` will never find them, always opening a new editor.
15826                            // Instead, we try to activate the existing editor in the pane first.
15827                            let (editor, pane_item_index) =
15828                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
15829                                    let editor = item.downcast::<Editor>()?;
15830                                    let singleton_buffer =
15831                                        editor.read(cx).buffer().read(cx).as_singleton()?;
15832                                    if singleton_buffer == buffer {
15833                                        Some((editor, i))
15834                                    } else {
15835                                        None
15836                                    }
15837                                })?;
15838                            pane.update(cx, |pane, cx| {
15839                                pane.activate_item(pane_item_index, true, true, window, cx)
15840                            });
15841                            Some(editor)
15842                        })
15843                        .flatten()
15844                        .unwrap_or_else(|| {
15845                            workspace.open_project_item::<Self>(
15846                                pane.clone(),
15847                                buffer,
15848                                true,
15849                                true,
15850                                window,
15851                                cx,
15852                            )
15853                        });
15854
15855                    editor.update(cx, |editor, cx| {
15856                        let autoscroll = match scroll_offset {
15857                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15858                            None => Autoscroll::newest(),
15859                        };
15860                        let nav_history = editor.nav_history.take();
15861                        editor.change_selections(Some(autoscroll), window, cx, |s| {
15862                            s.select_ranges(ranges);
15863                        });
15864                        editor.nav_history = nav_history;
15865                    });
15866                }
15867            })
15868        });
15869    }
15870
15871    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15872        let snapshot = self.buffer.read(cx).read(cx);
15873        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15874        Some(
15875            ranges
15876                .iter()
15877                .map(move |range| {
15878                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15879                })
15880                .collect(),
15881        )
15882    }
15883
15884    fn selection_replacement_ranges(
15885        &self,
15886        range: Range<OffsetUtf16>,
15887        cx: &mut App,
15888    ) -> Vec<Range<OffsetUtf16>> {
15889        let selections = self.selections.all::<OffsetUtf16>(cx);
15890        let newest_selection = selections
15891            .iter()
15892            .max_by_key(|selection| selection.id)
15893            .unwrap();
15894        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15895        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15896        let snapshot = self.buffer.read(cx).read(cx);
15897        selections
15898            .into_iter()
15899            .map(|mut selection| {
15900                selection.start.0 =
15901                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
15902                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15903                snapshot.clip_offset_utf16(selection.start, Bias::Left)
15904                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15905            })
15906            .collect()
15907    }
15908
15909    fn report_editor_event(
15910        &self,
15911        event_type: &'static str,
15912        file_extension: Option<String>,
15913        cx: &App,
15914    ) {
15915        if cfg!(any(test, feature = "test-support")) {
15916            return;
15917        }
15918
15919        let Some(project) = &self.project else { return };
15920
15921        // If None, we are in a file without an extension
15922        let file = self
15923            .buffer
15924            .read(cx)
15925            .as_singleton()
15926            .and_then(|b| b.read(cx).file());
15927        let file_extension = file_extension.or(file
15928            .as_ref()
15929            .and_then(|file| Path::new(file.file_name(cx)).extension())
15930            .and_then(|e| e.to_str())
15931            .map(|a| a.to_string()));
15932
15933        let vim_mode = cx
15934            .global::<SettingsStore>()
15935            .raw_user_settings()
15936            .get("vim_mode")
15937            == Some(&serde_json::Value::Bool(true));
15938
15939        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15940        let copilot_enabled = edit_predictions_provider
15941            == language::language_settings::EditPredictionProvider::Copilot;
15942        let copilot_enabled_for_language = self
15943            .buffer
15944            .read(cx)
15945            .language_settings(cx)
15946            .show_edit_predictions;
15947
15948        let project = project.read(cx);
15949        telemetry::event!(
15950            event_type,
15951            file_extension,
15952            vim_mode,
15953            copilot_enabled,
15954            copilot_enabled_for_language,
15955            edit_predictions_provider,
15956            is_via_ssh = project.is_via_ssh(),
15957        );
15958    }
15959
15960    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15961    /// with each line being an array of {text, highlight} objects.
15962    fn copy_highlight_json(
15963        &mut self,
15964        _: &CopyHighlightJson,
15965        window: &mut Window,
15966        cx: &mut Context<Self>,
15967    ) {
15968        #[derive(Serialize)]
15969        struct Chunk<'a> {
15970            text: String,
15971            highlight: Option<&'a str>,
15972        }
15973
15974        let snapshot = self.buffer.read(cx).snapshot(cx);
15975        let range = self
15976            .selected_text_range(false, window, cx)
15977            .and_then(|selection| {
15978                if selection.range.is_empty() {
15979                    None
15980                } else {
15981                    Some(selection.range)
15982                }
15983            })
15984            .unwrap_or_else(|| 0..snapshot.len());
15985
15986        let chunks = snapshot.chunks(range, true);
15987        let mut lines = Vec::new();
15988        let mut line: VecDeque<Chunk> = VecDeque::new();
15989
15990        let Some(style) = self.style.as_ref() else {
15991            return;
15992        };
15993
15994        for chunk in chunks {
15995            let highlight = chunk
15996                .syntax_highlight_id
15997                .and_then(|id| id.name(&style.syntax));
15998            let mut chunk_lines = chunk.text.split('\n').peekable();
15999            while let Some(text) = chunk_lines.next() {
16000                let mut merged_with_last_token = false;
16001                if let Some(last_token) = line.back_mut() {
16002                    if last_token.highlight == highlight {
16003                        last_token.text.push_str(text);
16004                        merged_with_last_token = true;
16005                    }
16006                }
16007
16008                if !merged_with_last_token {
16009                    line.push_back(Chunk {
16010                        text: text.into(),
16011                        highlight,
16012                    });
16013                }
16014
16015                if chunk_lines.peek().is_some() {
16016                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
16017                        line.pop_front();
16018                    }
16019                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
16020                        line.pop_back();
16021                    }
16022
16023                    lines.push(mem::take(&mut line));
16024                }
16025            }
16026        }
16027
16028        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
16029            return;
16030        };
16031        cx.write_to_clipboard(ClipboardItem::new_string(lines));
16032    }
16033
16034    pub fn open_context_menu(
16035        &mut self,
16036        _: &OpenContextMenu,
16037        window: &mut Window,
16038        cx: &mut Context<Self>,
16039    ) {
16040        self.request_autoscroll(Autoscroll::newest(), cx);
16041        let position = self.selections.newest_display(cx).start;
16042        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
16043    }
16044
16045    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
16046        &self.inlay_hint_cache
16047    }
16048
16049    pub fn replay_insert_event(
16050        &mut self,
16051        text: &str,
16052        relative_utf16_range: Option<Range<isize>>,
16053        window: &mut Window,
16054        cx: &mut Context<Self>,
16055    ) {
16056        if !self.input_enabled {
16057            cx.emit(EditorEvent::InputIgnored { text: text.into() });
16058            return;
16059        }
16060        if let Some(relative_utf16_range) = relative_utf16_range {
16061            let selections = self.selections.all::<OffsetUtf16>(cx);
16062            self.change_selections(None, window, cx, |s| {
16063                let new_ranges = selections.into_iter().map(|range| {
16064                    let start = OffsetUtf16(
16065                        range
16066                            .head()
16067                            .0
16068                            .saturating_add_signed(relative_utf16_range.start),
16069                    );
16070                    let end = OffsetUtf16(
16071                        range
16072                            .head()
16073                            .0
16074                            .saturating_add_signed(relative_utf16_range.end),
16075                    );
16076                    start..end
16077                });
16078                s.select_ranges(new_ranges);
16079            });
16080        }
16081
16082        self.handle_input(text, window, cx);
16083    }
16084
16085    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
16086        let Some(provider) = self.semantics_provider.as_ref() else {
16087            return false;
16088        };
16089
16090        let mut supports = false;
16091        self.buffer().update(cx, |this, cx| {
16092            this.for_each_buffer(|buffer| {
16093                supports |= provider.supports_inlay_hints(buffer, cx);
16094            });
16095        });
16096
16097        supports
16098    }
16099
16100    pub fn is_focused(&self, window: &Window) -> bool {
16101        self.focus_handle.is_focused(window)
16102    }
16103
16104    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16105        cx.emit(EditorEvent::Focused);
16106
16107        if let Some(descendant) = self
16108            .last_focused_descendant
16109            .take()
16110            .and_then(|descendant| descendant.upgrade())
16111        {
16112            window.focus(&descendant);
16113        } else {
16114            if let Some(blame) = self.blame.as_ref() {
16115                blame.update(cx, GitBlame::focus)
16116            }
16117
16118            self.blink_manager.update(cx, BlinkManager::enable);
16119            self.show_cursor_names(window, cx);
16120            self.buffer.update(cx, |buffer, cx| {
16121                buffer.finalize_last_transaction(cx);
16122                if self.leader_peer_id.is_none() {
16123                    buffer.set_active_selections(
16124                        &self.selections.disjoint_anchors(),
16125                        self.selections.line_mode,
16126                        self.cursor_shape,
16127                        cx,
16128                    );
16129                }
16130            });
16131        }
16132    }
16133
16134    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16135        cx.emit(EditorEvent::FocusedIn)
16136    }
16137
16138    fn handle_focus_out(
16139        &mut self,
16140        event: FocusOutEvent,
16141        _window: &mut Window,
16142        cx: &mut Context<Self>,
16143    ) {
16144        if event.blurred != self.focus_handle {
16145            self.last_focused_descendant = Some(event.blurred);
16146        }
16147        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
16148    }
16149
16150    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16151        self.blink_manager.update(cx, BlinkManager::disable);
16152        self.buffer
16153            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
16154
16155        if let Some(blame) = self.blame.as_ref() {
16156            blame.update(cx, GitBlame::blur)
16157        }
16158        if !self.hover_state.focused(window, cx) {
16159            hide_hover(self, cx);
16160        }
16161        if !self
16162            .context_menu
16163            .borrow()
16164            .as_ref()
16165            .is_some_and(|context_menu| context_menu.focused(window, cx))
16166        {
16167            self.hide_context_menu(window, cx);
16168        }
16169        self.discard_inline_completion(false, cx);
16170        cx.emit(EditorEvent::Blurred);
16171        cx.notify();
16172    }
16173
16174    pub fn register_action<A: Action>(
16175        &mut self,
16176        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
16177    ) -> Subscription {
16178        let id = self.next_editor_action_id.post_inc();
16179        let listener = Arc::new(listener);
16180        self.editor_actions.borrow_mut().insert(
16181            id,
16182            Box::new(move |window, _| {
16183                let listener = listener.clone();
16184                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
16185                    let action = action.downcast_ref().unwrap();
16186                    if phase == DispatchPhase::Bubble {
16187                        listener(action, window, cx)
16188                    }
16189                })
16190            }),
16191        );
16192
16193        let editor_actions = self.editor_actions.clone();
16194        Subscription::new(move || {
16195            editor_actions.borrow_mut().remove(&id);
16196        })
16197    }
16198
16199    pub fn file_header_size(&self) -> u32 {
16200        FILE_HEADER_HEIGHT
16201    }
16202
16203    pub fn restore(
16204        &mut self,
16205        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16206        window: &mut Window,
16207        cx: &mut Context<Self>,
16208    ) {
16209        let workspace = self.workspace();
16210        let project = self.project.as_ref();
16211        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16212            let mut tasks = Vec::new();
16213            for (buffer_id, changes) in revert_changes {
16214                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16215                    buffer.update(cx, |buffer, cx| {
16216                        buffer.edit(
16217                            changes
16218                                .into_iter()
16219                                .map(|(range, text)| (range, text.to_string())),
16220                            None,
16221                            cx,
16222                        );
16223                    });
16224
16225                    if let Some(project) =
16226                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16227                    {
16228                        project.update(cx, |project, cx| {
16229                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16230                        })
16231                    }
16232                }
16233            }
16234            tasks
16235        });
16236        cx.spawn_in(window, |_, mut cx| async move {
16237            for (buffer, task) in save_tasks {
16238                let result = task.await;
16239                if result.is_err() {
16240                    let Some(path) = buffer
16241                        .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16242                        .ok()
16243                    else {
16244                        continue;
16245                    };
16246                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16247                        let Some(task) = cx
16248                            .update_window_entity(&workspace, |workspace, window, cx| {
16249                                workspace
16250                                    .open_path_preview(path, None, false, false, false, window, cx)
16251                            })
16252                            .ok()
16253                        else {
16254                            continue;
16255                        };
16256                        task.await.log_err();
16257                    }
16258                }
16259            }
16260        })
16261        .detach();
16262        self.change_selections(None, window, cx, |selections| selections.refresh());
16263    }
16264
16265    pub fn to_pixel_point(
16266        &self,
16267        source: multi_buffer::Anchor,
16268        editor_snapshot: &EditorSnapshot,
16269        window: &mut Window,
16270    ) -> Option<gpui::Point<Pixels>> {
16271        let source_point = source.to_display_point(editor_snapshot);
16272        self.display_to_pixel_point(source_point, editor_snapshot, window)
16273    }
16274
16275    pub fn display_to_pixel_point(
16276        &self,
16277        source: DisplayPoint,
16278        editor_snapshot: &EditorSnapshot,
16279        window: &mut Window,
16280    ) -> Option<gpui::Point<Pixels>> {
16281        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16282        let text_layout_details = self.text_layout_details(window);
16283        let scroll_top = text_layout_details
16284            .scroll_anchor
16285            .scroll_position(editor_snapshot)
16286            .y;
16287
16288        if source.row().as_f32() < scroll_top.floor() {
16289            return None;
16290        }
16291        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16292        let source_y = line_height * (source.row().as_f32() - scroll_top);
16293        Some(gpui::Point::new(source_x, source_y))
16294    }
16295
16296    pub fn has_visible_completions_menu(&self) -> bool {
16297        !self.edit_prediction_preview_is_active()
16298            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16299                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16300            })
16301    }
16302
16303    pub fn register_addon<T: Addon>(&mut self, instance: T) {
16304        self.addons
16305            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16306    }
16307
16308    pub fn unregister_addon<T: Addon>(&mut self) {
16309        self.addons.remove(&std::any::TypeId::of::<T>());
16310    }
16311
16312    pub fn addon<T: Addon>(&self) -> Option<&T> {
16313        let type_id = std::any::TypeId::of::<T>();
16314        self.addons
16315            .get(&type_id)
16316            .and_then(|item| item.to_any().downcast_ref::<T>())
16317    }
16318
16319    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16320        let text_layout_details = self.text_layout_details(window);
16321        let style = &text_layout_details.editor_style;
16322        let font_id = window.text_system().resolve_font(&style.text.font());
16323        let font_size = style.text.font_size.to_pixels(window.rem_size());
16324        let line_height = style.text.line_height_in_pixels(window.rem_size());
16325        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16326
16327        gpui::Size::new(em_width, line_height)
16328    }
16329
16330    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16331        self.load_diff_task.clone()
16332    }
16333
16334    fn read_selections_from_db(
16335        &mut self,
16336        item_id: u64,
16337        workspace_id: WorkspaceId,
16338        window: &mut Window,
16339        cx: &mut Context<Editor>,
16340    ) {
16341        if !self.is_singleton(cx)
16342            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16343        {
16344            return;
16345        }
16346        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16347            return;
16348        };
16349        if selections.is_empty() {
16350            return;
16351        }
16352
16353        let snapshot = self.buffer.read(cx).snapshot(cx);
16354        self.change_selections(None, window, cx, |s| {
16355            s.select_ranges(selections.into_iter().map(|(start, end)| {
16356                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16357            }));
16358        });
16359    }
16360}
16361
16362fn insert_extra_newline_brackets(
16363    buffer: &MultiBufferSnapshot,
16364    range: Range<usize>,
16365    language: &language::LanguageScope,
16366) -> bool {
16367    let leading_whitespace_len = buffer
16368        .reversed_chars_at(range.start)
16369        .take_while(|c| c.is_whitespace() && *c != '\n')
16370        .map(|c| c.len_utf8())
16371        .sum::<usize>();
16372    let trailing_whitespace_len = buffer
16373        .chars_at(range.end)
16374        .take_while(|c| c.is_whitespace() && *c != '\n')
16375        .map(|c| c.len_utf8())
16376        .sum::<usize>();
16377    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16378
16379    language.brackets().any(|(pair, enabled)| {
16380        let pair_start = pair.start.trim_end();
16381        let pair_end = pair.end.trim_start();
16382
16383        enabled
16384            && pair.newline
16385            && buffer.contains_str_at(range.end, pair_end)
16386            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16387    })
16388}
16389
16390fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16391    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16392        [(buffer, range, _)] => (*buffer, range.clone()),
16393        _ => return false,
16394    };
16395    let pair = {
16396        let mut result: Option<BracketMatch> = None;
16397
16398        for pair in buffer
16399            .all_bracket_ranges(range.clone())
16400            .filter(move |pair| {
16401                pair.open_range.start <= range.start && pair.close_range.end >= range.end
16402            })
16403        {
16404            let len = pair.close_range.end - pair.open_range.start;
16405
16406            if let Some(existing) = &result {
16407                let existing_len = existing.close_range.end - existing.open_range.start;
16408                if len > existing_len {
16409                    continue;
16410                }
16411            }
16412
16413            result = Some(pair);
16414        }
16415
16416        result
16417    };
16418    let Some(pair) = pair else {
16419        return false;
16420    };
16421    pair.newline_only
16422        && buffer
16423            .chars_for_range(pair.open_range.end..range.start)
16424            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16425            .all(|c| c.is_whitespace() && c != '\n')
16426}
16427
16428fn get_uncommitted_diff_for_buffer(
16429    project: &Entity<Project>,
16430    buffers: impl IntoIterator<Item = Entity<Buffer>>,
16431    buffer: Entity<MultiBuffer>,
16432    cx: &mut App,
16433) -> Task<()> {
16434    let mut tasks = Vec::new();
16435    project.update(cx, |project, cx| {
16436        for buffer in buffers {
16437            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16438        }
16439    });
16440    cx.spawn(|mut cx| async move {
16441        let diffs = future::join_all(tasks).await;
16442        buffer
16443            .update(&mut cx, |buffer, cx| {
16444                for diff in diffs.into_iter().flatten() {
16445                    buffer.add_diff(diff, cx);
16446                }
16447            })
16448            .ok();
16449    })
16450}
16451
16452fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16453    let tab_size = tab_size.get() as usize;
16454    let mut width = offset;
16455
16456    for ch in text.chars() {
16457        width += if ch == '\t' {
16458            tab_size - (width % tab_size)
16459        } else {
16460            1
16461        };
16462    }
16463
16464    width - offset
16465}
16466
16467#[cfg(test)]
16468mod tests {
16469    use super::*;
16470
16471    #[test]
16472    fn test_string_size_with_expanded_tabs() {
16473        let nz = |val| NonZeroU32::new(val).unwrap();
16474        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16475        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16476        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16477        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16478        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16479        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16480        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16481        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16482    }
16483}
16484
16485/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16486struct WordBreakingTokenizer<'a> {
16487    input: &'a str,
16488}
16489
16490impl<'a> WordBreakingTokenizer<'a> {
16491    fn new(input: &'a str) -> Self {
16492        Self { input }
16493    }
16494}
16495
16496fn is_char_ideographic(ch: char) -> bool {
16497    use unicode_script::Script::*;
16498    use unicode_script::UnicodeScript;
16499    matches!(ch.script(), Han | Tangut | Yi)
16500}
16501
16502fn is_grapheme_ideographic(text: &str) -> bool {
16503    text.chars().any(is_char_ideographic)
16504}
16505
16506fn is_grapheme_whitespace(text: &str) -> bool {
16507    text.chars().any(|x| x.is_whitespace())
16508}
16509
16510fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16511    text.chars().next().map_or(false, |ch| {
16512        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16513    })
16514}
16515
16516#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16517struct WordBreakToken<'a> {
16518    token: &'a str,
16519    grapheme_len: usize,
16520    is_whitespace: bool,
16521}
16522
16523impl<'a> Iterator for WordBreakingTokenizer<'a> {
16524    /// Yields a span, the count of graphemes in the token, and whether it was
16525    /// whitespace. Note that it also breaks at word boundaries.
16526    type Item = WordBreakToken<'a>;
16527
16528    fn next(&mut self) -> Option<Self::Item> {
16529        use unicode_segmentation::UnicodeSegmentation;
16530        if self.input.is_empty() {
16531            return None;
16532        }
16533
16534        let mut iter = self.input.graphemes(true).peekable();
16535        let mut offset = 0;
16536        let mut graphemes = 0;
16537        if let Some(first_grapheme) = iter.next() {
16538            let is_whitespace = is_grapheme_whitespace(first_grapheme);
16539            offset += first_grapheme.len();
16540            graphemes += 1;
16541            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16542                if let Some(grapheme) = iter.peek().copied() {
16543                    if should_stay_with_preceding_ideograph(grapheme) {
16544                        offset += grapheme.len();
16545                        graphemes += 1;
16546                    }
16547                }
16548            } else {
16549                let mut words = self.input[offset..].split_word_bound_indices().peekable();
16550                let mut next_word_bound = words.peek().copied();
16551                if next_word_bound.map_or(false, |(i, _)| i == 0) {
16552                    next_word_bound = words.next();
16553                }
16554                while let Some(grapheme) = iter.peek().copied() {
16555                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
16556                        break;
16557                    };
16558                    if is_grapheme_whitespace(grapheme) != is_whitespace {
16559                        break;
16560                    };
16561                    offset += grapheme.len();
16562                    graphemes += 1;
16563                    iter.next();
16564                }
16565            }
16566            let token = &self.input[..offset];
16567            self.input = &self.input[offset..];
16568            if is_whitespace {
16569                Some(WordBreakToken {
16570                    token: " ",
16571                    grapheme_len: 1,
16572                    is_whitespace: true,
16573                })
16574            } else {
16575                Some(WordBreakToken {
16576                    token,
16577                    grapheme_len: graphemes,
16578                    is_whitespace: false,
16579                })
16580            }
16581        } else {
16582            None
16583        }
16584    }
16585}
16586
16587#[test]
16588fn test_word_breaking_tokenizer() {
16589    let tests: &[(&str, &[(&str, usize, bool)])] = &[
16590        ("", &[]),
16591        ("  ", &[(" ", 1, true)]),
16592        ("Ʒ", &[("Ʒ", 1, false)]),
16593        ("Ǽ", &[("Ǽ", 1, false)]),
16594        ("", &[("", 1, false)]),
16595        ("⋑⋑", &[("⋑⋑", 2, false)]),
16596        (
16597            "原理,进而",
16598            &[
16599                ("", 1, false),
16600                ("理,", 2, false),
16601                ("", 1, false),
16602                ("", 1, false),
16603            ],
16604        ),
16605        (
16606            "hello world",
16607            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16608        ),
16609        (
16610            "hello, world",
16611            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16612        ),
16613        (
16614            "  hello world",
16615            &[
16616                (" ", 1, true),
16617                ("hello", 5, false),
16618                (" ", 1, true),
16619                ("world", 5, false),
16620            ],
16621        ),
16622        (
16623            "这是什么 \n 钢笔",
16624            &[
16625                ("", 1, false),
16626                ("", 1, false),
16627                ("", 1, false),
16628                ("", 1, false),
16629                (" ", 1, true),
16630                ("", 1, false),
16631                ("", 1, false),
16632            ],
16633        ),
16634        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16635    ];
16636
16637    for (input, result) in tests {
16638        assert_eq!(
16639            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16640            result
16641                .iter()
16642                .copied()
16643                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16644                    token,
16645                    grapheme_len,
16646                    is_whitespace,
16647                })
16648                .collect::<Vec<_>>()
16649        );
16650    }
16651}
16652
16653fn wrap_with_prefix(
16654    line_prefix: String,
16655    unwrapped_text: String,
16656    wrap_column: usize,
16657    tab_size: NonZeroU32,
16658) -> String {
16659    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16660    let mut wrapped_text = String::new();
16661    let mut current_line = line_prefix.clone();
16662
16663    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16664    let mut current_line_len = line_prefix_len;
16665    for WordBreakToken {
16666        token,
16667        grapheme_len,
16668        is_whitespace,
16669    } in tokenizer
16670    {
16671        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16672            wrapped_text.push_str(current_line.trim_end());
16673            wrapped_text.push('\n');
16674            current_line.truncate(line_prefix.len());
16675            current_line_len = line_prefix_len;
16676            if !is_whitespace {
16677                current_line.push_str(token);
16678                current_line_len += grapheme_len;
16679            }
16680        } else if !is_whitespace {
16681            current_line.push_str(token);
16682            current_line_len += grapheme_len;
16683        } else if current_line_len != line_prefix_len {
16684            current_line.push(' ');
16685            current_line_len += 1;
16686        }
16687    }
16688
16689    if !current_line.is_empty() {
16690        wrapped_text.push_str(&current_line);
16691    }
16692    wrapped_text
16693}
16694
16695#[test]
16696fn test_wrap_with_prefix() {
16697    assert_eq!(
16698        wrap_with_prefix(
16699            "# ".to_string(),
16700            "abcdefg".to_string(),
16701            4,
16702            NonZeroU32::new(4).unwrap()
16703        ),
16704        "# abcdefg"
16705    );
16706    assert_eq!(
16707        wrap_with_prefix(
16708            "".to_string(),
16709            "\thello world".to_string(),
16710            8,
16711            NonZeroU32::new(4).unwrap()
16712        ),
16713        "hello\nworld"
16714    );
16715    assert_eq!(
16716        wrap_with_prefix(
16717            "// ".to_string(),
16718            "xx \nyy zz aa bb cc".to_string(),
16719            12,
16720            NonZeroU32::new(4).unwrap()
16721        ),
16722        "// xx yy zz\n// aa bb cc"
16723    );
16724    assert_eq!(
16725        wrap_with_prefix(
16726            String::new(),
16727            "这是什么 \n 钢笔".to_string(),
16728            3,
16729            NonZeroU32::new(4).unwrap()
16730        ),
16731        "这是什\n么 钢\n"
16732    );
16733}
16734
16735pub trait CollaborationHub {
16736    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16737    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16738    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16739}
16740
16741impl CollaborationHub for Entity<Project> {
16742    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16743        self.read(cx).collaborators()
16744    }
16745
16746    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16747        self.read(cx).user_store().read(cx).participant_indices()
16748    }
16749
16750    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16751        let this = self.read(cx);
16752        let user_ids = this.collaborators().values().map(|c| c.user_id);
16753        this.user_store().read_with(cx, |user_store, cx| {
16754            user_store.participant_names(user_ids, cx)
16755        })
16756    }
16757}
16758
16759pub trait SemanticsProvider {
16760    fn hover(
16761        &self,
16762        buffer: &Entity<Buffer>,
16763        position: text::Anchor,
16764        cx: &mut App,
16765    ) -> Option<Task<Vec<project::Hover>>>;
16766
16767    fn inlay_hints(
16768        &self,
16769        buffer_handle: Entity<Buffer>,
16770        range: Range<text::Anchor>,
16771        cx: &mut App,
16772    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16773
16774    fn resolve_inlay_hint(
16775        &self,
16776        hint: InlayHint,
16777        buffer_handle: Entity<Buffer>,
16778        server_id: LanguageServerId,
16779        cx: &mut App,
16780    ) -> Option<Task<anyhow::Result<InlayHint>>>;
16781
16782    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16783
16784    fn document_highlights(
16785        &self,
16786        buffer: &Entity<Buffer>,
16787        position: text::Anchor,
16788        cx: &mut App,
16789    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16790
16791    fn definitions(
16792        &self,
16793        buffer: &Entity<Buffer>,
16794        position: text::Anchor,
16795        kind: GotoDefinitionKind,
16796        cx: &mut App,
16797    ) -> Option<Task<Result<Vec<LocationLink>>>>;
16798
16799    fn range_for_rename(
16800        &self,
16801        buffer: &Entity<Buffer>,
16802        position: text::Anchor,
16803        cx: &mut App,
16804    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16805
16806    fn perform_rename(
16807        &self,
16808        buffer: &Entity<Buffer>,
16809        position: text::Anchor,
16810        new_name: String,
16811        cx: &mut App,
16812    ) -> Option<Task<Result<ProjectTransaction>>>;
16813}
16814
16815pub trait CompletionProvider {
16816    fn completions(
16817        &self,
16818        buffer: &Entity<Buffer>,
16819        buffer_position: text::Anchor,
16820        trigger: CompletionContext,
16821        window: &mut Window,
16822        cx: &mut Context<Editor>,
16823    ) -> Task<Result<Vec<Completion>>>;
16824
16825    fn resolve_completions(
16826        &self,
16827        buffer: Entity<Buffer>,
16828        completion_indices: Vec<usize>,
16829        completions: Rc<RefCell<Box<[Completion]>>>,
16830        cx: &mut Context<Editor>,
16831    ) -> Task<Result<bool>>;
16832
16833    fn apply_additional_edits_for_completion(
16834        &self,
16835        _buffer: Entity<Buffer>,
16836        _completions: Rc<RefCell<Box<[Completion]>>>,
16837        _completion_index: usize,
16838        _push_to_history: bool,
16839        _cx: &mut Context<Editor>,
16840    ) -> Task<Result<Option<language::Transaction>>> {
16841        Task::ready(Ok(None))
16842    }
16843
16844    fn is_completion_trigger(
16845        &self,
16846        buffer: &Entity<Buffer>,
16847        position: language::Anchor,
16848        text: &str,
16849        trigger_in_words: bool,
16850        cx: &mut Context<Editor>,
16851    ) -> bool;
16852
16853    fn sort_completions(&self) -> bool {
16854        true
16855    }
16856}
16857
16858pub trait CodeActionProvider {
16859    fn id(&self) -> Arc<str>;
16860
16861    fn code_actions(
16862        &self,
16863        buffer: &Entity<Buffer>,
16864        range: Range<text::Anchor>,
16865        window: &mut Window,
16866        cx: &mut App,
16867    ) -> Task<Result<Vec<CodeAction>>>;
16868
16869    fn apply_code_action(
16870        &self,
16871        buffer_handle: Entity<Buffer>,
16872        action: CodeAction,
16873        excerpt_id: ExcerptId,
16874        push_to_history: bool,
16875        window: &mut Window,
16876        cx: &mut App,
16877    ) -> Task<Result<ProjectTransaction>>;
16878}
16879
16880impl CodeActionProvider for Entity<Project> {
16881    fn id(&self) -> Arc<str> {
16882        "project".into()
16883    }
16884
16885    fn code_actions(
16886        &self,
16887        buffer: &Entity<Buffer>,
16888        range: Range<text::Anchor>,
16889        _window: &mut Window,
16890        cx: &mut App,
16891    ) -> Task<Result<Vec<CodeAction>>> {
16892        self.update(cx, |project, cx| {
16893            project.code_actions(buffer, range, None, cx)
16894        })
16895    }
16896
16897    fn apply_code_action(
16898        &self,
16899        buffer_handle: Entity<Buffer>,
16900        action: CodeAction,
16901        _excerpt_id: ExcerptId,
16902        push_to_history: bool,
16903        _window: &mut Window,
16904        cx: &mut App,
16905    ) -> Task<Result<ProjectTransaction>> {
16906        self.update(cx, |project, cx| {
16907            project.apply_code_action(buffer_handle, action, push_to_history, cx)
16908        })
16909    }
16910}
16911
16912fn snippet_completions(
16913    project: &Project,
16914    buffer: &Entity<Buffer>,
16915    buffer_position: text::Anchor,
16916    cx: &mut App,
16917) -> Task<Result<Vec<Completion>>> {
16918    let language = buffer.read(cx).language_at(buffer_position);
16919    let language_name = language.as_ref().map(|language| language.lsp_id());
16920    let snippet_store = project.snippets().read(cx);
16921    let snippets = snippet_store.snippets_for(language_name, cx);
16922
16923    if snippets.is_empty() {
16924        return Task::ready(Ok(vec![]));
16925    }
16926    let snapshot = buffer.read(cx).text_snapshot();
16927    let chars: String = snapshot
16928        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16929        .collect();
16930
16931    let scope = language.map(|language| language.default_scope());
16932    let executor = cx.background_executor().clone();
16933
16934    cx.background_spawn(async move {
16935        let classifier = CharClassifier::new(scope).for_completion(true);
16936        let mut last_word = chars
16937            .chars()
16938            .take_while(|c| classifier.is_word(*c))
16939            .collect::<String>();
16940        last_word = last_word.chars().rev().collect();
16941
16942        if last_word.is_empty() {
16943            return Ok(vec![]);
16944        }
16945
16946        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16947        let to_lsp = |point: &text::Anchor| {
16948            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16949            point_to_lsp(end)
16950        };
16951        let lsp_end = to_lsp(&buffer_position);
16952
16953        let candidates = snippets
16954            .iter()
16955            .enumerate()
16956            .flat_map(|(ix, snippet)| {
16957                snippet
16958                    .prefix
16959                    .iter()
16960                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16961            })
16962            .collect::<Vec<StringMatchCandidate>>();
16963
16964        let mut matches = fuzzy::match_strings(
16965            &candidates,
16966            &last_word,
16967            last_word.chars().any(|c| c.is_uppercase()),
16968            100,
16969            &Default::default(),
16970            executor,
16971        )
16972        .await;
16973
16974        // Remove all candidates where the query's start does not match the start of any word in the candidate
16975        if let Some(query_start) = last_word.chars().next() {
16976            matches.retain(|string_match| {
16977                split_words(&string_match.string).any(|word| {
16978                    // Check that the first codepoint of the word as lowercase matches the first
16979                    // codepoint of the query as lowercase
16980                    word.chars()
16981                        .flat_map(|codepoint| codepoint.to_lowercase())
16982                        .zip(query_start.to_lowercase())
16983                        .all(|(word_cp, query_cp)| word_cp == query_cp)
16984                })
16985            });
16986        }
16987
16988        let matched_strings = matches
16989            .into_iter()
16990            .map(|m| m.string)
16991            .collect::<HashSet<_>>();
16992
16993        let result: Vec<Completion> = snippets
16994            .into_iter()
16995            .filter_map(|snippet| {
16996                let matching_prefix = snippet
16997                    .prefix
16998                    .iter()
16999                    .find(|prefix| matched_strings.contains(*prefix))?;
17000                let start = as_offset - last_word.len();
17001                let start = snapshot.anchor_before(start);
17002                let range = start..buffer_position;
17003                let lsp_start = to_lsp(&start);
17004                let lsp_range = lsp::Range {
17005                    start: lsp_start,
17006                    end: lsp_end,
17007                };
17008                Some(Completion {
17009                    old_range: range,
17010                    new_text: snippet.body.clone(),
17011                    source: CompletionSource::Lsp {
17012                        server_id: LanguageServerId(usize::MAX),
17013                        resolved: true,
17014                        lsp_completion: Box::new(lsp::CompletionItem {
17015                            label: snippet.prefix.first().unwrap().clone(),
17016                            kind: Some(CompletionItemKind::SNIPPET),
17017                            label_details: snippet.description.as_ref().map(|description| {
17018                                lsp::CompletionItemLabelDetails {
17019                                    detail: Some(description.clone()),
17020                                    description: None,
17021                                }
17022                            }),
17023                            insert_text_format: Some(InsertTextFormat::SNIPPET),
17024                            text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
17025                                lsp::InsertReplaceEdit {
17026                                    new_text: snippet.body.clone(),
17027                                    insert: lsp_range,
17028                                    replace: lsp_range,
17029                                },
17030                            )),
17031                            filter_text: Some(snippet.body.clone()),
17032                            sort_text: Some(char::MAX.to_string()),
17033                            ..lsp::CompletionItem::default()
17034                        }),
17035                        lsp_defaults: None,
17036                    },
17037                    label: CodeLabel {
17038                        text: matching_prefix.clone(),
17039                        runs: Vec::new(),
17040                        filter_range: 0..matching_prefix.len(),
17041                    },
17042                    documentation: snippet
17043                        .description
17044                        .clone()
17045                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
17046                    confirm: None,
17047                })
17048            })
17049            .collect();
17050
17051        Ok(result)
17052    })
17053}
17054
17055impl CompletionProvider for Entity<Project> {
17056    fn completions(
17057        &self,
17058        buffer: &Entity<Buffer>,
17059        buffer_position: text::Anchor,
17060        options: CompletionContext,
17061        _window: &mut Window,
17062        cx: &mut Context<Editor>,
17063    ) -> Task<Result<Vec<Completion>>> {
17064        self.update(cx, |project, cx| {
17065            let snippets = snippet_completions(project, buffer, buffer_position, cx);
17066            let project_completions = project.completions(buffer, buffer_position, options, cx);
17067            cx.background_spawn(async move {
17068                let mut completions = project_completions.await?;
17069                let snippets_completions = snippets.await?;
17070                completions.extend(snippets_completions);
17071                Ok(completions)
17072            })
17073        })
17074    }
17075
17076    fn resolve_completions(
17077        &self,
17078        buffer: Entity<Buffer>,
17079        completion_indices: Vec<usize>,
17080        completions: Rc<RefCell<Box<[Completion]>>>,
17081        cx: &mut Context<Editor>,
17082    ) -> Task<Result<bool>> {
17083        self.update(cx, |project, cx| {
17084            project.lsp_store().update(cx, |lsp_store, cx| {
17085                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
17086            })
17087        })
17088    }
17089
17090    fn apply_additional_edits_for_completion(
17091        &self,
17092        buffer: Entity<Buffer>,
17093        completions: Rc<RefCell<Box<[Completion]>>>,
17094        completion_index: usize,
17095        push_to_history: bool,
17096        cx: &mut Context<Editor>,
17097    ) -> Task<Result<Option<language::Transaction>>> {
17098        self.update(cx, |project, cx| {
17099            project.lsp_store().update(cx, |lsp_store, cx| {
17100                lsp_store.apply_additional_edits_for_completion(
17101                    buffer,
17102                    completions,
17103                    completion_index,
17104                    push_to_history,
17105                    cx,
17106                )
17107            })
17108        })
17109    }
17110
17111    fn is_completion_trigger(
17112        &self,
17113        buffer: &Entity<Buffer>,
17114        position: language::Anchor,
17115        text: &str,
17116        trigger_in_words: bool,
17117        cx: &mut Context<Editor>,
17118    ) -> bool {
17119        let mut chars = text.chars();
17120        let char = if let Some(char) = chars.next() {
17121            char
17122        } else {
17123            return false;
17124        };
17125        if chars.next().is_some() {
17126            return false;
17127        }
17128
17129        let buffer = buffer.read(cx);
17130        let snapshot = buffer.snapshot();
17131        if !snapshot.settings_at(position, cx).show_completions_on_input {
17132            return false;
17133        }
17134        let classifier = snapshot.char_classifier_at(position).for_completion(true);
17135        if trigger_in_words && classifier.is_word(char) {
17136            return true;
17137        }
17138
17139        buffer.completion_triggers().contains(text)
17140    }
17141}
17142
17143impl SemanticsProvider for Entity<Project> {
17144    fn hover(
17145        &self,
17146        buffer: &Entity<Buffer>,
17147        position: text::Anchor,
17148        cx: &mut App,
17149    ) -> Option<Task<Vec<project::Hover>>> {
17150        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
17151    }
17152
17153    fn document_highlights(
17154        &self,
17155        buffer: &Entity<Buffer>,
17156        position: text::Anchor,
17157        cx: &mut App,
17158    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
17159        Some(self.update(cx, |project, cx| {
17160            project.document_highlights(buffer, position, cx)
17161        }))
17162    }
17163
17164    fn definitions(
17165        &self,
17166        buffer: &Entity<Buffer>,
17167        position: text::Anchor,
17168        kind: GotoDefinitionKind,
17169        cx: &mut App,
17170    ) -> Option<Task<Result<Vec<LocationLink>>>> {
17171        Some(self.update(cx, |project, cx| match kind {
17172            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
17173            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
17174            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
17175            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
17176        }))
17177    }
17178
17179    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
17180        // TODO: make this work for remote projects
17181        self.update(cx, |this, cx| {
17182            buffer.update(cx, |buffer, cx| {
17183                this.any_language_server_supports_inlay_hints(buffer, cx)
17184            })
17185        })
17186    }
17187
17188    fn inlay_hints(
17189        &self,
17190        buffer_handle: Entity<Buffer>,
17191        range: Range<text::Anchor>,
17192        cx: &mut App,
17193    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
17194        Some(self.update(cx, |project, cx| {
17195            project.inlay_hints(buffer_handle, range, cx)
17196        }))
17197    }
17198
17199    fn resolve_inlay_hint(
17200        &self,
17201        hint: InlayHint,
17202        buffer_handle: Entity<Buffer>,
17203        server_id: LanguageServerId,
17204        cx: &mut App,
17205    ) -> Option<Task<anyhow::Result<InlayHint>>> {
17206        Some(self.update(cx, |project, cx| {
17207            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
17208        }))
17209    }
17210
17211    fn range_for_rename(
17212        &self,
17213        buffer: &Entity<Buffer>,
17214        position: text::Anchor,
17215        cx: &mut App,
17216    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17217        Some(self.update(cx, |project, cx| {
17218            let buffer = buffer.clone();
17219            let task = project.prepare_rename(buffer.clone(), position, cx);
17220            cx.spawn(|_, mut cx| async move {
17221                Ok(match task.await? {
17222                    PrepareRenameResponse::Success(range) => Some(range),
17223                    PrepareRenameResponse::InvalidPosition => None,
17224                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17225                        // Fallback on using TreeSitter info to determine identifier range
17226                        buffer.update(&mut cx, |buffer, _| {
17227                            let snapshot = buffer.snapshot();
17228                            let (range, kind) = snapshot.surrounding_word(position);
17229                            if kind != Some(CharKind::Word) {
17230                                return None;
17231                            }
17232                            Some(
17233                                snapshot.anchor_before(range.start)
17234                                    ..snapshot.anchor_after(range.end),
17235                            )
17236                        })?
17237                    }
17238                })
17239            })
17240        }))
17241    }
17242
17243    fn perform_rename(
17244        &self,
17245        buffer: &Entity<Buffer>,
17246        position: text::Anchor,
17247        new_name: String,
17248        cx: &mut App,
17249    ) -> Option<Task<Result<ProjectTransaction>>> {
17250        Some(self.update(cx, |project, cx| {
17251            project.perform_rename(buffer.clone(), position, new_name, cx)
17252        }))
17253    }
17254}
17255
17256fn inlay_hint_settings(
17257    location: Anchor,
17258    snapshot: &MultiBufferSnapshot,
17259    cx: &mut Context<Editor>,
17260) -> InlayHintSettings {
17261    let file = snapshot.file_at(location);
17262    let language = snapshot.language_at(location).map(|l| l.name());
17263    language_settings(language, file, cx).inlay_hints
17264}
17265
17266fn consume_contiguous_rows(
17267    contiguous_row_selections: &mut Vec<Selection<Point>>,
17268    selection: &Selection<Point>,
17269    display_map: &DisplaySnapshot,
17270    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17271) -> (MultiBufferRow, MultiBufferRow) {
17272    contiguous_row_selections.push(selection.clone());
17273    let start_row = MultiBufferRow(selection.start.row);
17274    let mut end_row = ending_row(selection, display_map);
17275
17276    while let Some(next_selection) = selections.peek() {
17277        if next_selection.start.row <= end_row.0 {
17278            end_row = ending_row(next_selection, display_map);
17279            contiguous_row_selections.push(selections.next().unwrap().clone());
17280        } else {
17281            break;
17282        }
17283    }
17284    (start_row, end_row)
17285}
17286
17287fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17288    if next_selection.end.column > 0 || next_selection.is_empty() {
17289        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17290    } else {
17291        MultiBufferRow(next_selection.end.row)
17292    }
17293}
17294
17295impl EditorSnapshot {
17296    pub fn remote_selections_in_range<'a>(
17297        &'a self,
17298        range: &'a Range<Anchor>,
17299        collaboration_hub: &dyn CollaborationHub,
17300        cx: &'a App,
17301    ) -> impl 'a + Iterator<Item = RemoteSelection> {
17302        let participant_names = collaboration_hub.user_names(cx);
17303        let participant_indices = collaboration_hub.user_participant_indices(cx);
17304        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17305        let collaborators_by_replica_id = collaborators_by_peer_id
17306            .iter()
17307            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17308            .collect::<HashMap<_, _>>();
17309        self.buffer_snapshot
17310            .selections_in_range(range, false)
17311            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17312                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17313                let participant_index = participant_indices.get(&collaborator.user_id).copied();
17314                let user_name = participant_names.get(&collaborator.user_id).cloned();
17315                Some(RemoteSelection {
17316                    replica_id,
17317                    selection,
17318                    cursor_shape,
17319                    line_mode,
17320                    participant_index,
17321                    peer_id: collaborator.peer_id,
17322                    user_name,
17323                })
17324            })
17325    }
17326
17327    pub fn hunks_for_ranges(
17328        &self,
17329        ranges: impl IntoIterator<Item = Range<Point>>,
17330    ) -> Vec<MultiBufferDiffHunk> {
17331        let mut hunks = Vec::new();
17332        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17333            HashMap::default();
17334        for query_range in ranges {
17335            let query_rows =
17336                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17337            for hunk in self.buffer_snapshot.diff_hunks_in_range(
17338                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17339            ) {
17340                // Include deleted hunks that are adjacent to the query range, because
17341                // otherwise they would be missed.
17342                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
17343                if hunk.status().is_deleted() {
17344                    intersects_range |= hunk.row_range.start == query_rows.end;
17345                    intersects_range |= hunk.row_range.end == query_rows.start;
17346                }
17347                if intersects_range {
17348                    if !processed_buffer_rows
17349                        .entry(hunk.buffer_id)
17350                        .or_default()
17351                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17352                    {
17353                        continue;
17354                    }
17355                    hunks.push(hunk);
17356                }
17357            }
17358        }
17359
17360        hunks
17361    }
17362
17363    fn display_diff_hunks_for_rows<'a>(
17364        &'a self,
17365        display_rows: Range<DisplayRow>,
17366        folded_buffers: &'a HashSet<BufferId>,
17367    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17368        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17369        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17370
17371        self.buffer_snapshot
17372            .diff_hunks_in_range(buffer_start..buffer_end)
17373            .filter_map(|hunk| {
17374                if folded_buffers.contains(&hunk.buffer_id) {
17375                    return None;
17376                }
17377
17378                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17379                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17380
17381                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17382                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17383
17384                let display_hunk = if hunk_display_start.column() != 0 {
17385                    DisplayDiffHunk::Folded {
17386                        display_row: hunk_display_start.row(),
17387                    }
17388                } else {
17389                    let mut end_row = hunk_display_end.row();
17390                    if hunk_display_end.column() > 0 {
17391                        end_row.0 += 1;
17392                    }
17393                    let is_created_file = hunk.is_created_file();
17394                    DisplayDiffHunk::Unfolded {
17395                        status: hunk.status(),
17396                        diff_base_byte_range: hunk.diff_base_byte_range,
17397                        display_row_range: hunk_display_start.row()..end_row,
17398                        multi_buffer_range: Anchor::range_in_buffer(
17399                            hunk.excerpt_id,
17400                            hunk.buffer_id,
17401                            hunk.buffer_range,
17402                        ),
17403                        is_created_file,
17404                    }
17405                };
17406
17407                Some(display_hunk)
17408            })
17409    }
17410
17411    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17412        self.display_snapshot.buffer_snapshot.language_at(position)
17413    }
17414
17415    pub fn is_focused(&self) -> bool {
17416        self.is_focused
17417    }
17418
17419    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17420        self.placeholder_text.as_ref()
17421    }
17422
17423    pub fn scroll_position(&self) -> gpui::Point<f32> {
17424        self.scroll_anchor.scroll_position(&self.display_snapshot)
17425    }
17426
17427    fn gutter_dimensions(
17428        &self,
17429        font_id: FontId,
17430        font_size: Pixels,
17431        max_line_number_width: Pixels,
17432        cx: &App,
17433    ) -> Option<GutterDimensions> {
17434        if !self.show_gutter {
17435            return None;
17436        }
17437
17438        let descent = cx.text_system().descent(font_id, font_size);
17439        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17440        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17441
17442        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17443            matches!(
17444                ProjectSettings::get_global(cx).git.git_gutter,
17445                Some(GitGutterSetting::TrackedFiles)
17446            )
17447        });
17448        let gutter_settings = EditorSettings::get_global(cx).gutter;
17449        let show_line_numbers = self
17450            .show_line_numbers
17451            .unwrap_or(gutter_settings.line_numbers);
17452        let line_gutter_width = if show_line_numbers {
17453            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17454            let min_width_for_number_on_gutter = em_advance * 4.0;
17455            max_line_number_width.max(min_width_for_number_on_gutter)
17456        } else {
17457            0.0.into()
17458        };
17459
17460        let show_code_actions = self
17461            .show_code_actions
17462            .unwrap_or(gutter_settings.code_actions);
17463
17464        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17465
17466        let git_blame_entries_width =
17467            self.git_blame_gutter_max_author_length
17468                .map(|max_author_length| {
17469                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17470
17471                    /// The number of characters to dedicate to gaps and margins.
17472                    const SPACING_WIDTH: usize = 4;
17473
17474                    let max_char_count = max_author_length
17475                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17476                        + ::git::SHORT_SHA_LENGTH
17477                        + MAX_RELATIVE_TIMESTAMP.len()
17478                        + SPACING_WIDTH;
17479
17480                    em_advance * max_char_count
17481                });
17482
17483        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17484        left_padding += if show_code_actions || show_runnables {
17485            em_width * 3.0
17486        } else if show_git_gutter && show_line_numbers {
17487            em_width * 2.0
17488        } else if show_git_gutter || show_line_numbers {
17489            em_width
17490        } else {
17491            px(0.)
17492        };
17493
17494        let right_padding = if gutter_settings.folds && show_line_numbers {
17495            em_width * 4.0
17496        } else if gutter_settings.folds {
17497            em_width * 3.0
17498        } else if show_line_numbers {
17499            em_width
17500        } else {
17501            px(0.)
17502        };
17503
17504        Some(GutterDimensions {
17505            left_padding,
17506            right_padding,
17507            width: line_gutter_width + left_padding + right_padding,
17508            margin: -descent,
17509            git_blame_entries_width,
17510        })
17511    }
17512
17513    pub fn render_crease_toggle(
17514        &self,
17515        buffer_row: MultiBufferRow,
17516        row_contains_cursor: bool,
17517        editor: Entity<Editor>,
17518        window: &mut Window,
17519        cx: &mut App,
17520    ) -> Option<AnyElement> {
17521        let folded = self.is_line_folded(buffer_row);
17522        let mut is_foldable = false;
17523
17524        if let Some(crease) = self
17525            .crease_snapshot
17526            .query_row(buffer_row, &self.buffer_snapshot)
17527        {
17528            is_foldable = true;
17529            match crease {
17530                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17531                    if let Some(render_toggle) = render_toggle {
17532                        let toggle_callback =
17533                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17534                                if folded {
17535                                    editor.update(cx, |editor, cx| {
17536                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17537                                    });
17538                                } else {
17539                                    editor.update(cx, |editor, cx| {
17540                                        editor.unfold_at(
17541                                            &crate::UnfoldAt { buffer_row },
17542                                            window,
17543                                            cx,
17544                                        )
17545                                    });
17546                                }
17547                            });
17548                        return Some((render_toggle)(
17549                            buffer_row,
17550                            folded,
17551                            toggle_callback,
17552                            window,
17553                            cx,
17554                        ));
17555                    }
17556                }
17557            }
17558        }
17559
17560        is_foldable |= self.starts_indent(buffer_row);
17561
17562        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17563            Some(
17564                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17565                    .toggle_state(folded)
17566                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17567                        if folded {
17568                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17569                        } else {
17570                            this.fold_at(&FoldAt { buffer_row }, window, cx);
17571                        }
17572                    }))
17573                    .into_any_element(),
17574            )
17575        } else {
17576            None
17577        }
17578    }
17579
17580    pub fn render_crease_trailer(
17581        &self,
17582        buffer_row: MultiBufferRow,
17583        window: &mut Window,
17584        cx: &mut App,
17585    ) -> Option<AnyElement> {
17586        let folded = self.is_line_folded(buffer_row);
17587        if let Crease::Inline { render_trailer, .. } = self
17588            .crease_snapshot
17589            .query_row(buffer_row, &self.buffer_snapshot)?
17590        {
17591            let render_trailer = render_trailer.as_ref()?;
17592            Some(render_trailer(buffer_row, folded, window, cx))
17593        } else {
17594            None
17595        }
17596    }
17597}
17598
17599impl Deref for EditorSnapshot {
17600    type Target = DisplaySnapshot;
17601
17602    fn deref(&self) -> &Self::Target {
17603        &self.display_snapshot
17604    }
17605}
17606
17607#[derive(Clone, Debug, PartialEq, Eq)]
17608pub enum EditorEvent {
17609    InputIgnored {
17610        text: Arc<str>,
17611    },
17612    InputHandled {
17613        utf16_range_to_replace: Option<Range<isize>>,
17614        text: Arc<str>,
17615    },
17616    ExcerptsAdded {
17617        buffer: Entity<Buffer>,
17618        predecessor: ExcerptId,
17619        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17620    },
17621    ExcerptsRemoved {
17622        ids: Vec<ExcerptId>,
17623    },
17624    BufferFoldToggled {
17625        ids: Vec<ExcerptId>,
17626        folded: bool,
17627    },
17628    ExcerptsEdited {
17629        ids: Vec<ExcerptId>,
17630    },
17631    ExcerptsExpanded {
17632        ids: Vec<ExcerptId>,
17633    },
17634    BufferEdited,
17635    Edited {
17636        transaction_id: clock::Lamport,
17637    },
17638    Reparsed(BufferId),
17639    Focused,
17640    FocusedIn,
17641    Blurred,
17642    DirtyChanged,
17643    Saved,
17644    TitleChanged,
17645    DiffBaseChanged,
17646    SelectionsChanged {
17647        local: bool,
17648    },
17649    ScrollPositionChanged {
17650        local: bool,
17651        autoscroll: bool,
17652    },
17653    Closed,
17654    TransactionUndone {
17655        transaction_id: clock::Lamport,
17656    },
17657    TransactionBegun {
17658        transaction_id: clock::Lamport,
17659    },
17660    Reloaded,
17661    CursorShapeChanged,
17662}
17663
17664impl EventEmitter<EditorEvent> for Editor {}
17665
17666impl Focusable for Editor {
17667    fn focus_handle(&self, _cx: &App) -> FocusHandle {
17668        self.focus_handle.clone()
17669    }
17670}
17671
17672impl Render for Editor {
17673    fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17674        let settings = ThemeSettings::get_global(cx);
17675
17676        let mut text_style = match self.mode {
17677            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17678                color: cx.theme().colors().editor_foreground,
17679                font_family: settings.ui_font.family.clone(),
17680                font_features: settings.ui_font.features.clone(),
17681                font_fallbacks: settings.ui_font.fallbacks.clone(),
17682                font_size: rems(0.875).into(),
17683                font_weight: settings.ui_font.weight,
17684                line_height: relative(settings.buffer_line_height.value()),
17685                ..Default::default()
17686            },
17687            EditorMode::Full => TextStyle {
17688                color: cx.theme().colors().editor_foreground,
17689                font_family: settings.buffer_font.family.clone(),
17690                font_features: settings.buffer_font.features.clone(),
17691                font_fallbacks: settings.buffer_font.fallbacks.clone(),
17692                font_size: settings.buffer_font_size(cx).into(),
17693                font_weight: settings.buffer_font.weight,
17694                line_height: relative(settings.buffer_line_height.value()),
17695                ..Default::default()
17696            },
17697        };
17698        if let Some(text_style_refinement) = &self.text_style_refinement {
17699            text_style.refine(text_style_refinement)
17700        }
17701
17702        let background = match self.mode {
17703            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17704            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17705            EditorMode::Full => cx.theme().colors().editor_background,
17706        };
17707
17708        EditorElement::new(
17709            &cx.entity(),
17710            EditorStyle {
17711                background,
17712                local_player: cx.theme().players().local(),
17713                text: text_style,
17714                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17715                syntax: cx.theme().syntax().clone(),
17716                status: cx.theme().status().clone(),
17717                inlay_hints_style: make_inlay_hints_style(cx),
17718                inline_completion_styles: make_suggestion_styles(cx),
17719                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17720            },
17721        )
17722    }
17723}
17724
17725impl EntityInputHandler for Editor {
17726    fn text_for_range(
17727        &mut self,
17728        range_utf16: Range<usize>,
17729        adjusted_range: &mut Option<Range<usize>>,
17730        _: &mut Window,
17731        cx: &mut Context<Self>,
17732    ) -> Option<String> {
17733        let snapshot = self.buffer.read(cx).read(cx);
17734        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17735        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17736        if (start.0..end.0) != range_utf16 {
17737            adjusted_range.replace(start.0..end.0);
17738        }
17739        Some(snapshot.text_for_range(start..end).collect())
17740    }
17741
17742    fn selected_text_range(
17743        &mut self,
17744        ignore_disabled_input: bool,
17745        _: &mut Window,
17746        cx: &mut Context<Self>,
17747    ) -> Option<UTF16Selection> {
17748        // Prevent the IME menu from appearing when holding down an alphabetic key
17749        // while input is disabled.
17750        if !ignore_disabled_input && !self.input_enabled {
17751            return None;
17752        }
17753
17754        let selection = self.selections.newest::<OffsetUtf16>(cx);
17755        let range = selection.range();
17756
17757        Some(UTF16Selection {
17758            range: range.start.0..range.end.0,
17759            reversed: selection.reversed,
17760        })
17761    }
17762
17763    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17764        let snapshot = self.buffer.read(cx).read(cx);
17765        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17766        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17767    }
17768
17769    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17770        self.clear_highlights::<InputComposition>(cx);
17771        self.ime_transaction.take();
17772    }
17773
17774    fn replace_text_in_range(
17775        &mut self,
17776        range_utf16: Option<Range<usize>>,
17777        text: &str,
17778        window: &mut Window,
17779        cx: &mut Context<Self>,
17780    ) {
17781        if !self.input_enabled {
17782            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17783            return;
17784        }
17785
17786        self.transact(window, cx, |this, window, cx| {
17787            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17788                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17789                Some(this.selection_replacement_ranges(range_utf16, cx))
17790            } else {
17791                this.marked_text_ranges(cx)
17792            };
17793
17794            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17795                let newest_selection_id = this.selections.newest_anchor().id;
17796                this.selections
17797                    .all::<OffsetUtf16>(cx)
17798                    .iter()
17799                    .zip(ranges_to_replace.iter())
17800                    .find_map(|(selection, range)| {
17801                        if selection.id == newest_selection_id {
17802                            Some(
17803                                (range.start.0 as isize - selection.head().0 as isize)
17804                                    ..(range.end.0 as isize - selection.head().0 as isize),
17805                            )
17806                        } else {
17807                            None
17808                        }
17809                    })
17810            });
17811
17812            cx.emit(EditorEvent::InputHandled {
17813                utf16_range_to_replace: range_to_replace,
17814                text: text.into(),
17815            });
17816
17817            if let Some(new_selected_ranges) = new_selected_ranges {
17818                this.change_selections(None, window, cx, |selections| {
17819                    selections.select_ranges(new_selected_ranges)
17820                });
17821                this.backspace(&Default::default(), window, cx);
17822            }
17823
17824            this.handle_input(text, window, cx);
17825        });
17826
17827        if let Some(transaction) = self.ime_transaction {
17828            self.buffer.update(cx, |buffer, cx| {
17829                buffer.group_until_transaction(transaction, cx);
17830            });
17831        }
17832
17833        self.unmark_text(window, cx);
17834    }
17835
17836    fn replace_and_mark_text_in_range(
17837        &mut self,
17838        range_utf16: Option<Range<usize>>,
17839        text: &str,
17840        new_selected_range_utf16: Option<Range<usize>>,
17841        window: &mut Window,
17842        cx: &mut Context<Self>,
17843    ) {
17844        if !self.input_enabled {
17845            return;
17846        }
17847
17848        let transaction = self.transact(window, cx, |this, window, cx| {
17849            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17850                let snapshot = this.buffer.read(cx).read(cx);
17851                if let Some(relative_range_utf16) = range_utf16.as_ref() {
17852                    for marked_range in &mut marked_ranges {
17853                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17854                        marked_range.start.0 += relative_range_utf16.start;
17855                        marked_range.start =
17856                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17857                        marked_range.end =
17858                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17859                    }
17860                }
17861                Some(marked_ranges)
17862            } else if let Some(range_utf16) = range_utf16 {
17863                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17864                Some(this.selection_replacement_ranges(range_utf16, cx))
17865            } else {
17866                None
17867            };
17868
17869            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17870                let newest_selection_id = this.selections.newest_anchor().id;
17871                this.selections
17872                    .all::<OffsetUtf16>(cx)
17873                    .iter()
17874                    .zip(ranges_to_replace.iter())
17875                    .find_map(|(selection, range)| {
17876                        if selection.id == newest_selection_id {
17877                            Some(
17878                                (range.start.0 as isize - selection.head().0 as isize)
17879                                    ..(range.end.0 as isize - selection.head().0 as isize),
17880                            )
17881                        } else {
17882                            None
17883                        }
17884                    })
17885            });
17886
17887            cx.emit(EditorEvent::InputHandled {
17888                utf16_range_to_replace: range_to_replace,
17889                text: text.into(),
17890            });
17891
17892            if let Some(ranges) = ranges_to_replace {
17893                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17894            }
17895
17896            let marked_ranges = {
17897                let snapshot = this.buffer.read(cx).read(cx);
17898                this.selections
17899                    .disjoint_anchors()
17900                    .iter()
17901                    .map(|selection| {
17902                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17903                    })
17904                    .collect::<Vec<_>>()
17905            };
17906
17907            if text.is_empty() {
17908                this.unmark_text(window, cx);
17909            } else {
17910                this.highlight_text::<InputComposition>(
17911                    marked_ranges.clone(),
17912                    HighlightStyle {
17913                        underline: Some(UnderlineStyle {
17914                            thickness: px(1.),
17915                            color: None,
17916                            wavy: false,
17917                        }),
17918                        ..Default::default()
17919                    },
17920                    cx,
17921                );
17922            }
17923
17924            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17925            let use_autoclose = this.use_autoclose;
17926            let use_auto_surround = this.use_auto_surround;
17927            this.set_use_autoclose(false);
17928            this.set_use_auto_surround(false);
17929            this.handle_input(text, window, cx);
17930            this.set_use_autoclose(use_autoclose);
17931            this.set_use_auto_surround(use_auto_surround);
17932
17933            if let Some(new_selected_range) = new_selected_range_utf16 {
17934                let snapshot = this.buffer.read(cx).read(cx);
17935                let new_selected_ranges = marked_ranges
17936                    .into_iter()
17937                    .map(|marked_range| {
17938                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17939                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17940                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17941                        snapshot.clip_offset_utf16(new_start, Bias::Left)
17942                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17943                    })
17944                    .collect::<Vec<_>>();
17945
17946                drop(snapshot);
17947                this.change_selections(None, window, cx, |selections| {
17948                    selections.select_ranges(new_selected_ranges)
17949                });
17950            }
17951        });
17952
17953        self.ime_transaction = self.ime_transaction.or(transaction);
17954        if let Some(transaction) = self.ime_transaction {
17955            self.buffer.update(cx, |buffer, cx| {
17956                buffer.group_until_transaction(transaction, cx);
17957            });
17958        }
17959
17960        if self.text_highlights::<InputComposition>(cx).is_none() {
17961            self.ime_transaction.take();
17962        }
17963    }
17964
17965    fn bounds_for_range(
17966        &mut self,
17967        range_utf16: Range<usize>,
17968        element_bounds: gpui::Bounds<Pixels>,
17969        window: &mut Window,
17970        cx: &mut Context<Self>,
17971    ) -> Option<gpui::Bounds<Pixels>> {
17972        let text_layout_details = self.text_layout_details(window);
17973        let gpui::Size {
17974            width: em_width,
17975            height: line_height,
17976        } = self.character_size(window);
17977
17978        let snapshot = self.snapshot(window, cx);
17979        let scroll_position = snapshot.scroll_position();
17980        let scroll_left = scroll_position.x * em_width;
17981
17982        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17983        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17984            + self.gutter_dimensions.width
17985            + self.gutter_dimensions.margin;
17986        let y = line_height * (start.row().as_f32() - scroll_position.y);
17987
17988        Some(Bounds {
17989            origin: element_bounds.origin + point(x, y),
17990            size: size(em_width, line_height),
17991        })
17992    }
17993
17994    fn character_index_for_point(
17995        &mut self,
17996        point: gpui::Point<Pixels>,
17997        _window: &mut Window,
17998        _cx: &mut Context<Self>,
17999    ) -> Option<usize> {
18000        let position_map = self.last_position_map.as_ref()?;
18001        if !position_map.text_hitbox.contains(&point) {
18002            return None;
18003        }
18004        let display_point = position_map.point_for_position(point).previous_valid;
18005        let anchor = position_map
18006            .snapshot
18007            .display_point_to_anchor(display_point, Bias::Left);
18008        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
18009        Some(utf16_offset.0)
18010    }
18011}
18012
18013trait SelectionExt {
18014    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
18015    fn spanned_rows(
18016        &self,
18017        include_end_if_at_line_start: bool,
18018        map: &DisplaySnapshot,
18019    ) -> Range<MultiBufferRow>;
18020}
18021
18022impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
18023    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
18024        let start = self
18025            .start
18026            .to_point(&map.buffer_snapshot)
18027            .to_display_point(map);
18028        let end = self
18029            .end
18030            .to_point(&map.buffer_snapshot)
18031            .to_display_point(map);
18032        if self.reversed {
18033            end..start
18034        } else {
18035            start..end
18036        }
18037    }
18038
18039    fn spanned_rows(
18040        &self,
18041        include_end_if_at_line_start: bool,
18042        map: &DisplaySnapshot,
18043    ) -> Range<MultiBufferRow> {
18044        let start = self.start.to_point(&map.buffer_snapshot);
18045        let mut end = self.end.to_point(&map.buffer_snapshot);
18046        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
18047            end.row -= 1;
18048        }
18049
18050        let buffer_start = map.prev_line_boundary(start).0;
18051        let buffer_end = map.next_line_boundary(end).0;
18052        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
18053    }
18054}
18055
18056impl<T: InvalidationRegion> InvalidationStack<T> {
18057    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
18058    where
18059        S: Clone + ToOffset,
18060    {
18061        while let Some(region) = self.last() {
18062            let all_selections_inside_invalidation_ranges =
18063                if selections.len() == region.ranges().len() {
18064                    selections
18065                        .iter()
18066                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
18067                        .all(|(selection, invalidation_range)| {
18068                            let head = selection.head().to_offset(buffer);
18069                            invalidation_range.start <= head && invalidation_range.end >= head
18070                        })
18071                } else {
18072                    false
18073                };
18074
18075            if all_selections_inside_invalidation_ranges {
18076                break;
18077            } else {
18078                self.pop();
18079            }
18080        }
18081    }
18082}
18083
18084impl<T> Default for InvalidationStack<T> {
18085    fn default() -> Self {
18086        Self(Default::default())
18087    }
18088}
18089
18090impl<T> Deref for InvalidationStack<T> {
18091    type Target = Vec<T>;
18092
18093    fn deref(&self) -> &Self::Target {
18094        &self.0
18095    }
18096}
18097
18098impl<T> DerefMut for InvalidationStack<T> {
18099    fn deref_mut(&mut self) -> &mut Self::Target {
18100        &mut self.0
18101    }
18102}
18103
18104impl InvalidationRegion for SnippetState {
18105    fn ranges(&self) -> &[Range<Anchor>] {
18106        &self.ranges[self.active_index]
18107    }
18108}
18109
18110pub fn diagnostic_block_renderer(
18111    diagnostic: Diagnostic,
18112    max_message_rows: Option<u8>,
18113    allow_closing: bool,
18114) -> RenderBlock {
18115    let (text_without_backticks, code_ranges) =
18116        highlight_diagnostic_message(&diagnostic, max_message_rows);
18117
18118    Arc::new(move |cx: &mut BlockContext| {
18119        let group_id: SharedString = cx.block_id.to_string().into();
18120
18121        let mut text_style = cx.window.text_style().clone();
18122        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
18123        let theme_settings = ThemeSettings::get_global(cx);
18124        text_style.font_family = theme_settings.buffer_font.family.clone();
18125        text_style.font_style = theme_settings.buffer_font.style;
18126        text_style.font_features = theme_settings.buffer_font.features.clone();
18127        text_style.font_weight = theme_settings.buffer_font.weight;
18128
18129        let multi_line_diagnostic = diagnostic.message.contains('\n');
18130
18131        let buttons = |diagnostic: &Diagnostic| {
18132            if multi_line_diagnostic {
18133                v_flex()
18134            } else {
18135                h_flex()
18136            }
18137            .when(allow_closing, |div| {
18138                div.children(diagnostic.is_primary.then(|| {
18139                    IconButton::new("close-block", IconName::XCircle)
18140                        .icon_color(Color::Muted)
18141                        .size(ButtonSize::Compact)
18142                        .style(ButtonStyle::Transparent)
18143                        .visible_on_hover(group_id.clone())
18144                        .on_click(move |_click, window, cx| {
18145                            window.dispatch_action(Box::new(Cancel), cx)
18146                        })
18147                        .tooltip(|window, cx| {
18148                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
18149                        })
18150                }))
18151            })
18152            .child(
18153                IconButton::new("copy-block", IconName::Copy)
18154                    .icon_color(Color::Muted)
18155                    .size(ButtonSize::Compact)
18156                    .style(ButtonStyle::Transparent)
18157                    .visible_on_hover(group_id.clone())
18158                    .on_click({
18159                        let message = diagnostic.message.clone();
18160                        move |_click, _, cx| {
18161                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
18162                        }
18163                    })
18164                    .tooltip(Tooltip::text("Copy diagnostic message")),
18165            )
18166        };
18167
18168        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
18169            AvailableSpace::min_size(),
18170            cx.window,
18171            cx.app,
18172        );
18173
18174        h_flex()
18175            .id(cx.block_id)
18176            .group(group_id.clone())
18177            .relative()
18178            .size_full()
18179            .block_mouse_down()
18180            .pl(cx.gutter_dimensions.width)
18181            .w(cx.max_width - cx.gutter_dimensions.full_width())
18182            .child(
18183                div()
18184                    .flex()
18185                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
18186                    .flex_shrink(),
18187            )
18188            .child(buttons(&diagnostic))
18189            .child(div().flex().flex_shrink_0().child(
18190                StyledText::new(text_without_backticks.clone()).with_default_highlights(
18191                    &text_style,
18192                    code_ranges.iter().map(|range| {
18193                        (
18194                            range.clone(),
18195                            HighlightStyle {
18196                                font_weight: Some(FontWeight::BOLD),
18197                                ..Default::default()
18198                            },
18199                        )
18200                    }),
18201                ),
18202            ))
18203            .into_any_element()
18204    })
18205}
18206
18207fn inline_completion_edit_text(
18208    current_snapshot: &BufferSnapshot,
18209    edits: &[(Range<Anchor>, String)],
18210    edit_preview: &EditPreview,
18211    include_deletions: bool,
18212    cx: &App,
18213) -> HighlightedText {
18214    let edits = edits
18215        .iter()
18216        .map(|(anchor, text)| {
18217            (
18218                anchor.start.text_anchor..anchor.end.text_anchor,
18219                text.clone(),
18220            )
18221        })
18222        .collect::<Vec<_>>();
18223
18224    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18225}
18226
18227pub fn highlight_diagnostic_message(
18228    diagnostic: &Diagnostic,
18229    mut max_message_rows: Option<u8>,
18230) -> (SharedString, Vec<Range<usize>>) {
18231    let mut text_without_backticks = String::new();
18232    let mut code_ranges = Vec::new();
18233
18234    if let Some(source) = &diagnostic.source {
18235        text_without_backticks.push_str(source);
18236        code_ranges.push(0..source.len());
18237        text_without_backticks.push_str(": ");
18238    }
18239
18240    let mut prev_offset = 0;
18241    let mut in_code_block = false;
18242    let has_row_limit = max_message_rows.is_some();
18243    let mut newline_indices = diagnostic
18244        .message
18245        .match_indices('\n')
18246        .filter(|_| has_row_limit)
18247        .map(|(ix, _)| ix)
18248        .fuse()
18249        .peekable();
18250
18251    for (quote_ix, _) in diagnostic
18252        .message
18253        .match_indices('`')
18254        .chain([(diagnostic.message.len(), "")])
18255    {
18256        let mut first_newline_ix = None;
18257        let mut last_newline_ix = None;
18258        while let Some(newline_ix) = newline_indices.peek() {
18259            if *newline_ix < quote_ix {
18260                if first_newline_ix.is_none() {
18261                    first_newline_ix = Some(*newline_ix);
18262                }
18263                last_newline_ix = Some(*newline_ix);
18264
18265                if let Some(rows_left) = &mut max_message_rows {
18266                    if *rows_left == 0 {
18267                        break;
18268                    } else {
18269                        *rows_left -= 1;
18270                    }
18271                }
18272                let _ = newline_indices.next();
18273            } else {
18274                break;
18275            }
18276        }
18277        let prev_len = text_without_backticks.len();
18278        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18279        text_without_backticks.push_str(new_text);
18280        if in_code_block {
18281            code_ranges.push(prev_len..text_without_backticks.len());
18282        }
18283        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18284        in_code_block = !in_code_block;
18285        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18286            text_without_backticks.push_str("...");
18287            break;
18288        }
18289    }
18290
18291    (text_without_backticks.into(), code_ranges)
18292}
18293
18294fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18295    match severity {
18296        DiagnosticSeverity::ERROR => colors.error,
18297        DiagnosticSeverity::WARNING => colors.warning,
18298        DiagnosticSeverity::INFORMATION => colors.info,
18299        DiagnosticSeverity::HINT => colors.info,
18300        _ => colors.ignored,
18301    }
18302}
18303
18304pub fn styled_runs_for_code_label<'a>(
18305    label: &'a CodeLabel,
18306    syntax_theme: &'a theme::SyntaxTheme,
18307) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18308    let fade_out = HighlightStyle {
18309        fade_out: Some(0.35),
18310        ..Default::default()
18311    };
18312
18313    let mut prev_end = label.filter_range.end;
18314    label
18315        .runs
18316        .iter()
18317        .enumerate()
18318        .flat_map(move |(ix, (range, highlight_id))| {
18319            let style = if let Some(style) = highlight_id.style(syntax_theme) {
18320                style
18321            } else {
18322                return Default::default();
18323            };
18324            let mut muted_style = style;
18325            muted_style.highlight(fade_out);
18326
18327            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18328            if range.start >= label.filter_range.end {
18329                if range.start > prev_end {
18330                    runs.push((prev_end..range.start, fade_out));
18331                }
18332                runs.push((range.clone(), muted_style));
18333            } else if range.end <= label.filter_range.end {
18334                runs.push((range.clone(), style));
18335            } else {
18336                runs.push((range.start..label.filter_range.end, style));
18337                runs.push((label.filter_range.end..range.end, muted_style));
18338            }
18339            prev_end = cmp::max(prev_end, range.end);
18340
18341            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18342                runs.push((prev_end..label.text.len(), fade_out));
18343            }
18344
18345            runs
18346        })
18347}
18348
18349pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18350    let mut prev_index = 0;
18351    let mut prev_codepoint: Option<char> = None;
18352    text.char_indices()
18353        .chain([(text.len(), '\0')])
18354        .filter_map(move |(index, codepoint)| {
18355            let prev_codepoint = prev_codepoint.replace(codepoint)?;
18356            let is_boundary = index == text.len()
18357                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18358                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18359            if is_boundary {
18360                let chunk = &text[prev_index..index];
18361                prev_index = index;
18362                Some(chunk)
18363            } else {
18364                None
18365            }
18366        })
18367}
18368
18369pub trait RangeToAnchorExt: Sized {
18370    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18371
18372    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18373        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18374        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18375    }
18376}
18377
18378impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18379    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18380        let start_offset = self.start.to_offset(snapshot);
18381        let end_offset = self.end.to_offset(snapshot);
18382        if start_offset == end_offset {
18383            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18384        } else {
18385            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18386        }
18387    }
18388}
18389
18390pub trait RowExt {
18391    fn as_f32(&self) -> f32;
18392
18393    fn next_row(&self) -> Self;
18394
18395    fn previous_row(&self) -> Self;
18396
18397    fn minus(&self, other: Self) -> u32;
18398}
18399
18400impl RowExt for DisplayRow {
18401    fn as_f32(&self) -> f32 {
18402        self.0 as f32
18403    }
18404
18405    fn next_row(&self) -> Self {
18406        Self(self.0 + 1)
18407    }
18408
18409    fn previous_row(&self) -> Self {
18410        Self(self.0.saturating_sub(1))
18411    }
18412
18413    fn minus(&self, other: Self) -> u32 {
18414        self.0 - other.0
18415    }
18416}
18417
18418impl RowExt for MultiBufferRow {
18419    fn as_f32(&self) -> f32 {
18420        self.0 as f32
18421    }
18422
18423    fn next_row(&self) -> Self {
18424        Self(self.0 + 1)
18425    }
18426
18427    fn previous_row(&self) -> Self {
18428        Self(self.0.saturating_sub(1))
18429    }
18430
18431    fn minus(&self, other: Self) -> u32 {
18432        self.0 - other.0
18433    }
18434}
18435
18436trait RowRangeExt {
18437    type Row;
18438
18439    fn len(&self) -> usize;
18440
18441    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18442}
18443
18444impl RowRangeExt for Range<MultiBufferRow> {
18445    type Row = MultiBufferRow;
18446
18447    fn len(&self) -> usize {
18448        (self.end.0 - self.start.0) as usize
18449    }
18450
18451    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18452        (self.start.0..self.end.0).map(MultiBufferRow)
18453    }
18454}
18455
18456impl RowRangeExt for Range<DisplayRow> {
18457    type Row = DisplayRow;
18458
18459    fn len(&self) -> usize {
18460        (self.end.0 - self.start.0) as usize
18461    }
18462
18463    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18464        (self.start.0..self.end.0).map(DisplayRow)
18465    }
18466}
18467
18468/// If select range has more than one line, we
18469/// just point the cursor to range.start.
18470fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18471    if range.start.row == range.end.row {
18472        range
18473    } else {
18474        range.start..range.start
18475    }
18476}
18477pub struct KillRing(ClipboardItem);
18478impl Global for KillRing {}
18479
18480const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18481
18482fn all_edits_insertions_or_deletions(
18483    edits: &Vec<(Range<Anchor>, String)>,
18484    snapshot: &MultiBufferSnapshot,
18485) -> bool {
18486    let mut all_insertions = true;
18487    let mut all_deletions = true;
18488
18489    for (range, new_text) in edits.iter() {
18490        let range_is_empty = range.to_offset(&snapshot).is_empty();
18491        let text_is_empty = new_text.is_empty();
18492
18493        if range_is_empty != text_is_empty {
18494            if range_is_empty {
18495                all_deletions = false;
18496            } else {
18497                all_insertions = false;
18498            }
18499        } else {
18500            return false;
18501        }
18502
18503        if !all_insertions && !all_deletions {
18504            return false;
18505        }
18506    }
18507    all_insertions || all_deletions
18508}
18509
18510struct MissingEditPredictionKeybindingTooltip;
18511
18512impl Render for MissingEditPredictionKeybindingTooltip {
18513    fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18514        ui::tooltip_container(window, cx, |container, _, cx| {
18515            container
18516                .flex_shrink_0()
18517                .max_w_80()
18518                .min_h(rems_from_px(124.))
18519                .justify_between()
18520                .child(
18521                    v_flex()
18522                        .flex_1()
18523                        .text_ui_sm(cx)
18524                        .child(Label::new("Conflict with Accept Keybinding"))
18525                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
18526                )
18527                .child(
18528                    h_flex()
18529                        .pb_1()
18530                        .gap_1()
18531                        .items_end()
18532                        .w_full()
18533                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
18534                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
18535                        }))
18536                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
18537                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
18538                        })),
18539                )
18540        })
18541    }
18542}
18543
18544#[derive(Debug, Clone, Copy, PartialEq)]
18545pub struct LineHighlight {
18546    pub background: Background,
18547    pub border: Option<gpui::Hsla>,
18548}
18549
18550impl From<Hsla> for LineHighlight {
18551    fn from(hsla: Hsla) -> Self {
18552        Self {
18553            background: hsla.into(),
18554            border: None,
18555        }
18556    }
18557}
18558
18559impl From<Background> for LineHighlight {
18560    fn from(background: Background) -> Self {
18561        Self {
18562            background,
18563            border: None,
18564        }
18565    }
18566}