editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod commit_tooltip;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use buffer_diff::{DiffHunkSecondaryStatus, DiffHunkStatus};
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{
   71    future::{self, Shared},
   72    FutureExt,
   73};
   74use fuzzy::StringMatchCandidate;
   75
   76use ::git::{status::FileStatus, Restore};
   77use code_context_menus::{
   78    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   79    CompletionsMenu, ContextMenuOrigin,
   80};
   81use git::blame::GitBlame;
   82use gpui::{
   83    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   84    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   85    ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler,
   86    EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
   87    HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
   88    ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription, Task,
   89    TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   90    WeakEntity, WeakFocusHandle, Window,
   91};
   92use highlight_matching_bracket::refresh_matching_bracket_highlights;
   93use hover_popover::{hide_hover, HoverState};
   94use indent_guides::ActiveIndentGuidesState;
   95use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   96pub use inline_completion::Direction;
   97use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   98pub use items::MAX_TAB_TITLE_LEN;
   99use itertools::Itertools;
  100use language::{
  101    language_settings::{
  102        self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
  103    },
  104    point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
  105    Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, EditPredictionsMode,
  106    EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
  107    Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
  108};
  109use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  110use linked_editing_ranges::refresh_linked_ranges;
  111use mouse_context_menu::MouseContextMenu;
  112use persistence::DB;
  113pub use proposed_changes_editor::{
  114    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  115};
  116use smallvec::smallvec;
  117use std::iter::Peekable;
  118use task::{ResolvedTask, TaskTemplate, TaskVariables};
  119
  120use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  121pub use lsp::CompletionContext;
  122use lsp::{
  123    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  124    LanguageServerId, LanguageServerName,
  125};
  126
  127use language::BufferSnapshot;
  128use movement::TextLayoutDetails;
  129pub use multi_buffer::{
  130    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  131    ToOffset, ToPoint,
  132};
  133use multi_buffer::{
  134    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  135    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  136};
  137use project::{
  138    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  139    project_settings::{GitGutterSetting, ProjectSettings},
  140    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  141    PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  142};
  143use rand::prelude::*;
  144use rpc::{proto::*, ErrorExt};
  145use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  146use selections_collection::{
  147    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  148};
  149use serde::{Deserialize, Serialize};
  150use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  151use smallvec::SmallVec;
  152use snippet::Snippet;
  153use std::{
  154    any::TypeId,
  155    borrow::Cow,
  156    cell::RefCell,
  157    cmp::{self, Ordering, Reverse},
  158    mem,
  159    num::NonZeroU32,
  160    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  161    path::{Path, PathBuf},
  162    rc::Rc,
  163    sync::Arc,
  164    time::{Duration, Instant},
  165};
  166pub use sum_tree::Bias;
  167use sum_tree::TreeMap;
  168use text::{BufferId, OffsetUtf16, Rope};
  169use theme::{
  170    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  171    ThemeColors, ThemeSettings,
  172};
  173use ui::{
  174    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  175    Tooltip,
  176};
  177use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  178use workspace::{
  179    item::{ItemHandle, PreviewTabsSettings},
  180    ItemId, RestoreOnStartupBehavior,
  181};
  182use workspace::{
  183    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  184    WorkspaceSettings,
  185};
  186use workspace::{
  187    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  188};
  189use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  190
  191use crate::hover_links::{find_url, find_url_from_range};
  192use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  193
  194pub const FILE_HEADER_HEIGHT: u32 = 2;
  195pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  196pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  197pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  198const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  199const MAX_LINE_LEN: usize = 1024;
  200const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  201const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  202pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  203#[doc(hidden)]
  204pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  205
  206pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  207pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  208
  209pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  210pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  211
  212const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  213    alt: true,
  214    shift: true,
  215    control: false,
  216    platform: false,
  217    function: false,
  218};
  219
  220#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  221pub enum InlayId {
  222    InlineCompletion(usize),
  223    Hint(usize),
  224}
  225
  226impl InlayId {
  227    fn id(&self) -> usize {
  228        match self {
  229            Self::InlineCompletion(id) => *id,
  230            Self::Hint(id) => *id,
  231        }
  232    }
  233}
  234
  235enum DocumentHighlightRead {}
  236enum DocumentHighlightWrite {}
  237enum InputComposition {}
  238enum SelectedTextHighlight {}
  239
  240#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  241pub enum Navigated {
  242    Yes,
  243    No,
  244}
  245
  246impl Navigated {
  247    pub fn from_bool(yes: bool) -> Navigated {
  248        if yes {
  249            Navigated::Yes
  250        } else {
  251            Navigated::No
  252        }
  253    }
  254}
  255
  256#[derive(Debug, Clone, PartialEq, Eq)]
  257enum DisplayDiffHunk {
  258    Folded {
  259        display_row: DisplayRow,
  260    },
  261    Unfolded {
  262        diff_base_byte_range: Range<usize>,
  263        display_row_range: Range<DisplayRow>,
  264        multi_buffer_range: Range<Anchor>,
  265        status: DiffHunkStatus,
  266    },
  267}
  268
  269pub fn init_settings(cx: &mut App) {
  270    EditorSettings::register(cx);
  271}
  272
  273pub fn init(cx: &mut App) {
  274    init_settings(cx);
  275
  276    workspace::register_project_item::<Editor>(cx);
  277    workspace::FollowableViewRegistry::register::<Editor>(cx);
  278    workspace::register_serializable_item::<Editor>(cx);
  279
  280    cx.observe_new(
  281        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  282            workspace.register_action(Editor::new_file);
  283            workspace.register_action(Editor::new_file_vertical);
  284            workspace.register_action(Editor::new_file_horizontal);
  285            workspace.register_action(Editor::cancel_language_server_work);
  286        },
  287    )
  288    .detach();
  289
  290    cx.on_action(move |_: &workspace::NewFile, cx| {
  291        let app_state = workspace::AppState::global(cx);
  292        if let Some(app_state) = app_state.upgrade() {
  293            workspace::open_new(
  294                Default::default(),
  295                app_state,
  296                cx,
  297                |workspace, window, cx| {
  298                    Editor::new_file(workspace, &Default::default(), window, cx)
  299                },
  300            )
  301            .detach();
  302        }
  303    });
  304    cx.on_action(move |_: &workspace::NewWindow, cx| {
  305        let app_state = workspace::AppState::global(cx);
  306        if let Some(app_state) = app_state.upgrade() {
  307            workspace::open_new(
  308                Default::default(),
  309                app_state,
  310                cx,
  311                |workspace, window, cx| {
  312                    cx.activate(true);
  313                    Editor::new_file(workspace, &Default::default(), window, cx)
  314                },
  315            )
  316            .detach();
  317        }
  318    });
  319}
  320
  321pub struct SearchWithinRange;
  322
  323trait InvalidationRegion {
  324    fn ranges(&self) -> &[Range<Anchor>];
  325}
  326
  327#[derive(Clone, Debug, PartialEq)]
  328pub enum SelectPhase {
  329    Begin {
  330        position: DisplayPoint,
  331        add: bool,
  332        click_count: usize,
  333    },
  334    BeginColumnar {
  335        position: DisplayPoint,
  336        reset: bool,
  337        goal_column: u32,
  338    },
  339    Extend {
  340        position: DisplayPoint,
  341        click_count: usize,
  342    },
  343    Update {
  344        position: DisplayPoint,
  345        goal_column: u32,
  346        scroll_delta: gpui::Point<f32>,
  347    },
  348    End,
  349}
  350
  351#[derive(Clone, Debug)]
  352pub enum SelectMode {
  353    Character,
  354    Word(Range<Anchor>),
  355    Line(Range<Anchor>),
  356    All,
  357}
  358
  359#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  360pub enum EditorMode {
  361    SingleLine { auto_width: bool },
  362    AutoHeight { max_lines: usize },
  363    Full,
  364}
  365
  366#[derive(Copy, Clone, Debug)]
  367pub enum SoftWrap {
  368    /// Prefer not to wrap at all.
  369    ///
  370    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  371    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  372    GitDiff,
  373    /// Prefer a single line generally, unless an overly long line is encountered.
  374    None,
  375    /// Soft wrap lines that exceed the editor width.
  376    EditorWidth,
  377    /// Soft wrap lines at the preferred line length.
  378    Column(u32),
  379    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  380    Bounded(u32),
  381}
  382
  383#[derive(Clone)]
  384pub struct EditorStyle {
  385    pub background: Hsla,
  386    pub local_player: PlayerColor,
  387    pub text: TextStyle,
  388    pub scrollbar_width: Pixels,
  389    pub syntax: Arc<SyntaxTheme>,
  390    pub status: StatusColors,
  391    pub inlay_hints_style: HighlightStyle,
  392    pub inline_completion_styles: InlineCompletionStyles,
  393    pub unnecessary_code_fade: f32,
  394}
  395
  396impl Default for EditorStyle {
  397    fn default() -> Self {
  398        Self {
  399            background: Hsla::default(),
  400            local_player: PlayerColor::default(),
  401            text: TextStyle::default(),
  402            scrollbar_width: Pixels::default(),
  403            syntax: Default::default(),
  404            // HACK: Status colors don't have a real default.
  405            // We should look into removing the status colors from the editor
  406            // style and retrieve them directly from the theme.
  407            status: StatusColors::dark(),
  408            inlay_hints_style: HighlightStyle::default(),
  409            inline_completion_styles: InlineCompletionStyles {
  410                insertion: HighlightStyle::default(),
  411                whitespace: HighlightStyle::default(),
  412            },
  413            unnecessary_code_fade: Default::default(),
  414        }
  415    }
  416}
  417
  418pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  419    let show_background = language_settings::language_settings(None, None, cx)
  420        .inlay_hints
  421        .show_background;
  422
  423    HighlightStyle {
  424        color: Some(cx.theme().status().hint),
  425        background_color: show_background.then(|| cx.theme().status().hint_background),
  426        ..HighlightStyle::default()
  427    }
  428}
  429
  430pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  431    InlineCompletionStyles {
  432        insertion: HighlightStyle {
  433            color: Some(cx.theme().status().predictive),
  434            ..HighlightStyle::default()
  435        },
  436        whitespace: HighlightStyle {
  437            background_color: Some(cx.theme().status().created_background),
  438            ..HighlightStyle::default()
  439        },
  440    }
  441}
  442
  443type CompletionId = usize;
  444
  445pub(crate) enum EditDisplayMode {
  446    TabAccept,
  447    DiffPopover,
  448    Inline,
  449}
  450
  451enum InlineCompletion {
  452    Edit {
  453        edits: Vec<(Range<Anchor>, String)>,
  454        edit_preview: Option<EditPreview>,
  455        display_mode: EditDisplayMode,
  456        snapshot: BufferSnapshot,
  457    },
  458    Move {
  459        target: Anchor,
  460        snapshot: BufferSnapshot,
  461    },
  462}
  463
  464struct InlineCompletionState {
  465    inlay_ids: Vec<InlayId>,
  466    completion: InlineCompletion,
  467    completion_id: Option<SharedString>,
  468    invalidation_range: Range<Anchor>,
  469}
  470
  471enum EditPredictionSettings {
  472    Disabled,
  473    Enabled {
  474        show_in_menu: bool,
  475        preview_requires_modifier: bool,
  476    },
  477}
  478
  479enum InlineCompletionHighlight {}
  480
  481#[derive(Debug, Clone)]
  482struct InlineDiagnostic {
  483    message: SharedString,
  484    group_id: usize,
  485    is_primary: bool,
  486    start: Point,
  487    severity: DiagnosticSeverity,
  488}
  489
  490pub enum MenuInlineCompletionsPolicy {
  491    Never,
  492    ByProvider,
  493}
  494
  495pub enum EditPredictionPreview {
  496    /// Modifier is not pressed
  497    Inactive,
  498    /// Modifier pressed
  499    Active {
  500        previous_scroll_position: Option<ScrollAnchor>,
  501    },
  502}
  503
  504#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  505struct EditorActionId(usize);
  506
  507impl EditorActionId {
  508    pub fn post_inc(&mut self) -> Self {
  509        let answer = self.0;
  510
  511        *self = Self(answer + 1);
  512
  513        Self(answer)
  514    }
  515}
  516
  517// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  518// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  519
  520type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  521type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  522
  523#[derive(Default)]
  524struct ScrollbarMarkerState {
  525    scrollbar_size: Size<Pixels>,
  526    dirty: bool,
  527    markers: Arc<[PaintQuad]>,
  528    pending_refresh: Option<Task<Result<()>>>,
  529}
  530
  531impl ScrollbarMarkerState {
  532    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  533        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  534    }
  535}
  536
  537#[derive(Clone, Debug)]
  538struct RunnableTasks {
  539    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  540    offset: multi_buffer::Anchor,
  541    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  542    column: u32,
  543    // Values of all named captures, including those starting with '_'
  544    extra_variables: HashMap<String, String>,
  545    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  546    context_range: Range<BufferOffset>,
  547}
  548
  549impl RunnableTasks {
  550    fn resolve<'a>(
  551        &'a self,
  552        cx: &'a task::TaskContext,
  553    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  554        self.templates.iter().filter_map(|(kind, template)| {
  555            template
  556                .resolve_task(&kind.to_id_base(), cx)
  557                .map(|task| (kind.clone(), task))
  558        })
  559    }
  560}
  561
  562#[derive(Clone)]
  563struct ResolvedTasks {
  564    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  565    position: Anchor,
  566}
  567#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  568struct BufferOffset(usize);
  569
  570// Addons allow storing per-editor state in other crates (e.g. Vim)
  571pub trait Addon: 'static {
  572    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  573
  574    fn render_buffer_header_controls(
  575        &self,
  576        _: &ExcerptInfo,
  577        _: &Window,
  578        _: &App,
  579    ) -> Option<AnyElement> {
  580        None
  581    }
  582
  583    fn to_any(&self) -> &dyn std::any::Any;
  584}
  585
  586#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  587pub enum IsVimMode {
  588    Yes,
  589    No,
  590}
  591
  592/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  593///
  594/// See the [module level documentation](self) for more information.
  595pub struct Editor {
  596    focus_handle: FocusHandle,
  597    last_focused_descendant: Option<WeakFocusHandle>,
  598    /// The text buffer being edited
  599    buffer: Entity<MultiBuffer>,
  600    /// Map of how text in the buffer should be displayed.
  601    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  602    pub display_map: Entity<DisplayMap>,
  603    pub selections: SelectionsCollection,
  604    pub scroll_manager: ScrollManager,
  605    /// When inline assist editors are linked, they all render cursors because
  606    /// typing enters text into each of them, even the ones that aren't focused.
  607    pub(crate) show_cursor_when_unfocused: bool,
  608    columnar_selection_tail: Option<Anchor>,
  609    add_selections_state: Option<AddSelectionsState>,
  610    select_next_state: Option<SelectNextState>,
  611    select_prev_state: Option<SelectNextState>,
  612    selection_history: SelectionHistory,
  613    autoclose_regions: Vec<AutocloseRegion>,
  614    snippet_stack: InvalidationStack<SnippetState>,
  615    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  616    ime_transaction: Option<TransactionId>,
  617    active_diagnostics: Option<ActiveDiagnosticGroup>,
  618    show_inline_diagnostics: bool,
  619    inline_diagnostics_update: Task<()>,
  620    inline_diagnostics_enabled: bool,
  621    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  622    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  623
  624    // TODO: make this a access method
  625    pub project: Option<Entity<Project>>,
  626    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  627    completion_provider: Option<Box<dyn CompletionProvider>>,
  628    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  629    blink_manager: Entity<BlinkManager>,
  630    show_cursor_names: bool,
  631    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  632    pub show_local_selections: bool,
  633    mode: EditorMode,
  634    show_breadcrumbs: bool,
  635    show_gutter: bool,
  636    show_scrollbars: bool,
  637    show_line_numbers: Option<bool>,
  638    use_relative_line_numbers: Option<bool>,
  639    show_git_diff_gutter: Option<bool>,
  640    show_code_actions: Option<bool>,
  641    show_runnables: Option<bool>,
  642    show_wrap_guides: Option<bool>,
  643    show_indent_guides: Option<bool>,
  644    placeholder_text: Option<Arc<str>>,
  645    highlight_order: usize,
  646    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  647    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  648    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  649    scrollbar_marker_state: ScrollbarMarkerState,
  650    active_indent_guides_state: ActiveIndentGuidesState,
  651    nav_history: Option<ItemNavHistory>,
  652    context_menu: RefCell<Option<CodeContextMenu>>,
  653    mouse_context_menu: Option<MouseContextMenu>,
  654    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  655    signature_help_state: SignatureHelpState,
  656    auto_signature_help: Option<bool>,
  657    find_all_references_task_sources: Vec<Anchor>,
  658    next_completion_id: CompletionId,
  659    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  660    code_actions_task: Option<Task<Result<()>>>,
  661    selection_highlight_task: Option<Task<()>>,
  662    document_highlights_task: Option<Task<()>>,
  663    linked_editing_range_task: Option<Task<Option<()>>>,
  664    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  665    pending_rename: Option<RenameState>,
  666    searchable: bool,
  667    cursor_shape: CursorShape,
  668    current_line_highlight: Option<CurrentLineHighlight>,
  669    collapse_matches: bool,
  670    autoindent_mode: Option<AutoindentMode>,
  671    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  672    input_enabled: bool,
  673    use_modal_editing: bool,
  674    read_only: bool,
  675    leader_peer_id: Option<PeerId>,
  676    remote_id: Option<ViewId>,
  677    hover_state: HoverState,
  678    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  679    gutter_hovered: bool,
  680    hovered_link_state: Option<HoveredLinkState>,
  681    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  682    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  683    active_inline_completion: Option<InlineCompletionState>,
  684    /// Used to prevent flickering as the user types while the menu is open
  685    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  686    edit_prediction_settings: EditPredictionSettings,
  687    inline_completions_hidden_for_vim_mode: bool,
  688    show_inline_completions_override: Option<bool>,
  689    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  690    edit_prediction_preview: EditPredictionPreview,
  691    edit_prediction_indent_conflict: bool,
  692    edit_prediction_requires_modifier_in_indent_conflict: bool,
  693    inlay_hint_cache: InlayHintCache,
  694    next_inlay_id: usize,
  695    _subscriptions: Vec<Subscription>,
  696    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  697    gutter_dimensions: GutterDimensions,
  698    style: Option<EditorStyle>,
  699    text_style_refinement: Option<TextStyleRefinement>,
  700    next_editor_action_id: EditorActionId,
  701    editor_actions:
  702        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  703    use_autoclose: bool,
  704    use_auto_surround: bool,
  705    auto_replace_emoji_shortcode: bool,
  706    show_git_blame_gutter: bool,
  707    show_git_blame_inline: bool,
  708    show_git_blame_inline_delay_task: Option<Task<()>>,
  709    git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
  710    git_blame_inline_enabled: bool,
  711    serialize_dirty_buffers: bool,
  712    show_selection_menu: Option<bool>,
  713    blame: Option<Entity<GitBlame>>,
  714    blame_subscription: Option<Subscription>,
  715    custom_context_menu: Option<
  716        Box<
  717            dyn 'static
  718                + Fn(
  719                    &mut Self,
  720                    DisplayPoint,
  721                    &mut Window,
  722                    &mut Context<Self>,
  723                ) -> Option<Entity<ui::ContextMenu>>,
  724        >,
  725    >,
  726    last_bounds: Option<Bounds<Pixels>>,
  727    last_position_map: Option<Rc<PositionMap>>,
  728    expect_bounds_change: Option<Bounds<Pixels>>,
  729    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  730    tasks_update_task: Option<Task<()>>,
  731    in_project_search: bool,
  732    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  733    breadcrumb_header: Option<String>,
  734    focused_block: Option<FocusedBlock>,
  735    next_scroll_position: NextScrollCursorCenterTopBottom,
  736    addons: HashMap<TypeId, Box<dyn Addon>>,
  737    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  738    load_diff_task: Option<Shared<Task<()>>>,
  739    selection_mark_mode: bool,
  740    toggle_fold_multiple_buffers: Task<()>,
  741    _scroll_cursor_center_top_bottom_task: Task<()>,
  742    serialize_selections: Task<()>,
  743}
  744
  745#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  746enum NextScrollCursorCenterTopBottom {
  747    #[default]
  748    Center,
  749    Top,
  750    Bottom,
  751}
  752
  753impl NextScrollCursorCenterTopBottom {
  754    fn next(&self) -> Self {
  755        match self {
  756            Self::Center => Self::Top,
  757            Self::Top => Self::Bottom,
  758            Self::Bottom => Self::Center,
  759        }
  760    }
  761}
  762
  763#[derive(Clone)]
  764pub struct EditorSnapshot {
  765    pub mode: EditorMode,
  766    show_gutter: bool,
  767    show_line_numbers: Option<bool>,
  768    show_git_diff_gutter: Option<bool>,
  769    show_code_actions: Option<bool>,
  770    show_runnables: Option<bool>,
  771    git_blame_gutter_max_author_length: Option<usize>,
  772    pub display_snapshot: DisplaySnapshot,
  773    pub placeholder_text: Option<Arc<str>>,
  774    is_focused: bool,
  775    scroll_anchor: ScrollAnchor,
  776    ongoing_scroll: OngoingScroll,
  777    current_line_highlight: CurrentLineHighlight,
  778    gutter_hovered: bool,
  779}
  780
  781const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  782
  783#[derive(Default, Debug, Clone, Copy)]
  784pub struct GutterDimensions {
  785    pub left_padding: Pixels,
  786    pub right_padding: Pixels,
  787    pub width: Pixels,
  788    pub margin: Pixels,
  789    pub git_blame_entries_width: Option<Pixels>,
  790}
  791
  792impl GutterDimensions {
  793    /// The full width of the space taken up by the gutter.
  794    pub fn full_width(&self) -> Pixels {
  795        self.margin + self.width
  796    }
  797
  798    /// The width of the space reserved for the fold indicators,
  799    /// use alongside 'justify_end' and `gutter_width` to
  800    /// right align content with the line numbers
  801    pub fn fold_area_width(&self) -> Pixels {
  802        self.margin + self.right_padding
  803    }
  804}
  805
  806#[derive(Debug)]
  807pub struct RemoteSelection {
  808    pub replica_id: ReplicaId,
  809    pub selection: Selection<Anchor>,
  810    pub cursor_shape: CursorShape,
  811    pub peer_id: PeerId,
  812    pub line_mode: bool,
  813    pub participant_index: Option<ParticipantIndex>,
  814    pub user_name: Option<SharedString>,
  815}
  816
  817#[derive(Clone, Debug)]
  818struct SelectionHistoryEntry {
  819    selections: Arc<[Selection<Anchor>]>,
  820    select_next_state: Option<SelectNextState>,
  821    select_prev_state: Option<SelectNextState>,
  822    add_selections_state: Option<AddSelectionsState>,
  823}
  824
  825enum SelectionHistoryMode {
  826    Normal,
  827    Undoing,
  828    Redoing,
  829}
  830
  831#[derive(Clone, PartialEq, Eq, Hash)]
  832struct HoveredCursor {
  833    replica_id: u16,
  834    selection_id: usize,
  835}
  836
  837impl Default for SelectionHistoryMode {
  838    fn default() -> Self {
  839        Self::Normal
  840    }
  841}
  842
  843#[derive(Default)]
  844struct SelectionHistory {
  845    #[allow(clippy::type_complexity)]
  846    selections_by_transaction:
  847        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  848    mode: SelectionHistoryMode,
  849    undo_stack: VecDeque<SelectionHistoryEntry>,
  850    redo_stack: VecDeque<SelectionHistoryEntry>,
  851}
  852
  853impl SelectionHistory {
  854    fn insert_transaction(
  855        &mut self,
  856        transaction_id: TransactionId,
  857        selections: Arc<[Selection<Anchor>]>,
  858    ) {
  859        self.selections_by_transaction
  860            .insert(transaction_id, (selections, None));
  861    }
  862
  863    #[allow(clippy::type_complexity)]
  864    fn transaction(
  865        &self,
  866        transaction_id: TransactionId,
  867    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  868        self.selections_by_transaction.get(&transaction_id)
  869    }
  870
  871    #[allow(clippy::type_complexity)]
  872    fn transaction_mut(
  873        &mut self,
  874        transaction_id: TransactionId,
  875    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  876        self.selections_by_transaction.get_mut(&transaction_id)
  877    }
  878
  879    fn push(&mut self, entry: SelectionHistoryEntry) {
  880        if !entry.selections.is_empty() {
  881            match self.mode {
  882                SelectionHistoryMode::Normal => {
  883                    self.push_undo(entry);
  884                    self.redo_stack.clear();
  885                }
  886                SelectionHistoryMode::Undoing => self.push_redo(entry),
  887                SelectionHistoryMode::Redoing => self.push_undo(entry),
  888            }
  889        }
  890    }
  891
  892    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  893        if self
  894            .undo_stack
  895            .back()
  896            .map_or(true, |e| e.selections != entry.selections)
  897        {
  898            self.undo_stack.push_back(entry);
  899            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  900                self.undo_stack.pop_front();
  901            }
  902        }
  903    }
  904
  905    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  906        if self
  907            .redo_stack
  908            .back()
  909            .map_or(true, |e| e.selections != entry.selections)
  910        {
  911            self.redo_stack.push_back(entry);
  912            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  913                self.redo_stack.pop_front();
  914            }
  915        }
  916    }
  917}
  918
  919struct RowHighlight {
  920    index: usize,
  921    range: Range<Anchor>,
  922    color: Hsla,
  923    should_autoscroll: bool,
  924}
  925
  926#[derive(Clone, Debug)]
  927struct AddSelectionsState {
  928    above: bool,
  929    stack: Vec<usize>,
  930}
  931
  932#[derive(Clone)]
  933struct SelectNextState {
  934    query: AhoCorasick,
  935    wordwise: bool,
  936    done: bool,
  937}
  938
  939impl std::fmt::Debug for SelectNextState {
  940    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  941        f.debug_struct(std::any::type_name::<Self>())
  942            .field("wordwise", &self.wordwise)
  943            .field("done", &self.done)
  944            .finish()
  945    }
  946}
  947
  948#[derive(Debug)]
  949struct AutocloseRegion {
  950    selection_id: usize,
  951    range: Range<Anchor>,
  952    pair: BracketPair,
  953}
  954
  955#[derive(Debug)]
  956struct SnippetState {
  957    ranges: Vec<Vec<Range<Anchor>>>,
  958    active_index: usize,
  959    choices: Vec<Option<Vec<String>>>,
  960}
  961
  962#[doc(hidden)]
  963pub struct RenameState {
  964    pub range: Range<Anchor>,
  965    pub old_name: Arc<str>,
  966    pub editor: Entity<Editor>,
  967    block_id: CustomBlockId,
  968}
  969
  970struct InvalidationStack<T>(Vec<T>);
  971
  972struct RegisteredInlineCompletionProvider {
  973    provider: Arc<dyn InlineCompletionProviderHandle>,
  974    _subscription: Subscription,
  975}
  976
  977#[derive(Debug)]
  978struct ActiveDiagnosticGroup {
  979    primary_range: Range<Anchor>,
  980    primary_message: String,
  981    group_id: usize,
  982    blocks: HashMap<CustomBlockId, Diagnostic>,
  983    is_valid: bool,
  984}
  985
  986#[derive(Serialize, Deserialize, Clone, Debug)]
  987pub struct ClipboardSelection {
  988    /// The number of bytes in this selection.
  989    pub len: usize,
  990    /// Whether this was a full-line selection.
  991    pub is_entire_line: bool,
  992    /// The column where this selection originally started.
  993    pub start_column: u32,
  994}
  995
  996#[derive(Debug)]
  997pub(crate) struct NavigationData {
  998    cursor_anchor: Anchor,
  999    cursor_position: Point,
 1000    scroll_anchor: ScrollAnchor,
 1001    scroll_top_row: u32,
 1002}
 1003
 1004#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1005pub enum GotoDefinitionKind {
 1006    Symbol,
 1007    Declaration,
 1008    Type,
 1009    Implementation,
 1010}
 1011
 1012#[derive(Debug, Clone)]
 1013enum InlayHintRefreshReason {
 1014    Toggle(bool),
 1015    SettingsChange(InlayHintSettings),
 1016    NewLinesShown,
 1017    BufferEdited(HashSet<Arc<Language>>),
 1018    RefreshRequested,
 1019    ExcerptsRemoved(Vec<ExcerptId>),
 1020}
 1021
 1022impl InlayHintRefreshReason {
 1023    fn description(&self) -> &'static str {
 1024        match self {
 1025            Self::Toggle(_) => "toggle",
 1026            Self::SettingsChange(_) => "settings change",
 1027            Self::NewLinesShown => "new lines shown",
 1028            Self::BufferEdited(_) => "buffer edited",
 1029            Self::RefreshRequested => "refresh requested",
 1030            Self::ExcerptsRemoved(_) => "excerpts removed",
 1031        }
 1032    }
 1033}
 1034
 1035pub enum FormatTarget {
 1036    Buffers,
 1037    Ranges(Vec<Range<MultiBufferPoint>>),
 1038}
 1039
 1040pub(crate) struct FocusedBlock {
 1041    id: BlockId,
 1042    focus_handle: WeakFocusHandle,
 1043}
 1044
 1045#[derive(Clone)]
 1046enum JumpData {
 1047    MultiBufferRow {
 1048        row: MultiBufferRow,
 1049        line_offset_from_top: u32,
 1050    },
 1051    MultiBufferPoint {
 1052        excerpt_id: ExcerptId,
 1053        position: Point,
 1054        anchor: text::Anchor,
 1055        line_offset_from_top: u32,
 1056    },
 1057}
 1058
 1059pub enum MultibufferSelectionMode {
 1060    First,
 1061    All,
 1062}
 1063
 1064impl Editor {
 1065    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1066        let buffer = cx.new(|cx| Buffer::local("", cx));
 1067        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1068        Self::new(
 1069            EditorMode::SingleLine { auto_width: false },
 1070            buffer,
 1071            None,
 1072            false,
 1073            window,
 1074            cx,
 1075        )
 1076    }
 1077
 1078    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1079        let buffer = cx.new(|cx| Buffer::local("", cx));
 1080        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1081        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1082    }
 1083
 1084    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1085        let buffer = cx.new(|cx| Buffer::local("", cx));
 1086        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1087        Self::new(
 1088            EditorMode::SingleLine { auto_width: true },
 1089            buffer,
 1090            None,
 1091            false,
 1092            window,
 1093            cx,
 1094        )
 1095    }
 1096
 1097    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1098        let buffer = cx.new(|cx| Buffer::local("", cx));
 1099        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1100        Self::new(
 1101            EditorMode::AutoHeight { max_lines },
 1102            buffer,
 1103            None,
 1104            false,
 1105            window,
 1106            cx,
 1107        )
 1108    }
 1109
 1110    pub fn for_buffer(
 1111        buffer: Entity<Buffer>,
 1112        project: Option<Entity<Project>>,
 1113        window: &mut Window,
 1114        cx: &mut Context<Self>,
 1115    ) -> Self {
 1116        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1117        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1118    }
 1119
 1120    pub fn for_multibuffer(
 1121        buffer: Entity<MultiBuffer>,
 1122        project: Option<Entity<Project>>,
 1123        show_excerpt_controls: bool,
 1124        window: &mut Window,
 1125        cx: &mut Context<Self>,
 1126    ) -> Self {
 1127        Self::new(
 1128            EditorMode::Full,
 1129            buffer,
 1130            project,
 1131            show_excerpt_controls,
 1132            window,
 1133            cx,
 1134        )
 1135    }
 1136
 1137    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1138        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1139        let mut clone = Self::new(
 1140            self.mode,
 1141            self.buffer.clone(),
 1142            self.project.clone(),
 1143            show_excerpt_controls,
 1144            window,
 1145            cx,
 1146        );
 1147        self.display_map.update(cx, |display_map, cx| {
 1148            let snapshot = display_map.snapshot(cx);
 1149            clone.display_map.update(cx, |display_map, cx| {
 1150                display_map.set_state(&snapshot, cx);
 1151            });
 1152        });
 1153        clone.selections.clone_state(&self.selections);
 1154        clone.scroll_manager.clone_state(&self.scroll_manager);
 1155        clone.searchable = self.searchable;
 1156        clone
 1157    }
 1158
 1159    pub fn new(
 1160        mode: EditorMode,
 1161        buffer: Entity<MultiBuffer>,
 1162        project: Option<Entity<Project>>,
 1163        show_excerpt_controls: bool,
 1164        window: &mut Window,
 1165        cx: &mut Context<Self>,
 1166    ) -> Self {
 1167        let style = window.text_style();
 1168        let font_size = style.font_size.to_pixels(window.rem_size());
 1169        let editor = cx.entity().downgrade();
 1170        let fold_placeholder = FoldPlaceholder {
 1171            constrain_width: true,
 1172            render: Arc::new(move |fold_id, fold_range, cx| {
 1173                let editor = editor.clone();
 1174                div()
 1175                    .id(fold_id)
 1176                    .bg(cx.theme().colors().ghost_element_background)
 1177                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1178                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1179                    .rounded_sm()
 1180                    .size_full()
 1181                    .cursor_pointer()
 1182                    .child("")
 1183                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1184                    .on_click(move |_, _window, cx| {
 1185                        editor
 1186                            .update(cx, |editor, cx| {
 1187                                editor.unfold_ranges(
 1188                                    &[fold_range.start..fold_range.end],
 1189                                    true,
 1190                                    false,
 1191                                    cx,
 1192                                );
 1193                                cx.stop_propagation();
 1194                            })
 1195                            .ok();
 1196                    })
 1197                    .into_any()
 1198            }),
 1199            merge_adjacent: true,
 1200            ..Default::default()
 1201        };
 1202        let display_map = cx.new(|cx| {
 1203            DisplayMap::new(
 1204                buffer.clone(),
 1205                style.font(),
 1206                font_size,
 1207                None,
 1208                show_excerpt_controls,
 1209                FILE_HEADER_HEIGHT,
 1210                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1211                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1212                fold_placeholder,
 1213                cx,
 1214            )
 1215        });
 1216
 1217        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1218
 1219        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1220
 1221        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1222            .then(|| language_settings::SoftWrap::None);
 1223
 1224        let mut project_subscriptions = Vec::new();
 1225        if mode == EditorMode::Full {
 1226            if let Some(project) = project.as_ref() {
 1227                if buffer.read(cx).is_singleton() {
 1228                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1229                        cx.emit(EditorEvent::TitleChanged);
 1230                    }));
 1231                }
 1232                project_subscriptions.push(cx.subscribe_in(
 1233                    project,
 1234                    window,
 1235                    |editor, _, event, window, cx| {
 1236                        if let project::Event::RefreshInlayHints = event {
 1237                            editor
 1238                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1239                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1240                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1241                                let focus_handle = editor.focus_handle(cx);
 1242                                if focus_handle.is_focused(window) {
 1243                                    let snapshot = buffer.read(cx).snapshot();
 1244                                    for (range, snippet) in snippet_edits {
 1245                                        let editor_range =
 1246                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1247                                        editor
 1248                                            .insert_snippet(
 1249                                                &[editor_range],
 1250                                                snippet.clone(),
 1251                                                window,
 1252                                                cx,
 1253                                            )
 1254                                            .ok();
 1255                                    }
 1256                                }
 1257                            }
 1258                        }
 1259                    },
 1260                ));
 1261                if let Some(task_inventory) = project
 1262                    .read(cx)
 1263                    .task_store()
 1264                    .read(cx)
 1265                    .task_inventory()
 1266                    .cloned()
 1267                {
 1268                    project_subscriptions.push(cx.observe_in(
 1269                        &task_inventory,
 1270                        window,
 1271                        |editor, _, window, cx| {
 1272                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1273                        },
 1274                    ));
 1275                }
 1276            }
 1277        }
 1278
 1279        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1280
 1281        let inlay_hint_settings =
 1282            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1283        let focus_handle = cx.focus_handle();
 1284        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1285            .detach();
 1286        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1287            .detach();
 1288        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1289            .detach();
 1290        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1291            .detach();
 1292
 1293        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1294            Some(false)
 1295        } else {
 1296            None
 1297        };
 1298
 1299        let mut code_action_providers = Vec::new();
 1300        let mut load_uncommitted_diff = None;
 1301        if let Some(project) = project.clone() {
 1302            load_uncommitted_diff = Some(
 1303                get_uncommitted_diff_for_buffer(
 1304                    &project,
 1305                    buffer.read(cx).all_buffers(),
 1306                    buffer.clone(),
 1307                    cx,
 1308                )
 1309                .shared(),
 1310            );
 1311            code_action_providers.push(Rc::new(project) as Rc<_>);
 1312        }
 1313
 1314        let mut this = Self {
 1315            focus_handle,
 1316            show_cursor_when_unfocused: false,
 1317            last_focused_descendant: None,
 1318            buffer: buffer.clone(),
 1319            display_map: display_map.clone(),
 1320            selections,
 1321            scroll_manager: ScrollManager::new(cx),
 1322            columnar_selection_tail: None,
 1323            add_selections_state: None,
 1324            select_next_state: None,
 1325            select_prev_state: None,
 1326            selection_history: Default::default(),
 1327            autoclose_regions: Default::default(),
 1328            snippet_stack: Default::default(),
 1329            select_larger_syntax_node_stack: Vec::new(),
 1330            ime_transaction: Default::default(),
 1331            active_diagnostics: None,
 1332            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1333            inline_diagnostics_update: Task::ready(()),
 1334            inline_diagnostics: Vec::new(),
 1335            soft_wrap_mode_override,
 1336            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1337            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1338            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1339            project,
 1340            blink_manager: blink_manager.clone(),
 1341            show_local_selections: true,
 1342            show_scrollbars: true,
 1343            mode,
 1344            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1345            show_gutter: mode == EditorMode::Full,
 1346            show_line_numbers: None,
 1347            use_relative_line_numbers: None,
 1348            show_git_diff_gutter: None,
 1349            show_code_actions: None,
 1350            show_runnables: None,
 1351            show_wrap_guides: None,
 1352            show_indent_guides,
 1353            placeholder_text: None,
 1354            highlight_order: 0,
 1355            highlighted_rows: HashMap::default(),
 1356            background_highlights: Default::default(),
 1357            gutter_highlights: TreeMap::default(),
 1358            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1359            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1360            nav_history: None,
 1361            context_menu: RefCell::new(None),
 1362            mouse_context_menu: None,
 1363            completion_tasks: Default::default(),
 1364            signature_help_state: SignatureHelpState::default(),
 1365            auto_signature_help: None,
 1366            find_all_references_task_sources: Vec::new(),
 1367            next_completion_id: 0,
 1368            next_inlay_id: 0,
 1369            code_action_providers,
 1370            available_code_actions: Default::default(),
 1371            code_actions_task: Default::default(),
 1372            selection_highlight_task: Default::default(),
 1373            document_highlights_task: Default::default(),
 1374            linked_editing_range_task: Default::default(),
 1375            pending_rename: Default::default(),
 1376            searchable: true,
 1377            cursor_shape: EditorSettings::get_global(cx)
 1378                .cursor_shape
 1379                .unwrap_or_default(),
 1380            current_line_highlight: None,
 1381            autoindent_mode: Some(AutoindentMode::EachLine),
 1382            collapse_matches: false,
 1383            workspace: None,
 1384            input_enabled: true,
 1385            use_modal_editing: mode == EditorMode::Full,
 1386            read_only: false,
 1387            use_autoclose: true,
 1388            use_auto_surround: true,
 1389            auto_replace_emoji_shortcode: false,
 1390            leader_peer_id: None,
 1391            remote_id: None,
 1392            hover_state: Default::default(),
 1393            pending_mouse_down: None,
 1394            hovered_link_state: Default::default(),
 1395            edit_prediction_provider: None,
 1396            active_inline_completion: None,
 1397            stale_inline_completion_in_menu: None,
 1398            edit_prediction_preview: EditPredictionPreview::Inactive,
 1399            inline_diagnostics_enabled: mode == EditorMode::Full,
 1400            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1401
 1402            gutter_hovered: false,
 1403            pixel_position_of_newest_cursor: None,
 1404            last_bounds: None,
 1405            last_position_map: None,
 1406            expect_bounds_change: None,
 1407            gutter_dimensions: GutterDimensions::default(),
 1408            style: None,
 1409            show_cursor_names: false,
 1410            hovered_cursors: Default::default(),
 1411            next_editor_action_id: EditorActionId::default(),
 1412            editor_actions: Rc::default(),
 1413            inline_completions_hidden_for_vim_mode: false,
 1414            show_inline_completions_override: None,
 1415            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1416            edit_prediction_settings: EditPredictionSettings::Disabled,
 1417            edit_prediction_indent_conflict: false,
 1418            edit_prediction_requires_modifier_in_indent_conflict: true,
 1419            custom_context_menu: None,
 1420            show_git_blame_gutter: false,
 1421            show_git_blame_inline: false,
 1422            show_selection_menu: None,
 1423            show_git_blame_inline_delay_task: None,
 1424            git_blame_inline_tooltip: None,
 1425            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1426            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1427                .session
 1428                .restore_unsaved_buffers,
 1429            blame: None,
 1430            blame_subscription: None,
 1431            tasks: Default::default(),
 1432            _subscriptions: vec![
 1433                cx.observe(&buffer, Self::on_buffer_changed),
 1434                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1435                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1436                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1437                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1438                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1439                cx.observe_window_activation(window, |editor, window, cx| {
 1440                    let active = window.is_window_active();
 1441                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1442                        if active {
 1443                            blink_manager.enable(cx);
 1444                        } else {
 1445                            blink_manager.disable(cx);
 1446                        }
 1447                    });
 1448                }),
 1449            ],
 1450            tasks_update_task: None,
 1451            linked_edit_ranges: Default::default(),
 1452            in_project_search: false,
 1453            previous_search_ranges: None,
 1454            breadcrumb_header: None,
 1455            focused_block: None,
 1456            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1457            addons: HashMap::default(),
 1458            registered_buffers: HashMap::default(),
 1459            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1460            selection_mark_mode: false,
 1461            toggle_fold_multiple_buffers: Task::ready(()),
 1462            serialize_selections: Task::ready(()),
 1463            text_style_refinement: None,
 1464            load_diff_task: load_uncommitted_diff,
 1465        };
 1466        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1467        this._subscriptions.extend(project_subscriptions);
 1468
 1469        this.end_selection(window, cx);
 1470        this.scroll_manager.show_scrollbar(window, cx);
 1471
 1472        if mode == EditorMode::Full {
 1473            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1474            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1475
 1476            if this.git_blame_inline_enabled {
 1477                this.git_blame_inline_enabled = true;
 1478                this.start_git_blame_inline(false, window, cx);
 1479            }
 1480
 1481            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1482                if let Some(project) = this.project.as_ref() {
 1483                    let handle = project.update(cx, |project, cx| {
 1484                        project.register_buffer_with_language_servers(&buffer, cx)
 1485                    });
 1486                    this.registered_buffers
 1487                        .insert(buffer.read(cx).remote_id(), handle);
 1488                }
 1489            }
 1490        }
 1491
 1492        this.report_editor_event("Editor Opened", None, cx);
 1493        this
 1494    }
 1495
 1496    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1497        self.mouse_context_menu
 1498            .as_ref()
 1499            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1500    }
 1501
 1502    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1503        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1504    }
 1505
 1506    fn key_context_internal(
 1507        &self,
 1508        has_active_edit_prediction: bool,
 1509        window: &Window,
 1510        cx: &App,
 1511    ) -> KeyContext {
 1512        let mut key_context = KeyContext::new_with_defaults();
 1513        key_context.add("Editor");
 1514        let mode = match self.mode {
 1515            EditorMode::SingleLine { .. } => "single_line",
 1516            EditorMode::AutoHeight { .. } => "auto_height",
 1517            EditorMode::Full => "full",
 1518        };
 1519
 1520        if EditorSettings::jupyter_enabled(cx) {
 1521            key_context.add("jupyter");
 1522        }
 1523
 1524        key_context.set("mode", mode);
 1525        if self.pending_rename.is_some() {
 1526            key_context.add("renaming");
 1527        }
 1528
 1529        match self.context_menu.borrow().as_ref() {
 1530            Some(CodeContextMenu::Completions(_)) => {
 1531                key_context.add("menu");
 1532                key_context.add("showing_completions");
 1533            }
 1534            Some(CodeContextMenu::CodeActions(_)) => {
 1535                key_context.add("menu");
 1536                key_context.add("showing_code_actions")
 1537            }
 1538            None => {}
 1539        }
 1540
 1541        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1542        if !self.focus_handle(cx).contains_focused(window, cx)
 1543            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1544        {
 1545            for addon in self.addons.values() {
 1546                addon.extend_key_context(&mut key_context, cx)
 1547            }
 1548        }
 1549
 1550        if let Some(extension) = self
 1551            .buffer
 1552            .read(cx)
 1553            .as_singleton()
 1554            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1555        {
 1556            key_context.set("extension", extension.to_string());
 1557        }
 1558
 1559        if has_active_edit_prediction {
 1560            if self.edit_prediction_in_conflict() {
 1561                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1562            } else {
 1563                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1564                key_context.add("copilot_suggestion");
 1565            }
 1566        }
 1567
 1568        if self.selection_mark_mode {
 1569            key_context.add("selection_mode");
 1570        }
 1571
 1572        key_context
 1573    }
 1574
 1575    pub fn edit_prediction_in_conflict(&self) -> bool {
 1576        if !self.show_edit_predictions_in_menu() {
 1577            return false;
 1578        }
 1579
 1580        let showing_completions = self
 1581            .context_menu
 1582            .borrow()
 1583            .as_ref()
 1584            .map_or(false, |context| {
 1585                matches!(context, CodeContextMenu::Completions(_))
 1586            });
 1587
 1588        showing_completions
 1589            || self.edit_prediction_requires_modifier()
 1590            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1591            // bindings to insert tab characters.
 1592            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1593    }
 1594
 1595    pub fn accept_edit_prediction_keybind(
 1596        &self,
 1597        window: &Window,
 1598        cx: &App,
 1599    ) -> AcceptEditPredictionBinding {
 1600        let key_context = self.key_context_internal(true, window, cx);
 1601        let in_conflict = self.edit_prediction_in_conflict();
 1602
 1603        AcceptEditPredictionBinding(
 1604            window
 1605                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1606                .into_iter()
 1607                .filter(|binding| {
 1608                    !in_conflict
 1609                        || binding
 1610                            .keystrokes()
 1611                            .first()
 1612                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1613                })
 1614                .rev()
 1615                .min_by_key(|binding| {
 1616                    binding
 1617                        .keystrokes()
 1618                        .first()
 1619                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1620                }),
 1621        )
 1622    }
 1623
 1624    pub fn new_file(
 1625        workspace: &mut Workspace,
 1626        _: &workspace::NewFile,
 1627        window: &mut Window,
 1628        cx: &mut Context<Workspace>,
 1629    ) {
 1630        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1631            "Failed to create buffer",
 1632            window,
 1633            cx,
 1634            |e, _, _| match e.error_code() {
 1635                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1636                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1637                e.error_tag("required").unwrap_or("the latest version")
 1638            )),
 1639                _ => None,
 1640            },
 1641        );
 1642    }
 1643
 1644    pub fn new_in_workspace(
 1645        workspace: &mut Workspace,
 1646        window: &mut Window,
 1647        cx: &mut Context<Workspace>,
 1648    ) -> Task<Result<Entity<Editor>>> {
 1649        let project = workspace.project().clone();
 1650        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1651
 1652        cx.spawn_in(window, |workspace, mut cx| async move {
 1653            let buffer = create.await?;
 1654            workspace.update_in(&mut cx, |workspace, window, cx| {
 1655                let editor =
 1656                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1657                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1658                editor
 1659            })
 1660        })
 1661    }
 1662
 1663    fn new_file_vertical(
 1664        workspace: &mut Workspace,
 1665        _: &workspace::NewFileSplitVertical,
 1666        window: &mut Window,
 1667        cx: &mut Context<Workspace>,
 1668    ) {
 1669        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1670    }
 1671
 1672    fn new_file_horizontal(
 1673        workspace: &mut Workspace,
 1674        _: &workspace::NewFileSplitHorizontal,
 1675        window: &mut Window,
 1676        cx: &mut Context<Workspace>,
 1677    ) {
 1678        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1679    }
 1680
 1681    fn new_file_in_direction(
 1682        workspace: &mut Workspace,
 1683        direction: SplitDirection,
 1684        window: &mut Window,
 1685        cx: &mut Context<Workspace>,
 1686    ) {
 1687        let project = workspace.project().clone();
 1688        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1689
 1690        cx.spawn_in(window, |workspace, mut cx| async move {
 1691            let buffer = create.await?;
 1692            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1693                workspace.split_item(
 1694                    direction,
 1695                    Box::new(
 1696                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1697                    ),
 1698                    window,
 1699                    cx,
 1700                )
 1701            })?;
 1702            anyhow::Ok(())
 1703        })
 1704        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1705            match e.error_code() {
 1706                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1707                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1708                e.error_tag("required").unwrap_or("the latest version")
 1709            )),
 1710                _ => None,
 1711            }
 1712        });
 1713    }
 1714
 1715    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1716        self.leader_peer_id
 1717    }
 1718
 1719    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1720        &self.buffer
 1721    }
 1722
 1723    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1724        self.workspace.as_ref()?.0.upgrade()
 1725    }
 1726
 1727    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1728        self.buffer().read(cx).title(cx)
 1729    }
 1730
 1731    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1732        let git_blame_gutter_max_author_length = self
 1733            .render_git_blame_gutter(cx)
 1734            .then(|| {
 1735                if let Some(blame) = self.blame.as_ref() {
 1736                    let max_author_length =
 1737                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1738                    Some(max_author_length)
 1739                } else {
 1740                    None
 1741                }
 1742            })
 1743            .flatten();
 1744
 1745        EditorSnapshot {
 1746            mode: self.mode,
 1747            show_gutter: self.show_gutter,
 1748            show_line_numbers: self.show_line_numbers,
 1749            show_git_diff_gutter: self.show_git_diff_gutter,
 1750            show_code_actions: self.show_code_actions,
 1751            show_runnables: self.show_runnables,
 1752            git_blame_gutter_max_author_length,
 1753            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1754            scroll_anchor: self.scroll_manager.anchor(),
 1755            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1756            placeholder_text: self.placeholder_text.clone(),
 1757            is_focused: self.focus_handle.is_focused(window),
 1758            current_line_highlight: self
 1759                .current_line_highlight
 1760                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1761            gutter_hovered: self.gutter_hovered,
 1762        }
 1763    }
 1764
 1765    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1766        self.buffer.read(cx).language_at(point, cx)
 1767    }
 1768
 1769    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1770        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1771    }
 1772
 1773    pub fn active_excerpt(
 1774        &self,
 1775        cx: &App,
 1776    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1777        self.buffer
 1778            .read(cx)
 1779            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1780    }
 1781
 1782    pub fn mode(&self) -> EditorMode {
 1783        self.mode
 1784    }
 1785
 1786    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1787        self.collaboration_hub.as_deref()
 1788    }
 1789
 1790    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1791        self.collaboration_hub = Some(hub);
 1792    }
 1793
 1794    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1795        self.in_project_search = in_project_search;
 1796    }
 1797
 1798    pub fn set_custom_context_menu(
 1799        &mut self,
 1800        f: impl 'static
 1801            + Fn(
 1802                &mut Self,
 1803                DisplayPoint,
 1804                &mut Window,
 1805                &mut Context<Self>,
 1806            ) -> Option<Entity<ui::ContextMenu>>,
 1807    ) {
 1808        self.custom_context_menu = Some(Box::new(f))
 1809    }
 1810
 1811    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1812        self.completion_provider = provider;
 1813    }
 1814
 1815    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1816        self.semantics_provider.clone()
 1817    }
 1818
 1819    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1820        self.semantics_provider = provider;
 1821    }
 1822
 1823    pub fn set_edit_prediction_provider<T>(
 1824        &mut self,
 1825        provider: Option<Entity<T>>,
 1826        window: &mut Window,
 1827        cx: &mut Context<Self>,
 1828    ) where
 1829        T: EditPredictionProvider,
 1830    {
 1831        self.edit_prediction_provider =
 1832            provider.map(|provider| RegisteredInlineCompletionProvider {
 1833                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1834                    if this.focus_handle.is_focused(window) {
 1835                        this.update_visible_inline_completion(window, cx);
 1836                    }
 1837                }),
 1838                provider: Arc::new(provider),
 1839            });
 1840        self.update_edit_prediction_settings(cx);
 1841        self.refresh_inline_completion(false, false, window, cx);
 1842    }
 1843
 1844    pub fn placeholder_text(&self) -> Option<&str> {
 1845        self.placeholder_text.as_deref()
 1846    }
 1847
 1848    pub fn set_placeholder_text(
 1849        &mut self,
 1850        placeholder_text: impl Into<Arc<str>>,
 1851        cx: &mut Context<Self>,
 1852    ) {
 1853        let placeholder_text = Some(placeholder_text.into());
 1854        if self.placeholder_text != placeholder_text {
 1855            self.placeholder_text = placeholder_text;
 1856            cx.notify();
 1857        }
 1858    }
 1859
 1860    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1861        self.cursor_shape = cursor_shape;
 1862
 1863        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1864        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1865
 1866        cx.notify();
 1867    }
 1868
 1869    pub fn set_current_line_highlight(
 1870        &mut self,
 1871        current_line_highlight: Option<CurrentLineHighlight>,
 1872    ) {
 1873        self.current_line_highlight = current_line_highlight;
 1874    }
 1875
 1876    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1877        self.collapse_matches = collapse_matches;
 1878    }
 1879
 1880    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1881        let buffers = self.buffer.read(cx).all_buffers();
 1882        let Some(project) = self.project.as_ref() else {
 1883            return;
 1884        };
 1885        project.update(cx, |project, cx| {
 1886            for buffer in buffers {
 1887                self.registered_buffers
 1888                    .entry(buffer.read(cx).remote_id())
 1889                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1890            }
 1891        })
 1892    }
 1893
 1894    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1895        if self.collapse_matches {
 1896            return range.start..range.start;
 1897        }
 1898        range.clone()
 1899    }
 1900
 1901    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1902        if self.display_map.read(cx).clip_at_line_ends != clip {
 1903            self.display_map
 1904                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1905        }
 1906    }
 1907
 1908    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1909        self.input_enabled = input_enabled;
 1910    }
 1911
 1912    pub fn set_inline_completions_hidden_for_vim_mode(
 1913        &mut self,
 1914        hidden: bool,
 1915        window: &mut Window,
 1916        cx: &mut Context<Self>,
 1917    ) {
 1918        if hidden != self.inline_completions_hidden_for_vim_mode {
 1919            self.inline_completions_hidden_for_vim_mode = hidden;
 1920            if hidden {
 1921                self.update_visible_inline_completion(window, cx);
 1922            } else {
 1923                self.refresh_inline_completion(true, false, window, cx);
 1924            }
 1925        }
 1926    }
 1927
 1928    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1929        self.menu_inline_completions_policy = value;
 1930    }
 1931
 1932    pub fn set_autoindent(&mut self, autoindent: bool) {
 1933        if autoindent {
 1934            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1935        } else {
 1936            self.autoindent_mode = None;
 1937        }
 1938    }
 1939
 1940    pub fn read_only(&self, cx: &App) -> bool {
 1941        self.read_only || self.buffer.read(cx).read_only()
 1942    }
 1943
 1944    pub fn set_read_only(&mut self, read_only: bool) {
 1945        self.read_only = read_only;
 1946    }
 1947
 1948    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1949        self.use_autoclose = autoclose;
 1950    }
 1951
 1952    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1953        self.use_auto_surround = auto_surround;
 1954    }
 1955
 1956    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1957        self.auto_replace_emoji_shortcode = auto_replace;
 1958    }
 1959
 1960    pub fn toggle_edit_predictions(
 1961        &mut self,
 1962        _: &ToggleEditPrediction,
 1963        window: &mut Window,
 1964        cx: &mut Context<Self>,
 1965    ) {
 1966        if self.show_inline_completions_override.is_some() {
 1967            self.set_show_edit_predictions(None, window, cx);
 1968        } else {
 1969            let show_edit_predictions = !self.edit_predictions_enabled();
 1970            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1971        }
 1972    }
 1973
 1974    pub fn set_show_edit_predictions(
 1975        &mut self,
 1976        show_edit_predictions: Option<bool>,
 1977        window: &mut Window,
 1978        cx: &mut Context<Self>,
 1979    ) {
 1980        self.show_inline_completions_override = show_edit_predictions;
 1981        self.update_edit_prediction_settings(cx);
 1982
 1983        if let Some(false) = show_edit_predictions {
 1984            self.discard_inline_completion(false, cx);
 1985        } else {
 1986            self.refresh_inline_completion(false, true, window, cx);
 1987        }
 1988    }
 1989
 1990    fn inline_completions_disabled_in_scope(
 1991        &self,
 1992        buffer: &Entity<Buffer>,
 1993        buffer_position: language::Anchor,
 1994        cx: &App,
 1995    ) -> bool {
 1996        let snapshot = buffer.read(cx).snapshot();
 1997        let settings = snapshot.settings_at(buffer_position, cx);
 1998
 1999        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2000            return false;
 2001        };
 2002
 2003        scope.override_name().map_or(false, |scope_name| {
 2004            settings
 2005                .edit_predictions_disabled_in
 2006                .iter()
 2007                .any(|s| s == scope_name)
 2008        })
 2009    }
 2010
 2011    pub fn set_use_modal_editing(&mut self, to: bool) {
 2012        self.use_modal_editing = to;
 2013    }
 2014
 2015    pub fn use_modal_editing(&self) -> bool {
 2016        self.use_modal_editing
 2017    }
 2018
 2019    fn selections_did_change(
 2020        &mut self,
 2021        local: bool,
 2022        old_cursor_position: &Anchor,
 2023        show_completions: bool,
 2024        window: &mut Window,
 2025        cx: &mut Context<Self>,
 2026    ) {
 2027        window.invalidate_character_coordinates();
 2028
 2029        // Copy selections to primary selection buffer
 2030        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2031        if local {
 2032            let selections = self.selections.all::<usize>(cx);
 2033            let buffer_handle = self.buffer.read(cx).read(cx);
 2034
 2035            let mut text = String::new();
 2036            for (index, selection) in selections.iter().enumerate() {
 2037                let text_for_selection = buffer_handle
 2038                    .text_for_range(selection.start..selection.end)
 2039                    .collect::<String>();
 2040
 2041                text.push_str(&text_for_selection);
 2042                if index != selections.len() - 1 {
 2043                    text.push('\n');
 2044                }
 2045            }
 2046
 2047            if !text.is_empty() {
 2048                cx.write_to_primary(ClipboardItem::new_string(text));
 2049            }
 2050        }
 2051
 2052        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2053            self.buffer.update(cx, |buffer, cx| {
 2054                buffer.set_active_selections(
 2055                    &self.selections.disjoint_anchors(),
 2056                    self.selections.line_mode,
 2057                    self.cursor_shape,
 2058                    cx,
 2059                )
 2060            });
 2061        }
 2062        let display_map = self
 2063            .display_map
 2064            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2065        let buffer = &display_map.buffer_snapshot;
 2066        self.add_selections_state = None;
 2067        self.select_next_state = None;
 2068        self.select_prev_state = None;
 2069        self.select_larger_syntax_node_stack.clear();
 2070        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2071        self.snippet_stack
 2072            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2073        self.take_rename(false, window, cx);
 2074
 2075        let new_cursor_position = self.selections.newest_anchor().head();
 2076
 2077        self.push_to_nav_history(
 2078            *old_cursor_position,
 2079            Some(new_cursor_position.to_point(buffer)),
 2080            cx,
 2081        );
 2082
 2083        if local {
 2084            let new_cursor_position = self.selections.newest_anchor().head();
 2085            let mut context_menu = self.context_menu.borrow_mut();
 2086            let completion_menu = match context_menu.as_ref() {
 2087                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2088                _ => {
 2089                    *context_menu = None;
 2090                    None
 2091                }
 2092            };
 2093            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2094                if !self.registered_buffers.contains_key(&buffer_id) {
 2095                    if let Some(project) = self.project.as_ref() {
 2096                        project.update(cx, |project, cx| {
 2097                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2098                                return;
 2099                            };
 2100                            self.registered_buffers.insert(
 2101                                buffer_id,
 2102                                project.register_buffer_with_language_servers(&buffer, cx),
 2103                            );
 2104                        })
 2105                    }
 2106                }
 2107            }
 2108
 2109            if let Some(completion_menu) = completion_menu {
 2110                let cursor_position = new_cursor_position.to_offset(buffer);
 2111                let (word_range, kind) =
 2112                    buffer.surrounding_word(completion_menu.initial_position, true);
 2113                if kind == Some(CharKind::Word)
 2114                    && word_range.to_inclusive().contains(&cursor_position)
 2115                {
 2116                    let mut completion_menu = completion_menu.clone();
 2117                    drop(context_menu);
 2118
 2119                    let query = Self::completion_query(buffer, cursor_position);
 2120                    cx.spawn(move |this, mut cx| async move {
 2121                        completion_menu
 2122                            .filter(query.as_deref(), cx.background_executor().clone())
 2123                            .await;
 2124
 2125                        this.update(&mut cx, |this, cx| {
 2126                            let mut context_menu = this.context_menu.borrow_mut();
 2127                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2128                            else {
 2129                                return;
 2130                            };
 2131
 2132                            if menu.id > completion_menu.id {
 2133                                return;
 2134                            }
 2135
 2136                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2137                            drop(context_menu);
 2138                            cx.notify();
 2139                        })
 2140                    })
 2141                    .detach();
 2142
 2143                    if show_completions {
 2144                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2145                    }
 2146                } else {
 2147                    drop(context_menu);
 2148                    self.hide_context_menu(window, cx);
 2149                }
 2150            } else {
 2151                drop(context_menu);
 2152            }
 2153
 2154            hide_hover(self, cx);
 2155
 2156            if old_cursor_position.to_display_point(&display_map).row()
 2157                != new_cursor_position.to_display_point(&display_map).row()
 2158            {
 2159                self.available_code_actions.take();
 2160            }
 2161            self.refresh_code_actions(window, cx);
 2162            self.refresh_document_highlights(cx);
 2163            self.refresh_selected_text_highlights(window, cx);
 2164            refresh_matching_bracket_highlights(self, window, cx);
 2165            self.update_visible_inline_completion(window, cx);
 2166            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2167            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2168            if self.git_blame_inline_enabled {
 2169                self.start_inline_blame_timer(window, cx);
 2170            }
 2171        }
 2172
 2173        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2174        cx.emit(EditorEvent::SelectionsChanged { local });
 2175
 2176        let selections = &self.selections.disjoint;
 2177        if selections.len() == 1 {
 2178            cx.emit(SearchEvent::ActiveMatchChanged)
 2179        }
 2180        if local
 2181            && self.is_singleton(cx)
 2182            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2183        {
 2184            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2185                let background_executor = cx.background_executor().clone();
 2186                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2187                let snapshot = self.buffer().read(cx).snapshot(cx);
 2188                let selections = selections.clone();
 2189                self.serialize_selections = cx.background_spawn(async move {
 2190                    background_executor.timer(Duration::from_millis(100)).await;
 2191                    let selections = selections
 2192                        .iter()
 2193                        .map(|selection| {
 2194                            (
 2195                                selection.start.to_offset(&snapshot),
 2196                                selection.end.to_offset(&snapshot),
 2197                            )
 2198                        })
 2199                        .collect();
 2200                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2201                        .await
 2202                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2203                        .log_err();
 2204                });
 2205            }
 2206        }
 2207
 2208        cx.notify();
 2209    }
 2210
 2211    pub fn change_selections<R>(
 2212        &mut self,
 2213        autoscroll: Option<Autoscroll>,
 2214        window: &mut Window,
 2215        cx: &mut Context<Self>,
 2216        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2217    ) -> R {
 2218        self.change_selections_inner(autoscroll, true, window, cx, change)
 2219    }
 2220
 2221    fn change_selections_inner<R>(
 2222        &mut self,
 2223        autoscroll: Option<Autoscroll>,
 2224        request_completions: bool,
 2225        window: &mut Window,
 2226        cx: &mut Context<Self>,
 2227        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2228    ) -> R {
 2229        let old_cursor_position = self.selections.newest_anchor().head();
 2230        self.push_to_selection_history();
 2231
 2232        let (changed, result) = self.selections.change_with(cx, change);
 2233
 2234        if changed {
 2235            if let Some(autoscroll) = autoscroll {
 2236                self.request_autoscroll(autoscroll, cx);
 2237            }
 2238            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2239
 2240            if self.should_open_signature_help_automatically(
 2241                &old_cursor_position,
 2242                self.signature_help_state.backspace_pressed(),
 2243                cx,
 2244            ) {
 2245                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2246            }
 2247            self.signature_help_state.set_backspace_pressed(false);
 2248        }
 2249
 2250        result
 2251    }
 2252
 2253    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2254    where
 2255        I: IntoIterator<Item = (Range<S>, T)>,
 2256        S: ToOffset,
 2257        T: Into<Arc<str>>,
 2258    {
 2259        if self.read_only(cx) {
 2260            return;
 2261        }
 2262
 2263        self.buffer
 2264            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2265    }
 2266
 2267    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2268    where
 2269        I: IntoIterator<Item = (Range<S>, T)>,
 2270        S: ToOffset,
 2271        T: Into<Arc<str>>,
 2272    {
 2273        if self.read_only(cx) {
 2274            return;
 2275        }
 2276
 2277        self.buffer.update(cx, |buffer, cx| {
 2278            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2279        });
 2280    }
 2281
 2282    pub fn edit_with_block_indent<I, S, T>(
 2283        &mut self,
 2284        edits: I,
 2285        original_start_columns: Vec<u32>,
 2286        cx: &mut Context<Self>,
 2287    ) where
 2288        I: IntoIterator<Item = (Range<S>, T)>,
 2289        S: ToOffset,
 2290        T: Into<Arc<str>>,
 2291    {
 2292        if self.read_only(cx) {
 2293            return;
 2294        }
 2295
 2296        self.buffer.update(cx, |buffer, cx| {
 2297            buffer.edit(
 2298                edits,
 2299                Some(AutoindentMode::Block {
 2300                    original_start_columns,
 2301                }),
 2302                cx,
 2303            )
 2304        });
 2305    }
 2306
 2307    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2308        self.hide_context_menu(window, cx);
 2309
 2310        match phase {
 2311            SelectPhase::Begin {
 2312                position,
 2313                add,
 2314                click_count,
 2315            } => self.begin_selection(position, add, click_count, window, cx),
 2316            SelectPhase::BeginColumnar {
 2317                position,
 2318                goal_column,
 2319                reset,
 2320            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2321            SelectPhase::Extend {
 2322                position,
 2323                click_count,
 2324            } => self.extend_selection(position, click_count, window, cx),
 2325            SelectPhase::Update {
 2326                position,
 2327                goal_column,
 2328                scroll_delta,
 2329            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2330            SelectPhase::End => self.end_selection(window, cx),
 2331        }
 2332    }
 2333
 2334    fn extend_selection(
 2335        &mut self,
 2336        position: DisplayPoint,
 2337        click_count: usize,
 2338        window: &mut Window,
 2339        cx: &mut Context<Self>,
 2340    ) {
 2341        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2342        let tail = self.selections.newest::<usize>(cx).tail();
 2343        self.begin_selection(position, false, click_count, window, cx);
 2344
 2345        let position = position.to_offset(&display_map, Bias::Left);
 2346        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2347
 2348        let mut pending_selection = self
 2349            .selections
 2350            .pending_anchor()
 2351            .expect("extend_selection not called with pending selection");
 2352        if position >= tail {
 2353            pending_selection.start = tail_anchor;
 2354        } else {
 2355            pending_selection.end = tail_anchor;
 2356            pending_selection.reversed = true;
 2357        }
 2358
 2359        let mut pending_mode = self.selections.pending_mode().unwrap();
 2360        match &mut pending_mode {
 2361            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2362            _ => {}
 2363        }
 2364
 2365        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2366            s.set_pending(pending_selection, pending_mode)
 2367        });
 2368    }
 2369
 2370    fn begin_selection(
 2371        &mut self,
 2372        position: DisplayPoint,
 2373        add: bool,
 2374        click_count: usize,
 2375        window: &mut Window,
 2376        cx: &mut Context<Self>,
 2377    ) {
 2378        if !self.focus_handle.is_focused(window) {
 2379            self.last_focused_descendant = None;
 2380            window.focus(&self.focus_handle);
 2381        }
 2382
 2383        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2384        let buffer = &display_map.buffer_snapshot;
 2385        let newest_selection = self.selections.newest_anchor().clone();
 2386        let position = display_map.clip_point(position, Bias::Left);
 2387
 2388        let start;
 2389        let end;
 2390        let mode;
 2391        let mut auto_scroll;
 2392        match click_count {
 2393            1 => {
 2394                start = buffer.anchor_before(position.to_point(&display_map));
 2395                end = start;
 2396                mode = SelectMode::Character;
 2397                auto_scroll = true;
 2398            }
 2399            2 => {
 2400                let range = movement::surrounding_word(&display_map, position);
 2401                start = buffer.anchor_before(range.start.to_point(&display_map));
 2402                end = buffer.anchor_before(range.end.to_point(&display_map));
 2403                mode = SelectMode::Word(start..end);
 2404                auto_scroll = true;
 2405            }
 2406            3 => {
 2407                let position = display_map
 2408                    .clip_point(position, Bias::Left)
 2409                    .to_point(&display_map);
 2410                let line_start = display_map.prev_line_boundary(position).0;
 2411                let next_line_start = buffer.clip_point(
 2412                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2413                    Bias::Left,
 2414                );
 2415                start = buffer.anchor_before(line_start);
 2416                end = buffer.anchor_before(next_line_start);
 2417                mode = SelectMode::Line(start..end);
 2418                auto_scroll = true;
 2419            }
 2420            _ => {
 2421                start = buffer.anchor_before(0);
 2422                end = buffer.anchor_before(buffer.len());
 2423                mode = SelectMode::All;
 2424                auto_scroll = false;
 2425            }
 2426        }
 2427        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2428
 2429        let point_to_delete: Option<usize> = {
 2430            let selected_points: Vec<Selection<Point>> =
 2431                self.selections.disjoint_in_range(start..end, cx);
 2432
 2433            if !add || click_count > 1 {
 2434                None
 2435            } else if !selected_points.is_empty() {
 2436                Some(selected_points[0].id)
 2437            } else {
 2438                let clicked_point_already_selected =
 2439                    self.selections.disjoint.iter().find(|selection| {
 2440                        selection.start.to_point(buffer) == start.to_point(buffer)
 2441                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2442                    });
 2443
 2444                clicked_point_already_selected.map(|selection| selection.id)
 2445            }
 2446        };
 2447
 2448        let selections_count = self.selections.count();
 2449
 2450        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2451            if let Some(point_to_delete) = point_to_delete {
 2452                s.delete(point_to_delete);
 2453
 2454                if selections_count == 1 {
 2455                    s.set_pending_anchor_range(start..end, mode);
 2456                }
 2457            } else {
 2458                if !add {
 2459                    s.clear_disjoint();
 2460                } else if click_count > 1 {
 2461                    s.delete(newest_selection.id)
 2462                }
 2463
 2464                s.set_pending_anchor_range(start..end, mode);
 2465            }
 2466        });
 2467    }
 2468
 2469    fn begin_columnar_selection(
 2470        &mut self,
 2471        position: DisplayPoint,
 2472        goal_column: u32,
 2473        reset: bool,
 2474        window: &mut Window,
 2475        cx: &mut Context<Self>,
 2476    ) {
 2477        if !self.focus_handle.is_focused(window) {
 2478            self.last_focused_descendant = None;
 2479            window.focus(&self.focus_handle);
 2480        }
 2481
 2482        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2483
 2484        if reset {
 2485            let pointer_position = display_map
 2486                .buffer_snapshot
 2487                .anchor_before(position.to_point(&display_map));
 2488
 2489            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2490                s.clear_disjoint();
 2491                s.set_pending_anchor_range(
 2492                    pointer_position..pointer_position,
 2493                    SelectMode::Character,
 2494                );
 2495            });
 2496        }
 2497
 2498        let tail = self.selections.newest::<Point>(cx).tail();
 2499        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2500
 2501        if !reset {
 2502            self.select_columns(
 2503                tail.to_display_point(&display_map),
 2504                position,
 2505                goal_column,
 2506                &display_map,
 2507                window,
 2508                cx,
 2509            );
 2510        }
 2511    }
 2512
 2513    fn update_selection(
 2514        &mut self,
 2515        position: DisplayPoint,
 2516        goal_column: u32,
 2517        scroll_delta: gpui::Point<f32>,
 2518        window: &mut Window,
 2519        cx: &mut Context<Self>,
 2520    ) {
 2521        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2522
 2523        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2524            let tail = tail.to_display_point(&display_map);
 2525            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2526        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2527            let buffer = self.buffer.read(cx).snapshot(cx);
 2528            let head;
 2529            let tail;
 2530            let mode = self.selections.pending_mode().unwrap();
 2531            match &mode {
 2532                SelectMode::Character => {
 2533                    head = position.to_point(&display_map);
 2534                    tail = pending.tail().to_point(&buffer);
 2535                }
 2536                SelectMode::Word(original_range) => {
 2537                    let original_display_range = original_range.start.to_display_point(&display_map)
 2538                        ..original_range.end.to_display_point(&display_map);
 2539                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2540                        ..original_display_range.end.to_point(&display_map);
 2541                    if movement::is_inside_word(&display_map, position)
 2542                        || original_display_range.contains(&position)
 2543                    {
 2544                        let word_range = movement::surrounding_word(&display_map, position);
 2545                        if word_range.start < original_display_range.start {
 2546                            head = word_range.start.to_point(&display_map);
 2547                        } else {
 2548                            head = word_range.end.to_point(&display_map);
 2549                        }
 2550                    } else {
 2551                        head = position.to_point(&display_map);
 2552                    }
 2553
 2554                    if head <= original_buffer_range.start {
 2555                        tail = original_buffer_range.end;
 2556                    } else {
 2557                        tail = original_buffer_range.start;
 2558                    }
 2559                }
 2560                SelectMode::Line(original_range) => {
 2561                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2562
 2563                    let position = display_map
 2564                        .clip_point(position, Bias::Left)
 2565                        .to_point(&display_map);
 2566                    let line_start = display_map.prev_line_boundary(position).0;
 2567                    let next_line_start = buffer.clip_point(
 2568                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2569                        Bias::Left,
 2570                    );
 2571
 2572                    if line_start < original_range.start {
 2573                        head = line_start
 2574                    } else {
 2575                        head = next_line_start
 2576                    }
 2577
 2578                    if head <= original_range.start {
 2579                        tail = original_range.end;
 2580                    } else {
 2581                        tail = original_range.start;
 2582                    }
 2583                }
 2584                SelectMode::All => {
 2585                    return;
 2586                }
 2587            };
 2588
 2589            if head < tail {
 2590                pending.start = buffer.anchor_before(head);
 2591                pending.end = buffer.anchor_before(tail);
 2592                pending.reversed = true;
 2593            } else {
 2594                pending.start = buffer.anchor_before(tail);
 2595                pending.end = buffer.anchor_before(head);
 2596                pending.reversed = false;
 2597            }
 2598
 2599            self.change_selections(None, window, cx, |s| {
 2600                s.set_pending(pending, mode);
 2601            });
 2602        } else {
 2603            log::error!("update_selection dispatched with no pending selection");
 2604            return;
 2605        }
 2606
 2607        self.apply_scroll_delta(scroll_delta, window, cx);
 2608        cx.notify();
 2609    }
 2610
 2611    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2612        self.columnar_selection_tail.take();
 2613        if self.selections.pending_anchor().is_some() {
 2614            let selections = self.selections.all::<usize>(cx);
 2615            self.change_selections(None, window, cx, |s| {
 2616                s.select(selections);
 2617                s.clear_pending();
 2618            });
 2619        }
 2620    }
 2621
 2622    fn select_columns(
 2623        &mut self,
 2624        tail: DisplayPoint,
 2625        head: DisplayPoint,
 2626        goal_column: u32,
 2627        display_map: &DisplaySnapshot,
 2628        window: &mut Window,
 2629        cx: &mut Context<Self>,
 2630    ) {
 2631        let start_row = cmp::min(tail.row(), head.row());
 2632        let end_row = cmp::max(tail.row(), head.row());
 2633        let start_column = cmp::min(tail.column(), goal_column);
 2634        let end_column = cmp::max(tail.column(), goal_column);
 2635        let reversed = start_column < tail.column();
 2636
 2637        let selection_ranges = (start_row.0..=end_row.0)
 2638            .map(DisplayRow)
 2639            .filter_map(|row| {
 2640                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2641                    let start = display_map
 2642                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2643                        .to_point(display_map);
 2644                    let end = display_map
 2645                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2646                        .to_point(display_map);
 2647                    if reversed {
 2648                        Some(end..start)
 2649                    } else {
 2650                        Some(start..end)
 2651                    }
 2652                } else {
 2653                    None
 2654                }
 2655            })
 2656            .collect::<Vec<_>>();
 2657
 2658        self.change_selections(None, window, cx, |s| {
 2659            s.select_ranges(selection_ranges);
 2660        });
 2661        cx.notify();
 2662    }
 2663
 2664    pub fn has_pending_nonempty_selection(&self) -> bool {
 2665        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2666            Some(Selection { start, end, .. }) => start != end,
 2667            None => false,
 2668        };
 2669
 2670        pending_nonempty_selection
 2671            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2672    }
 2673
 2674    pub fn has_pending_selection(&self) -> bool {
 2675        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2676    }
 2677
 2678    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2679        self.selection_mark_mode = false;
 2680
 2681        if self.clear_expanded_diff_hunks(cx) {
 2682            cx.notify();
 2683            return;
 2684        }
 2685        if self.dismiss_menus_and_popups(true, window, cx) {
 2686            return;
 2687        }
 2688
 2689        if self.mode == EditorMode::Full
 2690            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2691        {
 2692            return;
 2693        }
 2694
 2695        cx.propagate();
 2696    }
 2697
 2698    pub fn dismiss_menus_and_popups(
 2699        &mut self,
 2700        is_user_requested: bool,
 2701        window: &mut Window,
 2702        cx: &mut Context<Self>,
 2703    ) -> bool {
 2704        if self.take_rename(false, window, cx).is_some() {
 2705            return true;
 2706        }
 2707
 2708        if hide_hover(self, cx) {
 2709            return true;
 2710        }
 2711
 2712        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2713            return true;
 2714        }
 2715
 2716        if self.hide_context_menu(window, cx).is_some() {
 2717            return true;
 2718        }
 2719
 2720        if self.mouse_context_menu.take().is_some() {
 2721            return true;
 2722        }
 2723
 2724        if is_user_requested && self.discard_inline_completion(true, cx) {
 2725            return true;
 2726        }
 2727
 2728        if self.snippet_stack.pop().is_some() {
 2729            return true;
 2730        }
 2731
 2732        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2733            self.dismiss_diagnostics(cx);
 2734            return true;
 2735        }
 2736
 2737        false
 2738    }
 2739
 2740    fn linked_editing_ranges_for(
 2741        &self,
 2742        selection: Range<text::Anchor>,
 2743        cx: &App,
 2744    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2745        if self.linked_edit_ranges.is_empty() {
 2746            return None;
 2747        }
 2748        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2749            selection.end.buffer_id.and_then(|end_buffer_id| {
 2750                if selection.start.buffer_id != Some(end_buffer_id) {
 2751                    return None;
 2752                }
 2753                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2754                let snapshot = buffer.read(cx).snapshot();
 2755                self.linked_edit_ranges
 2756                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2757                    .map(|ranges| (ranges, snapshot, buffer))
 2758            })?;
 2759        use text::ToOffset as TO;
 2760        // find offset from the start of current range to current cursor position
 2761        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2762
 2763        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2764        let start_difference = start_offset - start_byte_offset;
 2765        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2766        let end_difference = end_offset - start_byte_offset;
 2767        // Current range has associated linked ranges.
 2768        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2769        for range in linked_ranges.iter() {
 2770            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2771            let end_offset = start_offset + end_difference;
 2772            let start_offset = start_offset + start_difference;
 2773            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2774                continue;
 2775            }
 2776            if self.selections.disjoint_anchor_ranges().any(|s| {
 2777                if s.start.buffer_id != selection.start.buffer_id
 2778                    || s.end.buffer_id != selection.end.buffer_id
 2779                {
 2780                    return false;
 2781                }
 2782                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2783                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2784            }) {
 2785                continue;
 2786            }
 2787            let start = buffer_snapshot.anchor_after(start_offset);
 2788            let end = buffer_snapshot.anchor_after(end_offset);
 2789            linked_edits
 2790                .entry(buffer.clone())
 2791                .or_default()
 2792                .push(start..end);
 2793        }
 2794        Some(linked_edits)
 2795    }
 2796
 2797    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2798        let text: Arc<str> = text.into();
 2799
 2800        if self.read_only(cx) {
 2801            return;
 2802        }
 2803
 2804        let selections = self.selections.all_adjusted(cx);
 2805        let mut bracket_inserted = false;
 2806        let mut edits = Vec::new();
 2807        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2808        let mut new_selections = Vec::with_capacity(selections.len());
 2809        let mut new_autoclose_regions = Vec::new();
 2810        let snapshot = self.buffer.read(cx).read(cx);
 2811
 2812        for (selection, autoclose_region) in
 2813            self.selections_with_autoclose_regions(selections, &snapshot)
 2814        {
 2815            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2816                // Determine if the inserted text matches the opening or closing
 2817                // bracket of any of this language's bracket pairs.
 2818                let mut bracket_pair = None;
 2819                let mut is_bracket_pair_start = false;
 2820                let mut is_bracket_pair_end = false;
 2821                if !text.is_empty() {
 2822                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2823                    //  and they are removing the character that triggered IME popup.
 2824                    for (pair, enabled) in scope.brackets() {
 2825                        if !pair.close && !pair.surround {
 2826                            continue;
 2827                        }
 2828
 2829                        if enabled && pair.start.ends_with(text.as_ref()) {
 2830                            let prefix_len = pair.start.len() - text.len();
 2831                            let preceding_text_matches_prefix = prefix_len == 0
 2832                                || (selection.start.column >= (prefix_len as u32)
 2833                                    && snapshot.contains_str_at(
 2834                                        Point::new(
 2835                                            selection.start.row,
 2836                                            selection.start.column - (prefix_len as u32),
 2837                                        ),
 2838                                        &pair.start[..prefix_len],
 2839                                    ));
 2840                            if preceding_text_matches_prefix {
 2841                                bracket_pair = Some(pair.clone());
 2842                                is_bracket_pair_start = true;
 2843                                break;
 2844                            }
 2845                        }
 2846                        if pair.end.as_str() == text.as_ref() {
 2847                            bracket_pair = Some(pair.clone());
 2848                            is_bracket_pair_end = true;
 2849                            break;
 2850                        }
 2851                    }
 2852                }
 2853
 2854                if let Some(bracket_pair) = bracket_pair {
 2855                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2856                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2857                    let auto_surround =
 2858                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2859                    if selection.is_empty() {
 2860                        if is_bracket_pair_start {
 2861                            // If the inserted text is a suffix of an opening bracket and the
 2862                            // selection is preceded by the rest of the opening bracket, then
 2863                            // insert the closing bracket.
 2864                            let following_text_allows_autoclose = snapshot
 2865                                .chars_at(selection.start)
 2866                                .next()
 2867                                .map_or(true, |c| scope.should_autoclose_before(c));
 2868
 2869                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2870                                && bracket_pair.start.len() == 1
 2871                            {
 2872                                let target = bracket_pair.start.chars().next().unwrap();
 2873                                let current_line_count = snapshot
 2874                                    .reversed_chars_at(selection.start)
 2875                                    .take_while(|&c| c != '\n')
 2876                                    .filter(|&c| c == target)
 2877                                    .count();
 2878                                current_line_count % 2 == 1
 2879                            } else {
 2880                                false
 2881                            };
 2882
 2883                            if autoclose
 2884                                && bracket_pair.close
 2885                                && following_text_allows_autoclose
 2886                                && !is_closing_quote
 2887                            {
 2888                                let anchor = snapshot.anchor_before(selection.end);
 2889                                new_selections.push((selection.map(|_| anchor), text.len()));
 2890                                new_autoclose_regions.push((
 2891                                    anchor,
 2892                                    text.len(),
 2893                                    selection.id,
 2894                                    bracket_pair.clone(),
 2895                                ));
 2896                                edits.push((
 2897                                    selection.range(),
 2898                                    format!("{}{}", text, bracket_pair.end).into(),
 2899                                ));
 2900                                bracket_inserted = true;
 2901                                continue;
 2902                            }
 2903                        }
 2904
 2905                        if let Some(region) = autoclose_region {
 2906                            // If the selection is followed by an auto-inserted closing bracket,
 2907                            // then don't insert that closing bracket again; just move the selection
 2908                            // past the closing bracket.
 2909                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2910                                && text.as_ref() == region.pair.end.as_str();
 2911                            if should_skip {
 2912                                let anchor = snapshot.anchor_after(selection.end);
 2913                                new_selections
 2914                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2915                                continue;
 2916                            }
 2917                        }
 2918
 2919                        let always_treat_brackets_as_autoclosed = snapshot
 2920                            .settings_at(selection.start, cx)
 2921                            .always_treat_brackets_as_autoclosed;
 2922                        if always_treat_brackets_as_autoclosed
 2923                            && is_bracket_pair_end
 2924                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2925                        {
 2926                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2927                            // and the inserted text is a closing bracket and the selection is followed
 2928                            // by the closing bracket then move the selection past the closing bracket.
 2929                            let anchor = snapshot.anchor_after(selection.end);
 2930                            new_selections.push((selection.map(|_| anchor), text.len()));
 2931                            continue;
 2932                        }
 2933                    }
 2934                    // If an opening bracket is 1 character long and is typed while
 2935                    // text is selected, then surround that text with the bracket pair.
 2936                    else if auto_surround
 2937                        && bracket_pair.surround
 2938                        && is_bracket_pair_start
 2939                        && bracket_pair.start.chars().count() == 1
 2940                    {
 2941                        edits.push((selection.start..selection.start, text.clone()));
 2942                        edits.push((
 2943                            selection.end..selection.end,
 2944                            bracket_pair.end.as_str().into(),
 2945                        ));
 2946                        bracket_inserted = true;
 2947                        new_selections.push((
 2948                            Selection {
 2949                                id: selection.id,
 2950                                start: snapshot.anchor_after(selection.start),
 2951                                end: snapshot.anchor_before(selection.end),
 2952                                reversed: selection.reversed,
 2953                                goal: selection.goal,
 2954                            },
 2955                            0,
 2956                        ));
 2957                        continue;
 2958                    }
 2959                }
 2960            }
 2961
 2962            if self.auto_replace_emoji_shortcode
 2963                && selection.is_empty()
 2964                && text.as_ref().ends_with(':')
 2965            {
 2966                if let Some(possible_emoji_short_code) =
 2967                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2968                {
 2969                    if !possible_emoji_short_code.is_empty() {
 2970                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2971                            let emoji_shortcode_start = Point::new(
 2972                                selection.start.row,
 2973                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2974                            );
 2975
 2976                            // Remove shortcode from buffer
 2977                            edits.push((
 2978                                emoji_shortcode_start..selection.start,
 2979                                "".to_string().into(),
 2980                            ));
 2981                            new_selections.push((
 2982                                Selection {
 2983                                    id: selection.id,
 2984                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2985                                    end: snapshot.anchor_before(selection.start),
 2986                                    reversed: selection.reversed,
 2987                                    goal: selection.goal,
 2988                                },
 2989                                0,
 2990                            ));
 2991
 2992                            // Insert emoji
 2993                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2994                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2995                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2996
 2997                            continue;
 2998                        }
 2999                    }
 3000                }
 3001            }
 3002
 3003            // If not handling any auto-close operation, then just replace the selected
 3004            // text with the given input and move the selection to the end of the
 3005            // newly inserted text.
 3006            let anchor = snapshot.anchor_after(selection.end);
 3007            if !self.linked_edit_ranges.is_empty() {
 3008                let start_anchor = snapshot.anchor_before(selection.start);
 3009
 3010                let is_word_char = text.chars().next().map_or(true, |char| {
 3011                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3012                    classifier.is_word(char)
 3013                });
 3014
 3015                if is_word_char {
 3016                    if let Some(ranges) = self
 3017                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3018                    {
 3019                        for (buffer, edits) in ranges {
 3020                            linked_edits
 3021                                .entry(buffer.clone())
 3022                                .or_default()
 3023                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3024                        }
 3025                    }
 3026                }
 3027            }
 3028
 3029            new_selections.push((selection.map(|_| anchor), 0));
 3030            edits.push((selection.start..selection.end, text.clone()));
 3031        }
 3032
 3033        drop(snapshot);
 3034
 3035        self.transact(window, cx, |this, window, cx| {
 3036            this.buffer.update(cx, |buffer, cx| {
 3037                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3038            });
 3039            for (buffer, edits) in linked_edits {
 3040                buffer.update(cx, |buffer, cx| {
 3041                    let snapshot = buffer.snapshot();
 3042                    let edits = edits
 3043                        .into_iter()
 3044                        .map(|(range, text)| {
 3045                            use text::ToPoint as TP;
 3046                            let end_point = TP::to_point(&range.end, &snapshot);
 3047                            let start_point = TP::to_point(&range.start, &snapshot);
 3048                            (start_point..end_point, text)
 3049                        })
 3050                        .sorted_by_key(|(range, _)| range.start)
 3051                        .collect::<Vec<_>>();
 3052                    buffer.edit(edits, None, cx);
 3053                })
 3054            }
 3055            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3056            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3057            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3058            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3059                .zip(new_selection_deltas)
 3060                .map(|(selection, delta)| Selection {
 3061                    id: selection.id,
 3062                    start: selection.start + delta,
 3063                    end: selection.end + delta,
 3064                    reversed: selection.reversed,
 3065                    goal: SelectionGoal::None,
 3066                })
 3067                .collect::<Vec<_>>();
 3068
 3069            let mut i = 0;
 3070            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3071                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3072                let start = map.buffer_snapshot.anchor_before(position);
 3073                let end = map.buffer_snapshot.anchor_after(position);
 3074                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3075                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3076                        Ordering::Less => i += 1,
 3077                        Ordering::Greater => break,
 3078                        Ordering::Equal => {
 3079                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3080                                Ordering::Less => i += 1,
 3081                                Ordering::Equal => break,
 3082                                Ordering::Greater => break,
 3083                            }
 3084                        }
 3085                    }
 3086                }
 3087                this.autoclose_regions.insert(
 3088                    i,
 3089                    AutocloseRegion {
 3090                        selection_id,
 3091                        range: start..end,
 3092                        pair,
 3093                    },
 3094                );
 3095            }
 3096
 3097            let had_active_inline_completion = this.has_active_inline_completion();
 3098            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3099                s.select(new_selections)
 3100            });
 3101
 3102            if !bracket_inserted {
 3103                if let Some(on_type_format_task) =
 3104                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3105                {
 3106                    on_type_format_task.detach_and_log_err(cx);
 3107                }
 3108            }
 3109
 3110            let editor_settings = EditorSettings::get_global(cx);
 3111            if bracket_inserted
 3112                && (editor_settings.auto_signature_help
 3113                    || editor_settings.show_signature_help_after_edits)
 3114            {
 3115                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3116            }
 3117
 3118            let trigger_in_words =
 3119                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3120            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3121            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3122            this.refresh_inline_completion(true, false, window, cx);
 3123        });
 3124    }
 3125
 3126    fn find_possible_emoji_shortcode_at_position(
 3127        snapshot: &MultiBufferSnapshot,
 3128        position: Point,
 3129    ) -> Option<String> {
 3130        let mut chars = Vec::new();
 3131        let mut found_colon = false;
 3132        for char in snapshot.reversed_chars_at(position).take(100) {
 3133            // Found a possible emoji shortcode in the middle of the buffer
 3134            if found_colon {
 3135                if char.is_whitespace() {
 3136                    chars.reverse();
 3137                    return Some(chars.iter().collect());
 3138                }
 3139                // If the previous character is not a whitespace, we are in the middle of a word
 3140                // and we only want to complete the shortcode if the word is made up of other emojis
 3141                let mut containing_word = String::new();
 3142                for ch in snapshot
 3143                    .reversed_chars_at(position)
 3144                    .skip(chars.len() + 1)
 3145                    .take(100)
 3146                {
 3147                    if ch.is_whitespace() {
 3148                        break;
 3149                    }
 3150                    containing_word.push(ch);
 3151                }
 3152                let containing_word = containing_word.chars().rev().collect::<String>();
 3153                if util::word_consists_of_emojis(containing_word.as_str()) {
 3154                    chars.reverse();
 3155                    return Some(chars.iter().collect());
 3156                }
 3157            }
 3158
 3159            if char.is_whitespace() || !char.is_ascii() {
 3160                return None;
 3161            }
 3162            if char == ':' {
 3163                found_colon = true;
 3164            } else {
 3165                chars.push(char);
 3166            }
 3167        }
 3168        // Found a possible emoji shortcode at the beginning of the buffer
 3169        chars.reverse();
 3170        Some(chars.iter().collect())
 3171    }
 3172
 3173    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3174        self.transact(window, cx, |this, window, cx| {
 3175            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3176                let selections = this.selections.all::<usize>(cx);
 3177                let multi_buffer = this.buffer.read(cx);
 3178                let buffer = multi_buffer.snapshot(cx);
 3179                selections
 3180                    .iter()
 3181                    .map(|selection| {
 3182                        let start_point = selection.start.to_point(&buffer);
 3183                        let mut indent =
 3184                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3185                        indent.len = cmp::min(indent.len, start_point.column);
 3186                        let start = selection.start;
 3187                        let end = selection.end;
 3188                        let selection_is_empty = start == end;
 3189                        let language_scope = buffer.language_scope_at(start);
 3190                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3191                            &language_scope
 3192                        {
 3193                            let insert_extra_newline =
 3194                                insert_extra_newline_brackets(&buffer, start..end, language)
 3195                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3196
 3197                            // Comment extension on newline is allowed only for cursor selections
 3198                            let comment_delimiter = maybe!({
 3199                                if !selection_is_empty {
 3200                                    return None;
 3201                                }
 3202
 3203                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3204                                    return None;
 3205                                }
 3206
 3207                                let delimiters = language.line_comment_prefixes();
 3208                                let max_len_of_delimiter =
 3209                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3210                                let (snapshot, range) =
 3211                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3212
 3213                                let mut index_of_first_non_whitespace = 0;
 3214                                let comment_candidate = snapshot
 3215                                    .chars_for_range(range)
 3216                                    .skip_while(|c| {
 3217                                        let should_skip = c.is_whitespace();
 3218                                        if should_skip {
 3219                                            index_of_first_non_whitespace += 1;
 3220                                        }
 3221                                        should_skip
 3222                                    })
 3223                                    .take(max_len_of_delimiter)
 3224                                    .collect::<String>();
 3225                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3226                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3227                                })?;
 3228                                let cursor_is_placed_after_comment_marker =
 3229                                    index_of_first_non_whitespace + comment_prefix.len()
 3230                                        <= start_point.column as usize;
 3231                                if cursor_is_placed_after_comment_marker {
 3232                                    Some(comment_prefix.clone())
 3233                                } else {
 3234                                    None
 3235                                }
 3236                            });
 3237                            (comment_delimiter, insert_extra_newline)
 3238                        } else {
 3239                            (None, false)
 3240                        };
 3241
 3242                        let capacity_for_delimiter = comment_delimiter
 3243                            .as_deref()
 3244                            .map(str::len)
 3245                            .unwrap_or_default();
 3246                        let mut new_text =
 3247                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3248                        new_text.push('\n');
 3249                        new_text.extend(indent.chars());
 3250                        if let Some(delimiter) = &comment_delimiter {
 3251                            new_text.push_str(delimiter);
 3252                        }
 3253                        if insert_extra_newline {
 3254                            new_text = new_text.repeat(2);
 3255                        }
 3256
 3257                        let anchor = buffer.anchor_after(end);
 3258                        let new_selection = selection.map(|_| anchor);
 3259                        (
 3260                            (start..end, new_text),
 3261                            (insert_extra_newline, new_selection),
 3262                        )
 3263                    })
 3264                    .unzip()
 3265            };
 3266
 3267            this.edit_with_autoindent(edits, cx);
 3268            let buffer = this.buffer.read(cx).snapshot(cx);
 3269            let new_selections = selection_fixup_info
 3270                .into_iter()
 3271                .map(|(extra_newline_inserted, new_selection)| {
 3272                    let mut cursor = new_selection.end.to_point(&buffer);
 3273                    if extra_newline_inserted {
 3274                        cursor.row -= 1;
 3275                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3276                    }
 3277                    new_selection.map(|_| cursor)
 3278                })
 3279                .collect();
 3280
 3281            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3282                s.select(new_selections)
 3283            });
 3284            this.refresh_inline_completion(true, false, window, cx);
 3285        });
 3286    }
 3287
 3288    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3289        let buffer = self.buffer.read(cx);
 3290        let snapshot = buffer.snapshot(cx);
 3291
 3292        let mut edits = Vec::new();
 3293        let mut rows = Vec::new();
 3294
 3295        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3296            let cursor = selection.head();
 3297            let row = cursor.row;
 3298
 3299            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3300
 3301            let newline = "\n".to_string();
 3302            edits.push((start_of_line..start_of_line, newline));
 3303
 3304            rows.push(row + rows_inserted as u32);
 3305        }
 3306
 3307        self.transact(window, cx, |editor, window, cx| {
 3308            editor.edit(edits, cx);
 3309
 3310            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3311                let mut index = 0;
 3312                s.move_cursors_with(|map, _, _| {
 3313                    let row = rows[index];
 3314                    index += 1;
 3315
 3316                    let point = Point::new(row, 0);
 3317                    let boundary = map.next_line_boundary(point).1;
 3318                    let clipped = map.clip_point(boundary, Bias::Left);
 3319
 3320                    (clipped, SelectionGoal::None)
 3321                });
 3322            });
 3323
 3324            let mut indent_edits = Vec::new();
 3325            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3326            for row in rows {
 3327                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3328                for (row, indent) in indents {
 3329                    if indent.len == 0 {
 3330                        continue;
 3331                    }
 3332
 3333                    let text = match indent.kind {
 3334                        IndentKind::Space => " ".repeat(indent.len as usize),
 3335                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3336                    };
 3337                    let point = Point::new(row.0, 0);
 3338                    indent_edits.push((point..point, text));
 3339                }
 3340            }
 3341            editor.edit(indent_edits, cx);
 3342        });
 3343    }
 3344
 3345    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3346        let buffer = self.buffer.read(cx);
 3347        let snapshot = buffer.snapshot(cx);
 3348
 3349        let mut edits = Vec::new();
 3350        let mut rows = Vec::new();
 3351        let mut rows_inserted = 0;
 3352
 3353        for selection in self.selections.all_adjusted(cx) {
 3354            let cursor = selection.head();
 3355            let row = cursor.row;
 3356
 3357            let point = Point::new(row + 1, 0);
 3358            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3359
 3360            let newline = "\n".to_string();
 3361            edits.push((start_of_line..start_of_line, newline));
 3362
 3363            rows_inserted += 1;
 3364            rows.push(row + rows_inserted);
 3365        }
 3366
 3367        self.transact(window, cx, |editor, window, cx| {
 3368            editor.edit(edits, cx);
 3369
 3370            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3371                let mut index = 0;
 3372                s.move_cursors_with(|map, _, _| {
 3373                    let row = rows[index];
 3374                    index += 1;
 3375
 3376                    let point = Point::new(row, 0);
 3377                    let boundary = map.next_line_boundary(point).1;
 3378                    let clipped = map.clip_point(boundary, Bias::Left);
 3379
 3380                    (clipped, SelectionGoal::None)
 3381                });
 3382            });
 3383
 3384            let mut indent_edits = Vec::new();
 3385            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3386            for row in rows {
 3387                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3388                for (row, indent) in indents {
 3389                    if indent.len == 0 {
 3390                        continue;
 3391                    }
 3392
 3393                    let text = match indent.kind {
 3394                        IndentKind::Space => " ".repeat(indent.len as usize),
 3395                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3396                    };
 3397                    let point = Point::new(row.0, 0);
 3398                    indent_edits.push((point..point, text));
 3399                }
 3400            }
 3401            editor.edit(indent_edits, cx);
 3402        });
 3403    }
 3404
 3405    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3406        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3407            original_start_columns: Vec::new(),
 3408        });
 3409        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3410    }
 3411
 3412    fn insert_with_autoindent_mode(
 3413        &mut self,
 3414        text: &str,
 3415        autoindent_mode: Option<AutoindentMode>,
 3416        window: &mut Window,
 3417        cx: &mut Context<Self>,
 3418    ) {
 3419        if self.read_only(cx) {
 3420            return;
 3421        }
 3422
 3423        let text: Arc<str> = text.into();
 3424        self.transact(window, cx, |this, window, cx| {
 3425            let old_selections = this.selections.all_adjusted(cx);
 3426            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3427                let anchors = {
 3428                    let snapshot = buffer.read(cx);
 3429                    old_selections
 3430                        .iter()
 3431                        .map(|s| {
 3432                            let anchor = snapshot.anchor_after(s.head());
 3433                            s.map(|_| anchor)
 3434                        })
 3435                        .collect::<Vec<_>>()
 3436                };
 3437                buffer.edit(
 3438                    old_selections
 3439                        .iter()
 3440                        .map(|s| (s.start..s.end, text.clone())),
 3441                    autoindent_mode,
 3442                    cx,
 3443                );
 3444                anchors
 3445            });
 3446
 3447            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3448                s.select_anchors(selection_anchors);
 3449            });
 3450
 3451            cx.notify();
 3452        });
 3453    }
 3454
 3455    fn trigger_completion_on_input(
 3456        &mut self,
 3457        text: &str,
 3458        trigger_in_words: bool,
 3459        window: &mut Window,
 3460        cx: &mut Context<Self>,
 3461    ) {
 3462        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3463            self.show_completions(
 3464                &ShowCompletions {
 3465                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3466                },
 3467                window,
 3468                cx,
 3469            );
 3470        } else {
 3471            self.hide_context_menu(window, cx);
 3472        }
 3473    }
 3474
 3475    fn is_completion_trigger(
 3476        &self,
 3477        text: &str,
 3478        trigger_in_words: bool,
 3479        cx: &mut Context<Self>,
 3480    ) -> bool {
 3481        let position = self.selections.newest_anchor().head();
 3482        let multibuffer = self.buffer.read(cx);
 3483        let Some(buffer) = position
 3484            .buffer_id
 3485            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3486        else {
 3487            return false;
 3488        };
 3489
 3490        if let Some(completion_provider) = &self.completion_provider {
 3491            completion_provider.is_completion_trigger(
 3492                &buffer,
 3493                position.text_anchor,
 3494                text,
 3495                trigger_in_words,
 3496                cx,
 3497            )
 3498        } else {
 3499            false
 3500        }
 3501    }
 3502
 3503    /// If any empty selections is touching the start of its innermost containing autoclose
 3504    /// region, expand it to select the brackets.
 3505    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3506        let selections = self.selections.all::<usize>(cx);
 3507        let buffer = self.buffer.read(cx).read(cx);
 3508        let new_selections = self
 3509            .selections_with_autoclose_regions(selections, &buffer)
 3510            .map(|(mut selection, region)| {
 3511                if !selection.is_empty() {
 3512                    return selection;
 3513                }
 3514
 3515                if let Some(region) = region {
 3516                    let mut range = region.range.to_offset(&buffer);
 3517                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3518                        range.start -= region.pair.start.len();
 3519                        if buffer.contains_str_at(range.start, &region.pair.start)
 3520                            && buffer.contains_str_at(range.end, &region.pair.end)
 3521                        {
 3522                            range.end += region.pair.end.len();
 3523                            selection.start = range.start;
 3524                            selection.end = range.end;
 3525
 3526                            return selection;
 3527                        }
 3528                    }
 3529                }
 3530
 3531                let always_treat_brackets_as_autoclosed = buffer
 3532                    .settings_at(selection.start, cx)
 3533                    .always_treat_brackets_as_autoclosed;
 3534
 3535                if !always_treat_brackets_as_autoclosed {
 3536                    return selection;
 3537                }
 3538
 3539                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3540                    for (pair, enabled) in scope.brackets() {
 3541                        if !enabled || !pair.close {
 3542                            continue;
 3543                        }
 3544
 3545                        if buffer.contains_str_at(selection.start, &pair.end) {
 3546                            let pair_start_len = pair.start.len();
 3547                            if buffer.contains_str_at(
 3548                                selection.start.saturating_sub(pair_start_len),
 3549                                &pair.start,
 3550                            ) {
 3551                                selection.start -= pair_start_len;
 3552                                selection.end += pair.end.len();
 3553
 3554                                return selection;
 3555                            }
 3556                        }
 3557                    }
 3558                }
 3559
 3560                selection
 3561            })
 3562            .collect();
 3563
 3564        drop(buffer);
 3565        self.change_selections(None, window, cx, |selections| {
 3566            selections.select(new_selections)
 3567        });
 3568    }
 3569
 3570    /// Iterate the given selections, and for each one, find the smallest surrounding
 3571    /// autoclose region. This uses the ordering of the selections and the autoclose
 3572    /// regions to avoid repeated comparisons.
 3573    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3574        &'a self,
 3575        selections: impl IntoIterator<Item = Selection<D>>,
 3576        buffer: &'a MultiBufferSnapshot,
 3577    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3578        let mut i = 0;
 3579        let mut regions = self.autoclose_regions.as_slice();
 3580        selections.into_iter().map(move |selection| {
 3581            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3582
 3583            let mut enclosing = None;
 3584            while let Some(pair_state) = regions.get(i) {
 3585                if pair_state.range.end.to_offset(buffer) < range.start {
 3586                    regions = &regions[i + 1..];
 3587                    i = 0;
 3588                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3589                    break;
 3590                } else {
 3591                    if pair_state.selection_id == selection.id {
 3592                        enclosing = Some(pair_state);
 3593                    }
 3594                    i += 1;
 3595                }
 3596            }
 3597
 3598            (selection, enclosing)
 3599        })
 3600    }
 3601
 3602    /// Remove any autoclose regions that no longer contain their selection.
 3603    fn invalidate_autoclose_regions(
 3604        &mut self,
 3605        mut selections: &[Selection<Anchor>],
 3606        buffer: &MultiBufferSnapshot,
 3607    ) {
 3608        self.autoclose_regions.retain(|state| {
 3609            let mut i = 0;
 3610            while let Some(selection) = selections.get(i) {
 3611                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3612                    selections = &selections[1..];
 3613                    continue;
 3614                }
 3615                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3616                    break;
 3617                }
 3618                if selection.id == state.selection_id {
 3619                    return true;
 3620                } else {
 3621                    i += 1;
 3622                }
 3623            }
 3624            false
 3625        });
 3626    }
 3627
 3628    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3629        let offset = position.to_offset(buffer);
 3630        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3631        if offset > word_range.start && kind == Some(CharKind::Word) {
 3632            Some(
 3633                buffer
 3634                    .text_for_range(word_range.start..offset)
 3635                    .collect::<String>(),
 3636            )
 3637        } else {
 3638            None
 3639        }
 3640    }
 3641
 3642    pub fn toggle_inlay_hints(
 3643        &mut self,
 3644        _: &ToggleInlayHints,
 3645        _: &mut Window,
 3646        cx: &mut Context<Self>,
 3647    ) {
 3648        self.refresh_inlay_hints(
 3649            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3650            cx,
 3651        );
 3652    }
 3653
 3654    pub fn inlay_hints_enabled(&self) -> bool {
 3655        self.inlay_hint_cache.enabled
 3656    }
 3657
 3658    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3659        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3660            return;
 3661        }
 3662
 3663        let reason_description = reason.description();
 3664        let ignore_debounce = matches!(
 3665            reason,
 3666            InlayHintRefreshReason::SettingsChange(_)
 3667                | InlayHintRefreshReason::Toggle(_)
 3668                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3669        );
 3670        let (invalidate_cache, required_languages) = match reason {
 3671            InlayHintRefreshReason::Toggle(enabled) => {
 3672                self.inlay_hint_cache.enabled = enabled;
 3673                if enabled {
 3674                    (InvalidationStrategy::RefreshRequested, None)
 3675                } else {
 3676                    self.inlay_hint_cache.clear();
 3677                    self.splice_inlays(
 3678                        &self
 3679                            .visible_inlay_hints(cx)
 3680                            .iter()
 3681                            .map(|inlay| inlay.id)
 3682                            .collect::<Vec<InlayId>>(),
 3683                        Vec::new(),
 3684                        cx,
 3685                    );
 3686                    return;
 3687                }
 3688            }
 3689            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3690                match self.inlay_hint_cache.update_settings(
 3691                    &self.buffer,
 3692                    new_settings,
 3693                    self.visible_inlay_hints(cx),
 3694                    cx,
 3695                ) {
 3696                    ControlFlow::Break(Some(InlaySplice {
 3697                        to_remove,
 3698                        to_insert,
 3699                    })) => {
 3700                        self.splice_inlays(&to_remove, to_insert, cx);
 3701                        return;
 3702                    }
 3703                    ControlFlow::Break(None) => return,
 3704                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3705                }
 3706            }
 3707            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3708                if let Some(InlaySplice {
 3709                    to_remove,
 3710                    to_insert,
 3711                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3712                {
 3713                    self.splice_inlays(&to_remove, to_insert, cx);
 3714                }
 3715                return;
 3716            }
 3717            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3718            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3719                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3720            }
 3721            InlayHintRefreshReason::RefreshRequested => {
 3722                (InvalidationStrategy::RefreshRequested, None)
 3723            }
 3724        };
 3725
 3726        if let Some(InlaySplice {
 3727            to_remove,
 3728            to_insert,
 3729        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3730            reason_description,
 3731            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3732            invalidate_cache,
 3733            ignore_debounce,
 3734            cx,
 3735        ) {
 3736            self.splice_inlays(&to_remove, to_insert, cx);
 3737        }
 3738    }
 3739
 3740    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3741        self.display_map
 3742            .read(cx)
 3743            .current_inlays()
 3744            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3745            .cloned()
 3746            .collect()
 3747    }
 3748
 3749    pub fn excerpts_for_inlay_hints_query(
 3750        &self,
 3751        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3752        cx: &mut Context<Editor>,
 3753    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3754        let Some(project) = self.project.as_ref() else {
 3755            return HashMap::default();
 3756        };
 3757        let project = project.read(cx);
 3758        let multi_buffer = self.buffer().read(cx);
 3759        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3760        let multi_buffer_visible_start = self
 3761            .scroll_manager
 3762            .anchor()
 3763            .anchor
 3764            .to_point(&multi_buffer_snapshot);
 3765        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3766            multi_buffer_visible_start
 3767                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3768            Bias::Left,
 3769        );
 3770        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3771        multi_buffer_snapshot
 3772            .range_to_buffer_ranges(multi_buffer_visible_range)
 3773            .into_iter()
 3774            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3775            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3776                let buffer_file = project::File::from_dyn(buffer.file())?;
 3777                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3778                let worktree_entry = buffer_worktree
 3779                    .read(cx)
 3780                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3781                if worktree_entry.is_ignored {
 3782                    return None;
 3783                }
 3784
 3785                let language = buffer.language()?;
 3786                if let Some(restrict_to_languages) = restrict_to_languages {
 3787                    if !restrict_to_languages.contains(language) {
 3788                        return None;
 3789                    }
 3790                }
 3791                Some((
 3792                    excerpt_id,
 3793                    (
 3794                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3795                        buffer.version().clone(),
 3796                        excerpt_visible_range,
 3797                    ),
 3798                ))
 3799            })
 3800            .collect()
 3801    }
 3802
 3803    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3804        TextLayoutDetails {
 3805            text_system: window.text_system().clone(),
 3806            editor_style: self.style.clone().unwrap(),
 3807            rem_size: window.rem_size(),
 3808            scroll_anchor: self.scroll_manager.anchor(),
 3809            visible_rows: self.visible_line_count(),
 3810            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3811        }
 3812    }
 3813
 3814    pub fn splice_inlays(
 3815        &self,
 3816        to_remove: &[InlayId],
 3817        to_insert: Vec<Inlay>,
 3818        cx: &mut Context<Self>,
 3819    ) {
 3820        self.display_map.update(cx, |display_map, cx| {
 3821            display_map.splice_inlays(to_remove, to_insert, cx)
 3822        });
 3823        cx.notify();
 3824    }
 3825
 3826    fn trigger_on_type_formatting(
 3827        &self,
 3828        input: String,
 3829        window: &mut Window,
 3830        cx: &mut Context<Self>,
 3831    ) -> Option<Task<Result<()>>> {
 3832        if input.len() != 1 {
 3833            return None;
 3834        }
 3835
 3836        let project = self.project.as_ref()?;
 3837        let position = self.selections.newest_anchor().head();
 3838        let (buffer, buffer_position) = self
 3839            .buffer
 3840            .read(cx)
 3841            .text_anchor_for_position(position, cx)?;
 3842
 3843        let settings = language_settings::language_settings(
 3844            buffer
 3845                .read(cx)
 3846                .language_at(buffer_position)
 3847                .map(|l| l.name()),
 3848            buffer.read(cx).file(),
 3849            cx,
 3850        );
 3851        if !settings.use_on_type_format {
 3852            return None;
 3853        }
 3854
 3855        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3856        // hence we do LSP request & edit on host side only — add formats to host's history.
 3857        let push_to_lsp_host_history = true;
 3858        // If this is not the host, append its history with new edits.
 3859        let push_to_client_history = project.read(cx).is_via_collab();
 3860
 3861        let on_type_formatting = project.update(cx, |project, cx| {
 3862            project.on_type_format(
 3863                buffer.clone(),
 3864                buffer_position,
 3865                input,
 3866                push_to_lsp_host_history,
 3867                cx,
 3868            )
 3869        });
 3870        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3871            if let Some(transaction) = on_type_formatting.await? {
 3872                if push_to_client_history {
 3873                    buffer
 3874                        .update(&mut cx, |buffer, _| {
 3875                            buffer.push_transaction(transaction, Instant::now());
 3876                        })
 3877                        .ok();
 3878                }
 3879                editor.update(&mut cx, |editor, cx| {
 3880                    editor.refresh_document_highlights(cx);
 3881                })?;
 3882            }
 3883            Ok(())
 3884        }))
 3885    }
 3886
 3887    pub fn show_completions(
 3888        &mut self,
 3889        options: &ShowCompletions,
 3890        window: &mut Window,
 3891        cx: &mut Context<Self>,
 3892    ) {
 3893        if self.pending_rename.is_some() {
 3894            return;
 3895        }
 3896
 3897        let Some(provider) = self.completion_provider.as_ref() else {
 3898            return;
 3899        };
 3900
 3901        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3902            return;
 3903        }
 3904
 3905        let position = self.selections.newest_anchor().head();
 3906        if position.diff_base_anchor.is_some() {
 3907            return;
 3908        }
 3909        let (buffer, buffer_position) =
 3910            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3911                output
 3912            } else {
 3913                return;
 3914            };
 3915        let show_completion_documentation = buffer
 3916            .read(cx)
 3917            .snapshot()
 3918            .settings_at(buffer_position, cx)
 3919            .show_completion_documentation;
 3920
 3921        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3922
 3923        let trigger_kind = match &options.trigger {
 3924            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3925                CompletionTriggerKind::TRIGGER_CHARACTER
 3926            }
 3927            _ => CompletionTriggerKind::INVOKED,
 3928        };
 3929        let completion_context = CompletionContext {
 3930            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3931                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3932                    Some(String::from(trigger))
 3933                } else {
 3934                    None
 3935                }
 3936            }),
 3937            trigger_kind,
 3938        };
 3939        let completions =
 3940            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3941        let sort_completions = provider.sort_completions();
 3942
 3943        let id = post_inc(&mut self.next_completion_id);
 3944        let task = cx.spawn_in(window, |editor, mut cx| {
 3945            async move {
 3946                editor.update(&mut cx, |this, _| {
 3947                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3948                })?;
 3949                let completions = completions.await.log_err();
 3950                let menu = if let Some(completions) = completions {
 3951                    let mut menu = CompletionsMenu::new(
 3952                        id,
 3953                        sort_completions,
 3954                        show_completion_documentation,
 3955                        position,
 3956                        buffer.clone(),
 3957                        completions.into(),
 3958                    );
 3959
 3960                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3961                        .await;
 3962
 3963                    menu.visible().then_some(menu)
 3964                } else {
 3965                    None
 3966                };
 3967
 3968                editor.update_in(&mut cx, |editor, window, cx| {
 3969                    match editor.context_menu.borrow().as_ref() {
 3970                        None => {}
 3971                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3972                            if prev_menu.id > id {
 3973                                return;
 3974                            }
 3975                        }
 3976                        _ => return,
 3977                    }
 3978
 3979                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3980                        let mut menu = menu.unwrap();
 3981                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3982
 3983                        *editor.context_menu.borrow_mut() =
 3984                            Some(CodeContextMenu::Completions(menu));
 3985
 3986                        if editor.show_edit_predictions_in_menu() {
 3987                            editor.update_visible_inline_completion(window, cx);
 3988                        } else {
 3989                            editor.discard_inline_completion(false, cx);
 3990                        }
 3991
 3992                        cx.notify();
 3993                    } else if editor.completion_tasks.len() <= 1 {
 3994                        // If there are no more completion tasks and the last menu was
 3995                        // empty, we should hide it.
 3996                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3997                        // If it was already hidden and we don't show inline
 3998                        // completions in the menu, we should also show the
 3999                        // inline-completion when available.
 4000                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4001                            editor.update_visible_inline_completion(window, cx);
 4002                        }
 4003                    }
 4004                })?;
 4005
 4006                Ok::<_, anyhow::Error>(())
 4007            }
 4008            .log_err()
 4009        });
 4010
 4011        self.completion_tasks.push((id, task));
 4012    }
 4013
 4014    pub fn confirm_completion(
 4015        &mut self,
 4016        action: &ConfirmCompletion,
 4017        window: &mut Window,
 4018        cx: &mut Context<Self>,
 4019    ) -> Option<Task<Result<()>>> {
 4020        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4021    }
 4022
 4023    pub fn compose_completion(
 4024        &mut self,
 4025        action: &ComposeCompletion,
 4026        window: &mut Window,
 4027        cx: &mut Context<Self>,
 4028    ) -> Option<Task<Result<()>>> {
 4029        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4030    }
 4031
 4032    fn do_completion(
 4033        &mut self,
 4034        item_ix: Option<usize>,
 4035        intent: CompletionIntent,
 4036        window: &mut Window,
 4037        cx: &mut Context<Editor>,
 4038    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4039        use language::ToOffset as _;
 4040
 4041        let completions_menu =
 4042            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4043                menu
 4044            } else {
 4045                return None;
 4046            };
 4047
 4048        let entries = completions_menu.entries.borrow();
 4049        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4050        if self.show_edit_predictions_in_menu() {
 4051            self.discard_inline_completion(true, cx);
 4052        }
 4053        let candidate_id = mat.candidate_id;
 4054        drop(entries);
 4055
 4056        let buffer_handle = completions_menu.buffer;
 4057        let completion = completions_menu
 4058            .completions
 4059            .borrow()
 4060            .get(candidate_id)?
 4061            .clone();
 4062        cx.stop_propagation();
 4063
 4064        let snippet;
 4065        let text;
 4066
 4067        if completion.is_snippet() {
 4068            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4069            text = snippet.as_ref().unwrap().text.clone();
 4070        } else {
 4071            snippet = None;
 4072            text = completion.new_text.clone();
 4073        };
 4074        let selections = self.selections.all::<usize>(cx);
 4075        let buffer = buffer_handle.read(cx);
 4076        let old_range = completion.old_range.to_offset(buffer);
 4077        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4078
 4079        let newest_selection = self.selections.newest_anchor();
 4080        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4081            return None;
 4082        }
 4083
 4084        let lookbehind = newest_selection
 4085            .start
 4086            .text_anchor
 4087            .to_offset(buffer)
 4088            .saturating_sub(old_range.start);
 4089        let lookahead = old_range
 4090            .end
 4091            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4092        let mut common_prefix_len = old_text
 4093            .bytes()
 4094            .zip(text.bytes())
 4095            .take_while(|(a, b)| a == b)
 4096            .count();
 4097
 4098        let snapshot = self.buffer.read(cx).snapshot(cx);
 4099        let mut range_to_replace: Option<Range<isize>> = None;
 4100        let mut ranges = Vec::new();
 4101        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4102        for selection in &selections {
 4103            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4104                let start = selection.start.saturating_sub(lookbehind);
 4105                let end = selection.end + lookahead;
 4106                if selection.id == newest_selection.id {
 4107                    range_to_replace = Some(
 4108                        ((start + common_prefix_len) as isize - selection.start as isize)
 4109                            ..(end as isize - selection.start as isize),
 4110                    );
 4111                }
 4112                ranges.push(start + common_prefix_len..end);
 4113            } else {
 4114                common_prefix_len = 0;
 4115                ranges.clear();
 4116                ranges.extend(selections.iter().map(|s| {
 4117                    if s.id == newest_selection.id {
 4118                        range_to_replace = Some(
 4119                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4120                                - selection.start as isize
 4121                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4122                                    - selection.start as isize,
 4123                        );
 4124                        old_range.clone()
 4125                    } else {
 4126                        s.start..s.end
 4127                    }
 4128                }));
 4129                break;
 4130            }
 4131            if !self.linked_edit_ranges.is_empty() {
 4132                let start_anchor = snapshot.anchor_before(selection.head());
 4133                let end_anchor = snapshot.anchor_after(selection.tail());
 4134                if let Some(ranges) = self
 4135                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4136                {
 4137                    for (buffer, edits) in ranges {
 4138                        linked_edits.entry(buffer.clone()).or_default().extend(
 4139                            edits
 4140                                .into_iter()
 4141                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4142                        );
 4143                    }
 4144                }
 4145            }
 4146        }
 4147        let text = &text[common_prefix_len..];
 4148
 4149        cx.emit(EditorEvent::InputHandled {
 4150            utf16_range_to_replace: range_to_replace,
 4151            text: text.into(),
 4152        });
 4153
 4154        self.transact(window, cx, |this, window, cx| {
 4155            if let Some(mut snippet) = snippet {
 4156                snippet.text = text.to_string();
 4157                for tabstop in snippet
 4158                    .tabstops
 4159                    .iter_mut()
 4160                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4161                {
 4162                    tabstop.start -= common_prefix_len as isize;
 4163                    tabstop.end -= common_prefix_len as isize;
 4164                }
 4165
 4166                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4167            } else {
 4168                this.buffer.update(cx, |buffer, cx| {
 4169                    buffer.edit(
 4170                        ranges.iter().map(|range| (range.clone(), text)),
 4171                        this.autoindent_mode.clone(),
 4172                        cx,
 4173                    );
 4174                });
 4175            }
 4176            for (buffer, edits) in linked_edits {
 4177                buffer.update(cx, |buffer, cx| {
 4178                    let snapshot = buffer.snapshot();
 4179                    let edits = edits
 4180                        .into_iter()
 4181                        .map(|(range, text)| {
 4182                            use text::ToPoint as TP;
 4183                            let end_point = TP::to_point(&range.end, &snapshot);
 4184                            let start_point = TP::to_point(&range.start, &snapshot);
 4185                            (start_point..end_point, text)
 4186                        })
 4187                        .sorted_by_key(|(range, _)| range.start)
 4188                        .collect::<Vec<_>>();
 4189                    buffer.edit(edits, None, cx);
 4190                })
 4191            }
 4192
 4193            this.refresh_inline_completion(true, false, window, cx);
 4194        });
 4195
 4196        let show_new_completions_on_confirm = completion
 4197            .confirm
 4198            .as_ref()
 4199            .map_or(false, |confirm| confirm(intent, window, cx));
 4200        if show_new_completions_on_confirm {
 4201            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4202        }
 4203
 4204        let provider = self.completion_provider.as_ref()?;
 4205        drop(completion);
 4206        let apply_edits = provider.apply_additional_edits_for_completion(
 4207            buffer_handle,
 4208            completions_menu.completions.clone(),
 4209            candidate_id,
 4210            true,
 4211            cx,
 4212        );
 4213
 4214        let editor_settings = EditorSettings::get_global(cx);
 4215        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4216            // After the code completion is finished, users often want to know what signatures are needed.
 4217            // so we should automatically call signature_help
 4218            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4219        }
 4220
 4221        Some(cx.foreground_executor().spawn(async move {
 4222            apply_edits.await?;
 4223            Ok(())
 4224        }))
 4225    }
 4226
 4227    pub fn toggle_code_actions(
 4228        &mut self,
 4229        action: &ToggleCodeActions,
 4230        window: &mut Window,
 4231        cx: &mut Context<Self>,
 4232    ) {
 4233        let mut context_menu = self.context_menu.borrow_mut();
 4234        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4235            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4236                // Toggle if we're selecting the same one
 4237                *context_menu = None;
 4238                cx.notify();
 4239                return;
 4240            } else {
 4241                // Otherwise, clear it and start a new one
 4242                *context_menu = None;
 4243                cx.notify();
 4244            }
 4245        }
 4246        drop(context_menu);
 4247        let snapshot = self.snapshot(window, cx);
 4248        let deployed_from_indicator = action.deployed_from_indicator;
 4249        let mut task = self.code_actions_task.take();
 4250        let action = action.clone();
 4251        cx.spawn_in(window, |editor, mut cx| async move {
 4252            while let Some(prev_task) = task {
 4253                prev_task.await.log_err();
 4254                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4255            }
 4256
 4257            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4258                if editor.focus_handle.is_focused(window) {
 4259                    let multibuffer_point = action
 4260                        .deployed_from_indicator
 4261                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4262                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4263                    let (buffer, buffer_row) = snapshot
 4264                        .buffer_snapshot
 4265                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4266                        .and_then(|(buffer_snapshot, range)| {
 4267                            editor
 4268                                .buffer
 4269                                .read(cx)
 4270                                .buffer(buffer_snapshot.remote_id())
 4271                                .map(|buffer| (buffer, range.start.row))
 4272                        })?;
 4273                    let (_, code_actions) = editor
 4274                        .available_code_actions
 4275                        .clone()
 4276                        .and_then(|(location, code_actions)| {
 4277                            let snapshot = location.buffer.read(cx).snapshot();
 4278                            let point_range = location.range.to_point(&snapshot);
 4279                            let point_range = point_range.start.row..=point_range.end.row;
 4280                            if point_range.contains(&buffer_row) {
 4281                                Some((location, code_actions))
 4282                            } else {
 4283                                None
 4284                            }
 4285                        })
 4286                        .unzip();
 4287                    let buffer_id = buffer.read(cx).remote_id();
 4288                    let tasks = editor
 4289                        .tasks
 4290                        .get(&(buffer_id, buffer_row))
 4291                        .map(|t| Arc::new(t.to_owned()));
 4292                    if tasks.is_none() && code_actions.is_none() {
 4293                        return None;
 4294                    }
 4295
 4296                    editor.completion_tasks.clear();
 4297                    editor.discard_inline_completion(false, cx);
 4298                    let task_context =
 4299                        tasks
 4300                            .as_ref()
 4301                            .zip(editor.project.clone())
 4302                            .map(|(tasks, project)| {
 4303                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4304                            });
 4305
 4306                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4307                        let task_context = match task_context {
 4308                            Some(task_context) => task_context.await,
 4309                            None => None,
 4310                        };
 4311                        let resolved_tasks =
 4312                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4313                                Rc::new(ResolvedTasks {
 4314                                    templates: tasks.resolve(&task_context).collect(),
 4315                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4316                                        multibuffer_point.row,
 4317                                        tasks.column,
 4318                                    )),
 4319                                })
 4320                            });
 4321                        let spawn_straight_away = resolved_tasks
 4322                            .as_ref()
 4323                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4324                            && code_actions
 4325                                .as_ref()
 4326                                .map_or(true, |actions| actions.is_empty());
 4327                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4328                            *editor.context_menu.borrow_mut() =
 4329                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4330                                    buffer,
 4331                                    actions: CodeActionContents {
 4332                                        tasks: resolved_tasks,
 4333                                        actions: code_actions,
 4334                                    },
 4335                                    selected_item: Default::default(),
 4336                                    scroll_handle: UniformListScrollHandle::default(),
 4337                                    deployed_from_indicator,
 4338                                }));
 4339                            if spawn_straight_away {
 4340                                if let Some(task) = editor.confirm_code_action(
 4341                                    &ConfirmCodeAction { item_ix: Some(0) },
 4342                                    window,
 4343                                    cx,
 4344                                ) {
 4345                                    cx.notify();
 4346                                    return task;
 4347                                }
 4348                            }
 4349                            cx.notify();
 4350                            Task::ready(Ok(()))
 4351                        }) {
 4352                            task.await
 4353                        } else {
 4354                            Ok(())
 4355                        }
 4356                    }))
 4357                } else {
 4358                    Some(Task::ready(Ok(())))
 4359                }
 4360            })?;
 4361            if let Some(task) = spawned_test_task {
 4362                task.await?;
 4363            }
 4364
 4365            Ok::<_, anyhow::Error>(())
 4366        })
 4367        .detach_and_log_err(cx);
 4368    }
 4369
 4370    pub fn confirm_code_action(
 4371        &mut self,
 4372        action: &ConfirmCodeAction,
 4373        window: &mut Window,
 4374        cx: &mut Context<Self>,
 4375    ) -> Option<Task<Result<()>>> {
 4376        let actions_menu =
 4377            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4378                menu
 4379            } else {
 4380                return None;
 4381            };
 4382        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4383        let action = actions_menu.actions.get(action_ix)?;
 4384        let title = action.label();
 4385        let buffer = actions_menu.buffer;
 4386        let workspace = self.workspace()?;
 4387
 4388        match action {
 4389            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4390                workspace.update(cx, |workspace, cx| {
 4391                    workspace::tasks::schedule_resolved_task(
 4392                        workspace,
 4393                        task_source_kind,
 4394                        resolved_task,
 4395                        false,
 4396                        cx,
 4397                    );
 4398
 4399                    Some(Task::ready(Ok(())))
 4400                })
 4401            }
 4402            CodeActionsItem::CodeAction {
 4403                excerpt_id,
 4404                action,
 4405                provider,
 4406            } => {
 4407                let apply_code_action =
 4408                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4409                let workspace = workspace.downgrade();
 4410                Some(cx.spawn_in(window, |editor, cx| async move {
 4411                    let project_transaction = apply_code_action.await?;
 4412                    Self::open_project_transaction(
 4413                        &editor,
 4414                        workspace,
 4415                        project_transaction,
 4416                        title,
 4417                        cx,
 4418                    )
 4419                    .await
 4420                }))
 4421            }
 4422        }
 4423    }
 4424
 4425    pub async fn open_project_transaction(
 4426        this: &WeakEntity<Editor>,
 4427        workspace: WeakEntity<Workspace>,
 4428        transaction: ProjectTransaction,
 4429        title: String,
 4430        mut cx: AsyncWindowContext,
 4431    ) -> Result<()> {
 4432        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4433        cx.update(|_, cx| {
 4434            entries.sort_unstable_by_key(|(buffer, _)| {
 4435                buffer.read(cx).file().map(|f| f.path().clone())
 4436            });
 4437        })?;
 4438
 4439        // If the project transaction's edits are all contained within this editor, then
 4440        // avoid opening a new editor to display them.
 4441
 4442        if let Some((buffer, transaction)) = entries.first() {
 4443            if entries.len() == 1 {
 4444                let excerpt = this.update(&mut cx, |editor, cx| {
 4445                    editor
 4446                        .buffer()
 4447                        .read(cx)
 4448                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4449                })?;
 4450                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4451                    if excerpted_buffer == *buffer {
 4452                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4453                            let excerpt_range = excerpt_range.to_offset(buffer);
 4454                            buffer
 4455                                .edited_ranges_for_transaction::<usize>(transaction)
 4456                                .all(|range| {
 4457                                    excerpt_range.start <= range.start
 4458                                        && excerpt_range.end >= range.end
 4459                                })
 4460                        })?;
 4461
 4462                        if all_edits_within_excerpt {
 4463                            return Ok(());
 4464                        }
 4465                    }
 4466                }
 4467            }
 4468        } else {
 4469            return Ok(());
 4470        }
 4471
 4472        let mut ranges_to_highlight = Vec::new();
 4473        let excerpt_buffer = cx.new(|cx| {
 4474            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4475            for (buffer_handle, transaction) in &entries {
 4476                let buffer = buffer_handle.read(cx);
 4477                ranges_to_highlight.extend(
 4478                    multibuffer.push_excerpts_with_context_lines(
 4479                        buffer_handle.clone(),
 4480                        buffer
 4481                            .edited_ranges_for_transaction::<usize>(transaction)
 4482                            .collect(),
 4483                        DEFAULT_MULTIBUFFER_CONTEXT,
 4484                        cx,
 4485                    ),
 4486                );
 4487            }
 4488            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4489            multibuffer
 4490        })?;
 4491
 4492        workspace.update_in(&mut cx, |workspace, window, cx| {
 4493            let project = workspace.project().clone();
 4494            let editor = cx
 4495                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4496            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4497            editor.update(cx, |editor, cx| {
 4498                editor.highlight_background::<Self>(
 4499                    &ranges_to_highlight,
 4500                    |theme| theme.editor_highlighted_line_background,
 4501                    cx,
 4502                );
 4503            });
 4504        })?;
 4505
 4506        Ok(())
 4507    }
 4508
 4509    pub fn clear_code_action_providers(&mut self) {
 4510        self.code_action_providers.clear();
 4511        self.available_code_actions.take();
 4512    }
 4513
 4514    pub fn add_code_action_provider(
 4515        &mut self,
 4516        provider: Rc<dyn CodeActionProvider>,
 4517        window: &mut Window,
 4518        cx: &mut Context<Self>,
 4519    ) {
 4520        if self
 4521            .code_action_providers
 4522            .iter()
 4523            .any(|existing_provider| existing_provider.id() == provider.id())
 4524        {
 4525            return;
 4526        }
 4527
 4528        self.code_action_providers.push(provider);
 4529        self.refresh_code_actions(window, cx);
 4530    }
 4531
 4532    pub fn remove_code_action_provider(
 4533        &mut self,
 4534        id: Arc<str>,
 4535        window: &mut Window,
 4536        cx: &mut Context<Self>,
 4537    ) {
 4538        self.code_action_providers
 4539            .retain(|provider| provider.id() != id);
 4540        self.refresh_code_actions(window, cx);
 4541    }
 4542
 4543    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4544        let buffer = self.buffer.read(cx);
 4545        let newest_selection = self.selections.newest_anchor().clone();
 4546        if newest_selection.head().diff_base_anchor.is_some() {
 4547            return None;
 4548        }
 4549        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4550        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4551        if start_buffer != end_buffer {
 4552            return None;
 4553        }
 4554
 4555        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4556            cx.background_executor()
 4557                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4558                .await;
 4559
 4560            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4561                let providers = this.code_action_providers.clone();
 4562                let tasks = this
 4563                    .code_action_providers
 4564                    .iter()
 4565                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4566                    .collect::<Vec<_>>();
 4567                (providers, tasks)
 4568            })?;
 4569
 4570            let mut actions = Vec::new();
 4571            for (provider, provider_actions) in
 4572                providers.into_iter().zip(future::join_all(tasks).await)
 4573            {
 4574                if let Some(provider_actions) = provider_actions.log_err() {
 4575                    actions.extend(provider_actions.into_iter().map(|action| {
 4576                        AvailableCodeAction {
 4577                            excerpt_id: newest_selection.start.excerpt_id,
 4578                            action,
 4579                            provider: provider.clone(),
 4580                        }
 4581                    }));
 4582                }
 4583            }
 4584
 4585            this.update(&mut cx, |this, cx| {
 4586                this.available_code_actions = if actions.is_empty() {
 4587                    None
 4588                } else {
 4589                    Some((
 4590                        Location {
 4591                            buffer: start_buffer,
 4592                            range: start..end,
 4593                        },
 4594                        actions.into(),
 4595                    ))
 4596                };
 4597                cx.notify();
 4598            })
 4599        }));
 4600        None
 4601    }
 4602
 4603    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4604        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4605            self.show_git_blame_inline = false;
 4606
 4607            self.show_git_blame_inline_delay_task =
 4608                Some(cx.spawn_in(window, |this, mut cx| async move {
 4609                    cx.background_executor().timer(delay).await;
 4610
 4611                    this.update(&mut cx, |this, cx| {
 4612                        this.show_git_blame_inline = true;
 4613                        cx.notify();
 4614                    })
 4615                    .log_err();
 4616                }));
 4617        }
 4618    }
 4619
 4620    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4621        if self.pending_rename.is_some() {
 4622            return None;
 4623        }
 4624
 4625        let provider = self.semantics_provider.clone()?;
 4626        let buffer = self.buffer.read(cx);
 4627        let newest_selection = self.selections.newest_anchor().clone();
 4628        let cursor_position = newest_selection.head();
 4629        let (cursor_buffer, cursor_buffer_position) =
 4630            buffer.text_anchor_for_position(cursor_position, cx)?;
 4631        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4632        if cursor_buffer != tail_buffer {
 4633            return None;
 4634        }
 4635        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4636        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4637            cx.background_executor()
 4638                .timer(Duration::from_millis(debounce))
 4639                .await;
 4640
 4641            let highlights = if let Some(highlights) = cx
 4642                .update(|cx| {
 4643                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4644                })
 4645                .ok()
 4646                .flatten()
 4647            {
 4648                highlights.await.log_err()
 4649            } else {
 4650                None
 4651            };
 4652
 4653            if let Some(highlights) = highlights {
 4654                this.update(&mut cx, |this, cx| {
 4655                    if this.pending_rename.is_some() {
 4656                        return;
 4657                    }
 4658
 4659                    let buffer_id = cursor_position.buffer_id;
 4660                    let buffer = this.buffer.read(cx);
 4661                    if !buffer
 4662                        .text_anchor_for_position(cursor_position, cx)
 4663                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4664                    {
 4665                        return;
 4666                    }
 4667
 4668                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4669                    let mut write_ranges = Vec::new();
 4670                    let mut read_ranges = Vec::new();
 4671                    for highlight in highlights {
 4672                        for (excerpt_id, excerpt_range) in
 4673                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4674                        {
 4675                            let start = highlight
 4676                                .range
 4677                                .start
 4678                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4679                            let end = highlight
 4680                                .range
 4681                                .end
 4682                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4683                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4684                                continue;
 4685                            }
 4686
 4687                            let range = Anchor {
 4688                                buffer_id,
 4689                                excerpt_id,
 4690                                text_anchor: start,
 4691                                diff_base_anchor: None,
 4692                            }..Anchor {
 4693                                buffer_id,
 4694                                excerpt_id,
 4695                                text_anchor: end,
 4696                                diff_base_anchor: None,
 4697                            };
 4698                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4699                                write_ranges.push(range);
 4700                            } else {
 4701                                read_ranges.push(range);
 4702                            }
 4703                        }
 4704                    }
 4705
 4706                    this.highlight_background::<DocumentHighlightRead>(
 4707                        &read_ranges,
 4708                        |theme| theme.editor_document_highlight_read_background,
 4709                        cx,
 4710                    );
 4711                    this.highlight_background::<DocumentHighlightWrite>(
 4712                        &write_ranges,
 4713                        |theme| theme.editor_document_highlight_write_background,
 4714                        cx,
 4715                    );
 4716                    cx.notify();
 4717                })
 4718                .log_err();
 4719            }
 4720        }));
 4721        None
 4722    }
 4723
 4724    pub fn refresh_selected_text_highlights(
 4725        &mut self,
 4726        window: &mut Window,
 4727        cx: &mut Context<Editor>,
 4728    ) {
 4729        self.selection_highlight_task.take();
 4730        if !EditorSettings::get_global(cx).selection_highlight {
 4731            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4732            return;
 4733        }
 4734        if self.selections.count() != 1 || self.selections.line_mode {
 4735            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4736            return;
 4737        }
 4738        let selection = self.selections.newest::<Point>(cx);
 4739        if selection.is_empty() || selection.start.row != selection.end.row {
 4740            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4741            return;
 4742        }
 4743        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4744        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4745            cx.background_executor()
 4746                .timer(Duration::from_millis(debounce))
 4747                .await;
 4748            let Some(Some(matches_task)) = editor
 4749                .update_in(&mut cx, |editor, _, cx| {
 4750                    if editor.selections.count() != 1 || editor.selections.line_mode {
 4751                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4752                        return None;
 4753                    }
 4754                    let selection = editor.selections.newest::<Point>(cx);
 4755                    if selection.is_empty() || selection.start.row != selection.end.row {
 4756                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4757                        return None;
 4758                    }
 4759                    let buffer = editor.buffer().read(cx).snapshot(cx);
 4760                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 4761                    if query.trim().is_empty() {
 4762                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4763                        return None;
 4764                    }
 4765                    Some(cx.background_spawn(async move {
 4766                        let mut ranges = Vec::new();
 4767                        let selection_anchors = selection.range().to_anchors(&buffer);
 4768                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 4769                            for (search_buffer, search_range, excerpt_id) in
 4770                                buffer.range_to_buffer_ranges(range)
 4771                            {
 4772                                ranges.extend(
 4773                                    project::search::SearchQuery::text(
 4774                                        query.clone(),
 4775                                        false,
 4776                                        false,
 4777                                        false,
 4778                                        Default::default(),
 4779                                        Default::default(),
 4780                                        None,
 4781                                    )
 4782                                    .unwrap()
 4783                                    .search(search_buffer, Some(search_range.clone()))
 4784                                    .await
 4785                                    .into_iter()
 4786                                    .filter_map(
 4787                                        |match_range| {
 4788                                            let start = search_buffer.anchor_after(
 4789                                                search_range.start + match_range.start,
 4790                                            );
 4791                                            let end = search_buffer.anchor_before(
 4792                                                search_range.start + match_range.end,
 4793                                            );
 4794                                            let range = Anchor::range_in_buffer(
 4795                                                excerpt_id,
 4796                                                search_buffer.remote_id(),
 4797                                                start..end,
 4798                                            );
 4799                                            (range != selection_anchors).then_some(range)
 4800                                        },
 4801                                    ),
 4802                                );
 4803                            }
 4804                        }
 4805                        ranges
 4806                    }))
 4807                })
 4808                .log_err()
 4809            else {
 4810                return;
 4811            };
 4812            let matches = matches_task.await;
 4813            editor
 4814                .update_in(&mut cx, |editor, _, cx| {
 4815                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4816                    if !matches.is_empty() {
 4817                        editor.highlight_background::<SelectedTextHighlight>(
 4818                            &matches,
 4819                            |theme| theme.editor_document_highlight_bracket_background,
 4820                            cx,
 4821                        )
 4822                    }
 4823                })
 4824                .log_err();
 4825        }));
 4826    }
 4827
 4828    pub fn refresh_inline_completion(
 4829        &mut self,
 4830        debounce: bool,
 4831        user_requested: bool,
 4832        window: &mut Window,
 4833        cx: &mut Context<Self>,
 4834    ) -> Option<()> {
 4835        let provider = self.edit_prediction_provider()?;
 4836        let cursor = self.selections.newest_anchor().head();
 4837        let (buffer, cursor_buffer_position) =
 4838            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4839
 4840        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4841            self.discard_inline_completion(false, cx);
 4842            return None;
 4843        }
 4844
 4845        if !user_requested
 4846            && (!self.should_show_edit_predictions()
 4847                || !self.is_focused(window)
 4848                || buffer.read(cx).is_empty())
 4849        {
 4850            self.discard_inline_completion(false, cx);
 4851            return None;
 4852        }
 4853
 4854        self.update_visible_inline_completion(window, cx);
 4855        provider.refresh(
 4856            self.project.clone(),
 4857            buffer,
 4858            cursor_buffer_position,
 4859            debounce,
 4860            cx,
 4861        );
 4862        Some(())
 4863    }
 4864
 4865    fn show_edit_predictions_in_menu(&self) -> bool {
 4866        match self.edit_prediction_settings {
 4867            EditPredictionSettings::Disabled => false,
 4868            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4869        }
 4870    }
 4871
 4872    pub fn edit_predictions_enabled(&self) -> bool {
 4873        match self.edit_prediction_settings {
 4874            EditPredictionSettings::Disabled => false,
 4875            EditPredictionSettings::Enabled { .. } => true,
 4876        }
 4877    }
 4878
 4879    fn edit_prediction_requires_modifier(&self) -> bool {
 4880        match self.edit_prediction_settings {
 4881            EditPredictionSettings::Disabled => false,
 4882            EditPredictionSettings::Enabled {
 4883                preview_requires_modifier,
 4884                ..
 4885            } => preview_requires_modifier,
 4886        }
 4887    }
 4888
 4889    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 4890        if self.edit_prediction_provider.is_none() {
 4891            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 4892        } else {
 4893            let selection = self.selections.newest_anchor();
 4894            let cursor = selection.head();
 4895
 4896            if let Some((buffer, cursor_buffer_position)) =
 4897                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4898            {
 4899                self.edit_prediction_settings =
 4900                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 4901            }
 4902        }
 4903    }
 4904
 4905    fn edit_prediction_settings_at_position(
 4906        &self,
 4907        buffer: &Entity<Buffer>,
 4908        buffer_position: language::Anchor,
 4909        cx: &App,
 4910    ) -> EditPredictionSettings {
 4911        if self.mode != EditorMode::Full
 4912            || !self.show_inline_completions_override.unwrap_or(true)
 4913            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4914        {
 4915            return EditPredictionSettings::Disabled;
 4916        }
 4917
 4918        let buffer = buffer.read(cx);
 4919
 4920        let file = buffer.file();
 4921
 4922        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4923            return EditPredictionSettings::Disabled;
 4924        };
 4925
 4926        let by_provider = matches!(
 4927            self.menu_inline_completions_policy,
 4928            MenuInlineCompletionsPolicy::ByProvider
 4929        );
 4930
 4931        let show_in_menu = by_provider
 4932            && self
 4933                .edit_prediction_provider
 4934                .as_ref()
 4935                .map_or(false, |provider| {
 4936                    provider.provider.show_completions_in_menu()
 4937                });
 4938
 4939        let preview_requires_modifier =
 4940            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4941
 4942        EditPredictionSettings::Enabled {
 4943            show_in_menu,
 4944            preview_requires_modifier,
 4945        }
 4946    }
 4947
 4948    fn should_show_edit_predictions(&self) -> bool {
 4949        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4950    }
 4951
 4952    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4953        matches!(
 4954            self.edit_prediction_preview,
 4955            EditPredictionPreview::Active { .. }
 4956        )
 4957    }
 4958
 4959    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 4960        let cursor = self.selections.newest_anchor().head();
 4961        if let Some((buffer, cursor_position)) =
 4962            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4963        {
 4964            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 4965        } else {
 4966            false
 4967        }
 4968    }
 4969
 4970    fn edit_predictions_enabled_in_buffer(
 4971        &self,
 4972        buffer: &Entity<Buffer>,
 4973        buffer_position: language::Anchor,
 4974        cx: &App,
 4975    ) -> bool {
 4976        maybe!({
 4977            let provider = self.edit_prediction_provider()?;
 4978            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4979                return Some(false);
 4980            }
 4981            let buffer = buffer.read(cx);
 4982            let Some(file) = buffer.file() else {
 4983                return Some(true);
 4984            };
 4985            let settings = all_language_settings(Some(file), cx);
 4986            Some(settings.inline_completions_enabled_for_path(file.path()))
 4987        })
 4988        .unwrap_or(false)
 4989    }
 4990
 4991    fn cycle_inline_completion(
 4992        &mut self,
 4993        direction: Direction,
 4994        window: &mut Window,
 4995        cx: &mut Context<Self>,
 4996    ) -> Option<()> {
 4997        let provider = self.edit_prediction_provider()?;
 4998        let cursor = self.selections.newest_anchor().head();
 4999        let (buffer, cursor_buffer_position) =
 5000            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5001        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5002            return None;
 5003        }
 5004
 5005        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5006        self.update_visible_inline_completion(window, cx);
 5007
 5008        Some(())
 5009    }
 5010
 5011    pub fn show_inline_completion(
 5012        &mut self,
 5013        _: &ShowEditPrediction,
 5014        window: &mut Window,
 5015        cx: &mut Context<Self>,
 5016    ) {
 5017        if !self.has_active_inline_completion() {
 5018            self.refresh_inline_completion(false, true, window, cx);
 5019            return;
 5020        }
 5021
 5022        self.update_visible_inline_completion(window, cx);
 5023    }
 5024
 5025    pub fn display_cursor_names(
 5026        &mut self,
 5027        _: &DisplayCursorNames,
 5028        window: &mut Window,
 5029        cx: &mut Context<Self>,
 5030    ) {
 5031        self.show_cursor_names(window, cx);
 5032    }
 5033
 5034    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5035        self.show_cursor_names = true;
 5036        cx.notify();
 5037        cx.spawn_in(window, |this, mut cx| async move {
 5038            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5039            this.update(&mut cx, |this, cx| {
 5040                this.show_cursor_names = false;
 5041                cx.notify()
 5042            })
 5043            .ok()
 5044        })
 5045        .detach();
 5046    }
 5047
 5048    pub fn next_edit_prediction(
 5049        &mut self,
 5050        _: &NextEditPrediction,
 5051        window: &mut Window,
 5052        cx: &mut Context<Self>,
 5053    ) {
 5054        if self.has_active_inline_completion() {
 5055            self.cycle_inline_completion(Direction::Next, window, cx);
 5056        } else {
 5057            let is_copilot_disabled = self
 5058                .refresh_inline_completion(false, true, window, cx)
 5059                .is_none();
 5060            if is_copilot_disabled {
 5061                cx.propagate();
 5062            }
 5063        }
 5064    }
 5065
 5066    pub fn previous_edit_prediction(
 5067        &mut self,
 5068        _: &PreviousEditPrediction,
 5069        window: &mut Window,
 5070        cx: &mut Context<Self>,
 5071    ) {
 5072        if self.has_active_inline_completion() {
 5073            self.cycle_inline_completion(Direction::Prev, window, cx);
 5074        } else {
 5075            let is_copilot_disabled = self
 5076                .refresh_inline_completion(false, true, window, cx)
 5077                .is_none();
 5078            if is_copilot_disabled {
 5079                cx.propagate();
 5080            }
 5081        }
 5082    }
 5083
 5084    pub fn accept_edit_prediction(
 5085        &mut self,
 5086        _: &AcceptEditPrediction,
 5087        window: &mut Window,
 5088        cx: &mut Context<Self>,
 5089    ) {
 5090        if self.show_edit_predictions_in_menu() {
 5091            self.hide_context_menu(window, cx);
 5092        }
 5093
 5094        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5095            return;
 5096        };
 5097
 5098        self.report_inline_completion_event(
 5099            active_inline_completion.completion_id.clone(),
 5100            true,
 5101            cx,
 5102        );
 5103
 5104        match &active_inline_completion.completion {
 5105            InlineCompletion::Move { target, .. } => {
 5106                let target = *target;
 5107
 5108                if let Some(position_map) = &self.last_position_map {
 5109                    if position_map
 5110                        .visible_row_range
 5111                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5112                        || !self.edit_prediction_requires_modifier()
 5113                    {
 5114                        self.unfold_ranges(&[target..target], true, false, cx);
 5115                        // Note that this is also done in vim's handler of the Tab action.
 5116                        self.change_selections(
 5117                            Some(Autoscroll::newest()),
 5118                            window,
 5119                            cx,
 5120                            |selections| {
 5121                                selections.select_anchor_ranges([target..target]);
 5122                            },
 5123                        );
 5124                        self.clear_row_highlights::<EditPredictionPreview>();
 5125
 5126                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5127                            previous_scroll_position: None,
 5128                        };
 5129                    } else {
 5130                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5131                            previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
 5132                        };
 5133                        self.highlight_rows::<EditPredictionPreview>(
 5134                            target..target,
 5135                            cx.theme().colors().editor_highlighted_line_background,
 5136                            true,
 5137                            cx,
 5138                        );
 5139                        self.request_autoscroll(Autoscroll::fit(), cx);
 5140                    }
 5141                }
 5142            }
 5143            InlineCompletion::Edit { edits, .. } => {
 5144                if let Some(provider) = self.edit_prediction_provider() {
 5145                    provider.accept(cx);
 5146                }
 5147
 5148                let snapshot = self.buffer.read(cx).snapshot(cx);
 5149                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5150
 5151                self.buffer.update(cx, |buffer, cx| {
 5152                    buffer.edit(edits.iter().cloned(), None, cx)
 5153                });
 5154
 5155                self.change_selections(None, window, cx, |s| {
 5156                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5157                });
 5158
 5159                self.update_visible_inline_completion(window, cx);
 5160                if self.active_inline_completion.is_none() {
 5161                    self.refresh_inline_completion(true, true, window, cx);
 5162                }
 5163
 5164                cx.notify();
 5165            }
 5166        }
 5167
 5168        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5169    }
 5170
 5171    pub fn accept_partial_inline_completion(
 5172        &mut self,
 5173        _: &AcceptPartialEditPrediction,
 5174        window: &mut Window,
 5175        cx: &mut Context<Self>,
 5176    ) {
 5177        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5178            return;
 5179        };
 5180        if self.selections.count() != 1 {
 5181            return;
 5182        }
 5183
 5184        self.report_inline_completion_event(
 5185            active_inline_completion.completion_id.clone(),
 5186            true,
 5187            cx,
 5188        );
 5189
 5190        match &active_inline_completion.completion {
 5191            InlineCompletion::Move { target, .. } => {
 5192                let target = *target;
 5193                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5194                    selections.select_anchor_ranges([target..target]);
 5195                });
 5196            }
 5197            InlineCompletion::Edit { edits, .. } => {
 5198                // Find an insertion that starts at the cursor position.
 5199                let snapshot = self.buffer.read(cx).snapshot(cx);
 5200                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5201                let insertion = edits.iter().find_map(|(range, text)| {
 5202                    let range = range.to_offset(&snapshot);
 5203                    if range.is_empty() && range.start == cursor_offset {
 5204                        Some(text)
 5205                    } else {
 5206                        None
 5207                    }
 5208                });
 5209
 5210                if let Some(text) = insertion {
 5211                    let mut partial_completion = text
 5212                        .chars()
 5213                        .by_ref()
 5214                        .take_while(|c| c.is_alphabetic())
 5215                        .collect::<String>();
 5216                    if partial_completion.is_empty() {
 5217                        partial_completion = text
 5218                            .chars()
 5219                            .by_ref()
 5220                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5221                            .collect::<String>();
 5222                    }
 5223
 5224                    cx.emit(EditorEvent::InputHandled {
 5225                        utf16_range_to_replace: None,
 5226                        text: partial_completion.clone().into(),
 5227                    });
 5228
 5229                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5230
 5231                    self.refresh_inline_completion(true, true, window, cx);
 5232                    cx.notify();
 5233                } else {
 5234                    self.accept_edit_prediction(&Default::default(), window, cx);
 5235                }
 5236            }
 5237        }
 5238    }
 5239
 5240    fn discard_inline_completion(
 5241        &mut self,
 5242        should_report_inline_completion_event: bool,
 5243        cx: &mut Context<Self>,
 5244    ) -> bool {
 5245        if should_report_inline_completion_event {
 5246            let completion_id = self
 5247                .active_inline_completion
 5248                .as_ref()
 5249                .and_then(|active_completion| active_completion.completion_id.clone());
 5250
 5251            self.report_inline_completion_event(completion_id, false, cx);
 5252        }
 5253
 5254        if let Some(provider) = self.edit_prediction_provider() {
 5255            provider.discard(cx);
 5256        }
 5257
 5258        self.take_active_inline_completion(cx)
 5259    }
 5260
 5261    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5262        let Some(provider) = self.edit_prediction_provider() else {
 5263            return;
 5264        };
 5265
 5266        let Some((_, buffer, _)) = self
 5267            .buffer
 5268            .read(cx)
 5269            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5270        else {
 5271            return;
 5272        };
 5273
 5274        let extension = buffer
 5275            .read(cx)
 5276            .file()
 5277            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5278
 5279        let event_type = match accepted {
 5280            true => "Edit Prediction Accepted",
 5281            false => "Edit Prediction Discarded",
 5282        };
 5283        telemetry::event!(
 5284            event_type,
 5285            provider = provider.name(),
 5286            prediction_id = id,
 5287            suggestion_accepted = accepted,
 5288            file_extension = extension,
 5289        );
 5290    }
 5291
 5292    pub fn has_active_inline_completion(&self) -> bool {
 5293        self.active_inline_completion.is_some()
 5294    }
 5295
 5296    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5297        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5298            return false;
 5299        };
 5300
 5301        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5302        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5303        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5304        true
 5305    }
 5306
 5307    /// Returns true when we're displaying the edit prediction popover below the cursor
 5308    /// like we are not previewing and the LSP autocomplete menu is visible
 5309    /// or we are in `when_holding_modifier` mode.
 5310    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5311        if self.edit_prediction_preview_is_active()
 5312            || !self.show_edit_predictions_in_menu()
 5313            || !self.edit_predictions_enabled()
 5314        {
 5315            return false;
 5316        }
 5317
 5318        if self.has_visible_completions_menu() {
 5319            return true;
 5320        }
 5321
 5322        has_completion && self.edit_prediction_requires_modifier()
 5323    }
 5324
 5325    fn handle_modifiers_changed(
 5326        &mut self,
 5327        modifiers: Modifiers,
 5328        position_map: &PositionMap,
 5329        window: &mut Window,
 5330        cx: &mut Context<Self>,
 5331    ) {
 5332        if self.show_edit_predictions_in_menu() {
 5333            self.update_edit_prediction_preview(&modifiers, window, cx);
 5334        }
 5335
 5336        self.update_selection_mode(&modifiers, position_map, window, cx);
 5337
 5338        let mouse_position = window.mouse_position();
 5339        if !position_map.text_hitbox.is_hovered(window) {
 5340            return;
 5341        }
 5342
 5343        self.update_hovered_link(
 5344            position_map.point_for_position(mouse_position),
 5345            &position_map.snapshot,
 5346            modifiers,
 5347            window,
 5348            cx,
 5349        )
 5350    }
 5351
 5352    fn update_selection_mode(
 5353        &mut self,
 5354        modifiers: &Modifiers,
 5355        position_map: &PositionMap,
 5356        window: &mut Window,
 5357        cx: &mut Context<Self>,
 5358    ) {
 5359        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5360            return;
 5361        }
 5362
 5363        let mouse_position = window.mouse_position();
 5364        let point_for_position = position_map.point_for_position(mouse_position);
 5365        let position = point_for_position.previous_valid;
 5366
 5367        self.select(
 5368            SelectPhase::BeginColumnar {
 5369                position,
 5370                reset: false,
 5371                goal_column: point_for_position.exact_unclipped.column(),
 5372            },
 5373            window,
 5374            cx,
 5375        );
 5376    }
 5377
 5378    fn update_edit_prediction_preview(
 5379        &mut self,
 5380        modifiers: &Modifiers,
 5381        window: &mut Window,
 5382        cx: &mut Context<Self>,
 5383    ) {
 5384        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5385        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5386            return;
 5387        };
 5388
 5389        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5390            if matches!(
 5391                self.edit_prediction_preview,
 5392                EditPredictionPreview::Inactive
 5393            ) {
 5394                self.edit_prediction_preview = EditPredictionPreview::Active {
 5395                    previous_scroll_position: None,
 5396                };
 5397
 5398                self.update_visible_inline_completion(window, cx);
 5399                cx.notify();
 5400            }
 5401        } else if let EditPredictionPreview::Active {
 5402            previous_scroll_position,
 5403        } = self.edit_prediction_preview
 5404        {
 5405            if let (Some(previous_scroll_position), Some(position_map)) =
 5406                (previous_scroll_position, self.last_position_map.as_ref())
 5407            {
 5408                self.set_scroll_position(
 5409                    previous_scroll_position
 5410                        .scroll_position(&position_map.snapshot.display_snapshot),
 5411                    window,
 5412                    cx,
 5413                );
 5414            }
 5415
 5416            self.edit_prediction_preview = EditPredictionPreview::Inactive;
 5417            self.clear_row_highlights::<EditPredictionPreview>();
 5418            self.update_visible_inline_completion(window, cx);
 5419            cx.notify();
 5420        }
 5421    }
 5422
 5423    fn update_visible_inline_completion(
 5424        &mut self,
 5425        _window: &mut Window,
 5426        cx: &mut Context<Self>,
 5427    ) -> Option<()> {
 5428        let selection = self.selections.newest_anchor();
 5429        let cursor = selection.head();
 5430        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5431        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5432        let excerpt_id = cursor.excerpt_id;
 5433
 5434        let show_in_menu = self.show_edit_predictions_in_menu();
 5435        let completions_menu_has_precedence = !show_in_menu
 5436            && (self.context_menu.borrow().is_some()
 5437                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5438
 5439        if completions_menu_has_precedence
 5440            || !offset_selection.is_empty()
 5441            || self
 5442                .active_inline_completion
 5443                .as_ref()
 5444                .map_or(false, |completion| {
 5445                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5446                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5447                    !invalidation_range.contains(&offset_selection.head())
 5448                })
 5449        {
 5450            self.discard_inline_completion(false, cx);
 5451            return None;
 5452        }
 5453
 5454        self.take_active_inline_completion(cx);
 5455        let Some(provider) = self.edit_prediction_provider() else {
 5456            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5457            return None;
 5458        };
 5459
 5460        let (buffer, cursor_buffer_position) =
 5461            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5462
 5463        self.edit_prediction_settings =
 5464            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5465
 5466        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 5467
 5468        if self.edit_prediction_indent_conflict {
 5469            let cursor_point = cursor.to_point(&multibuffer);
 5470
 5471            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 5472
 5473            if let Some((_, indent)) = indents.iter().next() {
 5474                if indent.len == cursor_point.column {
 5475                    self.edit_prediction_indent_conflict = false;
 5476                }
 5477            }
 5478        }
 5479
 5480        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5481        let edits = inline_completion
 5482            .edits
 5483            .into_iter()
 5484            .flat_map(|(range, new_text)| {
 5485                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5486                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5487                Some((start..end, new_text))
 5488            })
 5489            .collect::<Vec<_>>();
 5490        if edits.is_empty() {
 5491            return None;
 5492        }
 5493
 5494        let first_edit_start = edits.first().unwrap().0.start;
 5495        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5496        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5497
 5498        let last_edit_end = edits.last().unwrap().0.end;
 5499        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5500        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5501
 5502        let cursor_row = cursor.to_point(&multibuffer).row;
 5503
 5504        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5505
 5506        let mut inlay_ids = Vec::new();
 5507        let invalidation_row_range;
 5508        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5509            Some(cursor_row..edit_end_row)
 5510        } else if cursor_row > edit_end_row {
 5511            Some(edit_start_row..cursor_row)
 5512        } else {
 5513            None
 5514        };
 5515        let is_move =
 5516            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5517        let completion = if is_move {
 5518            invalidation_row_range =
 5519                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5520            let target = first_edit_start;
 5521            InlineCompletion::Move { target, snapshot }
 5522        } else {
 5523            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5524                && !self.inline_completions_hidden_for_vim_mode;
 5525
 5526            if show_completions_in_buffer {
 5527                if edits
 5528                    .iter()
 5529                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5530                {
 5531                    let mut inlays = Vec::new();
 5532                    for (range, new_text) in &edits {
 5533                        let inlay = Inlay::inline_completion(
 5534                            post_inc(&mut self.next_inlay_id),
 5535                            range.start,
 5536                            new_text.as_str(),
 5537                        );
 5538                        inlay_ids.push(inlay.id);
 5539                        inlays.push(inlay);
 5540                    }
 5541
 5542                    self.splice_inlays(&[], inlays, cx);
 5543                } else {
 5544                    let background_color = cx.theme().status().deleted_background;
 5545                    self.highlight_text::<InlineCompletionHighlight>(
 5546                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5547                        HighlightStyle {
 5548                            background_color: Some(background_color),
 5549                            ..Default::default()
 5550                        },
 5551                        cx,
 5552                    );
 5553                }
 5554            }
 5555
 5556            invalidation_row_range = edit_start_row..edit_end_row;
 5557
 5558            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5559                if provider.show_tab_accept_marker() {
 5560                    EditDisplayMode::TabAccept
 5561                } else {
 5562                    EditDisplayMode::Inline
 5563                }
 5564            } else {
 5565                EditDisplayMode::DiffPopover
 5566            };
 5567
 5568            InlineCompletion::Edit {
 5569                edits,
 5570                edit_preview: inline_completion.edit_preview,
 5571                display_mode,
 5572                snapshot,
 5573            }
 5574        };
 5575
 5576        let invalidation_range = multibuffer
 5577            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5578            ..multibuffer.anchor_after(Point::new(
 5579                invalidation_row_range.end,
 5580                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5581            ));
 5582
 5583        self.stale_inline_completion_in_menu = None;
 5584        self.active_inline_completion = Some(InlineCompletionState {
 5585            inlay_ids,
 5586            completion,
 5587            completion_id: inline_completion.id,
 5588            invalidation_range,
 5589        });
 5590
 5591        cx.notify();
 5592
 5593        Some(())
 5594    }
 5595
 5596    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5597        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5598    }
 5599
 5600    fn render_code_actions_indicator(
 5601        &self,
 5602        _style: &EditorStyle,
 5603        row: DisplayRow,
 5604        is_active: bool,
 5605        cx: &mut Context<Self>,
 5606    ) -> Option<IconButton> {
 5607        if self.available_code_actions.is_some() {
 5608            Some(
 5609                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5610                    .shape(ui::IconButtonShape::Square)
 5611                    .icon_size(IconSize::XSmall)
 5612                    .icon_color(Color::Muted)
 5613                    .toggle_state(is_active)
 5614                    .tooltip({
 5615                        let focus_handle = self.focus_handle.clone();
 5616                        move |window, cx| {
 5617                            Tooltip::for_action_in(
 5618                                "Toggle Code Actions",
 5619                                &ToggleCodeActions {
 5620                                    deployed_from_indicator: None,
 5621                                },
 5622                                &focus_handle,
 5623                                window,
 5624                                cx,
 5625                            )
 5626                        }
 5627                    })
 5628                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5629                        window.focus(&editor.focus_handle(cx));
 5630                        editor.toggle_code_actions(
 5631                            &ToggleCodeActions {
 5632                                deployed_from_indicator: Some(row),
 5633                            },
 5634                            window,
 5635                            cx,
 5636                        );
 5637                    })),
 5638            )
 5639        } else {
 5640            None
 5641        }
 5642    }
 5643
 5644    fn clear_tasks(&mut self) {
 5645        self.tasks.clear()
 5646    }
 5647
 5648    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5649        if self.tasks.insert(key, value).is_some() {
 5650            // This case should hopefully be rare, but just in case...
 5651            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5652        }
 5653    }
 5654
 5655    fn build_tasks_context(
 5656        project: &Entity<Project>,
 5657        buffer: &Entity<Buffer>,
 5658        buffer_row: u32,
 5659        tasks: &Arc<RunnableTasks>,
 5660        cx: &mut Context<Self>,
 5661    ) -> Task<Option<task::TaskContext>> {
 5662        let position = Point::new(buffer_row, tasks.column);
 5663        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5664        let location = Location {
 5665            buffer: buffer.clone(),
 5666            range: range_start..range_start,
 5667        };
 5668        // Fill in the environmental variables from the tree-sitter captures
 5669        let mut captured_task_variables = TaskVariables::default();
 5670        for (capture_name, value) in tasks.extra_variables.clone() {
 5671            captured_task_variables.insert(
 5672                task::VariableName::Custom(capture_name.into()),
 5673                value.clone(),
 5674            );
 5675        }
 5676        project.update(cx, |project, cx| {
 5677            project.task_store().update(cx, |task_store, cx| {
 5678                task_store.task_context_for_location(captured_task_variables, location, cx)
 5679            })
 5680        })
 5681    }
 5682
 5683    pub fn spawn_nearest_task(
 5684        &mut self,
 5685        action: &SpawnNearestTask,
 5686        window: &mut Window,
 5687        cx: &mut Context<Self>,
 5688    ) {
 5689        let Some((workspace, _)) = self.workspace.clone() else {
 5690            return;
 5691        };
 5692        let Some(project) = self.project.clone() else {
 5693            return;
 5694        };
 5695
 5696        // Try to find a closest, enclosing node using tree-sitter that has a
 5697        // task
 5698        let Some((buffer, buffer_row, tasks)) = self
 5699            .find_enclosing_node_task(cx)
 5700            // Or find the task that's closest in row-distance.
 5701            .or_else(|| self.find_closest_task(cx))
 5702        else {
 5703            return;
 5704        };
 5705
 5706        let reveal_strategy = action.reveal;
 5707        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5708        cx.spawn_in(window, |_, mut cx| async move {
 5709            let context = task_context.await?;
 5710            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5711
 5712            let resolved = resolved_task.resolved.as_mut()?;
 5713            resolved.reveal = reveal_strategy;
 5714
 5715            workspace
 5716                .update(&mut cx, |workspace, cx| {
 5717                    workspace::tasks::schedule_resolved_task(
 5718                        workspace,
 5719                        task_source_kind,
 5720                        resolved_task,
 5721                        false,
 5722                        cx,
 5723                    );
 5724                })
 5725                .ok()
 5726        })
 5727        .detach();
 5728    }
 5729
 5730    fn find_closest_task(
 5731        &mut self,
 5732        cx: &mut Context<Self>,
 5733    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5734        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5735
 5736        let ((buffer_id, row), tasks) = self
 5737            .tasks
 5738            .iter()
 5739            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5740
 5741        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5742        let tasks = Arc::new(tasks.to_owned());
 5743        Some((buffer, *row, tasks))
 5744    }
 5745
 5746    fn find_enclosing_node_task(
 5747        &mut self,
 5748        cx: &mut Context<Self>,
 5749    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5750        let snapshot = self.buffer.read(cx).snapshot(cx);
 5751        let offset = self.selections.newest::<usize>(cx).head();
 5752        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5753        let buffer_id = excerpt.buffer().remote_id();
 5754
 5755        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5756        let mut cursor = layer.node().walk();
 5757
 5758        while cursor.goto_first_child_for_byte(offset).is_some() {
 5759            if cursor.node().end_byte() == offset {
 5760                cursor.goto_next_sibling();
 5761            }
 5762        }
 5763
 5764        // Ascend to the smallest ancestor that contains the range and has a task.
 5765        loop {
 5766            let node = cursor.node();
 5767            let node_range = node.byte_range();
 5768            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5769
 5770            // Check if this node contains our offset
 5771            if node_range.start <= offset && node_range.end >= offset {
 5772                // If it contains offset, check for task
 5773                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5774                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5775                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5776                }
 5777            }
 5778
 5779            if !cursor.goto_parent() {
 5780                break;
 5781            }
 5782        }
 5783        None
 5784    }
 5785
 5786    fn render_run_indicator(
 5787        &self,
 5788        _style: &EditorStyle,
 5789        is_active: bool,
 5790        row: DisplayRow,
 5791        cx: &mut Context<Self>,
 5792    ) -> IconButton {
 5793        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5794            .shape(ui::IconButtonShape::Square)
 5795            .icon_size(IconSize::XSmall)
 5796            .icon_color(Color::Muted)
 5797            .toggle_state(is_active)
 5798            .on_click(cx.listener(move |editor, _e, window, cx| {
 5799                window.focus(&editor.focus_handle(cx));
 5800                editor.toggle_code_actions(
 5801                    &ToggleCodeActions {
 5802                        deployed_from_indicator: Some(row),
 5803                    },
 5804                    window,
 5805                    cx,
 5806                );
 5807            }))
 5808    }
 5809
 5810    pub fn context_menu_visible(&self) -> bool {
 5811        !self.edit_prediction_preview_is_active()
 5812            && self
 5813                .context_menu
 5814                .borrow()
 5815                .as_ref()
 5816                .map_or(false, |menu| menu.visible())
 5817    }
 5818
 5819    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5820        self.context_menu
 5821            .borrow()
 5822            .as_ref()
 5823            .map(|menu| menu.origin())
 5824    }
 5825
 5826    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 5827    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 5828
 5829    #[allow(clippy::too_many_arguments)]
 5830    fn render_edit_prediction_popover(
 5831        &mut self,
 5832        text_bounds: &Bounds<Pixels>,
 5833        content_origin: gpui::Point<Pixels>,
 5834        editor_snapshot: &EditorSnapshot,
 5835        visible_row_range: Range<DisplayRow>,
 5836        scroll_top: f32,
 5837        scroll_bottom: f32,
 5838        line_layouts: &[LineWithInvisibles],
 5839        line_height: Pixels,
 5840        scroll_pixel_position: gpui::Point<Pixels>,
 5841        newest_selection_head: Option<DisplayPoint>,
 5842        editor_width: Pixels,
 5843        style: &EditorStyle,
 5844        window: &mut Window,
 5845        cx: &mut App,
 5846    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5847        let active_inline_completion = self.active_inline_completion.as_ref()?;
 5848
 5849        if self.edit_prediction_visible_in_cursor_popover(true) {
 5850            return None;
 5851        }
 5852
 5853        match &active_inline_completion.completion {
 5854            InlineCompletion::Move { target, .. } => {
 5855                let target_display_point = target.to_display_point(editor_snapshot);
 5856
 5857                if self.edit_prediction_requires_modifier() {
 5858                    if !self.edit_prediction_preview_is_active() {
 5859                        return None;
 5860                    }
 5861
 5862                    self.render_edit_prediction_modifier_jump_popover(
 5863                        text_bounds,
 5864                        content_origin,
 5865                        visible_row_range,
 5866                        line_layouts,
 5867                        line_height,
 5868                        scroll_pixel_position,
 5869                        newest_selection_head,
 5870                        target_display_point,
 5871                        window,
 5872                        cx,
 5873                    )
 5874                } else {
 5875                    self.render_edit_prediction_eager_jump_popover(
 5876                        text_bounds,
 5877                        content_origin,
 5878                        editor_snapshot,
 5879                        visible_row_range,
 5880                        scroll_top,
 5881                        scroll_bottom,
 5882                        line_height,
 5883                        scroll_pixel_position,
 5884                        target_display_point,
 5885                        editor_width,
 5886                        window,
 5887                        cx,
 5888                    )
 5889                }
 5890            }
 5891            InlineCompletion::Edit {
 5892                display_mode: EditDisplayMode::Inline,
 5893                ..
 5894            } => None,
 5895            InlineCompletion::Edit {
 5896                display_mode: EditDisplayMode::TabAccept,
 5897                edits,
 5898                ..
 5899            } => {
 5900                let range = &edits.first()?.0;
 5901                let target_display_point = range.end.to_display_point(editor_snapshot);
 5902
 5903                self.render_edit_prediction_end_of_line_popover(
 5904                    "Accept",
 5905                    editor_snapshot,
 5906                    visible_row_range,
 5907                    target_display_point,
 5908                    line_height,
 5909                    scroll_pixel_position,
 5910                    content_origin,
 5911                    editor_width,
 5912                    window,
 5913                    cx,
 5914                )
 5915            }
 5916            InlineCompletion::Edit {
 5917                edits,
 5918                edit_preview,
 5919                display_mode: EditDisplayMode::DiffPopover,
 5920                snapshot,
 5921            } => self.render_edit_prediction_diff_popover(
 5922                text_bounds,
 5923                content_origin,
 5924                editor_snapshot,
 5925                visible_row_range,
 5926                line_layouts,
 5927                line_height,
 5928                scroll_pixel_position,
 5929                newest_selection_head,
 5930                editor_width,
 5931                style,
 5932                edits,
 5933                edit_preview,
 5934                snapshot,
 5935                window,
 5936                cx,
 5937            ),
 5938        }
 5939    }
 5940
 5941    #[allow(clippy::too_many_arguments)]
 5942    fn render_edit_prediction_modifier_jump_popover(
 5943        &mut self,
 5944        text_bounds: &Bounds<Pixels>,
 5945        content_origin: gpui::Point<Pixels>,
 5946        visible_row_range: Range<DisplayRow>,
 5947        line_layouts: &[LineWithInvisibles],
 5948        line_height: Pixels,
 5949        scroll_pixel_position: gpui::Point<Pixels>,
 5950        newest_selection_head: Option<DisplayPoint>,
 5951        target_display_point: DisplayPoint,
 5952        window: &mut Window,
 5953        cx: &mut App,
 5954    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5955        let scrolled_content_origin =
 5956            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 5957
 5958        const SCROLL_PADDING_Y: Pixels = px(12.);
 5959
 5960        if target_display_point.row() < visible_row_range.start {
 5961            return self.render_edit_prediction_scroll_popover(
 5962                |_| SCROLL_PADDING_Y,
 5963                IconName::ArrowUp,
 5964                visible_row_range,
 5965                line_layouts,
 5966                newest_selection_head,
 5967                scrolled_content_origin,
 5968                window,
 5969                cx,
 5970            );
 5971        } else if target_display_point.row() >= visible_row_range.end {
 5972            return self.render_edit_prediction_scroll_popover(
 5973                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 5974                IconName::ArrowDown,
 5975                visible_row_range,
 5976                line_layouts,
 5977                newest_selection_head,
 5978                scrolled_content_origin,
 5979                window,
 5980                cx,
 5981            );
 5982        }
 5983
 5984        const POLE_WIDTH: Pixels = px(2.);
 5985
 5986        let mut element = v_flex()
 5987            .items_end()
 5988            .child(
 5989                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 5990                    .rounded_br(px(0.))
 5991                    .rounded_tr(px(0.))
 5992                    .border_r_2(),
 5993            )
 5994            .child(
 5995                div()
 5996                    .w(POLE_WIDTH)
 5997                    .bg(Editor::edit_prediction_callout_popover_border_color(cx))
 5998                    .h(line_height),
 5999            )
 6000            .into_any();
 6001
 6002        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6003
 6004        let line_layout =
 6005            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 6006        let target_column = target_display_point.column() as usize;
 6007
 6008        let target_x = line_layout.x_for_index(target_column);
 6009        let target_y =
 6010            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 6011
 6012        let mut origin = scrolled_content_origin + point(target_x, target_y)
 6013            - point(size.width - POLE_WIDTH, size.height - line_height);
 6014
 6015        origin.x = origin.x.max(content_origin.x);
 6016
 6017        element.prepaint_at(origin, window, cx);
 6018
 6019        Some((element, origin))
 6020    }
 6021
 6022    #[allow(clippy::too_many_arguments)]
 6023    fn render_edit_prediction_scroll_popover(
 6024        &mut self,
 6025        to_y: impl Fn(Size<Pixels>) -> Pixels,
 6026        scroll_icon: IconName,
 6027        visible_row_range: Range<DisplayRow>,
 6028        line_layouts: &[LineWithInvisibles],
 6029        newest_selection_head: Option<DisplayPoint>,
 6030        scrolled_content_origin: gpui::Point<Pixels>,
 6031        window: &mut Window,
 6032        cx: &mut App,
 6033    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6034        let mut element = self
 6035            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 6036            .into_any();
 6037
 6038        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6039
 6040        let cursor = newest_selection_head?;
 6041        let cursor_row_layout =
 6042            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6043        let cursor_column = cursor.column() as usize;
 6044
 6045        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6046
 6047        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6048
 6049        element.prepaint_at(origin, window, cx);
 6050        Some((element, origin))
 6051    }
 6052
 6053    #[allow(clippy::too_many_arguments)]
 6054    fn render_edit_prediction_eager_jump_popover(
 6055        &mut self,
 6056        text_bounds: &Bounds<Pixels>,
 6057        content_origin: gpui::Point<Pixels>,
 6058        editor_snapshot: &EditorSnapshot,
 6059        visible_row_range: Range<DisplayRow>,
 6060        scroll_top: f32,
 6061        scroll_bottom: f32,
 6062        line_height: Pixels,
 6063        scroll_pixel_position: gpui::Point<Pixels>,
 6064        target_display_point: DisplayPoint,
 6065        editor_width: Pixels,
 6066        window: &mut Window,
 6067        cx: &mut App,
 6068    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6069        if target_display_point.row().as_f32() < scroll_top {
 6070            let mut element = self
 6071                .render_edit_prediction_line_popover(
 6072                    "Jump to Edit",
 6073                    Some(IconName::ArrowUp),
 6074                    window,
 6075                    cx,
 6076                )?
 6077                .into_any();
 6078
 6079            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6080            let offset = point(
 6081                (text_bounds.size.width - size.width) / 2.,
 6082                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6083            );
 6084
 6085            let origin = text_bounds.origin + offset;
 6086            element.prepaint_at(origin, window, cx);
 6087            Some((element, origin))
 6088        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6089            let mut element = self
 6090                .render_edit_prediction_line_popover(
 6091                    "Jump to Edit",
 6092                    Some(IconName::ArrowDown),
 6093                    window,
 6094                    cx,
 6095                )?
 6096                .into_any();
 6097
 6098            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6099            let offset = point(
 6100                (text_bounds.size.width - size.width) / 2.,
 6101                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6102            );
 6103
 6104            let origin = text_bounds.origin + offset;
 6105            element.prepaint_at(origin, window, cx);
 6106            Some((element, origin))
 6107        } else {
 6108            self.render_edit_prediction_end_of_line_popover(
 6109                "Jump to Edit",
 6110                editor_snapshot,
 6111                visible_row_range,
 6112                target_display_point,
 6113                line_height,
 6114                scroll_pixel_position,
 6115                content_origin,
 6116                editor_width,
 6117                window,
 6118                cx,
 6119            )
 6120        }
 6121    }
 6122
 6123    #[allow(clippy::too_many_arguments)]
 6124    fn render_edit_prediction_end_of_line_popover(
 6125        self: &mut Editor,
 6126        label: &'static str,
 6127        editor_snapshot: &EditorSnapshot,
 6128        visible_row_range: Range<DisplayRow>,
 6129        target_display_point: DisplayPoint,
 6130        line_height: Pixels,
 6131        scroll_pixel_position: gpui::Point<Pixels>,
 6132        content_origin: gpui::Point<Pixels>,
 6133        editor_width: Pixels,
 6134        window: &mut Window,
 6135        cx: &mut App,
 6136    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6137        let target_line_end = DisplayPoint::new(
 6138            target_display_point.row(),
 6139            editor_snapshot.line_len(target_display_point.row()),
 6140        );
 6141
 6142        let mut element = self
 6143            .render_edit_prediction_line_popover(label, None, window, cx)?
 6144            .into_any();
 6145
 6146        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6147
 6148        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 6149
 6150        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 6151        let mut origin = start_point
 6152            + line_origin
 6153            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 6154        origin.x = origin.x.max(content_origin.x);
 6155
 6156        let max_x = content_origin.x + editor_width - size.width;
 6157
 6158        if origin.x > max_x {
 6159            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 6160
 6161            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 6162                origin.y += offset;
 6163                IconName::ArrowUp
 6164            } else {
 6165                origin.y -= offset;
 6166                IconName::ArrowDown
 6167            };
 6168
 6169            element = self
 6170                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 6171                .into_any();
 6172
 6173            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6174
 6175            origin.x = content_origin.x + editor_width - size.width - px(2.);
 6176        }
 6177
 6178        element.prepaint_at(origin, window, cx);
 6179        Some((element, origin))
 6180    }
 6181
 6182    #[allow(clippy::too_many_arguments)]
 6183    fn render_edit_prediction_diff_popover(
 6184        self: &Editor,
 6185        text_bounds: &Bounds<Pixels>,
 6186        content_origin: gpui::Point<Pixels>,
 6187        editor_snapshot: &EditorSnapshot,
 6188        visible_row_range: Range<DisplayRow>,
 6189        line_layouts: &[LineWithInvisibles],
 6190        line_height: Pixels,
 6191        scroll_pixel_position: gpui::Point<Pixels>,
 6192        newest_selection_head: Option<DisplayPoint>,
 6193        editor_width: Pixels,
 6194        style: &EditorStyle,
 6195        edits: &Vec<(Range<Anchor>, String)>,
 6196        edit_preview: &Option<language::EditPreview>,
 6197        snapshot: &language::BufferSnapshot,
 6198        window: &mut Window,
 6199        cx: &mut App,
 6200    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6201        let edit_start = edits
 6202            .first()
 6203            .unwrap()
 6204            .0
 6205            .start
 6206            .to_display_point(editor_snapshot);
 6207        let edit_end = edits
 6208            .last()
 6209            .unwrap()
 6210            .0
 6211            .end
 6212            .to_display_point(editor_snapshot);
 6213
 6214        let is_visible = visible_row_range.contains(&edit_start.row())
 6215            || visible_row_range.contains(&edit_end.row());
 6216        if !is_visible {
 6217            return None;
 6218        }
 6219
 6220        let highlighted_edits =
 6221            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 6222
 6223        let styled_text = highlighted_edits.to_styled_text(&style.text);
 6224        let line_count = highlighted_edits.text.lines().count();
 6225
 6226        const BORDER_WIDTH: Pixels = px(1.);
 6227
 6228        let mut element = h_flex()
 6229            .items_start()
 6230            .child(
 6231                h_flex()
 6232                    .bg(cx.theme().colors().editor_background)
 6233                    .border(BORDER_WIDTH)
 6234                    .shadow_sm()
 6235                    .border_color(cx.theme().colors().border)
 6236                    .rounded_l_lg()
 6237                    .when(line_count > 1, |el| el.rounded_br_lg())
 6238                    .pr_1()
 6239                    .child(styled_text),
 6240            )
 6241            .child(
 6242                h_flex()
 6243                    .h(line_height + BORDER_WIDTH * px(2.))
 6244                    .px_1p5()
 6245                    .gap_1()
 6246                    // Workaround: For some reason, there's a gap if we don't do this
 6247                    .ml(-BORDER_WIDTH)
 6248                    .shadow(smallvec![gpui::BoxShadow {
 6249                        color: gpui::black().opacity(0.05),
 6250                        offset: point(px(1.), px(1.)),
 6251                        blur_radius: px(2.),
 6252                        spread_radius: px(0.),
 6253                    }])
 6254                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 6255                    .border(BORDER_WIDTH)
 6256                    .border_color(cx.theme().colors().border)
 6257                    .rounded_r_lg()
 6258                    .children(self.render_edit_prediction_accept_keybind(window, cx)),
 6259            )
 6260            .into_any();
 6261
 6262        let longest_row =
 6263            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 6264        let longest_line_width = if visible_row_range.contains(&longest_row) {
 6265            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 6266        } else {
 6267            layout_line(
 6268                longest_row,
 6269                editor_snapshot,
 6270                style,
 6271                editor_width,
 6272                |_| false,
 6273                window,
 6274                cx,
 6275            )
 6276            .width
 6277        };
 6278
 6279        let viewport_bounds =
 6280            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 6281                right: -EditorElement::SCROLLBAR_WIDTH,
 6282                ..Default::default()
 6283            });
 6284
 6285        let x_after_longest =
 6286            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 6287                - scroll_pixel_position.x;
 6288
 6289        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6290
 6291        // Fully visible if it can be displayed within the window (allow overlapping other
 6292        // panes). However, this is only allowed if the popover starts within text_bounds.
 6293        let can_position_to_the_right = x_after_longest < text_bounds.right()
 6294            && x_after_longest + element_bounds.width < viewport_bounds.right();
 6295
 6296        let mut origin = if can_position_to_the_right {
 6297            point(
 6298                x_after_longest,
 6299                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 6300                    - scroll_pixel_position.y,
 6301            )
 6302        } else {
 6303            let cursor_row = newest_selection_head.map(|head| head.row());
 6304            let above_edit = edit_start
 6305                .row()
 6306                .0
 6307                .checked_sub(line_count as u32)
 6308                .map(DisplayRow);
 6309            let below_edit = Some(edit_end.row() + 1);
 6310            let above_cursor =
 6311                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 6312            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 6313
 6314            // Place the edit popover adjacent to the edit if there is a location
 6315            // available that is onscreen and does not obscure the cursor. Otherwise,
 6316            // place it adjacent to the cursor.
 6317            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 6318                .into_iter()
 6319                .flatten()
 6320                .find(|&start_row| {
 6321                    let end_row = start_row + line_count as u32;
 6322                    visible_row_range.contains(&start_row)
 6323                        && visible_row_range.contains(&end_row)
 6324                        && cursor_row.map_or(true, |cursor_row| {
 6325                            !((start_row..end_row).contains(&cursor_row))
 6326                        })
 6327                })?;
 6328
 6329            content_origin
 6330                + point(
 6331                    -scroll_pixel_position.x,
 6332                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 6333                )
 6334        };
 6335
 6336        origin.x -= BORDER_WIDTH;
 6337
 6338        window.defer_draw(element, origin, 1);
 6339
 6340        // Do not return an element, since it will already be drawn due to defer_draw.
 6341        None
 6342    }
 6343
 6344    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 6345        px(30.)
 6346    }
 6347
 6348    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 6349        if self.read_only(cx) {
 6350            cx.theme().players().read_only()
 6351        } else {
 6352            self.style.as_ref().unwrap().local_player
 6353        }
 6354    }
 6355
 6356    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 6357        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 6358        let accept_keystroke = accept_binding.keystroke()?;
 6359
 6360        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6361
 6362        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 6363            Color::Accent
 6364        } else {
 6365            Color::Muted
 6366        };
 6367
 6368        h_flex()
 6369            .px_0p5()
 6370            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 6371            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6372            .text_size(TextSize::XSmall.rems(cx))
 6373            .child(h_flex().children(ui::render_modifiers(
 6374                &accept_keystroke.modifiers,
 6375                PlatformStyle::platform(),
 6376                Some(modifiers_color),
 6377                Some(IconSize::XSmall.rems().into()),
 6378                true,
 6379            )))
 6380            .when(is_platform_style_mac, |parent| {
 6381                parent.child(accept_keystroke.key.clone())
 6382            })
 6383            .when(!is_platform_style_mac, |parent| {
 6384                parent.child(
 6385                    Key::new(
 6386                        util::capitalize(&accept_keystroke.key),
 6387                        Some(Color::Default),
 6388                    )
 6389                    .size(Some(IconSize::XSmall.rems().into())),
 6390                )
 6391            })
 6392            .into()
 6393    }
 6394
 6395    fn render_edit_prediction_line_popover(
 6396        &self,
 6397        label: impl Into<SharedString>,
 6398        icon: Option<IconName>,
 6399        window: &mut Window,
 6400        cx: &App,
 6401    ) -> Option<Div> {
 6402        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 6403
 6404        let result = h_flex()
 6405            .py_0p5()
 6406            .pl_1()
 6407            .pr(padding_right)
 6408            .gap_1()
 6409            .rounded(px(6.))
 6410            .border_1()
 6411            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6412            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 6413            .shadow_sm()
 6414            .children(self.render_edit_prediction_accept_keybind(window, cx))
 6415            .child(Label::new(label).size(LabelSize::Small))
 6416            .when_some(icon, |element, icon| {
 6417                element.child(
 6418                    div()
 6419                        .mt(px(1.5))
 6420                        .child(Icon::new(icon).size(IconSize::Small)),
 6421                )
 6422            });
 6423
 6424        Some(result)
 6425    }
 6426
 6427    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 6428        let accent_color = cx.theme().colors().text_accent;
 6429        let editor_bg_color = cx.theme().colors().editor_background;
 6430        editor_bg_color.blend(accent_color.opacity(0.1))
 6431    }
 6432
 6433    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 6434        let accent_color = cx.theme().colors().text_accent;
 6435        let editor_bg_color = cx.theme().colors().editor_background;
 6436        editor_bg_color.blend(accent_color.opacity(0.6))
 6437    }
 6438
 6439    #[allow(clippy::too_many_arguments)]
 6440    fn render_edit_prediction_cursor_popover(
 6441        &self,
 6442        min_width: Pixels,
 6443        max_width: Pixels,
 6444        cursor_point: Point,
 6445        style: &EditorStyle,
 6446        accept_keystroke: Option<&gpui::Keystroke>,
 6447        _window: &Window,
 6448        cx: &mut Context<Editor>,
 6449    ) -> Option<AnyElement> {
 6450        let provider = self.edit_prediction_provider.as_ref()?;
 6451
 6452        if provider.provider.needs_terms_acceptance(cx) {
 6453            return Some(
 6454                h_flex()
 6455                    .min_w(min_width)
 6456                    .flex_1()
 6457                    .px_2()
 6458                    .py_1()
 6459                    .gap_3()
 6460                    .elevation_2(cx)
 6461                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 6462                    .id("accept-terms")
 6463                    .cursor_pointer()
 6464                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 6465                    .on_click(cx.listener(|this, _event, window, cx| {
 6466                        cx.stop_propagation();
 6467                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 6468                        window.dispatch_action(
 6469                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 6470                            cx,
 6471                        );
 6472                    }))
 6473                    .child(
 6474                        h_flex()
 6475                            .flex_1()
 6476                            .gap_2()
 6477                            .child(Icon::new(IconName::ZedPredict))
 6478                            .child(Label::new("Accept Terms of Service"))
 6479                            .child(div().w_full())
 6480                            .child(
 6481                                Icon::new(IconName::ArrowUpRight)
 6482                                    .color(Color::Muted)
 6483                                    .size(IconSize::Small),
 6484                            )
 6485                            .into_any_element(),
 6486                    )
 6487                    .into_any(),
 6488            );
 6489        }
 6490
 6491        let is_refreshing = provider.provider.is_refreshing(cx);
 6492
 6493        fn pending_completion_container() -> Div {
 6494            h_flex()
 6495                .h_full()
 6496                .flex_1()
 6497                .gap_2()
 6498                .child(Icon::new(IconName::ZedPredict))
 6499        }
 6500
 6501        let completion = match &self.active_inline_completion {
 6502            Some(completion) => match &completion.completion {
 6503                InlineCompletion::Move {
 6504                    target, snapshot, ..
 6505                } if !self.has_visible_completions_menu() => {
 6506                    use text::ToPoint as _;
 6507
 6508                    return Some(
 6509                        h_flex()
 6510                            .px_2()
 6511                            .py_1()
 6512                            .gap_2()
 6513                            .elevation_2(cx)
 6514                            .border_color(cx.theme().colors().border)
 6515                            .rounded(px(6.))
 6516                            .rounded_tl(px(0.))
 6517                            .child(
 6518                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6519                                    Icon::new(IconName::ZedPredictDown)
 6520                                } else {
 6521                                    Icon::new(IconName::ZedPredictUp)
 6522                                },
 6523                            )
 6524                            .child(Label::new("Hold").size(LabelSize::Small))
 6525                            .child(h_flex().children(ui::render_modifiers(
 6526                                &accept_keystroke?.modifiers,
 6527                                PlatformStyle::platform(),
 6528                                Some(Color::Default),
 6529                                Some(IconSize::Small.rems().into()),
 6530                                false,
 6531                            )))
 6532                            .into_any(),
 6533                    );
 6534                }
 6535                _ => self.render_edit_prediction_cursor_popover_preview(
 6536                    completion,
 6537                    cursor_point,
 6538                    style,
 6539                    cx,
 6540                )?,
 6541            },
 6542
 6543            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 6544                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 6545                    stale_completion,
 6546                    cursor_point,
 6547                    style,
 6548                    cx,
 6549                )?,
 6550
 6551                None => {
 6552                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6553                }
 6554            },
 6555
 6556            None => pending_completion_container().child(Label::new("No Prediction")),
 6557        };
 6558
 6559        let completion = if is_refreshing {
 6560            completion
 6561                .with_animation(
 6562                    "loading-completion",
 6563                    Animation::new(Duration::from_secs(2))
 6564                        .repeat()
 6565                        .with_easing(pulsating_between(0.4, 0.8)),
 6566                    |label, delta| label.opacity(delta),
 6567                )
 6568                .into_any_element()
 6569        } else {
 6570            completion.into_any_element()
 6571        };
 6572
 6573        let has_completion = self.active_inline_completion.is_some();
 6574
 6575        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6576        Some(
 6577            h_flex()
 6578                .min_w(min_width)
 6579                .max_w(max_width)
 6580                .flex_1()
 6581                .elevation_2(cx)
 6582                .border_color(cx.theme().colors().border)
 6583                .child(
 6584                    div()
 6585                        .flex_1()
 6586                        .py_1()
 6587                        .px_2()
 6588                        .overflow_hidden()
 6589                        .child(completion),
 6590                )
 6591                .when_some(accept_keystroke, |el, accept_keystroke| {
 6592                    if !accept_keystroke.modifiers.modified() {
 6593                        return el;
 6594                    }
 6595
 6596                    el.child(
 6597                        h_flex()
 6598                            .h_full()
 6599                            .border_l_1()
 6600                            .rounded_r_lg()
 6601                            .border_color(cx.theme().colors().border)
 6602                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6603                            .gap_1()
 6604                            .py_1()
 6605                            .px_2()
 6606                            .child(
 6607                                h_flex()
 6608                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6609                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6610                                    .child(h_flex().children(ui::render_modifiers(
 6611                                        &accept_keystroke.modifiers,
 6612                                        PlatformStyle::platform(),
 6613                                        Some(if !has_completion {
 6614                                            Color::Muted
 6615                                        } else {
 6616                                            Color::Default
 6617                                        }),
 6618                                        None,
 6619                                        false,
 6620                                    ))),
 6621                            )
 6622                            .child(Label::new("Preview").into_any_element())
 6623                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6624                    )
 6625                })
 6626                .into_any(),
 6627        )
 6628    }
 6629
 6630    fn render_edit_prediction_cursor_popover_preview(
 6631        &self,
 6632        completion: &InlineCompletionState,
 6633        cursor_point: Point,
 6634        style: &EditorStyle,
 6635        cx: &mut Context<Editor>,
 6636    ) -> Option<Div> {
 6637        use text::ToPoint as _;
 6638
 6639        fn render_relative_row_jump(
 6640            prefix: impl Into<String>,
 6641            current_row: u32,
 6642            target_row: u32,
 6643        ) -> Div {
 6644            let (row_diff, arrow) = if target_row < current_row {
 6645                (current_row - target_row, IconName::ArrowUp)
 6646            } else {
 6647                (target_row - current_row, IconName::ArrowDown)
 6648            };
 6649
 6650            h_flex()
 6651                .child(
 6652                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6653                        .color(Color::Muted)
 6654                        .size(LabelSize::Small),
 6655                )
 6656                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6657        }
 6658
 6659        match &completion.completion {
 6660            InlineCompletion::Move {
 6661                target, snapshot, ..
 6662            } => Some(
 6663                h_flex()
 6664                    .px_2()
 6665                    .gap_2()
 6666                    .flex_1()
 6667                    .child(
 6668                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6669                            Icon::new(IconName::ZedPredictDown)
 6670                        } else {
 6671                            Icon::new(IconName::ZedPredictUp)
 6672                        },
 6673                    )
 6674                    .child(Label::new("Jump to Edit")),
 6675            ),
 6676
 6677            InlineCompletion::Edit {
 6678                edits,
 6679                edit_preview,
 6680                snapshot,
 6681                display_mode: _,
 6682            } => {
 6683                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6684
 6685                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6686                    &snapshot,
 6687                    &edits,
 6688                    edit_preview.as_ref()?,
 6689                    true,
 6690                    cx,
 6691                )
 6692                .first_line_preview();
 6693
 6694                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6695                    .with_highlights(&style.text, highlighted_edits.highlights);
 6696
 6697                let preview = h_flex()
 6698                    .gap_1()
 6699                    .min_w_16()
 6700                    .child(styled_text)
 6701                    .when(has_more_lines, |parent| parent.child(""));
 6702
 6703                let left = if first_edit_row != cursor_point.row {
 6704                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6705                        .into_any_element()
 6706                } else {
 6707                    Icon::new(IconName::ZedPredict).into_any_element()
 6708                };
 6709
 6710                Some(
 6711                    h_flex()
 6712                        .h_full()
 6713                        .flex_1()
 6714                        .gap_2()
 6715                        .pr_1()
 6716                        .overflow_x_hidden()
 6717                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6718                        .child(left)
 6719                        .child(preview),
 6720                )
 6721            }
 6722        }
 6723    }
 6724
 6725    fn render_context_menu(
 6726        &self,
 6727        style: &EditorStyle,
 6728        max_height_in_lines: u32,
 6729        y_flipped: bool,
 6730        window: &mut Window,
 6731        cx: &mut Context<Editor>,
 6732    ) -> Option<AnyElement> {
 6733        let menu = self.context_menu.borrow();
 6734        let menu = menu.as_ref()?;
 6735        if !menu.visible() {
 6736            return None;
 6737        };
 6738        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6739    }
 6740
 6741    fn render_context_menu_aside(
 6742        &mut self,
 6743        max_size: Size<Pixels>,
 6744        window: &mut Window,
 6745        cx: &mut Context<Editor>,
 6746    ) -> Option<AnyElement> {
 6747        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 6748            if menu.visible() {
 6749                menu.render_aside(self, max_size, window, cx)
 6750            } else {
 6751                None
 6752            }
 6753        })
 6754    }
 6755
 6756    fn hide_context_menu(
 6757        &mut self,
 6758        window: &mut Window,
 6759        cx: &mut Context<Self>,
 6760    ) -> Option<CodeContextMenu> {
 6761        cx.notify();
 6762        self.completion_tasks.clear();
 6763        let context_menu = self.context_menu.borrow_mut().take();
 6764        self.stale_inline_completion_in_menu.take();
 6765        self.update_visible_inline_completion(window, cx);
 6766        context_menu
 6767    }
 6768
 6769    fn show_snippet_choices(
 6770        &mut self,
 6771        choices: &Vec<String>,
 6772        selection: Range<Anchor>,
 6773        cx: &mut Context<Self>,
 6774    ) {
 6775        if selection.start.buffer_id.is_none() {
 6776            return;
 6777        }
 6778        let buffer_id = selection.start.buffer_id.unwrap();
 6779        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6780        let id = post_inc(&mut self.next_completion_id);
 6781
 6782        if let Some(buffer) = buffer {
 6783            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6784                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6785            ));
 6786        }
 6787    }
 6788
 6789    pub fn insert_snippet(
 6790        &mut self,
 6791        insertion_ranges: &[Range<usize>],
 6792        snippet: Snippet,
 6793        window: &mut Window,
 6794        cx: &mut Context<Self>,
 6795    ) -> Result<()> {
 6796        struct Tabstop<T> {
 6797            is_end_tabstop: bool,
 6798            ranges: Vec<Range<T>>,
 6799            choices: Option<Vec<String>>,
 6800        }
 6801
 6802        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6803            let snippet_text: Arc<str> = snippet.text.clone().into();
 6804            buffer.edit(
 6805                insertion_ranges
 6806                    .iter()
 6807                    .cloned()
 6808                    .map(|range| (range, snippet_text.clone())),
 6809                Some(AutoindentMode::EachLine),
 6810                cx,
 6811            );
 6812
 6813            let snapshot = &*buffer.read(cx);
 6814            let snippet = &snippet;
 6815            snippet
 6816                .tabstops
 6817                .iter()
 6818                .map(|tabstop| {
 6819                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6820                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6821                    });
 6822                    let mut tabstop_ranges = tabstop
 6823                        .ranges
 6824                        .iter()
 6825                        .flat_map(|tabstop_range| {
 6826                            let mut delta = 0_isize;
 6827                            insertion_ranges.iter().map(move |insertion_range| {
 6828                                let insertion_start = insertion_range.start as isize + delta;
 6829                                delta +=
 6830                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6831
 6832                                let start = ((insertion_start + tabstop_range.start) as usize)
 6833                                    .min(snapshot.len());
 6834                                let end = ((insertion_start + tabstop_range.end) as usize)
 6835                                    .min(snapshot.len());
 6836                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6837                            })
 6838                        })
 6839                        .collect::<Vec<_>>();
 6840                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6841
 6842                    Tabstop {
 6843                        is_end_tabstop,
 6844                        ranges: tabstop_ranges,
 6845                        choices: tabstop.choices.clone(),
 6846                    }
 6847                })
 6848                .collect::<Vec<_>>()
 6849        });
 6850        if let Some(tabstop) = tabstops.first() {
 6851            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6852                s.select_ranges(tabstop.ranges.iter().cloned());
 6853            });
 6854
 6855            if let Some(choices) = &tabstop.choices {
 6856                if let Some(selection) = tabstop.ranges.first() {
 6857                    self.show_snippet_choices(choices, selection.clone(), cx)
 6858                }
 6859            }
 6860
 6861            // If we're already at the last tabstop and it's at the end of the snippet,
 6862            // we're done, we don't need to keep the state around.
 6863            if !tabstop.is_end_tabstop {
 6864                let choices = tabstops
 6865                    .iter()
 6866                    .map(|tabstop| tabstop.choices.clone())
 6867                    .collect();
 6868
 6869                let ranges = tabstops
 6870                    .into_iter()
 6871                    .map(|tabstop| tabstop.ranges)
 6872                    .collect::<Vec<_>>();
 6873
 6874                self.snippet_stack.push(SnippetState {
 6875                    active_index: 0,
 6876                    ranges,
 6877                    choices,
 6878                });
 6879            }
 6880
 6881            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6882            if self.autoclose_regions.is_empty() {
 6883                let snapshot = self.buffer.read(cx).snapshot(cx);
 6884                for selection in &mut self.selections.all::<Point>(cx) {
 6885                    let selection_head = selection.head();
 6886                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6887                        continue;
 6888                    };
 6889
 6890                    let mut bracket_pair = None;
 6891                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6892                    let prev_chars = snapshot
 6893                        .reversed_chars_at(selection_head)
 6894                        .collect::<String>();
 6895                    for (pair, enabled) in scope.brackets() {
 6896                        if enabled
 6897                            && pair.close
 6898                            && prev_chars.starts_with(pair.start.as_str())
 6899                            && next_chars.starts_with(pair.end.as_str())
 6900                        {
 6901                            bracket_pair = Some(pair.clone());
 6902                            break;
 6903                        }
 6904                    }
 6905                    if let Some(pair) = bracket_pair {
 6906                        let start = snapshot.anchor_after(selection_head);
 6907                        let end = snapshot.anchor_after(selection_head);
 6908                        self.autoclose_regions.push(AutocloseRegion {
 6909                            selection_id: selection.id,
 6910                            range: start..end,
 6911                            pair,
 6912                        });
 6913                    }
 6914                }
 6915            }
 6916        }
 6917        Ok(())
 6918    }
 6919
 6920    pub fn move_to_next_snippet_tabstop(
 6921        &mut self,
 6922        window: &mut Window,
 6923        cx: &mut Context<Self>,
 6924    ) -> bool {
 6925        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6926    }
 6927
 6928    pub fn move_to_prev_snippet_tabstop(
 6929        &mut self,
 6930        window: &mut Window,
 6931        cx: &mut Context<Self>,
 6932    ) -> bool {
 6933        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6934    }
 6935
 6936    pub fn move_to_snippet_tabstop(
 6937        &mut self,
 6938        bias: Bias,
 6939        window: &mut Window,
 6940        cx: &mut Context<Self>,
 6941    ) -> bool {
 6942        if let Some(mut snippet) = self.snippet_stack.pop() {
 6943            match bias {
 6944                Bias::Left => {
 6945                    if snippet.active_index > 0 {
 6946                        snippet.active_index -= 1;
 6947                    } else {
 6948                        self.snippet_stack.push(snippet);
 6949                        return false;
 6950                    }
 6951                }
 6952                Bias::Right => {
 6953                    if snippet.active_index + 1 < snippet.ranges.len() {
 6954                        snippet.active_index += 1;
 6955                    } else {
 6956                        self.snippet_stack.push(snippet);
 6957                        return false;
 6958                    }
 6959                }
 6960            }
 6961            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6962                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6963                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6964                });
 6965
 6966                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6967                    if let Some(selection) = current_ranges.first() {
 6968                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6969                    }
 6970                }
 6971
 6972                // If snippet state is not at the last tabstop, push it back on the stack
 6973                if snippet.active_index + 1 < snippet.ranges.len() {
 6974                    self.snippet_stack.push(snippet);
 6975                }
 6976                return true;
 6977            }
 6978        }
 6979
 6980        false
 6981    }
 6982
 6983    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6984        self.transact(window, cx, |this, window, cx| {
 6985            this.select_all(&SelectAll, window, cx);
 6986            this.insert("", window, cx);
 6987        });
 6988    }
 6989
 6990    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6991        self.transact(window, cx, |this, window, cx| {
 6992            this.select_autoclose_pair(window, cx);
 6993            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6994            if !this.linked_edit_ranges.is_empty() {
 6995                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6996                let snapshot = this.buffer.read(cx).snapshot(cx);
 6997
 6998                for selection in selections.iter() {
 6999                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 7000                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 7001                    if selection_start.buffer_id != selection_end.buffer_id {
 7002                        continue;
 7003                    }
 7004                    if let Some(ranges) =
 7005                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 7006                    {
 7007                        for (buffer, entries) in ranges {
 7008                            linked_ranges.entry(buffer).or_default().extend(entries);
 7009                        }
 7010                    }
 7011                }
 7012            }
 7013
 7014            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7015            if !this.selections.line_mode {
 7016                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 7017                for selection in &mut selections {
 7018                    if selection.is_empty() {
 7019                        let old_head = selection.head();
 7020                        let mut new_head =
 7021                            movement::left(&display_map, old_head.to_display_point(&display_map))
 7022                                .to_point(&display_map);
 7023                        if let Some((buffer, line_buffer_range)) = display_map
 7024                            .buffer_snapshot
 7025                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 7026                        {
 7027                            let indent_size =
 7028                                buffer.indent_size_for_line(line_buffer_range.start.row);
 7029                            let indent_len = match indent_size.kind {
 7030                                IndentKind::Space => {
 7031                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 7032                                }
 7033                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 7034                            };
 7035                            if old_head.column <= indent_size.len && old_head.column > 0 {
 7036                                let indent_len = indent_len.get();
 7037                                new_head = cmp::min(
 7038                                    new_head,
 7039                                    MultiBufferPoint::new(
 7040                                        old_head.row,
 7041                                        ((old_head.column - 1) / indent_len) * indent_len,
 7042                                    ),
 7043                                );
 7044                            }
 7045                        }
 7046
 7047                        selection.set_head(new_head, SelectionGoal::None);
 7048                    }
 7049                }
 7050            }
 7051
 7052            this.signature_help_state.set_backspace_pressed(true);
 7053            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7054                s.select(selections)
 7055            });
 7056            this.insert("", window, cx);
 7057            let empty_str: Arc<str> = Arc::from("");
 7058            for (buffer, edits) in linked_ranges {
 7059                let snapshot = buffer.read(cx).snapshot();
 7060                use text::ToPoint as TP;
 7061
 7062                let edits = edits
 7063                    .into_iter()
 7064                    .map(|range| {
 7065                        let end_point = TP::to_point(&range.end, &snapshot);
 7066                        let mut start_point = TP::to_point(&range.start, &snapshot);
 7067
 7068                        if end_point == start_point {
 7069                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 7070                                .saturating_sub(1);
 7071                            start_point =
 7072                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 7073                        };
 7074
 7075                        (start_point..end_point, empty_str.clone())
 7076                    })
 7077                    .sorted_by_key(|(range, _)| range.start)
 7078                    .collect::<Vec<_>>();
 7079                buffer.update(cx, |this, cx| {
 7080                    this.edit(edits, None, cx);
 7081                })
 7082            }
 7083            this.refresh_inline_completion(true, false, window, cx);
 7084            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 7085        });
 7086    }
 7087
 7088    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 7089        self.transact(window, cx, |this, window, cx| {
 7090            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7091                let line_mode = s.line_mode;
 7092                s.move_with(|map, selection| {
 7093                    if selection.is_empty() && !line_mode {
 7094                        let cursor = movement::right(map, selection.head());
 7095                        selection.end = cursor;
 7096                        selection.reversed = true;
 7097                        selection.goal = SelectionGoal::None;
 7098                    }
 7099                })
 7100            });
 7101            this.insert("", window, cx);
 7102            this.refresh_inline_completion(true, false, window, cx);
 7103        });
 7104    }
 7105
 7106    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 7107        if self.move_to_prev_snippet_tabstop(window, cx) {
 7108            return;
 7109        }
 7110
 7111        self.outdent(&Outdent, window, cx);
 7112    }
 7113
 7114    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 7115        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 7116            return;
 7117        }
 7118
 7119        let mut selections = self.selections.all_adjusted(cx);
 7120        let buffer = self.buffer.read(cx);
 7121        let snapshot = buffer.snapshot(cx);
 7122        let rows_iter = selections.iter().map(|s| s.head().row);
 7123        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 7124
 7125        let mut edits = Vec::new();
 7126        let mut prev_edited_row = 0;
 7127        let mut row_delta = 0;
 7128        for selection in &mut selections {
 7129            if selection.start.row != prev_edited_row {
 7130                row_delta = 0;
 7131            }
 7132            prev_edited_row = selection.end.row;
 7133
 7134            // If the selection is non-empty, then increase the indentation of the selected lines.
 7135            if !selection.is_empty() {
 7136                row_delta =
 7137                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7138                continue;
 7139            }
 7140
 7141            // If the selection is empty and the cursor is in the leading whitespace before the
 7142            // suggested indentation, then auto-indent the line.
 7143            let cursor = selection.head();
 7144            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 7145            if let Some(suggested_indent) =
 7146                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 7147            {
 7148                if cursor.column < suggested_indent.len
 7149                    && cursor.column <= current_indent.len
 7150                    && current_indent.len <= suggested_indent.len
 7151                {
 7152                    selection.start = Point::new(cursor.row, suggested_indent.len);
 7153                    selection.end = selection.start;
 7154                    if row_delta == 0 {
 7155                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 7156                            cursor.row,
 7157                            current_indent,
 7158                            suggested_indent,
 7159                        ));
 7160                        row_delta = suggested_indent.len - current_indent.len;
 7161                    }
 7162                    continue;
 7163                }
 7164            }
 7165
 7166            // Otherwise, insert a hard or soft tab.
 7167            let settings = buffer.settings_at(cursor, cx);
 7168            let tab_size = if settings.hard_tabs {
 7169                IndentSize::tab()
 7170            } else {
 7171                let tab_size = settings.tab_size.get();
 7172                let char_column = snapshot
 7173                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 7174                    .flat_map(str::chars)
 7175                    .count()
 7176                    + row_delta as usize;
 7177                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 7178                IndentSize::spaces(chars_to_next_tab_stop)
 7179            };
 7180            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 7181            selection.end = selection.start;
 7182            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 7183            row_delta += tab_size.len;
 7184        }
 7185
 7186        self.transact(window, cx, |this, window, cx| {
 7187            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7188            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7189                s.select(selections)
 7190            });
 7191            this.refresh_inline_completion(true, false, window, cx);
 7192        });
 7193    }
 7194
 7195    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 7196        if self.read_only(cx) {
 7197            return;
 7198        }
 7199        let mut selections = self.selections.all::<Point>(cx);
 7200        let mut prev_edited_row = 0;
 7201        let mut row_delta = 0;
 7202        let mut edits = Vec::new();
 7203        let buffer = self.buffer.read(cx);
 7204        let snapshot = buffer.snapshot(cx);
 7205        for selection in &mut selections {
 7206            if selection.start.row != prev_edited_row {
 7207                row_delta = 0;
 7208            }
 7209            prev_edited_row = selection.end.row;
 7210
 7211            row_delta =
 7212                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7213        }
 7214
 7215        self.transact(window, cx, |this, window, cx| {
 7216            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7217            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7218                s.select(selections)
 7219            });
 7220        });
 7221    }
 7222
 7223    fn indent_selection(
 7224        buffer: &MultiBuffer,
 7225        snapshot: &MultiBufferSnapshot,
 7226        selection: &mut Selection<Point>,
 7227        edits: &mut Vec<(Range<Point>, String)>,
 7228        delta_for_start_row: u32,
 7229        cx: &App,
 7230    ) -> u32 {
 7231        let settings = buffer.settings_at(selection.start, cx);
 7232        let tab_size = settings.tab_size.get();
 7233        let indent_kind = if settings.hard_tabs {
 7234            IndentKind::Tab
 7235        } else {
 7236            IndentKind::Space
 7237        };
 7238        let mut start_row = selection.start.row;
 7239        let mut end_row = selection.end.row + 1;
 7240
 7241        // If a selection ends at the beginning of a line, don't indent
 7242        // that last line.
 7243        if selection.end.column == 0 && selection.end.row > selection.start.row {
 7244            end_row -= 1;
 7245        }
 7246
 7247        // Avoid re-indenting a row that has already been indented by a
 7248        // previous selection, but still update this selection's column
 7249        // to reflect that indentation.
 7250        if delta_for_start_row > 0 {
 7251            start_row += 1;
 7252            selection.start.column += delta_for_start_row;
 7253            if selection.end.row == selection.start.row {
 7254                selection.end.column += delta_for_start_row;
 7255            }
 7256        }
 7257
 7258        let mut delta_for_end_row = 0;
 7259        let has_multiple_rows = start_row + 1 != end_row;
 7260        for row in start_row..end_row {
 7261            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 7262            let indent_delta = match (current_indent.kind, indent_kind) {
 7263                (IndentKind::Space, IndentKind::Space) => {
 7264                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 7265                    IndentSize::spaces(columns_to_next_tab_stop)
 7266                }
 7267                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 7268                (_, IndentKind::Tab) => IndentSize::tab(),
 7269            };
 7270
 7271            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 7272                0
 7273            } else {
 7274                selection.start.column
 7275            };
 7276            let row_start = Point::new(row, start);
 7277            edits.push((
 7278                row_start..row_start,
 7279                indent_delta.chars().collect::<String>(),
 7280            ));
 7281
 7282            // Update this selection's endpoints to reflect the indentation.
 7283            if row == selection.start.row {
 7284                selection.start.column += indent_delta.len;
 7285            }
 7286            if row == selection.end.row {
 7287                selection.end.column += indent_delta.len;
 7288                delta_for_end_row = indent_delta.len;
 7289            }
 7290        }
 7291
 7292        if selection.start.row == selection.end.row {
 7293            delta_for_start_row + delta_for_end_row
 7294        } else {
 7295            delta_for_end_row
 7296        }
 7297    }
 7298
 7299    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 7300        if self.read_only(cx) {
 7301            return;
 7302        }
 7303        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7304        let selections = self.selections.all::<Point>(cx);
 7305        let mut deletion_ranges = Vec::new();
 7306        let mut last_outdent = None;
 7307        {
 7308            let buffer = self.buffer.read(cx);
 7309            let snapshot = buffer.snapshot(cx);
 7310            for selection in &selections {
 7311                let settings = buffer.settings_at(selection.start, cx);
 7312                let tab_size = settings.tab_size.get();
 7313                let mut rows = selection.spanned_rows(false, &display_map);
 7314
 7315                // Avoid re-outdenting a row that has already been outdented by a
 7316                // previous selection.
 7317                if let Some(last_row) = last_outdent {
 7318                    if last_row == rows.start {
 7319                        rows.start = rows.start.next_row();
 7320                    }
 7321                }
 7322                let has_multiple_rows = rows.len() > 1;
 7323                for row in rows.iter_rows() {
 7324                    let indent_size = snapshot.indent_size_for_line(row);
 7325                    if indent_size.len > 0 {
 7326                        let deletion_len = match indent_size.kind {
 7327                            IndentKind::Space => {
 7328                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 7329                                if columns_to_prev_tab_stop == 0 {
 7330                                    tab_size
 7331                                } else {
 7332                                    columns_to_prev_tab_stop
 7333                                }
 7334                            }
 7335                            IndentKind::Tab => 1,
 7336                        };
 7337                        let start = if has_multiple_rows
 7338                            || deletion_len > selection.start.column
 7339                            || indent_size.len < selection.start.column
 7340                        {
 7341                            0
 7342                        } else {
 7343                            selection.start.column - deletion_len
 7344                        };
 7345                        deletion_ranges.push(
 7346                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 7347                        );
 7348                        last_outdent = Some(row);
 7349                    }
 7350                }
 7351            }
 7352        }
 7353
 7354        self.transact(window, cx, |this, window, cx| {
 7355            this.buffer.update(cx, |buffer, cx| {
 7356                let empty_str: Arc<str> = Arc::default();
 7357                buffer.edit(
 7358                    deletion_ranges
 7359                        .into_iter()
 7360                        .map(|range| (range, empty_str.clone())),
 7361                    None,
 7362                    cx,
 7363                );
 7364            });
 7365            let selections = this.selections.all::<usize>(cx);
 7366            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7367                s.select(selections)
 7368            });
 7369        });
 7370    }
 7371
 7372    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 7373        if self.read_only(cx) {
 7374            return;
 7375        }
 7376        let selections = self
 7377            .selections
 7378            .all::<usize>(cx)
 7379            .into_iter()
 7380            .map(|s| s.range());
 7381
 7382        self.transact(window, cx, |this, window, cx| {
 7383            this.buffer.update(cx, |buffer, cx| {
 7384                buffer.autoindent_ranges(selections, cx);
 7385            });
 7386            let selections = this.selections.all::<usize>(cx);
 7387            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7388                s.select(selections)
 7389            });
 7390        });
 7391    }
 7392
 7393    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 7394        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7395        let selections = self.selections.all::<Point>(cx);
 7396
 7397        let mut new_cursors = Vec::new();
 7398        let mut edit_ranges = Vec::new();
 7399        let mut selections = selections.iter().peekable();
 7400        while let Some(selection) = selections.next() {
 7401            let mut rows = selection.spanned_rows(false, &display_map);
 7402            let goal_display_column = selection.head().to_display_point(&display_map).column();
 7403
 7404            // Accumulate contiguous regions of rows that we want to delete.
 7405            while let Some(next_selection) = selections.peek() {
 7406                let next_rows = next_selection.spanned_rows(false, &display_map);
 7407                if next_rows.start <= rows.end {
 7408                    rows.end = next_rows.end;
 7409                    selections.next().unwrap();
 7410                } else {
 7411                    break;
 7412                }
 7413            }
 7414
 7415            let buffer = &display_map.buffer_snapshot;
 7416            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 7417            let edit_end;
 7418            let cursor_buffer_row;
 7419            if buffer.max_point().row >= rows.end.0 {
 7420                // If there's a line after the range, delete the \n from the end of the row range
 7421                // and position the cursor on the next line.
 7422                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 7423                cursor_buffer_row = rows.end;
 7424            } else {
 7425                // If there isn't a line after the range, delete the \n from the line before the
 7426                // start of the row range and position the cursor there.
 7427                edit_start = edit_start.saturating_sub(1);
 7428                edit_end = buffer.len();
 7429                cursor_buffer_row = rows.start.previous_row();
 7430            }
 7431
 7432            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 7433            *cursor.column_mut() =
 7434                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 7435
 7436            new_cursors.push((
 7437                selection.id,
 7438                buffer.anchor_after(cursor.to_point(&display_map)),
 7439            ));
 7440            edit_ranges.push(edit_start..edit_end);
 7441        }
 7442
 7443        self.transact(window, cx, |this, window, cx| {
 7444            let buffer = this.buffer.update(cx, |buffer, cx| {
 7445                let empty_str: Arc<str> = Arc::default();
 7446                buffer.edit(
 7447                    edit_ranges
 7448                        .into_iter()
 7449                        .map(|range| (range, empty_str.clone())),
 7450                    None,
 7451                    cx,
 7452                );
 7453                buffer.snapshot(cx)
 7454            });
 7455            let new_selections = new_cursors
 7456                .into_iter()
 7457                .map(|(id, cursor)| {
 7458                    let cursor = cursor.to_point(&buffer);
 7459                    Selection {
 7460                        id,
 7461                        start: cursor,
 7462                        end: cursor,
 7463                        reversed: false,
 7464                        goal: SelectionGoal::None,
 7465                    }
 7466                })
 7467                .collect();
 7468
 7469            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7470                s.select(new_selections);
 7471            });
 7472        });
 7473    }
 7474
 7475    pub fn join_lines_impl(
 7476        &mut self,
 7477        insert_whitespace: bool,
 7478        window: &mut Window,
 7479        cx: &mut Context<Self>,
 7480    ) {
 7481        if self.read_only(cx) {
 7482            return;
 7483        }
 7484        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 7485        for selection in self.selections.all::<Point>(cx) {
 7486            let start = MultiBufferRow(selection.start.row);
 7487            // Treat single line selections as if they include the next line. Otherwise this action
 7488            // would do nothing for single line selections individual cursors.
 7489            let end = if selection.start.row == selection.end.row {
 7490                MultiBufferRow(selection.start.row + 1)
 7491            } else {
 7492                MultiBufferRow(selection.end.row)
 7493            };
 7494
 7495            if let Some(last_row_range) = row_ranges.last_mut() {
 7496                if start <= last_row_range.end {
 7497                    last_row_range.end = end;
 7498                    continue;
 7499                }
 7500            }
 7501            row_ranges.push(start..end);
 7502        }
 7503
 7504        let snapshot = self.buffer.read(cx).snapshot(cx);
 7505        let mut cursor_positions = Vec::new();
 7506        for row_range in &row_ranges {
 7507            let anchor = snapshot.anchor_before(Point::new(
 7508                row_range.end.previous_row().0,
 7509                snapshot.line_len(row_range.end.previous_row()),
 7510            ));
 7511            cursor_positions.push(anchor..anchor);
 7512        }
 7513
 7514        self.transact(window, cx, |this, window, cx| {
 7515            for row_range in row_ranges.into_iter().rev() {
 7516                for row in row_range.iter_rows().rev() {
 7517                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 7518                    let next_line_row = row.next_row();
 7519                    let indent = snapshot.indent_size_for_line(next_line_row);
 7520                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7521
 7522                    let replace =
 7523                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7524                            " "
 7525                        } else {
 7526                            ""
 7527                        };
 7528
 7529                    this.buffer.update(cx, |buffer, cx| {
 7530                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7531                    });
 7532                }
 7533            }
 7534
 7535            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7536                s.select_anchor_ranges(cursor_positions)
 7537            });
 7538        });
 7539    }
 7540
 7541    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7542        self.join_lines_impl(true, window, cx);
 7543    }
 7544
 7545    pub fn sort_lines_case_sensitive(
 7546        &mut self,
 7547        _: &SortLinesCaseSensitive,
 7548        window: &mut Window,
 7549        cx: &mut Context<Self>,
 7550    ) {
 7551        self.manipulate_lines(window, cx, |lines| lines.sort())
 7552    }
 7553
 7554    pub fn sort_lines_case_insensitive(
 7555        &mut self,
 7556        _: &SortLinesCaseInsensitive,
 7557        window: &mut Window,
 7558        cx: &mut Context<Self>,
 7559    ) {
 7560        self.manipulate_lines(window, cx, |lines| {
 7561            lines.sort_by_key(|line| line.to_lowercase())
 7562        })
 7563    }
 7564
 7565    pub fn unique_lines_case_insensitive(
 7566        &mut self,
 7567        _: &UniqueLinesCaseInsensitive,
 7568        window: &mut Window,
 7569        cx: &mut Context<Self>,
 7570    ) {
 7571        self.manipulate_lines(window, cx, |lines| {
 7572            let mut seen = HashSet::default();
 7573            lines.retain(|line| seen.insert(line.to_lowercase()));
 7574        })
 7575    }
 7576
 7577    pub fn unique_lines_case_sensitive(
 7578        &mut self,
 7579        _: &UniqueLinesCaseSensitive,
 7580        window: &mut Window,
 7581        cx: &mut Context<Self>,
 7582    ) {
 7583        self.manipulate_lines(window, cx, |lines| {
 7584            let mut seen = HashSet::default();
 7585            lines.retain(|line| seen.insert(*line));
 7586        })
 7587    }
 7588
 7589    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7590        let Some(project) = self.project.clone() else {
 7591            return;
 7592        };
 7593        self.reload(project, window, cx)
 7594            .detach_and_notify_err(window, cx);
 7595    }
 7596
 7597    pub fn restore_file(
 7598        &mut self,
 7599        _: &::git::RestoreFile,
 7600        window: &mut Window,
 7601        cx: &mut Context<Self>,
 7602    ) {
 7603        let mut buffer_ids = HashSet::default();
 7604        let snapshot = self.buffer().read(cx).snapshot(cx);
 7605        for selection in self.selections.all::<usize>(cx) {
 7606            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 7607        }
 7608
 7609        let buffer = self.buffer().read(cx);
 7610        let ranges = buffer_ids
 7611            .into_iter()
 7612            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 7613            .collect::<Vec<_>>();
 7614
 7615        self.restore_hunks_in_ranges(ranges, window, cx);
 7616    }
 7617
 7618    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 7619        let selections = self
 7620            .selections
 7621            .all(cx)
 7622            .into_iter()
 7623            .map(|s| s.range())
 7624            .collect();
 7625        self.restore_hunks_in_ranges(selections, window, cx);
 7626    }
 7627
 7628    fn restore_hunks_in_ranges(
 7629        &mut self,
 7630        ranges: Vec<Range<Point>>,
 7631        window: &mut Window,
 7632        cx: &mut Context<Editor>,
 7633    ) {
 7634        let mut revert_changes = HashMap::default();
 7635        let snapshot = self.buffer.read(cx).snapshot(cx);
 7636        let Some(project) = &self.project else {
 7637            return;
 7638        };
 7639
 7640        let chunk_by = self
 7641            .snapshot(window, cx)
 7642            .hunks_for_ranges(ranges.into_iter())
 7643            .into_iter()
 7644            .chunk_by(|hunk| hunk.buffer_id);
 7645        for (buffer_id, hunks) in &chunk_by {
 7646            let hunks = hunks.collect::<Vec<_>>();
 7647            for hunk in &hunks {
 7648                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 7649            }
 7650            Self::do_stage_or_unstage(project, false, buffer_id, hunks.into_iter(), &snapshot, cx);
 7651        }
 7652        drop(chunk_by);
 7653        if !revert_changes.is_empty() {
 7654            self.transact(window, cx, |editor, window, cx| {
 7655                editor.revert(revert_changes, window, cx);
 7656            });
 7657        }
 7658    }
 7659
 7660    pub fn open_active_item_in_terminal(
 7661        &mut self,
 7662        _: &OpenInTerminal,
 7663        window: &mut Window,
 7664        cx: &mut Context<Self>,
 7665    ) {
 7666        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7667            let project_path = buffer.read(cx).project_path(cx)?;
 7668            let project = self.project.as_ref()?.read(cx);
 7669            let entry = project.entry_for_path(&project_path, cx)?;
 7670            let parent = match &entry.canonical_path {
 7671                Some(canonical_path) => canonical_path.to_path_buf(),
 7672                None => project.absolute_path(&project_path, cx)?,
 7673            }
 7674            .parent()?
 7675            .to_path_buf();
 7676            Some(parent)
 7677        }) {
 7678            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7679        }
 7680    }
 7681
 7682    pub fn prepare_restore_change(
 7683        &self,
 7684        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7685        hunk: &MultiBufferDiffHunk,
 7686        cx: &mut App,
 7687    ) -> Option<()> {
 7688        let buffer = self.buffer.read(cx);
 7689        let diff = buffer.diff_for(hunk.buffer_id)?;
 7690        let buffer = buffer.buffer(hunk.buffer_id)?;
 7691        let buffer = buffer.read(cx);
 7692        let original_text = diff
 7693            .read(cx)
 7694            .base_text()
 7695            .as_ref()?
 7696            .as_rope()
 7697            .slice(hunk.diff_base_byte_range.clone());
 7698        let buffer_snapshot = buffer.snapshot();
 7699        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7700        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7701            probe
 7702                .0
 7703                .start
 7704                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7705                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7706        }) {
 7707            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7708            Some(())
 7709        } else {
 7710            None
 7711        }
 7712    }
 7713
 7714    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7715        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7716    }
 7717
 7718    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7719        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7720    }
 7721
 7722    fn manipulate_lines<Fn>(
 7723        &mut self,
 7724        window: &mut Window,
 7725        cx: &mut Context<Self>,
 7726        mut callback: Fn,
 7727    ) where
 7728        Fn: FnMut(&mut Vec<&str>),
 7729    {
 7730        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7731        let buffer = self.buffer.read(cx).snapshot(cx);
 7732
 7733        let mut edits = Vec::new();
 7734
 7735        let selections = self.selections.all::<Point>(cx);
 7736        let mut selections = selections.iter().peekable();
 7737        let mut contiguous_row_selections = Vec::new();
 7738        let mut new_selections = Vec::new();
 7739        let mut added_lines = 0;
 7740        let mut removed_lines = 0;
 7741
 7742        while let Some(selection) = selections.next() {
 7743            let (start_row, end_row) = consume_contiguous_rows(
 7744                &mut contiguous_row_selections,
 7745                selection,
 7746                &display_map,
 7747                &mut selections,
 7748            );
 7749
 7750            let start_point = Point::new(start_row.0, 0);
 7751            let end_point = Point::new(
 7752                end_row.previous_row().0,
 7753                buffer.line_len(end_row.previous_row()),
 7754            );
 7755            let text = buffer
 7756                .text_for_range(start_point..end_point)
 7757                .collect::<String>();
 7758
 7759            let mut lines = text.split('\n').collect_vec();
 7760
 7761            let lines_before = lines.len();
 7762            callback(&mut lines);
 7763            let lines_after = lines.len();
 7764
 7765            edits.push((start_point..end_point, lines.join("\n")));
 7766
 7767            // Selections must change based on added and removed line count
 7768            let start_row =
 7769                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7770            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7771            new_selections.push(Selection {
 7772                id: selection.id,
 7773                start: start_row,
 7774                end: end_row,
 7775                goal: SelectionGoal::None,
 7776                reversed: selection.reversed,
 7777            });
 7778
 7779            if lines_after > lines_before {
 7780                added_lines += lines_after - lines_before;
 7781            } else if lines_before > lines_after {
 7782                removed_lines += lines_before - lines_after;
 7783            }
 7784        }
 7785
 7786        self.transact(window, cx, |this, window, cx| {
 7787            let buffer = this.buffer.update(cx, |buffer, cx| {
 7788                buffer.edit(edits, None, cx);
 7789                buffer.snapshot(cx)
 7790            });
 7791
 7792            // Recalculate offsets on newly edited buffer
 7793            let new_selections = new_selections
 7794                .iter()
 7795                .map(|s| {
 7796                    let start_point = Point::new(s.start.0, 0);
 7797                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7798                    Selection {
 7799                        id: s.id,
 7800                        start: buffer.point_to_offset(start_point),
 7801                        end: buffer.point_to_offset(end_point),
 7802                        goal: s.goal,
 7803                        reversed: s.reversed,
 7804                    }
 7805                })
 7806                .collect();
 7807
 7808            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7809                s.select(new_selections);
 7810            });
 7811
 7812            this.request_autoscroll(Autoscroll::fit(), cx);
 7813        });
 7814    }
 7815
 7816    pub fn convert_to_upper_case(
 7817        &mut self,
 7818        _: &ConvertToUpperCase,
 7819        window: &mut Window,
 7820        cx: &mut Context<Self>,
 7821    ) {
 7822        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7823    }
 7824
 7825    pub fn convert_to_lower_case(
 7826        &mut self,
 7827        _: &ConvertToLowerCase,
 7828        window: &mut Window,
 7829        cx: &mut Context<Self>,
 7830    ) {
 7831        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7832    }
 7833
 7834    pub fn convert_to_title_case(
 7835        &mut self,
 7836        _: &ConvertToTitleCase,
 7837        window: &mut Window,
 7838        cx: &mut Context<Self>,
 7839    ) {
 7840        self.manipulate_text(window, cx, |text| {
 7841            text.split('\n')
 7842                .map(|line| line.to_case(Case::Title))
 7843                .join("\n")
 7844        })
 7845    }
 7846
 7847    pub fn convert_to_snake_case(
 7848        &mut self,
 7849        _: &ConvertToSnakeCase,
 7850        window: &mut Window,
 7851        cx: &mut Context<Self>,
 7852    ) {
 7853        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7854    }
 7855
 7856    pub fn convert_to_kebab_case(
 7857        &mut self,
 7858        _: &ConvertToKebabCase,
 7859        window: &mut Window,
 7860        cx: &mut Context<Self>,
 7861    ) {
 7862        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7863    }
 7864
 7865    pub fn convert_to_upper_camel_case(
 7866        &mut self,
 7867        _: &ConvertToUpperCamelCase,
 7868        window: &mut Window,
 7869        cx: &mut Context<Self>,
 7870    ) {
 7871        self.manipulate_text(window, cx, |text| {
 7872            text.split('\n')
 7873                .map(|line| line.to_case(Case::UpperCamel))
 7874                .join("\n")
 7875        })
 7876    }
 7877
 7878    pub fn convert_to_lower_camel_case(
 7879        &mut self,
 7880        _: &ConvertToLowerCamelCase,
 7881        window: &mut Window,
 7882        cx: &mut Context<Self>,
 7883    ) {
 7884        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7885    }
 7886
 7887    pub fn convert_to_opposite_case(
 7888        &mut self,
 7889        _: &ConvertToOppositeCase,
 7890        window: &mut Window,
 7891        cx: &mut Context<Self>,
 7892    ) {
 7893        self.manipulate_text(window, cx, |text| {
 7894            text.chars()
 7895                .fold(String::with_capacity(text.len()), |mut t, c| {
 7896                    if c.is_uppercase() {
 7897                        t.extend(c.to_lowercase());
 7898                    } else {
 7899                        t.extend(c.to_uppercase());
 7900                    }
 7901                    t
 7902                })
 7903        })
 7904    }
 7905
 7906    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7907    where
 7908        Fn: FnMut(&str) -> String,
 7909    {
 7910        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7911        let buffer = self.buffer.read(cx).snapshot(cx);
 7912
 7913        let mut new_selections = Vec::new();
 7914        let mut edits = Vec::new();
 7915        let mut selection_adjustment = 0i32;
 7916
 7917        for selection in self.selections.all::<usize>(cx) {
 7918            let selection_is_empty = selection.is_empty();
 7919
 7920            let (start, end) = if selection_is_empty {
 7921                let word_range = movement::surrounding_word(
 7922                    &display_map,
 7923                    selection.start.to_display_point(&display_map),
 7924                );
 7925                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7926                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7927                (start, end)
 7928            } else {
 7929                (selection.start, selection.end)
 7930            };
 7931
 7932            let text = buffer.text_for_range(start..end).collect::<String>();
 7933            let old_length = text.len() as i32;
 7934            let text = callback(&text);
 7935
 7936            new_selections.push(Selection {
 7937                start: (start as i32 - selection_adjustment) as usize,
 7938                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7939                goal: SelectionGoal::None,
 7940                ..selection
 7941            });
 7942
 7943            selection_adjustment += old_length - text.len() as i32;
 7944
 7945            edits.push((start..end, text));
 7946        }
 7947
 7948        self.transact(window, cx, |this, window, cx| {
 7949            this.buffer.update(cx, |buffer, cx| {
 7950                buffer.edit(edits, None, cx);
 7951            });
 7952
 7953            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7954                s.select(new_selections);
 7955            });
 7956
 7957            this.request_autoscroll(Autoscroll::fit(), cx);
 7958        });
 7959    }
 7960
 7961    pub fn duplicate(
 7962        &mut self,
 7963        upwards: bool,
 7964        whole_lines: bool,
 7965        window: &mut Window,
 7966        cx: &mut Context<Self>,
 7967    ) {
 7968        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7969        let buffer = &display_map.buffer_snapshot;
 7970        let selections = self.selections.all::<Point>(cx);
 7971
 7972        let mut edits = Vec::new();
 7973        let mut selections_iter = selections.iter().peekable();
 7974        while let Some(selection) = selections_iter.next() {
 7975            let mut rows = selection.spanned_rows(false, &display_map);
 7976            // duplicate line-wise
 7977            if whole_lines || selection.start == selection.end {
 7978                // Avoid duplicating the same lines twice.
 7979                while let Some(next_selection) = selections_iter.peek() {
 7980                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7981                    if next_rows.start < rows.end {
 7982                        rows.end = next_rows.end;
 7983                        selections_iter.next().unwrap();
 7984                    } else {
 7985                        break;
 7986                    }
 7987                }
 7988
 7989                // Copy the text from the selected row region and splice it either at the start
 7990                // or end of the region.
 7991                let start = Point::new(rows.start.0, 0);
 7992                let end = Point::new(
 7993                    rows.end.previous_row().0,
 7994                    buffer.line_len(rows.end.previous_row()),
 7995                );
 7996                let text = buffer
 7997                    .text_for_range(start..end)
 7998                    .chain(Some("\n"))
 7999                    .collect::<String>();
 8000                let insert_location = if upwards {
 8001                    Point::new(rows.end.0, 0)
 8002                } else {
 8003                    start
 8004                };
 8005                edits.push((insert_location..insert_location, text));
 8006            } else {
 8007                // duplicate character-wise
 8008                let start = selection.start;
 8009                let end = selection.end;
 8010                let text = buffer.text_for_range(start..end).collect::<String>();
 8011                edits.push((selection.end..selection.end, text));
 8012            }
 8013        }
 8014
 8015        self.transact(window, cx, |this, _, cx| {
 8016            this.buffer.update(cx, |buffer, cx| {
 8017                buffer.edit(edits, None, cx);
 8018            });
 8019
 8020            this.request_autoscroll(Autoscroll::fit(), cx);
 8021        });
 8022    }
 8023
 8024    pub fn duplicate_line_up(
 8025        &mut self,
 8026        _: &DuplicateLineUp,
 8027        window: &mut Window,
 8028        cx: &mut Context<Self>,
 8029    ) {
 8030        self.duplicate(true, true, window, cx);
 8031    }
 8032
 8033    pub fn duplicate_line_down(
 8034        &mut self,
 8035        _: &DuplicateLineDown,
 8036        window: &mut Window,
 8037        cx: &mut Context<Self>,
 8038    ) {
 8039        self.duplicate(false, true, window, cx);
 8040    }
 8041
 8042    pub fn duplicate_selection(
 8043        &mut self,
 8044        _: &DuplicateSelection,
 8045        window: &mut Window,
 8046        cx: &mut Context<Self>,
 8047    ) {
 8048        self.duplicate(false, false, window, cx);
 8049    }
 8050
 8051    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 8052        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8053        let buffer = self.buffer.read(cx).snapshot(cx);
 8054
 8055        let mut edits = Vec::new();
 8056        let mut unfold_ranges = Vec::new();
 8057        let mut refold_creases = Vec::new();
 8058
 8059        let selections = self.selections.all::<Point>(cx);
 8060        let mut selections = selections.iter().peekable();
 8061        let mut contiguous_row_selections = Vec::new();
 8062        let mut new_selections = Vec::new();
 8063
 8064        while let Some(selection) = selections.next() {
 8065            // Find all the selections that span a contiguous row range
 8066            let (start_row, end_row) = consume_contiguous_rows(
 8067                &mut contiguous_row_selections,
 8068                selection,
 8069                &display_map,
 8070                &mut selections,
 8071            );
 8072
 8073            // Move the text spanned by the row range to be before the line preceding the row range
 8074            if start_row.0 > 0 {
 8075                let range_to_move = Point::new(
 8076                    start_row.previous_row().0,
 8077                    buffer.line_len(start_row.previous_row()),
 8078                )
 8079                    ..Point::new(
 8080                        end_row.previous_row().0,
 8081                        buffer.line_len(end_row.previous_row()),
 8082                    );
 8083                let insertion_point = display_map
 8084                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 8085                    .0;
 8086
 8087                // Don't move lines across excerpts
 8088                if buffer
 8089                    .excerpt_containing(insertion_point..range_to_move.end)
 8090                    .is_some()
 8091                {
 8092                    let text = buffer
 8093                        .text_for_range(range_to_move.clone())
 8094                        .flat_map(|s| s.chars())
 8095                        .skip(1)
 8096                        .chain(['\n'])
 8097                        .collect::<String>();
 8098
 8099                    edits.push((
 8100                        buffer.anchor_after(range_to_move.start)
 8101                            ..buffer.anchor_before(range_to_move.end),
 8102                        String::new(),
 8103                    ));
 8104                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8105                    edits.push((insertion_anchor..insertion_anchor, text));
 8106
 8107                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 8108
 8109                    // Move selections up
 8110                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8111                        |mut selection| {
 8112                            selection.start.row -= row_delta;
 8113                            selection.end.row -= row_delta;
 8114                            selection
 8115                        },
 8116                    ));
 8117
 8118                    // Move folds up
 8119                    unfold_ranges.push(range_to_move.clone());
 8120                    for fold in display_map.folds_in_range(
 8121                        buffer.anchor_before(range_to_move.start)
 8122                            ..buffer.anchor_after(range_to_move.end),
 8123                    ) {
 8124                        let mut start = fold.range.start.to_point(&buffer);
 8125                        let mut end = fold.range.end.to_point(&buffer);
 8126                        start.row -= row_delta;
 8127                        end.row -= row_delta;
 8128                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8129                    }
 8130                }
 8131            }
 8132
 8133            // If we didn't move line(s), preserve the existing selections
 8134            new_selections.append(&mut contiguous_row_selections);
 8135        }
 8136
 8137        self.transact(window, cx, |this, window, cx| {
 8138            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8139            this.buffer.update(cx, |buffer, cx| {
 8140                for (range, text) in edits {
 8141                    buffer.edit([(range, text)], None, cx);
 8142                }
 8143            });
 8144            this.fold_creases(refold_creases, true, window, cx);
 8145            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8146                s.select(new_selections);
 8147            })
 8148        });
 8149    }
 8150
 8151    pub fn move_line_down(
 8152        &mut self,
 8153        _: &MoveLineDown,
 8154        window: &mut Window,
 8155        cx: &mut Context<Self>,
 8156    ) {
 8157        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8158        let buffer = self.buffer.read(cx).snapshot(cx);
 8159
 8160        let mut edits = Vec::new();
 8161        let mut unfold_ranges = Vec::new();
 8162        let mut refold_creases = Vec::new();
 8163
 8164        let selections = self.selections.all::<Point>(cx);
 8165        let mut selections = selections.iter().peekable();
 8166        let mut contiguous_row_selections = Vec::new();
 8167        let mut new_selections = Vec::new();
 8168
 8169        while let Some(selection) = selections.next() {
 8170            // Find all the selections that span a contiguous row range
 8171            let (start_row, end_row) = consume_contiguous_rows(
 8172                &mut contiguous_row_selections,
 8173                selection,
 8174                &display_map,
 8175                &mut selections,
 8176            );
 8177
 8178            // Move the text spanned by the row range to be after the last line of the row range
 8179            if end_row.0 <= buffer.max_point().row {
 8180                let range_to_move =
 8181                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 8182                let insertion_point = display_map
 8183                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 8184                    .0;
 8185
 8186                // Don't move lines across excerpt boundaries
 8187                if buffer
 8188                    .excerpt_containing(range_to_move.start..insertion_point)
 8189                    .is_some()
 8190                {
 8191                    let mut text = String::from("\n");
 8192                    text.extend(buffer.text_for_range(range_to_move.clone()));
 8193                    text.pop(); // Drop trailing newline
 8194                    edits.push((
 8195                        buffer.anchor_after(range_to_move.start)
 8196                            ..buffer.anchor_before(range_to_move.end),
 8197                        String::new(),
 8198                    ));
 8199                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8200                    edits.push((insertion_anchor..insertion_anchor, text));
 8201
 8202                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 8203
 8204                    // Move selections down
 8205                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8206                        |mut selection| {
 8207                            selection.start.row += row_delta;
 8208                            selection.end.row += row_delta;
 8209                            selection
 8210                        },
 8211                    ));
 8212
 8213                    // Move folds down
 8214                    unfold_ranges.push(range_to_move.clone());
 8215                    for fold in display_map.folds_in_range(
 8216                        buffer.anchor_before(range_to_move.start)
 8217                            ..buffer.anchor_after(range_to_move.end),
 8218                    ) {
 8219                        let mut start = fold.range.start.to_point(&buffer);
 8220                        let mut end = fold.range.end.to_point(&buffer);
 8221                        start.row += row_delta;
 8222                        end.row += row_delta;
 8223                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8224                    }
 8225                }
 8226            }
 8227
 8228            // If we didn't move line(s), preserve the existing selections
 8229            new_selections.append(&mut contiguous_row_selections);
 8230        }
 8231
 8232        self.transact(window, cx, |this, window, cx| {
 8233            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8234            this.buffer.update(cx, |buffer, cx| {
 8235                for (range, text) in edits {
 8236                    buffer.edit([(range, text)], None, cx);
 8237                }
 8238            });
 8239            this.fold_creases(refold_creases, true, window, cx);
 8240            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8241                s.select(new_selections)
 8242            });
 8243        });
 8244    }
 8245
 8246    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 8247        let text_layout_details = &self.text_layout_details(window);
 8248        self.transact(window, cx, |this, window, cx| {
 8249            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8250                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 8251                let line_mode = s.line_mode;
 8252                s.move_with(|display_map, selection| {
 8253                    if !selection.is_empty() || line_mode {
 8254                        return;
 8255                    }
 8256
 8257                    let mut head = selection.head();
 8258                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 8259                    if head.column() == display_map.line_len(head.row()) {
 8260                        transpose_offset = display_map
 8261                            .buffer_snapshot
 8262                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8263                    }
 8264
 8265                    if transpose_offset == 0 {
 8266                        return;
 8267                    }
 8268
 8269                    *head.column_mut() += 1;
 8270                    head = display_map.clip_point(head, Bias::Right);
 8271                    let goal = SelectionGoal::HorizontalPosition(
 8272                        display_map
 8273                            .x_for_display_point(head, text_layout_details)
 8274                            .into(),
 8275                    );
 8276                    selection.collapse_to(head, goal);
 8277
 8278                    let transpose_start = display_map
 8279                        .buffer_snapshot
 8280                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8281                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 8282                        let transpose_end = display_map
 8283                            .buffer_snapshot
 8284                            .clip_offset(transpose_offset + 1, Bias::Right);
 8285                        if let Some(ch) =
 8286                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 8287                        {
 8288                            edits.push((transpose_start..transpose_offset, String::new()));
 8289                            edits.push((transpose_end..transpose_end, ch.to_string()));
 8290                        }
 8291                    }
 8292                });
 8293                edits
 8294            });
 8295            this.buffer
 8296                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8297            let selections = this.selections.all::<usize>(cx);
 8298            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8299                s.select(selections);
 8300            });
 8301        });
 8302    }
 8303
 8304    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 8305        self.rewrap_impl(IsVimMode::No, cx)
 8306    }
 8307
 8308    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 8309        let buffer = self.buffer.read(cx).snapshot(cx);
 8310        let selections = self.selections.all::<Point>(cx);
 8311        let mut selections = selections.iter().peekable();
 8312
 8313        let mut edits = Vec::new();
 8314        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 8315
 8316        while let Some(selection) = selections.next() {
 8317            let mut start_row = selection.start.row;
 8318            let mut end_row = selection.end.row;
 8319
 8320            // Skip selections that overlap with a range that has already been rewrapped.
 8321            let selection_range = start_row..end_row;
 8322            if rewrapped_row_ranges
 8323                .iter()
 8324                .any(|range| range.overlaps(&selection_range))
 8325            {
 8326                continue;
 8327            }
 8328
 8329            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 8330
 8331            // Since not all lines in the selection may be at the same indent
 8332            // level, choose the indent size that is the most common between all
 8333            // of the lines.
 8334            //
 8335            // If there is a tie, we use the deepest indent.
 8336            let (indent_size, indent_end) = {
 8337                let mut indent_size_occurrences = HashMap::default();
 8338                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 8339
 8340                for row in start_row..=end_row {
 8341                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 8342                    rows_by_indent_size.entry(indent).or_default().push(row);
 8343                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 8344                }
 8345
 8346                let indent_size = indent_size_occurrences
 8347                    .into_iter()
 8348                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 8349                    .map(|(indent, _)| indent)
 8350                    .unwrap_or_default();
 8351                let row = rows_by_indent_size[&indent_size][0];
 8352                let indent_end = Point::new(row, indent_size.len);
 8353
 8354                (indent_size, indent_end)
 8355            };
 8356
 8357            let mut line_prefix = indent_size.chars().collect::<String>();
 8358
 8359            let mut inside_comment = false;
 8360            if let Some(comment_prefix) =
 8361                buffer
 8362                    .language_scope_at(selection.head())
 8363                    .and_then(|language| {
 8364                        language
 8365                            .line_comment_prefixes()
 8366                            .iter()
 8367                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 8368                            .cloned()
 8369                    })
 8370            {
 8371                line_prefix.push_str(&comment_prefix);
 8372                inside_comment = true;
 8373            }
 8374
 8375            let language_settings = buffer.settings_at(selection.head(), cx);
 8376            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 8377                RewrapBehavior::InComments => inside_comment,
 8378                RewrapBehavior::InSelections => !selection.is_empty(),
 8379                RewrapBehavior::Anywhere => true,
 8380            };
 8381
 8382            let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
 8383            if !should_rewrap {
 8384                continue;
 8385            }
 8386
 8387            if selection.is_empty() {
 8388                'expand_upwards: while start_row > 0 {
 8389                    let prev_row = start_row - 1;
 8390                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 8391                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 8392                    {
 8393                        start_row = prev_row;
 8394                    } else {
 8395                        break 'expand_upwards;
 8396                    }
 8397                }
 8398
 8399                'expand_downwards: while end_row < buffer.max_point().row {
 8400                    let next_row = end_row + 1;
 8401                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 8402                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 8403                    {
 8404                        end_row = next_row;
 8405                    } else {
 8406                        break 'expand_downwards;
 8407                    }
 8408                }
 8409            }
 8410
 8411            let start = Point::new(start_row, 0);
 8412            let start_offset = start.to_offset(&buffer);
 8413            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 8414            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 8415            let Some(lines_without_prefixes) = selection_text
 8416                .lines()
 8417                .map(|line| {
 8418                    line.strip_prefix(&line_prefix)
 8419                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 8420                        .ok_or_else(|| {
 8421                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 8422                        })
 8423                })
 8424                .collect::<Result<Vec<_>, _>>()
 8425                .log_err()
 8426            else {
 8427                continue;
 8428            };
 8429
 8430            let wrap_column = buffer
 8431                .settings_at(Point::new(start_row, 0), cx)
 8432                .preferred_line_length as usize;
 8433            let wrapped_text = wrap_with_prefix(
 8434                line_prefix,
 8435                lines_without_prefixes.join(" "),
 8436                wrap_column,
 8437                tab_size,
 8438            );
 8439
 8440            // TODO: should always use char-based diff while still supporting cursor behavior that
 8441            // matches vim.
 8442            let mut diff_options = DiffOptions::default();
 8443            if is_vim_mode == IsVimMode::Yes {
 8444                diff_options.max_word_diff_len = 0;
 8445                diff_options.max_word_diff_line_count = 0;
 8446            } else {
 8447                diff_options.max_word_diff_len = usize::MAX;
 8448                diff_options.max_word_diff_line_count = usize::MAX;
 8449            }
 8450
 8451            for (old_range, new_text) in
 8452                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 8453            {
 8454                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 8455                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 8456                edits.push((edit_start..edit_end, new_text));
 8457            }
 8458
 8459            rewrapped_row_ranges.push(start_row..=end_row);
 8460        }
 8461
 8462        self.buffer
 8463            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8464    }
 8465
 8466    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 8467        let mut text = String::new();
 8468        let buffer = self.buffer.read(cx).snapshot(cx);
 8469        let mut selections = self.selections.all::<Point>(cx);
 8470        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8471        {
 8472            let max_point = buffer.max_point();
 8473            let mut is_first = true;
 8474            for selection in &mut selections {
 8475                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8476                if is_entire_line {
 8477                    selection.start = Point::new(selection.start.row, 0);
 8478                    if !selection.is_empty() && selection.end.column == 0 {
 8479                        selection.end = cmp::min(max_point, selection.end);
 8480                    } else {
 8481                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 8482                    }
 8483                    selection.goal = SelectionGoal::None;
 8484                }
 8485                if is_first {
 8486                    is_first = false;
 8487                } else {
 8488                    text += "\n";
 8489                }
 8490                let mut len = 0;
 8491                for chunk in buffer.text_for_range(selection.start..selection.end) {
 8492                    text.push_str(chunk);
 8493                    len += chunk.len();
 8494                }
 8495                clipboard_selections.push(ClipboardSelection {
 8496                    len,
 8497                    is_entire_line,
 8498                    start_column: selection.start.column,
 8499                });
 8500            }
 8501        }
 8502
 8503        self.transact(window, cx, |this, window, cx| {
 8504            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8505                s.select(selections);
 8506            });
 8507            this.insert("", window, cx);
 8508        });
 8509        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 8510    }
 8511
 8512    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8513        let item = self.cut_common(window, cx);
 8514        cx.write_to_clipboard(item);
 8515    }
 8516
 8517    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8518        self.change_selections(None, window, cx, |s| {
 8519            s.move_with(|snapshot, sel| {
 8520                if sel.is_empty() {
 8521                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8522                }
 8523            });
 8524        });
 8525        let item = self.cut_common(window, cx);
 8526        cx.set_global(KillRing(item))
 8527    }
 8528
 8529    pub fn kill_ring_yank(
 8530        &mut self,
 8531        _: &KillRingYank,
 8532        window: &mut Window,
 8533        cx: &mut Context<Self>,
 8534    ) {
 8535        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8536            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8537                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8538            } else {
 8539                return;
 8540            }
 8541        } else {
 8542            return;
 8543        };
 8544        self.do_paste(&text, metadata, false, window, cx);
 8545    }
 8546
 8547    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8548        let selections = self.selections.all::<Point>(cx);
 8549        let buffer = self.buffer.read(cx).read(cx);
 8550        let mut text = String::new();
 8551
 8552        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8553        {
 8554            let max_point = buffer.max_point();
 8555            let mut is_first = true;
 8556            for selection in selections.iter() {
 8557                let mut start = selection.start;
 8558                let mut end = selection.end;
 8559                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8560                if is_entire_line {
 8561                    start = Point::new(start.row, 0);
 8562                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8563                }
 8564                if is_first {
 8565                    is_first = false;
 8566                } else {
 8567                    text += "\n";
 8568                }
 8569                let mut len = 0;
 8570                for chunk in buffer.text_for_range(start..end) {
 8571                    text.push_str(chunk);
 8572                    len += chunk.len();
 8573                }
 8574                clipboard_selections.push(ClipboardSelection {
 8575                    len,
 8576                    is_entire_line,
 8577                    start_column: start.column,
 8578                });
 8579            }
 8580        }
 8581
 8582        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8583            text,
 8584            clipboard_selections,
 8585        ));
 8586    }
 8587
 8588    pub fn do_paste(
 8589        &mut self,
 8590        text: &String,
 8591        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8592        handle_entire_lines: bool,
 8593        window: &mut Window,
 8594        cx: &mut Context<Self>,
 8595    ) {
 8596        if self.read_only(cx) {
 8597            return;
 8598        }
 8599
 8600        let clipboard_text = Cow::Borrowed(text);
 8601
 8602        self.transact(window, cx, |this, window, cx| {
 8603            if let Some(mut clipboard_selections) = clipboard_selections {
 8604                let old_selections = this.selections.all::<usize>(cx);
 8605                let all_selections_were_entire_line =
 8606                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8607                let first_selection_start_column =
 8608                    clipboard_selections.first().map(|s| s.start_column);
 8609                if clipboard_selections.len() != old_selections.len() {
 8610                    clipboard_selections.drain(..);
 8611                }
 8612                let cursor_offset = this.selections.last::<usize>(cx).head();
 8613                let mut auto_indent_on_paste = true;
 8614
 8615                this.buffer.update(cx, |buffer, cx| {
 8616                    let snapshot = buffer.read(cx);
 8617                    auto_indent_on_paste =
 8618                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 8619
 8620                    let mut start_offset = 0;
 8621                    let mut edits = Vec::new();
 8622                    let mut original_start_columns = Vec::new();
 8623                    for (ix, selection) in old_selections.iter().enumerate() {
 8624                        let to_insert;
 8625                        let entire_line;
 8626                        let original_start_column;
 8627                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8628                            let end_offset = start_offset + clipboard_selection.len;
 8629                            to_insert = &clipboard_text[start_offset..end_offset];
 8630                            entire_line = clipboard_selection.is_entire_line;
 8631                            start_offset = end_offset + 1;
 8632                            original_start_column = Some(clipboard_selection.start_column);
 8633                        } else {
 8634                            to_insert = clipboard_text.as_str();
 8635                            entire_line = all_selections_were_entire_line;
 8636                            original_start_column = first_selection_start_column
 8637                        }
 8638
 8639                        // If the corresponding selection was empty when this slice of the
 8640                        // clipboard text was written, then the entire line containing the
 8641                        // selection was copied. If this selection is also currently empty,
 8642                        // then paste the line before the current line of the buffer.
 8643                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8644                            let column = selection.start.to_point(&snapshot).column as usize;
 8645                            let line_start = selection.start - column;
 8646                            line_start..line_start
 8647                        } else {
 8648                            selection.range()
 8649                        };
 8650
 8651                        edits.push((range, to_insert));
 8652                        original_start_columns.extend(original_start_column);
 8653                    }
 8654                    drop(snapshot);
 8655
 8656                    buffer.edit(
 8657                        edits,
 8658                        if auto_indent_on_paste {
 8659                            Some(AutoindentMode::Block {
 8660                                original_start_columns,
 8661                            })
 8662                        } else {
 8663                            None
 8664                        },
 8665                        cx,
 8666                    );
 8667                });
 8668
 8669                let selections = this.selections.all::<usize>(cx);
 8670                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8671                    s.select(selections)
 8672                });
 8673            } else {
 8674                this.insert(&clipboard_text, window, cx);
 8675            }
 8676        });
 8677    }
 8678
 8679    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8680        if let Some(item) = cx.read_from_clipboard() {
 8681            let entries = item.entries();
 8682
 8683            match entries.first() {
 8684                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8685                // of all the pasted entries.
 8686                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8687                    .do_paste(
 8688                        clipboard_string.text(),
 8689                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8690                        true,
 8691                        window,
 8692                        cx,
 8693                    ),
 8694                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8695            }
 8696        }
 8697    }
 8698
 8699    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8700        if self.read_only(cx) {
 8701            return;
 8702        }
 8703
 8704        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8705            if let Some((selections, _)) =
 8706                self.selection_history.transaction(transaction_id).cloned()
 8707            {
 8708                self.change_selections(None, window, cx, |s| {
 8709                    s.select_anchors(selections.to_vec());
 8710                });
 8711            }
 8712            self.request_autoscroll(Autoscroll::fit(), cx);
 8713            self.unmark_text(window, cx);
 8714            self.refresh_inline_completion(true, false, window, cx);
 8715            cx.emit(EditorEvent::Edited { transaction_id });
 8716            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8717        }
 8718    }
 8719
 8720    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8721        if self.read_only(cx) {
 8722            return;
 8723        }
 8724
 8725        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8726            if let Some((_, Some(selections))) =
 8727                self.selection_history.transaction(transaction_id).cloned()
 8728            {
 8729                self.change_selections(None, window, cx, |s| {
 8730                    s.select_anchors(selections.to_vec());
 8731                });
 8732            }
 8733            self.request_autoscroll(Autoscroll::fit(), cx);
 8734            self.unmark_text(window, cx);
 8735            self.refresh_inline_completion(true, false, window, cx);
 8736            cx.emit(EditorEvent::Edited { transaction_id });
 8737        }
 8738    }
 8739
 8740    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8741        self.buffer
 8742            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8743    }
 8744
 8745    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8746        self.buffer
 8747            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8748    }
 8749
 8750    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8751        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8752            let line_mode = s.line_mode;
 8753            s.move_with(|map, selection| {
 8754                let cursor = if selection.is_empty() && !line_mode {
 8755                    movement::left(map, selection.start)
 8756                } else {
 8757                    selection.start
 8758                };
 8759                selection.collapse_to(cursor, SelectionGoal::None);
 8760            });
 8761        })
 8762    }
 8763
 8764    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8765        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8766            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8767        })
 8768    }
 8769
 8770    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8771        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8772            let line_mode = s.line_mode;
 8773            s.move_with(|map, selection| {
 8774                let cursor = if selection.is_empty() && !line_mode {
 8775                    movement::right(map, selection.end)
 8776                } else {
 8777                    selection.end
 8778                };
 8779                selection.collapse_to(cursor, SelectionGoal::None)
 8780            });
 8781        })
 8782    }
 8783
 8784    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8785        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8786            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8787        })
 8788    }
 8789
 8790    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8791        if self.take_rename(true, window, cx).is_some() {
 8792            return;
 8793        }
 8794
 8795        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8796            cx.propagate();
 8797            return;
 8798        }
 8799
 8800        let text_layout_details = &self.text_layout_details(window);
 8801        let selection_count = self.selections.count();
 8802        let first_selection = self.selections.first_anchor();
 8803
 8804        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8805            let line_mode = s.line_mode;
 8806            s.move_with(|map, selection| {
 8807                if !selection.is_empty() && !line_mode {
 8808                    selection.goal = SelectionGoal::None;
 8809                }
 8810                let (cursor, goal) = movement::up(
 8811                    map,
 8812                    selection.start,
 8813                    selection.goal,
 8814                    false,
 8815                    text_layout_details,
 8816                );
 8817                selection.collapse_to(cursor, goal);
 8818            });
 8819        });
 8820
 8821        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8822        {
 8823            cx.propagate();
 8824        }
 8825    }
 8826
 8827    pub fn move_up_by_lines(
 8828        &mut self,
 8829        action: &MoveUpByLines,
 8830        window: &mut Window,
 8831        cx: &mut Context<Self>,
 8832    ) {
 8833        if self.take_rename(true, window, cx).is_some() {
 8834            return;
 8835        }
 8836
 8837        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8838            cx.propagate();
 8839            return;
 8840        }
 8841
 8842        let text_layout_details = &self.text_layout_details(window);
 8843
 8844        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8845            let line_mode = s.line_mode;
 8846            s.move_with(|map, selection| {
 8847                if !selection.is_empty() && !line_mode {
 8848                    selection.goal = SelectionGoal::None;
 8849                }
 8850                let (cursor, goal) = movement::up_by_rows(
 8851                    map,
 8852                    selection.start,
 8853                    action.lines,
 8854                    selection.goal,
 8855                    false,
 8856                    text_layout_details,
 8857                );
 8858                selection.collapse_to(cursor, goal);
 8859            });
 8860        })
 8861    }
 8862
 8863    pub fn move_down_by_lines(
 8864        &mut self,
 8865        action: &MoveDownByLines,
 8866        window: &mut Window,
 8867        cx: &mut Context<Self>,
 8868    ) {
 8869        if self.take_rename(true, window, cx).is_some() {
 8870            return;
 8871        }
 8872
 8873        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8874            cx.propagate();
 8875            return;
 8876        }
 8877
 8878        let text_layout_details = &self.text_layout_details(window);
 8879
 8880        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8881            let line_mode = s.line_mode;
 8882            s.move_with(|map, selection| {
 8883                if !selection.is_empty() && !line_mode {
 8884                    selection.goal = SelectionGoal::None;
 8885                }
 8886                let (cursor, goal) = movement::down_by_rows(
 8887                    map,
 8888                    selection.start,
 8889                    action.lines,
 8890                    selection.goal,
 8891                    false,
 8892                    text_layout_details,
 8893                );
 8894                selection.collapse_to(cursor, goal);
 8895            });
 8896        })
 8897    }
 8898
 8899    pub fn select_down_by_lines(
 8900        &mut self,
 8901        action: &SelectDownByLines,
 8902        window: &mut Window,
 8903        cx: &mut Context<Self>,
 8904    ) {
 8905        let text_layout_details = &self.text_layout_details(window);
 8906        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8907            s.move_heads_with(|map, head, goal| {
 8908                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8909            })
 8910        })
 8911    }
 8912
 8913    pub fn select_up_by_lines(
 8914        &mut self,
 8915        action: &SelectUpByLines,
 8916        window: &mut Window,
 8917        cx: &mut Context<Self>,
 8918    ) {
 8919        let text_layout_details = &self.text_layout_details(window);
 8920        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8921            s.move_heads_with(|map, head, goal| {
 8922                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8923            })
 8924        })
 8925    }
 8926
 8927    pub fn select_page_up(
 8928        &mut self,
 8929        _: &SelectPageUp,
 8930        window: &mut Window,
 8931        cx: &mut Context<Self>,
 8932    ) {
 8933        let Some(row_count) = self.visible_row_count() else {
 8934            return;
 8935        };
 8936
 8937        let text_layout_details = &self.text_layout_details(window);
 8938
 8939        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8940            s.move_heads_with(|map, head, goal| {
 8941                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8942            })
 8943        })
 8944    }
 8945
 8946    pub fn move_page_up(
 8947        &mut self,
 8948        action: &MovePageUp,
 8949        window: &mut Window,
 8950        cx: &mut Context<Self>,
 8951    ) {
 8952        if self.take_rename(true, window, cx).is_some() {
 8953            return;
 8954        }
 8955
 8956        if self
 8957            .context_menu
 8958            .borrow_mut()
 8959            .as_mut()
 8960            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8961            .unwrap_or(false)
 8962        {
 8963            return;
 8964        }
 8965
 8966        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8967            cx.propagate();
 8968            return;
 8969        }
 8970
 8971        let Some(row_count) = self.visible_row_count() else {
 8972            return;
 8973        };
 8974
 8975        let autoscroll = if action.center_cursor {
 8976            Autoscroll::center()
 8977        } else {
 8978            Autoscroll::fit()
 8979        };
 8980
 8981        let text_layout_details = &self.text_layout_details(window);
 8982
 8983        self.change_selections(Some(autoscroll), window, cx, |s| {
 8984            let line_mode = s.line_mode;
 8985            s.move_with(|map, selection| {
 8986                if !selection.is_empty() && !line_mode {
 8987                    selection.goal = SelectionGoal::None;
 8988                }
 8989                let (cursor, goal) = movement::up_by_rows(
 8990                    map,
 8991                    selection.end,
 8992                    row_count,
 8993                    selection.goal,
 8994                    false,
 8995                    text_layout_details,
 8996                );
 8997                selection.collapse_to(cursor, goal);
 8998            });
 8999        });
 9000    }
 9001
 9002    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 9003        let text_layout_details = &self.text_layout_details(window);
 9004        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9005            s.move_heads_with(|map, head, goal| {
 9006                movement::up(map, head, goal, false, text_layout_details)
 9007            })
 9008        })
 9009    }
 9010
 9011    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 9012        self.take_rename(true, window, cx);
 9013
 9014        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9015            cx.propagate();
 9016            return;
 9017        }
 9018
 9019        let text_layout_details = &self.text_layout_details(window);
 9020        let selection_count = self.selections.count();
 9021        let first_selection = self.selections.first_anchor();
 9022
 9023        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9024            let line_mode = s.line_mode;
 9025            s.move_with(|map, selection| {
 9026                if !selection.is_empty() && !line_mode {
 9027                    selection.goal = SelectionGoal::None;
 9028                }
 9029                let (cursor, goal) = movement::down(
 9030                    map,
 9031                    selection.end,
 9032                    selection.goal,
 9033                    false,
 9034                    text_layout_details,
 9035                );
 9036                selection.collapse_to(cursor, goal);
 9037            });
 9038        });
 9039
 9040        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9041        {
 9042            cx.propagate();
 9043        }
 9044    }
 9045
 9046    pub fn select_page_down(
 9047        &mut self,
 9048        _: &SelectPageDown,
 9049        window: &mut Window,
 9050        cx: &mut Context<Self>,
 9051    ) {
 9052        let Some(row_count) = self.visible_row_count() else {
 9053            return;
 9054        };
 9055
 9056        let text_layout_details = &self.text_layout_details(window);
 9057
 9058        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9059            s.move_heads_with(|map, head, goal| {
 9060                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 9061            })
 9062        })
 9063    }
 9064
 9065    pub fn move_page_down(
 9066        &mut self,
 9067        action: &MovePageDown,
 9068        window: &mut Window,
 9069        cx: &mut Context<Self>,
 9070    ) {
 9071        if self.take_rename(true, window, cx).is_some() {
 9072            return;
 9073        }
 9074
 9075        if self
 9076            .context_menu
 9077            .borrow_mut()
 9078            .as_mut()
 9079            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 9080            .unwrap_or(false)
 9081        {
 9082            return;
 9083        }
 9084
 9085        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9086            cx.propagate();
 9087            return;
 9088        }
 9089
 9090        let Some(row_count) = self.visible_row_count() else {
 9091            return;
 9092        };
 9093
 9094        let autoscroll = if action.center_cursor {
 9095            Autoscroll::center()
 9096        } else {
 9097            Autoscroll::fit()
 9098        };
 9099
 9100        let text_layout_details = &self.text_layout_details(window);
 9101        self.change_selections(Some(autoscroll), window, cx, |s| {
 9102            let line_mode = s.line_mode;
 9103            s.move_with(|map, selection| {
 9104                if !selection.is_empty() && !line_mode {
 9105                    selection.goal = SelectionGoal::None;
 9106                }
 9107                let (cursor, goal) = movement::down_by_rows(
 9108                    map,
 9109                    selection.end,
 9110                    row_count,
 9111                    selection.goal,
 9112                    false,
 9113                    text_layout_details,
 9114                );
 9115                selection.collapse_to(cursor, goal);
 9116            });
 9117        });
 9118    }
 9119
 9120    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 9121        let text_layout_details = &self.text_layout_details(window);
 9122        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9123            s.move_heads_with(|map, head, goal| {
 9124                movement::down(map, head, goal, false, text_layout_details)
 9125            })
 9126        });
 9127    }
 9128
 9129    pub fn context_menu_first(
 9130        &mut self,
 9131        _: &ContextMenuFirst,
 9132        _window: &mut Window,
 9133        cx: &mut Context<Self>,
 9134    ) {
 9135        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9136            context_menu.select_first(self.completion_provider.as_deref(), cx);
 9137        }
 9138    }
 9139
 9140    pub fn context_menu_prev(
 9141        &mut self,
 9142        _: &ContextMenuPrev,
 9143        _window: &mut Window,
 9144        cx: &mut Context<Self>,
 9145    ) {
 9146        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9147            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 9148        }
 9149    }
 9150
 9151    pub fn context_menu_next(
 9152        &mut self,
 9153        _: &ContextMenuNext,
 9154        _window: &mut Window,
 9155        cx: &mut Context<Self>,
 9156    ) {
 9157        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9158            context_menu.select_next(self.completion_provider.as_deref(), cx);
 9159        }
 9160    }
 9161
 9162    pub fn context_menu_last(
 9163        &mut self,
 9164        _: &ContextMenuLast,
 9165        _window: &mut Window,
 9166        cx: &mut Context<Self>,
 9167    ) {
 9168        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9169            context_menu.select_last(self.completion_provider.as_deref(), cx);
 9170        }
 9171    }
 9172
 9173    pub fn move_to_previous_word_start(
 9174        &mut self,
 9175        _: &MoveToPreviousWordStart,
 9176        window: &mut Window,
 9177        cx: &mut Context<Self>,
 9178    ) {
 9179        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9180            s.move_cursors_with(|map, head, _| {
 9181                (
 9182                    movement::previous_word_start(map, head),
 9183                    SelectionGoal::None,
 9184                )
 9185            });
 9186        })
 9187    }
 9188
 9189    pub fn move_to_previous_subword_start(
 9190        &mut self,
 9191        _: &MoveToPreviousSubwordStart,
 9192        window: &mut Window,
 9193        cx: &mut Context<Self>,
 9194    ) {
 9195        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9196            s.move_cursors_with(|map, head, _| {
 9197                (
 9198                    movement::previous_subword_start(map, head),
 9199                    SelectionGoal::None,
 9200                )
 9201            });
 9202        })
 9203    }
 9204
 9205    pub fn select_to_previous_word_start(
 9206        &mut self,
 9207        _: &SelectToPreviousWordStart,
 9208        window: &mut Window,
 9209        cx: &mut Context<Self>,
 9210    ) {
 9211        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9212            s.move_heads_with(|map, head, _| {
 9213                (
 9214                    movement::previous_word_start(map, head),
 9215                    SelectionGoal::None,
 9216                )
 9217            });
 9218        })
 9219    }
 9220
 9221    pub fn select_to_previous_subword_start(
 9222        &mut self,
 9223        _: &SelectToPreviousSubwordStart,
 9224        window: &mut Window,
 9225        cx: &mut Context<Self>,
 9226    ) {
 9227        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9228            s.move_heads_with(|map, head, _| {
 9229                (
 9230                    movement::previous_subword_start(map, head),
 9231                    SelectionGoal::None,
 9232                )
 9233            });
 9234        })
 9235    }
 9236
 9237    pub fn delete_to_previous_word_start(
 9238        &mut self,
 9239        action: &DeleteToPreviousWordStart,
 9240        window: &mut Window,
 9241        cx: &mut Context<Self>,
 9242    ) {
 9243        self.transact(window, cx, |this, window, cx| {
 9244            this.select_autoclose_pair(window, cx);
 9245            this.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                        let cursor = if action.ignore_newlines {
 9250                            movement::previous_word_start(map, selection.head())
 9251                        } else {
 9252                            movement::previous_word_start_or_newline(map, selection.head())
 9253                        };
 9254                        selection.set_head(cursor, SelectionGoal::None);
 9255                    }
 9256                });
 9257            });
 9258            this.insert("", window, cx);
 9259        });
 9260    }
 9261
 9262    pub fn delete_to_previous_subword_start(
 9263        &mut self,
 9264        _: &DeleteToPreviousSubwordStart,
 9265        window: &mut Window,
 9266        cx: &mut Context<Self>,
 9267    ) {
 9268        self.transact(window, cx, |this, window, cx| {
 9269            this.select_autoclose_pair(window, cx);
 9270            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9271                let line_mode = s.line_mode;
 9272                s.move_with(|map, selection| {
 9273                    if selection.is_empty() && !line_mode {
 9274                        let cursor = movement::previous_subword_start(map, selection.head());
 9275                        selection.set_head(cursor, SelectionGoal::None);
 9276                    }
 9277                });
 9278            });
 9279            this.insert("", window, cx);
 9280        });
 9281    }
 9282
 9283    pub fn move_to_next_word_end(
 9284        &mut self,
 9285        _: &MoveToNextWordEnd,
 9286        window: &mut Window,
 9287        cx: &mut Context<Self>,
 9288    ) {
 9289        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9290            s.move_cursors_with(|map, head, _| {
 9291                (movement::next_word_end(map, head), SelectionGoal::None)
 9292            });
 9293        })
 9294    }
 9295
 9296    pub fn move_to_next_subword_end(
 9297        &mut self,
 9298        _: &MoveToNextSubwordEnd,
 9299        window: &mut Window,
 9300        cx: &mut Context<Self>,
 9301    ) {
 9302        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9303            s.move_cursors_with(|map, head, _| {
 9304                (movement::next_subword_end(map, head), SelectionGoal::None)
 9305            });
 9306        })
 9307    }
 9308
 9309    pub fn select_to_next_word_end(
 9310        &mut self,
 9311        _: &SelectToNextWordEnd,
 9312        window: &mut Window,
 9313        cx: &mut Context<Self>,
 9314    ) {
 9315        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9316            s.move_heads_with(|map, head, _| {
 9317                (movement::next_word_end(map, head), SelectionGoal::None)
 9318            });
 9319        })
 9320    }
 9321
 9322    pub fn select_to_next_subword_end(
 9323        &mut self,
 9324        _: &SelectToNextSubwordEnd,
 9325        window: &mut Window,
 9326        cx: &mut Context<Self>,
 9327    ) {
 9328        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9329            s.move_heads_with(|map, head, _| {
 9330                (movement::next_subword_end(map, head), SelectionGoal::None)
 9331            });
 9332        })
 9333    }
 9334
 9335    pub fn delete_to_next_word_end(
 9336        &mut self,
 9337        action: &DeleteToNextWordEnd,
 9338        window: &mut Window,
 9339        cx: &mut Context<Self>,
 9340    ) {
 9341        self.transact(window, cx, |this, window, cx| {
 9342            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9343                let line_mode = s.line_mode;
 9344                s.move_with(|map, selection| {
 9345                    if selection.is_empty() && !line_mode {
 9346                        let cursor = if action.ignore_newlines {
 9347                            movement::next_word_end(map, selection.head())
 9348                        } else {
 9349                            movement::next_word_end_or_newline(map, selection.head())
 9350                        };
 9351                        selection.set_head(cursor, SelectionGoal::None);
 9352                    }
 9353                });
 9354            });
 9355            this.insert("", window, cx);
 9356        });
 9357    }
 9358
 9359    pub fn delete_to_next_subword_end(
 9360        &mut self,
 9361        _: &DeleteToNextSubwordEnd,
 9362        window: &mut Window,
 9363        cx: &mut Context<Self>,
 9364    ) {
 9365        self.transact(window, cx, |this, window, cx| {
 9366            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9367                s.move_with(|map, selection| {
 9368                    if selection.is_empty() {
 9369                        let cursor = movement::next_subword_end(map, selection.head());
 9370                        selection.set_head(cursor, SelectionGoal::None);
 9371                    }
 9372                });
 9373            });
 9374            this.insert("", window, cx);
 9375        });
 9376    }
 9377
 9378    pub fn move_to_beginning_of_line(
 9379        &mut self,
 9380        action: &MoveToBeginningOfLine,
 9381        window: &mut Window,
 9382        cx: &mut Context<Self>,
 9383    ) {
 9384        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9385            s.move_cursors_with(|map, head, _| {
 9386                (
 9387                    movement::indented_line_beginning(
 9388                        map,
 9389                        head,
 9390                        action.stop_at_soft_wraps,
 9391                        action.stop_at_indent,
 9392                    ),
 9393                    SelectionGoal::None,
 9394                )
 9395            });
 9396        })
 9397    }
 9398
 9399    pub fn select_to_beginning_of_line(
 9400        &mut self,
 9401        action: &SelectToBeginningOfLine,
 9402        window: &mut Window,
 9403        cx: &mut Context<Self>,
 9404    ) {
 9405        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9406            s.move_heads_with(|map, head, _| {
 9407                (
 9408                    movement::indented_line_beginning(
 9409                        map,
 9410                        head,
 9411                        action.stop_at_soft_wraps,
 9412                        action.stop_at_indent,
 9413                    ),
 9414                    SelectionGoal::None,
 9415                )
 9416            });
 9417        });
 9418    }
 9419
 9420    pub fn delete_to_beginning_of_line(
 9421        &mut self,
 9422        _: &DeleteToBeginningOfLine,
 9423        window: &mut Window,
 9424        cx: &mut Context<Self>,
 9425    ) {
 9426        self.transact(window, cx, |this, window, cx| {
 9427            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9428                s.move_with(|_, selection| {
 9429                    selection.reversed = true;
 9430                });
 9431            });
 9432
 9433            this.select_to_beginning_of_line(
 9434                &SelectToBeginningOfLine {
 9435                    stop_at_soft_wraps: false,
 9436                    stop_at_indent: false,
 9437                },
 9438                window,
 9439                cx,
 9440            );
 9441            this.backspace(&Backspace, window, cx);
 9442        });
 9443    }
 9444
 9445    pub fn move_to_end_of_line(
 9446        &mut self,
 9447        action: &MoveToEndOfLine,
 9448        window: &mut Window,
 9449        cx: &mut Context<Self>,
 9450    ) {
 9451        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9452            s.move_cursors_with(|map, head, _| {
 9453                (
 9454                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9455                    SelectionGoal::None,
 9456                )
 9457            });
 9458        })
 9459    }
 9460
 9461    pub fn select_to_end_of_line(
 9462        &mut self,
 9463        action: &SelectToEndOfLine,
 9464        window: &mut Window,
 9465        cx: &mut Context<Self>,
 9466    ) {
 9467        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9468            s.move_heads_with(|map, head, _| {
 9469                (
 9470                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9471                    SelectionGoal::None,
 9472                )
 9473            });
 9474        })
 9475    }
 9476
 9477    pub fn delete_to_end_of_line(
 9478        &mut self,
 9479        _: &DeleteToEndOfLine,
 9480        window: &mut Window,
 9481        cx: &mut Context<Self>,
 9482    ) {
 9483        self.transact(window, cx, |this, window, cx| {
 9484            this.select_to_end_of_line(
 9485                &SelectToEndOfLine {
 9486                    stop_at_soft_wraps: false,
 9487                },
 9488                window,
 9489                cx,
 9490            );
 9491            this.delete(&Delete, window, cx);
 9492        });
 9493    }
 9494
 9495    pub fn cut_to_end_of_line(
 9496        &mut self,
 9497        _: &CutToEndOfLine,
 9498        window: &mut Window,
 9499        cx: &mut Context<Self>,
 9500    ) {
 9501        self.transact(window, cx, |this, window, cx| {
 9502            this.select_to_end_of_line(
 9503                &SelectToEndOfLine {
 9504                    stop_at_soft_wraps: false,
 9505                },
 9506                window,
 9507                cx,
 9508            );
 9509            this.cut(&Cut, window, cx);
 9510        });
 9511    }
 9512
 9513    pub fn move_to_start_of_paragraph(
 9514        &mut self,
 9515        _: &MoveToStartOfParagraph,
 9516        window: &mut Window,
 9517        cx: &mut Context<Self>,
 9518    ) {
 9519        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9520            cx.propagate();
 9521            return;
 9522        }
 9523
 9524        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9525            s.move_with(|map, selection| {
 9526                selection.collapse_to(
 9527                    movement::start_of_paragraph(map, selection.head(), 1),
 9528                    SelectionGoal::None,
 9529                )
 9530            });
 9531        })
 9532    }
 9533
 9534    pub fn move_to_end_of_paragraph(
 9535        &mut self,
 9536        _: &MoveToEndOfParagraph,
 9537        window: &mut Window,
 9538        cx: &mut Context<Self>,
 9539    ) {
 9540        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9541            cx.propagate();
 9542            return;
 9543        }
 9544
 9545        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9546            s.move_with(|map, selection| {
 9547                selection.collapse_to(
 9548                    movement::end_of_paragraph(map, selection.head(), 1),
 9549                    SelectionGoal::None,
 9550                )
 9551            });
 9552        })
 9553    }
 9554
 9555    pub fn select_to_start_of_paragraph(
 9556        &mut self,
 9557        _: &SelectToStartOfParagraph,
 9558        window: &mut Window,
 9559        cx: &mut Context<Self>,
 9560    ) {
 9561        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9562            cx.propagate();
 9563            return;
 9564        }
 9565
 9566        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9567            s.move_heads_with(|map, head, _| {
 9568                (
 9569                    movement::start_of_paragraph(map, head, 1),
 9570                    SelectionGoal::None,
 9571                )
 9572            });
 9573        })
 9574    }
 9575
 9576    pub fn select_to_end_of_paragraph(
 9577        &mut self,
 9578        _: &SelectToEndOfParagraph,
 9579        window: &mut Window,
 9580        cx: &mut Context<Self>,
 9581    ) {
 9582        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9583            cx.propagate();
 9584            return;
 9585        }
 9586
 9587        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9588            s.move_heads_with(|map, head, _| {
 9589                (
 9590                    movement::end_of_paragraph(map, head, 1),
 9591                    SelectionGoal::None,
 9592                )
 9593            });
 9594        })
 9595    }
 9596
 9597    pub fn move_to_start_of_excerpt(
 9598        &mut self,
 9599        _: &MoveToStartOfExcerpt,
 9600        window: &mut Window,
 9601        cx: &mut Context<Self>,
 9602    ) {
 9603        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9604            cx.propagate();
 9605            return;
 9606        }
 9607
 9608        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9609            s.move_with(|map, selection| {
 9610                selection.collapse_to(
 9611                    movement::start_of_excerpt(
 9612                        map,
 9613                        selection.head(),
 9614                        workspace::searchable::Direction::Prev,
 9615                    ),
 9616                    SelectionGoal::None,
 9617                )
 9618            });
 9619        })
 9620    }
 9621
 9622    pub fn move_to_end_of_excerpt(
 9623        &mut self,
 9624        _: &MoveToEndOfExcerpt,
 9625        window: &mut Window,
 9626        cx: &mut Context<Self>,
 9627    ) {
 9628        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9629            cx.propagate();
 9630            return;
 9631        }
 9632
 9633        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9634            s.move_with(|map, selection| {
 9635                selection.collapse_to(
 9636                    movement::end_of_excerpt(
 9637                        map,
 9638                        selection.head(),
 9639                        workspace::searchable::Direction::Next,
 9640                    ),
 9641                    SelectionGoal::None,
 9642                )
 9643            });
 9644        })
 9645    }
 9646
 9647    pub fn select_to_start_of_excerpt(
 9648        &mut self,
 9649        _: &SelectToStartOfExcerpt,
 9650        window: &mut Window,
 9651        cx: &mut Context<Self>,
 9652    ) {
 9653        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9654            cx.propagate();
 9655            return;
 9656        }
 9657
 9658        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9659            s.move_heads_with(|map, head, _| {
 9660                (
 9661                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
 9662                    SelectionGoal::None,
 9663                )
 9664            });
 9665        })
 9666    }
 9667
 9668    pub fn select_to_end_of_excerpt(
 9669        &mut self,
 9670        _: &SelectToEndOfExcerpt,
 9671        window: &mut Window,
 9672        cx: &mut Context<Self>,
 9673    ) {
 9674        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9675            cx.propagate();
 9676            return;
 9677        }
 9678
 9679        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9680            s.move_heads_with(|map, head, _| {
 9681                (
 9682                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
 9683                    SelectionGoal::None,
 9684                )
 9685            });
 9686        })
 9687    }
 9688
 9689    pub fn move_to_beginning(
 9690        &mut self,
 9691        _: &MoveToBeginning,
 9692        window: &mut Window,
 9693        cx: &mut Context<Self>,
 9694    ) {
 9695        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9696            cx.propagate();
 9697            return;
 9698        }
 9699
 9700        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9701            s.select_ranges(vec![0..0]);
 9702        });
 9703    }
 9704
 9705    pub fn select_to_beginning(
 9706        &mut self,
 9707        _: &SelectToBeginning,
 9708        window: &mut Window,
 9709        cx: &mut Context<Self>,
 9710    ) {
 9711        let mut selection = self.selections.last::<Point>(cx);
 9712        selection.set_head(Point::zero(), SelectionGoal::None);
 9713
 9714        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9715            s.select(vec![selection]);
 9716        });
 9717    }
 9718
 9719    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9720        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9721            cx.propagate();
 9722            return;
 9723        }
 9724
 9725        let cursor = self.buffer.read(cx).read(cx).len();
 9726        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9727            s.select_ranges(vec![cursor..cursor])
 9728        });
 9729    }
 9730
 9731    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9732        self.nav_history = nav_history;
 9733    }
 9734
 9735    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9736        self.nav_history.as_ref()
 9737    }
 9738
 9739    fn push_to_nav_history(
 9740        &mut self,
 9741        cursor_anchor: Anchor,
 9742        new_position: Option<Point>,
 9743        cx: &mut Context<Self>,
 9744    ) {
 9745        if let Some(nav_history) = self.nav_history.as_mut() {
 9746            let buffer = self.buffer.read(cx).read(cx);
 9747            let cursor_position = cursor_anchor.to_point(&buffer);
 9748            let scroll_state = self.scroll_manager.anchor();
 9749            let scroll_top_row = scroll_state.top_row(&buffer);
 9750            drop(buffer);
 9751
 9752            if let Some(new_position) = new_position {
 9753                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9754                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9755                    return;
 9756                }
 9757            }
 9758
 9759            nav_history.push(
 9760                Some(NavigationData {
 9761                    cursor_anchor,
 9762                    cursor_position,
 9763                    scroll_anchor: scroll_state,
 9764                    scroll_top_row,
 9765                }),
 9766                cx,
 9767            );
 9768        }
 9769    }
 9770
 9771    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9772        let buffer = self.buffer.read(cx).snapshot(cx);
 9773        let mut selection = self.selections.first::<usize>(cx);
 9774        selection.set_head(buffer.len(), SelectionGoal::None);
 9775        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9776            s.select(vec![selection]);
 9777        });
 9778    }
 9779
 9780    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9781        let end = self.buffer.read(cx).read(cx).len();
 9782        self.change_selections(None, window, cx, |s| {
 9783            s.select_ranges(vec![0..end]);
 9784        });
 9785    }
 9786
 9787    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9788        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9789        let mut selections = self.selections.all::<Point>(cx);
 9790        let max_point = display_map.buffer_snapshot.max_point();
 9791        for selection in &mut selections {
 9792            let rows = selection.spanned_rows(true, &display_map);
 9793            selection.start = Point::new(rows.start.0, 0);
 9794            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9795            selection.reversed = false;
 9796        }
 9797        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9798            s.select(selections);
 9799        });
 9800    }
 9801
 9802    pub fn split_selection_into_lines(
 9803        &mut self,
 9804        _: &SplitSelectionIntoLines,
 9805        window: &mut Window,
 9806        cx: &mut Context<Self>,
 9807    ) {
 9808        let selections = self
 9809            .selections
 9810            .all::<Point>(cx)
 9811            .into_iter()
 9812            .map(|selection| selection.start..selection.end)
 9813            .collect::<Vec<_>>();
 9814        self.unfold_ranges(&selections, true, true, cx);
 9815
 9816        let mut new_selection_ranges = Vec::new();
 9817        {
 9818            let buffer = self.buffer.read(cx).read(cx);
 9819            for selection in selections {
 9820                for row in selection.start.row..selection.end.row {
 9821                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9822                    new_selection_ranges.push(cursor..cursor);
 9823                }
 9824
 9825                let is_multiline_selection = selection.start.row != selection.end.row;
 9826                // Don't insert last one if it's a multi-line selection ending at the start of a line,
 9827                // so this action feels more ergonomic when paired with other selection operations
 9828                let should_skip_last = is_multiline_selection && selection.end.column == 0;
 9829                if !should_skip_last {
 9830                    new_selection_ranges.push(selection.end..selection.end);
 9831                }
 9832            }
 9833        }
 9834        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9835            s.select_ranges(new_selection_ranges);
 9836        });
 9837    }
 9838
 9839    pub fn add_selection_above(
 9840        &mut self,
 9841        _: &AddSelectionAbove,
 9842        window: &mut Window,
 9843        cx: &mut Context<Self>,
 9844    ) {
 9845        self.add_selection(true, window, cx);
 9846    }
 9847
 9848    pub fn add_selection_below(
 9849        &mut self,
 9850        _: &AddSelectionBelow,
 9851        window: &mut Window,
 9852        cx: &mut Context<Self>,
 9853    ) {
 9854        self.add_selection(false, window, cx);
 9855    }
 9856
 9857    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9858        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9859        let mut selections = self.selections.all::<Point>(cx);
 9860        let text_layout_details = self.text_layout_details(window);
 9861        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9862            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9863            let range = oldest_selection.display_range(&display_map).sorted();
 9864
 9865            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9866            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9867            let positions = start_x.min(end_x)..start_x.max(end_x);
 9868
 9869            selections.clear();
 9870            let mut stack = Vec::new();
 9871            for row in range.start.row().0..=range.end.row().0 {
 9872                if let Some(selection) = self.selections.build_columnar_selection(
 9873                    &display_map,
 9874                    DisplayRow(row),
 9875                    &positions,
 9876                    oldest_selection.reversed,
 9877                    &text_layout_details,
 9878                ) {
 9879                    stack.push(selection.id);
 9880                    selections.push(selection);
 9881                }
 9882            }
 9883
 9884            if above {
 9885                stack.reverse();
 9886            }
 9887
 9888            AddSelectionsState { above, stack }
 9889        });
 9890
 9891        let last_added_selection = *state.stack.last().unwrap();
 9892        let mut new_selections = Vec::new();
 9893        if above == state.above {
 9894            let end_row = if above {
 9895                DisplayRow(0)
 9896            } else {
 9897                display_map.max_point().row()
 9898            };
 9899
 9900            'outer: for selection in selections {
 9901                if selection.id == last_added_selection {
 9902                    let range = selection.display_range(&display_map).sorted();
 9903                    debug_assert_eq!(range.start.row(), range.end.row());
 9904                    let mut row = range.start.row();
 9905                    let positions =
 9906                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9907                            px(start)..px(end)
 9908                        } else {
 9909                            let start_x =
 9910                                display_map.x_for_display_point(range.start, &text_layout_details);
 9911                            let end_x =
 9912                                display_map.x_for_display_point(range.end, &text_layout_details);
 9913                            start_x.min(end_x)..start_x.max(end_x)
 9914                        };
 9915
 9916                    while row != end_row {
 9917                        if above {
 9918                            row.0 -= 1;
 9919                        } else {
 9920                            row.0 += 1;
 9921                        }
 9922
 9923                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9924                            &display_map,
 9925                            row,
 9926                            &positions,
 9927                            selection.reversed,
 9928                            &text_layout_details,
 9929                        ) {
 9930                            state.stack.push(new_selection.id);
 9931                            if above {
 9932                                new_selections.push(new_selection);
 9933                                new_selections.push(selection);
 9934                            } else {
 9935                                new_selections.push(selection);
 9936                                new_selections.push(new_selection);
 9937                            }
 9938
 9939                            continue 'outer;
 9940                        }
 9941                    }
 9942                }
 9943
 9944                new_selections.push(selection);
 9945            }
 9946        } else {
 9947            new_selections = selections;
 9948            new_selections.retain(|s| s.id != last_added_selection);
 9949            state.stack.pop();
 9950        }
 9951
 9952        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9953            s.select(new_selections);
 9954        });
 9955        if state.stack.len() > 1 {
 9956            self.add_selections_state = Some(state);
 9957        }
 9958    }
 9959
 9960    pub fn select_next_match_internal(
 9961        &mut self,
 9962        display_map: &DisplaySnapshot,
 9963        replace_newest: bool,
 9964        autoscroll: Option<Autoscroll>,
 9965        window: &mut Window,
 9966        cx: &mut Context<Self>,
 9967    ) -> Result<()> {
 9968        fn select_next_match_ranges(
 9969            this: &mut Editor,
 9970            range: Range<usize>,
 9971            replace_newest: bool,
 9972            auto_scroll: Option<Autoscroll>,
 9973            window: &mut Window,
 9974            cx: &mut Context<Editor>,
 9975        ) {
 9976            this.unfold_ranges(&[range.clone()], false, true, cx);
 9977            this.change_selections(auto_scroll, window, cx, |s| {
 9978                if replace_newest {
 9979                    s.delete(s.newest_anchor().id);
 9980                }
 9981                s.insert_range(range.clone());
 9982            });
 9983        }
 9984
 9985        let buffer = &display_map.buffer_snapshot;
 9986        let mut selections = self.selections.all::<usize>(cx);
 9987        if let Some(mut select_next_state) = self.select_next_state.take() {
 9988            let query = &select_next_state.query;
 9989            if !select_next_state.done {
 9990                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9991                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9992                let mut next_selected_range = None;
 9993
 9994                let bytes_after_last_selection =
 9995                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9996                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9997                let query_matches = query
 9998                    .stream_find_iter(bytes_after_last_selection)
 9999                    .map(|result| (last_selection.end, result))
10000                    .chain(
10001                        query
10002                            .stream_find_iter(bytes_before_first_selection)
10003                            .map(|result| (0, result)),
10004                    );
10005
10006                for (start_offset, query_match) in query_matches {
10007                    let query_match = query_match.unwrap(); // can only fail due to I/O
10008                    let offset_range =
10009                        start_offset + query_match.start()..start_offset + query_match.end();
10010                    let display_range = offset_range.start.to_display_point(display_map)
10011                        ..offset_range.end.to_display_point(display_map);
10012
10013                    if !select_next_state.wordwise
10014                        || (!movement::is_inside_word(display_map, display_range.start)
10015                            && !movement::is_inside_word(display_map, display_range.end))
10016                    {
10017                        // TODO: This is n^2, because we might check all the selections
10018                        if !selections
10019                            .iter()
10020                            .any(|selection| selection.range().overlaps(&offset_range))
10021                        {
10022                            next_selected_range = Some(offset_range);
10023                            break;
10024                        }
10025                    }
10026                }
10027
10028                if let Some(next_selected_range) = next_selected_range {
10029                    select_next_match_ranges(
10030                        self,
10031                        next_selected_range,
10032                        replace_newest,
10033                        autoscroll,
10034                        window,
10035                        cx,
10036                    );
10037                } else {
10038                    select_next_state.done = true;
10039                }
10040            }
10041
10042            self.select_next_state = Some(select_next_state);
10043        } else {
10044            let mut only_carets = true;
10045            let mut same_text_selected = true;
10046            let mut selected_text = None;
10047
10048            let mut selections_iter = selections.iter().peekable();
10049            while let Some(selection) = selections_iter.next() {
10050                if selection.start != selection.end {
10051                    only_carets = false;
10052                }
10053
10054                if same_text_selected {
10055                    if selected_text.is_none() {
10056                        selected_text =
10057                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10058                    }
10059
10060                    if let Some(next_selection) = selections_iter.peek() {
10061                        if next_selection.range().len() == selection.range().len() {
10062                            let next_selected_text = buffer
10063                                .text_for_range(next_selection.range())
10064                                .collect::<String>();
10065                            if Some(next_selected_text) != selected_text {
10066                                same_text_selected = false;
10067                                selected_text = None;
10068                            }
10069                        } else {
10070                            same_text_selected = false;
10071                            selected_text = None;
10072                        }
10073                    }
10074                }
10075            }
10076
10077            if only_carets {
10078                for selection in &mut selections {
10079                    let word_range = movement::surrounding_word(
10080                        display_map,
10081                        selection.start.to_display_point(display_map),
10082                    );
10083                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
10084                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
10085                    selection.goal = SelectionGoal::None;
10086                    selection.reversed = false;
10087                    select_next_match_ranges(
10088                        self,
10089                        selection.start..selection.end,
10090                        replace_newest,
10091                        autoscroll,
10092                        window,
10093                        cx,
10094                    );
10095                }
10096
10097                if selections.len() == 1 {
10098                    let selection = selections
10099                        .last()
10100                        .expect("ensured that there's only one selection");
10101                    let query = buffer
10102                        .text_for_range(selection.start..selection.end)
10103                        .collect::<String>();
10104                    let is_empty = query.is_empty();
10105                    let select_state = SelectNextState {
10106                        query: AhoCorasick::new(&[query])?,
10107                        wordwise: true,
10108                        done: is_empty,
10109                    };
10110                    self.select_next_state = Some(select_state);
10111                } else {
10112                    self.select_next_state = None;
10113                }
10114            } else if let Some(selected_text) = selected_text {
10115                self.select_next_state = Some(SelectNextState {
10116                    query: AhoCorasick::new(&[selected_text])?,
10117                    wordwise: false,
10118                    done: false,
10119                });
10120                self.select_next_match_internal(
10121                    display_map,
10122                    replace_newest,
10123                    autoscroll,
10124                    window,
10125                    cx,
10126                )?;
10127            }
10128        }
10129        Ok(())
10130    }
10131
10132    pub fn select_all_matches(
10133        &mut self,
10134        _action: &SelectAllMatches,
10135        window: &mut Window,
10136        cx: &mut Context<Self>,
10137    ) -> Result<()> {
10138        self.push_to_selection_history();
10139        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10140
10141        self.select_next_match_internal(&display_map, false, None, window, cx)?;
10142        let Some(select_next_state) = self.select_next_state.as_mut() else {
10143            return Ok(());
10144        };
10145        if select_next_state.done {
10146            return Ok(());
10147        }
10148
10149        let mut new_selections = self.selections.all::<usize>(cx);
10150
10151        let buffer = &display_map.buffer_snapshot;
10152        let query_matches = select_next_state
10153            .query
10154            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10155
10156        for query_match in query_matches {
10157            let query_match = query_match.unwrap(); // can only fail due to I/O
10158            let offset_range = query_match.start()..query_match.end();
10159            let display_range = offset_range.start.to_display_point(&display_map)
10160                ..offset_range.end.to_display_point(&display_map);
10161
10162            if !select_next_state.wordwise
10163                || (!movement::is_inside_word(&display_map, display_range.start)
10164                    && !movement::is_inside_word(&display_map, display_range.end))
10165            {
10166                self.selections.change_with(cx, |selections| {
10167                    new_selections.push(Selection {
10168                        id: selections.new_selection_id(),
10169                        start: offset_range.start,
10170                        end: offset_range.end,
10171                        reversed: false,
10172                        goal: SelectionGoal::None,
10173                    });
10174                });
10175            }
10176        }
10177
10178        new_selections.sort_by_key(|selection| selection.start);
10179        let mut ix = 0;
10180        while ix + 1 < new_selections.len() {
10181            let current_selection = &new_selections[ix];
10182            let next_selection = &new_selections[ix + 1];
10183            if current_selection.range().overlaps(&next_selection.range()) {
10184                if current_selection.id < next_selection.id {
10185                    new_selections.remove(ix + 1);
10186                } else {
10187                    new_selections.remove(ix);
10188                }
10189            } else {
10190                ix += 1;
10191            }
10192        }
10193
10194        let reversed = self.selections.oldest::<usize>(cx).reversed;
10195
10196        for selection in new_selections.iter_mut() {
10197            selection.reversed = reversed;
10198        }
10199
10200        select_next_state.done = true;
10201        self.unfold_ranges(
10202            &new_selections
10203                .iter()
10204                .map(|selection| selection.range())
10205                .collect::<Vec<_>>(),
10206            false,
10207            false,
10208            cx,
10209        );
10210        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10211            selections.select(new_selections)
10212        });
10213
10214        Ok(())
10215    }
10216
10217    pub fn select_next(
10218        &mut self,
10219        action: &SelectNext,
10220        window: &mut Window,
10221        cx: &mut Context<Self>,
10222    ) -> Result<()> {
10223        self.push_to_selection_history();
10224        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10225        self.select_next_match_internal(
10226            &display_map,
10227            action.replace_newest,
10228            Some(Autoscroll::newest()),
10229            window,
10230            cx,
10231        )?;
10232        Ok(())
10233    }
10234
10235    pub fn select_previous(
10236        &mut self,
10237        action: &SelectPrevious,
10238        window: &mut Window,
10239        cx: &mut Context<Self>,
10240    ) -> Result<()> {
10241        self.push_to_selection_history();
10242        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10243        let buffer = &display_map.buffer_snapshot;
10244        let mut selections = self.selections.all::<usize>(cx);
10245        if let Some(mut select_prev_state) = self.select_prev_state.take() {
10246            let query = &select_prev_state.query;
10247            if !select_prev_state.done {
10248                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10249                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10250                let mut next_selected_range = None;
10251                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10252                let bytes_before_last_selection =
10253                    buffer.reversed_bytes_in_range(0..last_selection.start);
10254                let bytes_after_first_selection =
10255                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10256                let query_matches = query
10257                    .stream_find_iter(bytes_before_last_selection)
10258                    .map(|result| (last_selection.start, result))
10259                    .chain(
10260                        query
10261                            .stream_find_iter(bytes_after_first_selection)
10262                            .map(|result| (buffer.len(), result)),
10263                    );
10264                for (end_offset, query_match) in query_matches {
10265                    let query_match = query_match.unwrap(); // can only fail due to I/O
10266                    let offset_range =
10267                        end_offset - query_match.end()..end_offset - query_match.start();
10268                    let display_range = offset_range.start.to_display_point(&display_map)
10269                        ..offset_range.end.to_display_point(&display_map);
10270
10271                    if !select_prev_state.wordwise
10272                        || (!movement::is_inside_word(&display_map, display_range.start)
10273                            && !movement::is_inside_word(&display_map, display_range.end))
10274                    {
10275                        next_selected_range = Some(offset_range);
10276                        break;
10277                    }
10278                }
10279
10280                if let Some(next_selected_range) = next_selected_range {
10281                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10282                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10283                        if action.replace_newest {
10284                            s.delete(s.newest_anchor().id);
10285                        }
10286                        s.insert_range(next_selected_range);
10287                    });
10288                } else {
10289                    select_prev_state.done = true;
10290                }
10291            }
10292
10293            self.select_prev_state = Some(select_prev_state);
10294        } else {
10295            let mut only_carets = true;
10296            let mut same_text_selected = true;
10297            let mut selected_text = None;
10298
10299            let mut selections_iter = selections.iter().peekable();
10300            while let Some(selection) = selections_iter.next() {
10301                if selection.start != selection.end {
10302                    only_carets = false;
10303                }
10304
10305                if same_text_selected {
10306                    if selected_text.is_none() {
10307                        selected_text =
10308                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10309                    }
10310
10311                    if let Some(next_selection) = selections_iter.peek() {
10312                        if next_selection.range().len() == selection.range().len() {
10313                            let next_selected_text = buffer
10314                                .text_for_range(next_selection.range())
10315                                .collect::<String>();
10316                            if Some(next_selected_text) != selected_text {
10317                                same_text_selected = false;
10318                                selected_text = None;
10319                            }
10320                        } else {
10321                            same_text_selected = false;
10322                            selected_text = None;
10323                        }
10324                    }
10325                }
10326            }
10327
10328            if only_carets {
10329                for selection in &mut selections {
10330                    let word_range = movement::surrounding_word(
10331                        &display_map,
10332                        selection.start.to_display_point(&display_map),
10333                    );
10334                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10335                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10336                    selection.goal = SelectionGoal::None;
10337                    selection.reversed = false;
10338                }
10339                if selections.len() == 1 {
10340                    let selection = selections
10341                        .last()
10342                        .expect("ensured that there's only one selection");
10343                    let query = buffer
10344                        .text_for_range(selection.start..selection.end)
10345                        .collect::<String>();
10346                    let is_empty = query.is_empty();
10347                    let select_state = SelectNextState {
10348                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10349                        wordwise: true,
10350                        done: is_empty,
10351                    };
10352                    self.select_prev_state = Some(select_state);
10353                } else {
10354                    self.select_prev_state = None;
10355                }
10356
10357                self.unfold_ranges(
10358                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10359                    false,
10360                    true,
10361                    cx,
10362                );
10363                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10364                    s.select(selections);
10365                });
10366            } else if let Some(selected_text) = selected_text {
10367                self.select_prev_state = Some(SelectNextState {
10368                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10369                    wordwise: false,
10370                    done: false,
10371                });
10372                self.select_previous(action, window, cx)?;
10373            }
10374        }
10375        Ok(())
10376    }
10377
10378    pub fn toggle_comments(
10379        &mut self,
10380        action: &ToggleComments,
10381        window: &mut Window,
10382        cx: &mut Context<Self>,
10383    ) {
10384        if self.read_only(cx) {
10385            return;
10386        }
10387        let text_layout_details = &self.text_layout_details(window);
10388        self.transact(window, cx, |this, window, cx| {
10389            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10390            let mut edits = Vec::new();
10391            let mut selection_edit_ranges = Vec::new();
10392            let mut last_toggled_row = None;
10393            let snapshot = this.buffer.read(cx).read(cx);
10394            let empty_str: Arc<str> = Arc::default();
10395            let mut suffixes_inserted = Vec::new();
10396            let ignore_indent = action.ignore_indent;
10397
10398            fn comment_prefix_range(
10399                snapshot: &MultiBufferSnapshot,
10400                row: MultiBufferRow,
10401                comment_prefix: &str,
10402                comment_prefix_whitespace: &str,
10403                ignore_indent: bool,
10404            ) -> Range<Point> {
10405                let indent_size = if ignore_indent {
10406                    0
10407                } else {
10408                    snapshot.indent_size_for_line(row).len
10409                };
10410
10411                let start = Point::new(row.0, indent_size);
10412
10413                let mut line_bytes = snapshot
10414                    .bytes_in_range(start..snapshot.max_point())
10415                    .flatten()
10416                    .copied();
10417
10418                // If this line currently begins with the line comment prefix, then record
10419                // the range containing the prefix.
10420                if line_bytes
10421                    .by_ref()
10422                    .take(comment_prefix.len())
10423                    .eq(comment_prefix.bytes())
10424                {
10425                    // Include any whitespace that matches the comment prefix.
10426                    let matching_whitespace_len = line_bytes
10427                        .zip(comment_prefix_whitespace.bytes())
10428                        .take_while(|(a, b)| a == b)
10429                        .count() as u32;
10430                    let end = Point::new(
10431                        start.row,
10432                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10433                    );
10434                    start..end
10435                } else {
10436                    start..start
10437                }
10438            }
10439
10440            fn comment_suffix_range(
10441                snapshot: &MultiBufferSnapshot,
10442                row: MultiBufferRow,
10443                comment_suffix: &str,
10444                comment_suffix_has_leading_space: bool,
10445            ) -> Range<Point> {
10446                let end = Point::new(row.0, snapshot.line_len(row));
10447                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10448
10449                let mut line_end_bytes = snapshot
10450                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10451                    .flatten()
10452                    .copied();
10453
10454                let leading_space_len = if suffix_start_column > 0
10455                    && line_end_bytes.next() == Some(b' ')
10456                    && comment_suffix_has_leading_space
10457                {
10458                    1
10459                } else {
10460                    0
10461                };
10462
10463                // If this line currently begins with the line comment prefix, then record
10464                // the range containing the prefix.
10465                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10466                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
10467                    start..end
10468                } else {
10469                    end..end
10470                }
10471            }
10472
10473            // TODO: Handle selections that cross excerpts
10474            for selection in &mut selections {
10475                let start_column = snapshot
10476                    .indent_size_for_line(MultiBufferRow(selection.start.row))
10477                    .len;
10478                let language = if let Some(language) =
10479                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10480                {
10481                    language
10482                } else {
10483                    continue;
10484                };
10485
10486                selection_edit_ranges.clear();
10487
10488                // If multiple selections contain a given row, avoid processing that
10489                // row more than once.
10490                let mut start_row = MultiBufferRow(selection.start.row);
10491                if last_toggled_row == Some(start_row) {
10492                    start_row = start_row.next_row();
10493                }
10494                let end_row =
10495                    if selection.end.row > selection.start.row && selection.end.column == 0 {
10496                        MultiBufferRow(selection.end.row - 1)
10497                    } else {
10498                        MultiBufferRow(selection.end.row)
10499                    };
10500                last_toggled_row = Some(end_row);
10501
10502                if start_row > end_row {
10503                    continue;
10504                }
10505
10506                // If the language has line comments, toggle those.
10507                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10508
10509                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10510                if ignore_indent {
10511                    full_comment_prefixes = full_comment_prefixes
10512                        .into_iter()
10513                        .map(|s| Arc::from(s.trim_end()))
10514                        .collect();
10515                }
10516
10517                if !full_comment_prefixes.is_empty() {
10518                    let first_prefix = full_comment_prefixes
10519                        .first()
10520                        .expect("prefixes is non-empty");
10521                    let prefix_trimmed_lengths = full_comment_prefixes
10522                        .iter()
10523                        .map(|p| p.trim_end_matches(' ').len())
10524                        .collect::<SmallVec<[usize; 4]>>();
10525
10526                    let mut all_selection_lines_are_comments = true;
10527
10528                    for row in start_row.0..=end_row.0 {
10529                        let row = MultiBufferRow(row);
10530                        if start_row < end_row && snapshot.is_line_blank(row) {
10531                            continue;
10532                        }
10533
10534                        let prefix_range = full_comment_prefixes
10535                            .iter()
10536                            .zip(prefix_trimmed_lengths.iter().copied())
10537                            .map(|(prefix, trimmed_prefix_len)| {
10538                                comment_prefix_range(
10539                                    snapshot.deref(),
10540                                    row,
10541                                    &prefix[..trimmed_prefix_len],
10542                                    &prefix[trimmed_prefix_len..],
10543                                    ignore_indent,
10544                                )
10545                            })
10546                            .max_by_key(|range| range.end.column - range.start.column)
10547                            .expect("prefixes is non-empty");
10548
10549                        if prefix_range.is_empty() {
10550                            all_selection_lines_are_comments = false;
10551                        }
10552
10553                        selection_edit_ranges.push(prefix_range);
10554                    }
10555
10556                    if all_selection_lines_are_comments {
10557                        edits.extend(
10558                            selection_edit_ranges
10559                                .iter()
10560                                .cloned()
10561                                .map(|range| (range, empty_str.clone())),
10562                        );
10563                    } else {
10564                        let min_column = selection_edit_ranges
10565                            .iter()
10566                            .map(|range| range.start.column)
10567                            .min()
10568                            .unwrap_or(0);
10569                        edits.extend(selection_edit_ranges.iter().map(|range| {
10570                            let position = Point::new(range.start.row, min_column);
10571                            (position..position, first_prefix.clone())
10572                        }));
10573                    }
10574                } else if let Some((full_comment_prefix, comment_suffix)) =
10575                    language.block_comment_delimiters()
10576                {
10577                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10578                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10579                    let prefix_range = comment_prefix_range(
10580                        snapshot.deref(),
10581                        start_row,
10582                        comment_prefix,
10583                        comment_prefix_whitespace,
10584                        ignore_indent,
10585                    );
10586                    let suffix_range = comment_suffix_range(
10587                        snapshot.deref(),
10588                        end_row,
10589                        comment_suffix.trim_start_matches(' '),
10590                        comment_suffix.starts_with(' '),
10591                    );
10592
10593                    if prefix_range.is_empty() || suffix_range.is_empty() {
10594                        edits.push((
10595                            prefix_range.start..prefix_range.start,
10596                            full_comment_prefix.clone(),
10597                        ));
10598                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10599                        suffixes_inserted.push((end_row, comment_suffix.len()));
10600                    } else {
10601                        edits.push((prefix_range, empty_str.clone()));
10602                        edits.push((suffix_range, empty_str.clone()));
10603                    }
10604                } else {
10605                    continue;
10606                }
10607            }
10608
10609            drop(snapshot);
10610            this.buffer.update(cx, |buffer, cx| {
10611                buffer.edit(edits, None, cx);
10612            });
10613
10614            // Adjust selections so that they end before any comment suffixes that
10615            // were inserted.
10616            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10617            let mut selections = this.selections.all::<Point>(cx);
10618            let snapshot = this.buffer.read(cx).read(cx);
10619            for selection in &mut selections {
10620                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10621                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10622                        Ordering::Less => {
10623                            suffixes_inserted.next();
10624                            continue;
10625                        }
10626                        Ordering::Greater => break,
10627                        Ordering::Equal => {
10628                            if selection.end.column == snapshot.line_len(row) {
10629                                if selection.is_empty() {
10630                                    selection.start.column -= suffix_len as u32;
10631                                }
10632                                selection.end.column -= suffix_len as u32;
10633                            }
10634                            break;
10635                        }
10636                    }
10637                }
10638            }
10639
10640            drop(snapshot);
10641            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10642                s.select(selections)
10643            });
10644
10645            let selections = this.selections.all::<Point>(cx);
10646            let selections_on_single_row = selections.windows(2).all(|selections| {
10647                selections[0].start.row == selections[1].start.row
10648                    && selections[0].end.row == selections[1].end.row
10649                    && selections[0].start.row == selections[0].end.row
10650            });
10651            let selections_selecting = selections
10652                .iter()
10653                .any(|selection| selection.start != selection.end);
10654            let advance_downwards = action.advance_downwards
10655                && selections_on_single_row
10656                && !selections_selecting
10657                && !matches!(this.mode, EditorMode::SingleLine { .. });
10658
10659            if advance_downwards {
10660                let snapshot = this.buffer.read(cx).snapshot(cx);
10661
10662                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10663                    s.move_cursors_with(|display_snapshot, display_point, _| {
10664                        let mut point = display_point.to_point(display_snapshot);
10665                        point.row += 1;
10666                        point = snapshot.clip_point(point, Bias::Left);
10667                        let display_point = point.to_display_point(display_snapshot);
10668                        let goal = SelectionGoal::HorizontalPosition(
10669                            display_snapshot
10670                                .x_for_display_point(display_point, text_layout_details)
10671                                .into(),
10672                        );
10673                        (display_point, goal)
10674                    })
10675                });
10676            }
10677        });
10678    }
10679
10680    pub fn select_enclosing_symbol(
10681        &mut self,
10682        _: &SelectEnclosingSymbol,
10683        window: &mut Window,
10684        cx: &mut Context<Self>,
10685    ) {
10686        let buffer = self.buffer.read(cx).snapshot(cx);
10687        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10688
10689        fn update_selection(
10690            selection: &Selection<usize>,
10691            buffer_snap: &MultiBufferSnapshot,
10692        ) -> Option<Selection<usize>> {
10693            let cursor = selection.head();
10694            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10695            for symbol in symbols.iter().rev() {
10696                let start = symbol.range.start.to_offset(buffer_snap);
10697                let end = symbol.range.end.to_offset(buffer_snap);
10698                let new_range = start..end;
10699                if start < selection.start || end > selection.end {
10700                    return Some(Selection {
10701                        id: selection.id,
10702                        start: new_range.start,
10703                        end: new_range.end,
10704                        goal: SelectionGoal::None,
10705                        reversed: selection.reversed,
10706                    });
10707                }
10708            }
10709            None
10710        }
10711
10712        let mut selected_larger_symbol = false;
10713        let new_selections = old_selections
10714            .iter()
10715            .map(|selection| match update_selection(selection, &buffer) {
10716                Some(new_selection) => {
10717                    if new_selection.range() != selection.range() {
10718                        selected_larger_symbol = true;
10719                    }
10720                    new_selection
10721                }
10722                None => selection.clone(),
10723            })
10724            .collect::<Vec<_>>();
10725
10726        if selected_larger_symbol {
10727            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10728                s.select(new_selections);
10729            });
10730        }
10731    }
10732
10733    pub fn select_larger_syntax_node(
10734        &mut self,
10735        _: &SelectLargerSyntaxNode,
10736        window: &mut Window,
10737        cx: &mut Context<Self>,
10738    ) {
10739        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10740        let buffer = self.buffer.read(cx).snapshot(cx);
10741        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10742
10743        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10744        let mut selected_larger_node = false;
10745        let new_selections = old_selections
10746            .iter()
10747            .map(|selection| {
10748                let old_range = selection.start..selection.end;
10749                let mut new_range = old_range.clone();
10750                let mut new_node = None;
10751                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10752                {
10753                    new_node = Some(node);
10754                    new_range = match containing_range {
10755                        MultiOrSingleBufferOffsetRange::Single(_) => break,
10756                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
10757                    };
10758                    if !display_map.intersects_fold(new_range.start)
10759                        && !display_map.intersects_fold(new_range.end)
10760                    {
10761                        break;
10762                    }
10763                }
10764
10765                if let Some(node) = new_node {
10766                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10767                    // nodes. Parent and grandparent are also logged because this operation will not
10768                    // visit nodes that have the same range as their parent.
10769                    log::info!("Node: {node:?}");
10770                    let parent = node.parent();
10771                    log::info!("Parent: {parent:?}");
10772                    let grandparent = parent.and_then(|x| x.parent());
10773                    log::info!("Grandparent: {grandparent:?}");
10774                }
10775
10776                selected_larger_node |= new_range != old_range;
10777                Selection {
10778                    id: selection.id,
10779                    start: new_range.start,
10780                    end: new_range.end,
10781                    goal: SelectionGoal::None,
10782                    reversed: selection.reversed,
10783                }
10784            })
10785            .collect::<Vec<_>>();
10786
10787        if selected_larger_node {
10788            stack.push(old_selections);
10789            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10790                s.select(new_selections);
10791            });
10792        }
10793        self.select_larger_syntax_node_stack = stack;
10794    }
10795
10796    pub fn select_smaller_syntax_node(
10797        &mut self,
10798        _: &SelectSmallerSyntaxNode,
10799        window: &mut Window,
10800        cx: &mut Context<Self>,
10801    ) {
10802        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10803        if let Some(selections) = stack.pop() {
10804            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10805                s.select(selections.to_vec());
10806            });
10807        }
10808        self.select_larger_syntax_node_stack = stack;
10809    }
10810
10811    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10812        if !EditorSettings::get_global(cx).gutter.runnables {
10813            self.clear_tasks();
10814            return Task::ready(());
10815        }
10816        let project = self.project.as_ref().map(Entity::downgrade);
10817        cx.spawn_in(window, |this, mut cx| async move {
10818            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10819            let Some(project) = project.and_then(|p| p.upgrade()) else {
10820                return;
10821            };
10822            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10823                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10824            }) else {
10825                return;
10826            };
10827
10828            let hide_runnables = project
10829                .update(&mut cx, |project, cx| {
10830                    // Do not display any test indicators in non-dev server remote projects.
10831                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10832                })
10833                .unwrap_or(true);
10834            if hide_runnables {
10835                return;
10836            }
10837            let new_rows =
10838                cx.background_spawn({
10839                    let snapshot = display_snapshot.clone();
10840                    async move {
10841                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10842                    }
10843                })
10844                    .await;
10845
10846            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10847            this.update(&mut cx, |this, _| {
10848                this.clear_tasks();
10849                for (key, value) in rows {
10850                    this.insert_tasks(key, value);
10851                }
10852            })
10853            .ok();
10854        })
10855    }
10856    fn fetch_runnable_ranges(
10857        snapshot: &DisplaySnapshot,
10858        range: Range<Anchor>,
10859    ) -> Vec<language::RunnableRange> {
10860        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10861    }
10862
10863    fn runnable_rows(
10864        project: Entity<Project>,
10865        snapshot: DisplaySnapshot,
10866        runnable_ranges: Vec<RunnableRange>,
10867        mut cx: AsyncWindowContext,
10868    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10869        runnable_ranges
10870            .into_iter()
10871            .filter_map(|mut runnable| {
10872                let tasks = cx
10873                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10874                    .ok()?;
10875                if tasks.is_empty() {
10876                    return None;
10877                }
10878
10879                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10880
10881                let row = snapshot
10882                    .buffer_snapshot
10883                    .buffer_line_for_row(MultiBufferRow(point.row))?
10884                    .1
10885                    .start
10886                    .row;
10887
10888                let context_range =
10889                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10890                Some((
10891                    (runnable.buffer_id, row),
10892                    RunnableTasks {
10893                        templates: tasks,
10894                        offset: snapshot
10895                            .buffer_snapshot
10896                            .anchor_before(runnable.run_range.start),
10897                        context_range,
10898                        column: point.column,
10899                        extra_variables: runnable.extra_captures,
10900                    },
10901                ))
10902            })
10903            .collect()
10904    }
10905
10906    fn templates_with_tags(
10907        project: &Entity<Project>,
10908        runnable: &mut Runnable,
10909        cx: &mut App,
10910    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10911        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10912            let (worktree_id, file) = project
10913                .buffer_for_id(runnable.buffer, cx)
10914                .and_then(|buffer| buffer.read(cx).file())
10915                .map(|file| (file.worktree_id(cx), file.clone()))
10916                .unzip();
10917
10918            (
10919                project.task_store().read(cx).task_inventory().cloned(),
10920                worktree_id,
10921                file,
10922            )
10923        });
10924
10925        let tags = mem::take(&mut runnable.tags);
10926        let mut tags: Vec<_> = tags
10927            .into_iter()
10928            .flat_map(|tag| {
10929                let tag = tag.0.clone();
10930                inventory
10931                    .as_ref()
10932                    .into_iter()
10933                    .flat_map(|inventory| {
10934                        inventory.read(cx).list_tasks(
10935                            file.clone(),
10936                            Some(runnable.language.clone()),
10937                            worktree_id,
10938                            cx,
10939                        )
10940                    })
10941                    .filter(move |(_, template)| {
10942                        template.tags.iter().any(|source_tag| source_tag == &tag)
10943                    })
10944            })
10945            .sorted_by_key(|(kind, _)| kind.to_owned())
10946            .collect();
10947        if let Some((leading_tag_source, _)) = tags.first() {
10948            // Strongest source wins; if we have worktree tag binding, prefer that to
10949            // global and language bindings;
10950            // if we have a global binding, prefer that to language binding.
10951            let first_mismatch = tags
10952                .iter()
10953                .position(|(tag_source, _)| tag_source != leading_tag_source);
10954            if let Some(index) = first_mismatch {
10955                tags.truncate(index);
10956            }
10957        }
10958
10959        tags
10960    }
10961
10962    pub fn move_to_enclosing_bracket(
10963        &mut self,
10964        _: &MoveToEnclosingBracket,
10965        window: &mut Window,
10966        cx: &mut Context<Self>,
10967    ) {
10968        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10969            s.move_offsets_with(|snapshot, selection| {
10970                let Some(enclosing_bracket_ranges) =
10971                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10972                else {
10973                    return;
10974                };
10975
10976                let mut best_length = usize::MAX;
10977                let mut best_inside = false;
10978                let mut best_in_bracket_range = false;
10979                let mut best_destination = None;
10980                for (open, close) in enclosing_bracket_ranges {
10981                    let close = close.to_inclusive();
10982                    let length = close.end() - open.start;
10983                    let inside = selection.start >= open.end && selection.end <= *close.start();
10984                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10985                        || close.contains(&selection.head());
10986
10987                    // If best is next to a bracket and current isn't, skip
10988                    if !in_bracket_range && best_in_bracket_range {
10989                        continue;
10990                    }
10991
10992                    // Prefer smaller lengths unless best is inside and current isn't
10993                    if length > best_length && (best_inside || !inside) {
10994                        continue;
10995                    }
10996
10997                    best_length = length;
10998                    best_inside = inside;
10999                    best_in_bracket_range = in_bracket_range;
11000                    best_destination = Some(
11001                        if close.contains(&selection.start) && close.contains(&selection.end) {
11002                            if inside {
11003                                open.end
11004                            } else {
11005                                open.start
11006                            }
11007                        } else if inside {
11008                            *close.start()
11009                        } else {
11010                            *close.end()
11011                        },
11012                    );
11013                }
11014
11015                if let Some(destination) = best_destination {
11016                    selection.collapse_to(destination, SelectionGoal::None);
11017                }
11018            })
11019        });
11020    }
11021
11022    pub fn undo_selection(
11023        &mut self,
11024        _: &UndoSelection,
11025        window: &mut Window,
11026        cx: &mut Context<Self>,
11027    ) {
11028        self.end_selection(window, cx);
11029        self.selection_history.mode = SelectionHistoryMode::Undoing;
11030        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11031            self.change_selections(None, window, cx, |s| {
11032                s.select_anchors(entry.selections.to_vec())
11033            });
11034            self.select_next_state = entry.select_next_state;
11035            self.select_prev_state = entry.select_prev_state;
11036            self.add_selections_state = entry.add_selections_state;
11037            self.request_autoscroll(Autoscroll::newest(), cx);
11038        }
11039        self.selection_history.mode = SelectionHistoryMode::Normal;
11040    }
11041
11042    pub fn redo_selection(
11043        &mut self,
11044        _: &RedoSelection,
11045        window: &mut Window,
11046        cx: &mut Context<Self>,
11047    ) {
11048        self.end_selection(window, cx);
11049        self.selection_history.mode = SelectionHistoryMode::Redoing;
11050        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11051            self.change_selections(None, window, cx, |s| {
11052                s.select_anchors(entry.selections.to_vec())
11053            });
11054            self.select_next_state = entry.select_next_state;
11055            self.select_prev_state = entry.select_prev_state;
11056            self.add_selections_state = entry.add_selections_state;
11057            self.request_autoscroll(Autoscroll::newest(), cx);
11058        }
11059        self.selection_history.mode = SelectionHistoryMode::Normal;
11060    }
11061
11062    pub fn expand_excerpts(
11063        &mut self,
11064        action: &ExpandExcerpts,
11065        _: &mut Window,
11066        cx: &mut Context<Self>,
11067    ) {
11068        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11069    }
11070
11071    pub fn expand_excerpts_down(
11072        &mut self,
11073        action: &ExpandExcerptsDown,
11074        _: &mut Window,
11075        cx: &mut Context<Self>,
11076    ) {
11077        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11078    }
11079
11080    pub fn expand_excerpts_up(
11081        &mut self,
11082        action: &ExpandExcerptsUp,
11083        _: &mut Window,
11084        cx: &mut Context<Self>,
11085    ) {
11086        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11087    }
11088
11089    pub fn expand_excerpts_for_direction(
11090        &mut self,
11091        lines: u32,
11092        direction: ExpandExcerptDirection,
11093
11094        cx: &mut Context<Self>,
11095    ) {
11096        let selections = self.selections.disjoint_anchors();
11097
11098        let lines = if lines == 0 {
11099            EditorSettings::get_global(cx).expand_excerpt_lines
11100        } else {
11101            lines
11102        };
11103
11104        self.buffer.update(cx, |buffer, cx| {
11105            let snapshot = buffer.snapshot(cx);
11106            let mut excerpt_ids = selections
11107                .iter()
11108                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11109                .collect::<Vec<_>>();
11110            excerpt_ids.sort();
11111            excerpt_ids.dedup();
11112            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11113        })
11114    }
11115
11116    pub fn expand_excerpt(
11117        &mut self,
11118        excerpt: ExcerptId,
11119        direction: ExpandExcerptDirection,
11120        cx: &mut Context<Self>,
11121    ) {
11122        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11123        self.buffer.update(cx, |buffer, cx| {
11124            buffer.expand_excerpts([excerpt], lines, direction, cx)
11125        })
11126    }
11127
11128    pub fn go_to_singleton_buffer_point(
11129        &mut self,
11130        point: Point,
11131        window: &mut Window,
11132        cx: &mut Context<Self>,
11133    ) {
11134        self.go_to_singleton_buffer_range(point..point, window, cx);
11135    }
11136
11137    pub fn go_to_singleton_buffer_range(
11138        &mut self,
11139        range: Range<Point>,
11140        window: &mut Window,
11141        cx: &mut Context<Self>,
11142    ) {
11143        let multibuffer = self.buffer().read(cx);
11144        let Some(buffer) = multibuffer.as_singleton() else {
11145            return;
11146        };
11147        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11148            return;
11149        };
11150        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11151            return;
11152        };
11153        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11154            s.select_anchor_ranges([start..end])
11155        });
11156    }
11157
11158    fn go_to_diagnostic(
11159        &mut self,
11160        _: &GoToDiagnostic,
11161        window: &mut Window,
11162        cx: &mut Context<Self>,
11163    ) {
11164        self.go_to_diagnostic_impl(Direction::Next, window, cx)
11165    }
11166
11167    fn go_to_prev_diagnostic(
11168        &mut self,
11169        _: &GoToPrevDiagnostic,
11170        window: &mut Window,
11171        cx: &mut Context<Self>,
11172    ) {
11173        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11174    }
11175
11176    pub fn go_to_diagnostic_impl(
11177        &mut self,
11178        direction: Direction,
11179        window: &mut Window,
11180        cx: &mut Context<Self>,
11181    ) {
11182        let buffer = self.buffer.read(cx).snapshot(cx);
11183        let selection = self.selections.newest::<usize>(cx);
11184
11185        // If there is an active Diagnostic Popover jump to its diagnostic instead.
11186        if direction == Direction::Next {
11187            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11188                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11189                    return;
11190                };
11191                self.activate_diagnostics(
11192                    buffer_id,
11193                    popover.local_diagnostic.diagnostic.group_id,
11194                    window,
11195                    cx,
11196                );
11197                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11198                    let primary_range_start = active_diagnostics.primary_range.start;
11199                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11200                        let mut new_selection = s.newest_anchor().clone();
11201                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11202                        s.select_anchors(vec![new_selection.clone()]);
11203                    });
11204                    self.refresh_inline_completion(false, true, window, cx);
11205                }
11206                return;
11207            }
11208        }
11209
11210        let active_group_id = self
11211            .active_diagnostics
11212            .as_ref()
11213            .map(|active_group| active_group.group_id);
11214        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11215            active_diagnostics
11216                .primary_range
11217                .to_offset(&buffer)
11218                .to_inclusive()
11219        });
11220        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11221            if active_primary_range.contains(&selection.head()) {
11222                *active_primary_range.start()
11223            } else {
11224                selection.head()
11225            }
11226        } else {
11227            selection.head()
11228        };
11229
11230        let snapshot = self.snapshot(window, cx);
11231        let primary_diagnostics_before = buffer
11232            .diagnostics_in_range::<usize>(0..search_start)
11233            .filter(|entry| entry.diagnostic.is_primary)
11234            .filter(|entry| entry.range.start != entry.range.end)
11235            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11236            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11237            .collect::<Vec<_>>();
11238        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11239            primary_diagnostics_before
11240                .iter()
11241                .position(|entry| entry.diagnostic.group_id == active_group_id)
11242        });
11243
11244        let primary_diagnostics_after = buffer
11245            .diagnostics_in_range::<usize>(search_start..buffer.len())
11246            .filter(|entry| entry.diagnostic.is_primary)
11247            .filter(|entry| entry.range.start != entry.range.end)
11248            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11249            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11250            .collect::<Vec<_>>();
11251        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11252            primary_diagnostics_after
11253                .iter()
11254                .enumerate()
11255                .rev()
11256                .find_map(|(i, entry)| {
11257                    if entry.diagnostic.group_id == active_group_id {
11258                        Some(i)
11259                    } else {
11260                        None
11261                    }
11262                })
11263        });
11264
11265        let next_primary_diagnostic = match direction {
11266            Direction::Prev => primary_diagnostics_before
11267                .iter()
11268                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11269                .rev()
11270                .next(),
11271            Direction::Next => primary_diagnostics_after
11272                .iter()
11273                .skip(
11274                    last_same_group_diagnostic_after
11275                        .map(|index| index + 1)
11276                        .unwrap_or(0),
11277                )
11278                .next(),
11279        };
11280
11281        // Cycle around to the start of the buffer, potentially moving back to the start of
11282        // the currently active diagnostic.
11283        let cycle_around = || match direction {
11284            Direction::Prev => primary_diagnostics_after
11285                .iter()
11286                .rev()
11287                .chain(primary_diagnostics_before.iter().rev())
11288                .next(),
11289            Direction::Next => primary_diagnostics_before
11290                .iter()
11291                .chain(primary_diagnostics_after.iter())
11292                .next(),
11293        };
11294
11295        if let Some((primary_range, group_id)) = next_primary_diagnostic
11296            .or_else(cycle_around)
11297            .map(|entry| (&entry.range, entry.diagnostic.group_id))
11298        {
11299            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11300                return;
11301            };
11302            self.activate_diagnostics(buffer_id, group_id, window, cx);
11303            if self.active_diagnostics.is_some() {
11304                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11305                    s.select(vec![Selection {
11306                        id: selection.id,
11307                        start: primary_range.start,
11308                        end: primary_range.start,
11309                        reversed: false,
11310                        goal: SelectionGoal::None,
11311                    }]);
11312                });
11313                self.refresh_inline_completion(false, true, window, cx);
11314            }
11315        }
11316    }
11317
11318    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11319        let snapshot = self.snapshot(window, cx);
11320        let selection = self.selections.newest::<Point>(cx);
11321        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
11322    }
11323
11324    fn go_to_hunk_after_position(
11325        &mut self,
11326        snapshot: &EditorSnapshot,
11327        position: Point,
11328        window: &mut Window,
11329        cx: &mut Context<Editor>,
11330    ) -> Option<MultiBufferDiffHunk> {
11331        let mut hunk = snapshot
11332            .buffer_snapshot
11333            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11334            .find(|hunk| hunk.row_range.start.0 > position.row);
11335        if hunk.is_none() {
11336            hunk = snapshot
11337                .buffer_snapshot
11338                .diff_hunks_in_range(Point::zero()..position)
11339                .find(|hunk| hunk.row_range.end.0 < position.row)
11340        }
11341        if let Some(hunk) = &hunk {
11342            let destination = Point::new(hunk.row_range.start.0, 0);
11343            self.unfold_ranges(&[destination..destination], false, false, cx);
11344            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11345                s.select_ranges(vec![destination..destination]);
11346            });
11347        }
11348
11349        hunk
11350    }
11351
11352    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
11353        let snapshot = self.snapshot(window, cx);
11354        let selection = self.selections.newest::<Point>(cx);
11355        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
11356    }
11357
11358    fn go_to_hunk_before_position(
11359        &mut self,
11360        snapshot: &EditorSnapshot,
11361        position: Point,
11362        window: &mut Window,
11363        cx: &mut Context<Editor>,
11364    ) -> Option<MultiBufferDiffHunk> {
11365        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
11366        if hunk.is_none() {
11367            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
11368        }
11369        if let Some(hunk) = &hunk {
11370            let destination = Point::new(hunk.row_range.start.0, 0);
11371            self.unfold_ranges(&[destination..destination], false, false, cx);
11372            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11373                s.select_ranges(vec![destination..destination]);
11374            });
11375        }
11376
11377        hunk
11378    }
11379
11380    pub fn go_to_definition(
11381        &mut self,
11382        _: &GoToDefinition,
11383        window: &mut Window,
11384        cx: &mut Context<Self>,
11385    ) -> Task<Result<Navigated>> {
11386        let definition =
11387            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11388        cx.spawn_in(window, |editor, mut cx| async move {
11389            if definition.await? == Navigated::Yes {
11390                return Ok(Navigated::Yes);
11391            }
11392            match editor.update_in(&mut cx, |editor, window, cx| {
11393                editor.find_all_references(&FindAllReferences, window, cx)
11394            })? {
11395                Some(references) => references.await,
11396                None => Ok(Navigated::No),
11397            }
11398        })
11399    }
11400
11401    pub fn go_to_declaration(
11402        &mut self,
11403        _: &GoToDeclaration,
11404        window: &mut Window,
11405        cx: &mut Context<Self>,
11406    ) -> Task<Result<Navigated>> {
11407        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11408    }
11409
11410    pub fn go_to_declaration_split(
11411        &mut self,
11412        _: &GoToDeclaration,
11413        window: &mut Window,
11414        cx: &mut Context<Self>,
11415    ) -> Task<Result<Navigated>> {
11416        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11417    }
11418
11419    pub fn go_to_implementation(
11420        &mut self,
11421        _: &GoToImplementation,
11422        window: &mut Window,
11423        cx: &mut Context<Self>,
11424    ) -> Task<Result<Navigated>> {
11425        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11426    }
11427
11428    pub fn go_to_implementation_split(
11429        &mut self,
11430        _: &GoToImplementationSplit,
11431        window: &mut Window,
11432        cx: &mut Context<Self>,
11433    ) -> Task<Result<Navigated>> {
11434        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11435    }
11436
11437    pub fn go_to_type_definition(
11438        &mut self,
11439        _: &GoToTypeDefinition,
11440        window: &mut Window,
11441        cx: &mut Context<Self>,
11442    ) -> Task<Result<Navigated>> {
11443        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11444    }
11445
11446    pub fn go_to_definition_split(
11447        &mut self,
11448        _: &GoToDefinitionSplit,
11449        window: &mut Window,
11450        cx: &mut Context<Self>,
11451    ) -> Task<Result<Navigated>> {
11452        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11453    }
11454
11455    pub fn go_to_type_definition_split(
11456        &mut self,
11457        _: &GoToTypeDefinitionSplit,
11458        window: &mut Window,
11459        cx: &mut Context<Self>,
11460    ) -> Task<Result<Navigated>> {
11461        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11462    }
11463
11464    fn go_to_definition_of_kind(
11465        &mut self,
11466        kind: GotoDefinitionKind,
11467        split: bool,
11468        window: &mut Window,
11469        cx: &mut Context<Self>,
11470    ) -> Task<Result<Navigated>> {
11471        let Some(provider) = self.semantics_provider.clone() else {
11472            return Task::ready(Ok(Navigated::No));
11473        };
11474        let head = self.selections.newest::<usize>(cx).head();
11475        let buffer = self.buffer.read(cx);
11476        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11477            text_anchor
11478        } else {
11479            return Task::ready(Ok(Navigated::No));
11480        };
11481
11482        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11483            return Task::ready(Ok(Navigated::No));
11484        };
11485
11486        cx.spawn_in(window, |editor, mut cx| async move {
11487            let definitions = definitions.await?;
11488            let navigated = editor
11489                .update_in(&mut cx, |editor, window, cx| {
11490                    editor.navigate_to_hover_links(
11491                        Some(kind),
11492                        definitions
11493                            .into_iter()
11494                            .filter(|location| {
11495                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11496                            })
11497                            .map(HoverLink::Text)
11498                            .collect::<Vec<_>>(),
11499                        split,
11500                        window,
11501                        cx,
11502                    )
11503                })?
11504                .await?;
11505            anyhow::Ok(navigated)
11506        })
11507    }
11508
11509    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11510        let selection = self.selections.newest_anchor();
11511        let head = selection.head();
11512        let tail = selection.tail();
11513
11514        let Some((buffer, start_position)) =
11515            self.buffer.read(cx).text_anchor_for_position(head, cx)
11516        else {
11517            return;
11518        };
11519
11520        let end_position = if head != tail {
11521            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11522                return;
11523            };
11524            Some(pos)
11525        } else {
11526            None
11527        };
11528
11529        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11530            let url = if let Some(end_pos) = end_position {
11531                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11532            } else {
11533                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11534            };
11535
11536            if let Some(url) = url {
11537                editor.update(&mut cx, |_, cx| {
11538                    cx.open_url(&url);
11539                })
11540            } else {
11541                Ok(())
11542            }
11543        });
11544
11545        url_finder.detach();
11546    }
11547
11548    pub fn open_selected_filename(
11549        &mut self,
11550        _: &OpenSelectedFilename,
11551        window: &mut Window,
11552        cx: &mut Context<Self>,
11553    ) {
11554        let Some(workspace) = self.workspace() else {
11555            return;
11556        };
11557
11558        let position = self.selections.newest_anchor().head();
11559
11560        let Some((buffer, buffer_position)) =
11561            self.buffer.read(cx).text_anchor_for_position(position, cx)
11562        else {
11563            return;
11564        };
11565
11566        let project = self.project.clone();
11567
11568        cx.spawn_in(window, |_, mut cx| async move {
11569            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11570
11571            if let Some((_, path)) = result {
11572                workspace
11573                    .update_in(&mut cx, |workspace, window, cx| {
11574                        workspace.open_resolved_path(path, window, cx)
11575                    })?
11576                    .await?;
11577            }
11578            anyhow::Ok(())
11579        })
11580        .detach();
11581    }
11582
11583    pub(crate) fn navigate_to_hover_links(
11584        &mut self,
11585        kind: Option<GotoDefinitionKind>,
11586        mut definitions: Vec<HoverLink>,
11587        split: bool,
11588        window: &mut Window,
11589        cx: &mut Context<Editor>,
11590    ) -> Task<Result<Navigated>> {
11591        // If there is one definition, just open it directly
11592        if definitions.len() == 1 {
11593            let definition = definitions.pop().unwrap();
11594
11595            enum TargetTaskResult {
11596                Location(Option<Location>),
11597                AlreadyNavigated,
11598            }
11599
11600            let target_task = match definition {
11601                HoverLink::Text(link) => {
11602                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11603                }
11604                HoverLink::InlayHint(lsp_location, server_id) => {
11605                    let computation =
11606                        self.compute_target_location(lsp_location, server_id, window, cx);
11607                    cx.background_spawn(async move {
11608                        let location = computation.await?;
11609                        Ok(TargetTaskResult::Location(location))
11610                    })
11611                }
11612                HoverLink::Url(url) => {
11613                    cx.open_url(&url);
11614                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11615                }
11616                HoverLink::File(path) => {
11617                    if let Some(workspace) = self.workspace() {
11618                        cx.spawn_in(window, |_, mut cx| async move {
11619                            workspace
11620                                .update_in(&mut cx, |workspace, window, cx| {
11621                                    workspace.open_resolved_path(path, window, cx)
11622                                })?
11623                                .await
11624                                .map(|_| TargetTaskResult::AlreadyNavigated)
11625                        })
11626                    } else {
11627                        Task::ready(Ok(TargetTaskResult::Location(None)))
11628                    }
11629                }
11630            };
11631            cx.spawn_in(window, |editor, mut cx| async move {
11632                let target = match target_task.await.context("target resolution task")? {
11633                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11634                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11635                    TargetTaskResult::Location(Some(target)) => target,
11636                };
11637
11638                editor.update_in(&mut cx, |editor, window, cx| {
11639                    let Some(workspace) = editor.workspace() else {
11640                        return Navigated::No;
11641                    };
11642                    let pane = workspace.read(cx).active_pane().clone();
11643
11644                    let range = target.range.to_point(target.buffer.read(cx));
11645                    let range = editor.range_for_match(&range);
11646                    let range = collapse_multiline_range(range);
11647
11648                    if !split
11649                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11650                    {
11651                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11652                    } else {
11653                        window.defer(cx, move |window, cx| {
11654                            let target_editor: Entity<Self> =
11655                                workspace.update(cx, |workspace, cx| {
11656                                    let pane = if split {
11657                                        workspace.adjacent_pane(window, cx)
11658                                    } else {
11659                                        workspace.active_pane().clone()
11660                                    };
11661
11662                                    workspace.open_project_item(
11663                                        pane,
11664                                        target.buffer.clone(),
11665                                        true,
11666                                        true,
11667                                        window,
11668                                        cx,
11669                                    )
11670                                });
11671                            target_editor.update(cx, |target_editor, cx| {
11672                                // When selecting a definition in a different buffer, disable the nav history
11673                                // to avoid creating a history entry at the previous cursor location.
11674                                pane.update(cx, |pane, _| pane.disable_history());
11675                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11676                                pane.update(cx, |pane, _| pane.enable_history());
11677                            });
11678                        });
11679                    }
11680                    Navigated::Yes
11681                })
11682            })
11683        } else if !definitions.is_empty() {
11684            cx.spawn_in(window, |editor, mut cx| async move {
11685                let (title, location_tasks, workspace) = editor
11686                    .update_in(&mut cx, |editor, window, cx| {
11687                        let tab_kind = match kind {
11688                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11689                            _ => "Definitions",
11690                        };
11691                        let title = definitions
11692                            .iter()
11693                            .find_map(|definition| match definition {
11694                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11695                                    let buffer = origin.buffer.read(cx);
11696                                    format!(
11697                                        "{} for {}",
11698                                        tab_kind,
11699                                        buffer
11700                                            .text_for_range(origin.range.clone())
11701                                            .collect::<String>()
11702                                    )
11703                                }),
11704                                HoverLink::InlayHint(_, _) => None,
11705                                HoverLink::Url(_) => None,
11706                                HoverLink::File(_) => None,
11707                            })
11708                            .unwrap_or(tab_kind.to_string());
11709                        let location_tasks = definitions
11710                            .into_iter()
11711                            .map(|definition| match definition {
11712                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11713                                HoverLink::InlayHint(lsp_location, server_id) => editor
11714                                    .compute_target_location(lsp_location, server_id, window, cx),
11715                                HoverLink::Url(_) => Task::ready(Ok(None)),
11716                                HoverLink::File(_) => Task::ready(Ok(None)),
11717                            })
11718                            .collect::<Vec<_>>();
11719                        (title, location_tasks, editor.workspace().clone())
11720                    })
11721                    .context("location tasks preparation")?;
11722
11723                let locations = future::join_all(location_tasks)
11724                    .await
11725                    .into_iter()
11726                    .filter_map(|location| location.transpose())
11727                    .collect::<Result<_>>()
11728                    .context("location tasks")?;
11729
11730                let Some(workspace) = workspace else {
11731                    return Ok(Navigated::No);
11732                };
11733                let opened = workspace
11734                    .update_in(&mut cx, |workspace, window, cx| {
11735                        Self::open_locations_in_multibuffer(
11736                            workspace,
11737                            locations,
11738                            title,
11739                            split,
11740                            MultibufferSelectionMode::First,
11741                            window,
11742                            cx,
11743                        )
11744                    })
11745                    .ok();
11746
11747                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11748            })
11749        } else {
11750            Task::ready(Ok(Navigated::No))
11751        }
11752    }
11753
11754    fn compute_target_location(
11755        &self,
11756        lsp_location: lsp::Location,
11757        server_id: LanguageServerId,
11758        window: &mut Window,
11759        cx: &mut Context<Self>,
11760    ) -> Task<anyhow::Result<Option<Location>>> {
11761        let Some(project) = self.project.clone() else {
11762            return Task::ready(Ok(None));
11763        };
11764
11765        cx.spawn_in(window, move |editor, mut cx| async move {
11766            let location_task = editor.update(&mut cx, |_, cx| {
11767                project.update(cx, |project, cx| {
11768                    let language_server_name = project
11769                        .language_server_statuses(cx)
11770                        .find(|(id, _)| server_id == *id)
11771                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11772                    language_server_name.map(|language_server_name| {
11773                        project.open_local_buffer_via_lsp(
11774                            lsp_location.uri.clone(),
11775                            server_id,
11776                            language_server_name,
11777                            cx,
11778                        )
11779                    })
11780                })
11781            })?;
11782            let location = match location_task {
11783                Some(task) => Some({
11784                    let target_buffer_handle = task.await.context("open local buffer")?;
11785                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11786                        let target_start = target_buffer
11787                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11788                        let target_end = target_buffer
11789                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11790                        target_buffer.anchor_after(target_start)
11791                            ..target_buffer.anchor_before(target_end)
11792                    })?;
11793                    Location {
11794                        buffer: target_buffer_handle,
11795                        range,
11796                    }
11797                }),
11798                None => None,
11799            };
11800            Ok(location)
11801        })
11802    }
11803
11804    pub fn find_all_references(
11805        &mut self,
11806        _: &FindAllReferences,
11807        window: &mut Window,
11808        cx: &mut Context<Self>,
11809    ) -> Option<Task<Result<Navigated>>> {
11810        let selection = self.selections.newest::<usize>(cx);
11811        let multi_buffer = self.buffer.read(cx);
11812        let head = selection.head();
11813
11814        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11815        let head_anchor = multi_buffer_snapshot.anchor_at(
11816            head,
11817            if head < selection.tail() {
11818                Bias::Right
11819            } else {
11820                Bias::Left
11821            },
11822        );
11823
11824        match self
11825            .find_all_references_task_sources
11826            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11827        {
11828            Ok(_) => {
11829                log::info!(
11830                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11831                );
11832                return None;
11833            }
11834            Err(i) => {
11835                self.find_all_references_task_sources.insert(i, head_anchor);
11836            }
11837        }
11838
11839        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11840        let workspace = self.workspace()?;
11841        let project = workspace.read(cx).project().clone();
11842        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11843        Some(cx.spawn_in(window, |editor, mut cx| async move {
11844            let _cleanup = defer({
11845                let mut cx = cx.clone();
11846                move || {
11847                    let _ = editor.update(&mut cx, |editor, _| {
11848                        if let Ok(i) =
11849                            editor
11850                                .find_all_references_task_sources
11851                                .binary_search_by(|anchor| {
11852                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11853                                })
11854                        {
11855                            editor.find_all_references_task_sources.remove(i);
11856                        }
11857                    });
11858                }
11859            });
11860
11861            let locations = references.await?;
11862            if locations.is_empty() {
11863                return anyhow::Ok(Navigated::No);
11864            }
11865
11866            workspace.update_in(&mut cx, |workspace, window, cx| {
11867                let title = locations
11868                    .first()
11869                    .as_ref()
11870                    .map(|location| {
11871                        let buffer = location.buffer.read(cx);
11872                        format!(
11873                            "References to `{}`",
11874                            buffer
11875                                .text_for_range(location.range.clone())
11876                                .collect::<String>()
11877                        )
11878                    })
11879                    .unwrap();
11880                Self::open_locations_in_multibuffer(
11881                    workspace,
11882                    locations,
11883                    title,
11884                    false,
11885                    MultibufferSelectionMode::First,
11886                    window,
11887                    cx,
11888                );
11889                Navigated::Yes
11890            })
11891        }))
11892    }
11893
11894    /// Opens a multibuffer with the given project locations in it
11895    pub fn open_locations_in_multibuffer(
11896        workspace: &mut Workspace,
11897        mut locations: Vec<Location>,
11898        title: String,
11899        split: bool,
11900        multibuffer_selection_mode: MultibufferSelectionMode,
11901        window: &mut Window,
11902        cx: &mut Context<Workspace>,
11903    ) {
11904        // If there are multiple definitions, open them in a multibuffer
11905        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11906        let mut locations = locations.into_iter().peekable();
11907        let mut ranges = Vec::new();
11908        let capability = workspace.project().read(cx).capability();
11909
11910        let excerpt_buffer = cx.new(|cx| {
11911            let mut multibuffer = MultiBuffer::new(capability);
11912            while let Some(location) = locations.next() {
11913                let buffer = location.buffer.read(cx);
11914                let mut ranges_for_buffer = Vec::new();
11915                let range = location.range.to_offset(buffer);
11916                ranges_for_buffer.push(range.clone());
11917
11918                while let Some(next_location) = locations.peek() {
11919                    if next_location.buffer == location.buffer {
11920                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11921                        locations.next();
11922                    } else {
11923                        break;
11924                    }
11925                }
11926
11927                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11928                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11929                    location.buffer.clone(),
11930                    ranges_for_buffer,
11931                    DEFAULT_MULTIBUFFER_CONTEXT,
11932                    cx,
11933                ))
11934            }
11935
11936            multibuffer.with_title(title)
11937        });
11938
11939        let editor = cx.new(|cx| {
11940            Editor::for_multibuffer(
11941                excerpt_buffer,
11942                Some(workspace.project().clone()),
11943                true,
11944                window,
11945                cx,
11946            )
11947        });
11948        editor.update(cx, |editor, cx| {
11949            match multibuffer_selection_mode {
11950                MultibufferSelectionMode::First => {
11951                    if let Some(first_range) = ranges.first() {
11952                        editor.change_selections(None, window, cx, |selections| {
11953                            selections.clear_disjoint();
11954                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11955                        });
11956                    }
11957                    editor.highlight_background::<Self>(
11958                        &ranges,
11959                        |theme| theme.editor_highlighted_line_background,
11960                        cx,
11961                    );
11962                }
11963                MultibufferSelectionMode::All => {
11964                    editor.change_selections(None, window, cx, |selections| {
11965                        selections.clear_disjoint();
11966                        selections.select_anchor_ranges(ranges);
11967                    });
11968                }
11969            }
11970            editor.register_buffers_with_language_servers(cx);
11971        });
11972
11973        let item = Box::new(editor);
11974        let item_id = item.item_id();
11975
11976        if split {
11977            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11978        } else {
11979            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11980                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11981                    pane.close_current_preview_item(window, cx)
11982                } else {
11983                    None
11984                }
11985            });
11986            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11987        }
11988        workspace.active_pane().update(cx, |pane, cx| {
11989            pane.set_preview_item_id(Some(item_id), cx);
11990        });
11991    }
11992
11993    pub fn rename(
11994        &mut self,
11995        _: &Rename,
11996        window: &mut Window,
11997        cx: &mut Context<Self>,
11998    ) -> Option<Task<Result<()>>> {
11999        use language::ToOffset as _;
12000
12001        let provider = self.semantics_provider.clone()?;
12002        let selection = self.selections.newest_anchor().clone();
12003        let (cursor_buffer, cursor_buffer_position) = self
12004            .buffer
12005            .read(cx)
12006            .text_anchor_for_position(selection.head(), cx)?;
12007        let (tail_buffer, cursor_buffer_position_end) = self
12008            .buffer
12009            .read(cx)
12010            .text_anchor_for_position(selection.tail(), cx)?;
12011        if tail_buffer != cursor_buffer {
12012            return None;
12013        }
12014
12015        let snapshot = cursor_buffer.read(cx).snapshot();
12016        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12017        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12018        let prepare_rename = provider
12019            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12020            .unwrap_or_else(|| Task::ready(Ok(None)));
12021        drop(snapshot);
12022
12023        Some(cx.spawn_in(window, |this, mut cx| async move {
12024            let rename_range = if let Some(range) = prepare_rename.await? {
12025                Some(range)
12026            } else {
12027                this.update(&mut cx, |this, cx| {
12028                    let buffer = this.buffer.read(cx).snapshot(cx);
12029                    let mut buffer_highlights = this
12030                        .document_highlights_for_position(selection.head(), &buffer)
12031                        .filter(|highlight| {
12032                            highlight.start.excerpt_id == selection.head().excerpt_id
12033                                && highlight.end.excerpt_id == selection.head().excerpt_id
12034                        });
12035                    buffer_highlights
12036                        .next()
12037                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12038                })?
12039            };
12040            if let Some(rename_range) = rename_range {
12041                this.update_in(&mut cx, |this, window, cx| {
12042                    let snapshot = cursor_buffer.read(cx).snapshot();
12043                    let rename_buffer_range = rename_range.to_offset(&snapshot);
12044                    let cursor_offset_in_rename_range =
12045                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12046                    let cursor_offset_in_rename_range_end =
12047                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12048
12049                    this.take_rename(false, window, cx);
12050                    let buffer = this.buffer.read(cx).read(cx);
12051                    let cursor_offset = selection.head().to_offset(&buffer);
12052                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12053                    let rename_end = rename_start + rename_buffer_range.len();
12054                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12055                    let mut old_highlight_id = None;
12056                    let old_name: Arc<str> = buffer
12057                        .chunks(rename_start..rename_end, true)
12058                        .map(|chunk| {
12059                            if old_highlight_id.is_none() {
12060                                old_highlight_id = chunk.syntax_highlight_id;
12061                            }
12062                            chunk.text
12063                        })
12064                        .collect::<String>()
12065                        .into();
12066
12067                    drop(buffer);
12068
12069                    // Position the selection in the rename editor so that it matches the current selection.
12070                    this.show_local_selections = false;
12071                    let rename_editor = cx.new(|cx| {
12072                        let mut editor = Editor::single_line(window, cx);
12073                        editor.buffer.update(cx, |buffer, cx| {
12074                            buffer.edit([(0..0, old_name.clone())], None, cx)
12075                        });
12076                        let rename_selection_range = match cursor_offset_in_rename_range
12077                            .cmp(&cursor_offset_in_rename_range_end)
12078                        {
12079                            Ordering::Equal => {
12080                                editor.select_all(&SelectAll, window, cx);
12081                                return editor;
12082                            }
12083                            Ordering::Less => {
12084                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12085                            }
12086                            Ordering::Greater => {
12087                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12088                            }
12089                        };
12090                        if rename_selection_range.end > old_name.len() {
12091                            editor.select_all(&SelectAll, window, cx);
12092                        } else {
12093                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12094                                s.select_ranges([rename_selection_range]);
12095                            });
12096                        }
12097                        editor
12098                    });
12099                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12100                        if e == &EditorEvent::Focused {
12101                            cx.emit(EditorEvent::FocusedIn)
12102                        }
12103                    })
12104                    .detach();
12105
12106                    let write_highlights =
12107                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12108                    let read_highlights =
12109                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
12110                    let ranges = write_highlights
12111                        .iter()
12112                        .flat_map(|(_, ranges)| ranges.iter())
12113                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12114                        .cloned()
12115                        .collect();
12116
12117                    this.highlight_text::<Rename>(
12118                        ranges,
12119                        HighlightStyle {
12120                            fade_out: Some(0.6),
12121                            ..Default::default()
12122                        },
12123                        cx,
12124                    );
12125                    let rename_focus_handle = rename_editor.focus_handle(cx);
12126                    window.focus(&rename_focus_handle);
12127                    let block_id = this.insert_blocks(
12128                        [BlockProperties {
12129                            style: BlockStyle::Flex,
12130                            placement: BlockPlacement::Below(range.start),
12131                            height: 1,
12132                            render: Arc::new({
12133                                let rename_editor = rename_editor.clone();
12134                                move |cx: &mut BlockContext| {
12135                                    let mut text_style = cx.editor_style.text.clone();
12136                                    if let Some(highlight_style) = old_highlight_id
12137                                        .and_then(|h| h.style(&cx.editor_style.syntax))
12138                                    {
12139                                        text_style = text_style.highlight(highlight_style);
12140                                    }
12141                                    div()
12142                                        .block_mouse_down()
12143                                        .pl(cx.anchor_x)
12144                                        .child(EditorElement::new(
12145                                            &rename_editor,
12146                                            EditorStyle {
12147                                                background: cx.theme().system().transparent,
12148                                                local_player: cx.editor_style.local_player,
12149                                                text: text_style,
12150                                                scrollbar_width: cx.editor_style.scrollbar_width,
12151                                                syntax: cx.editor_style.syntax.clone(),
12152                                                status: cx.editor_style.status.clone(),
12153                                                inlay_hints_style: HighlightStyle {
12154                                                    font_weight: Some(FontWeight::BOLD),
12155                                                    ..make_inlay_hints_style(cx.app)
12156                                                },
12157                                                inline_completion_styles: make_suggestion_styles(
12158                                                    cx.app,
12159                                                ),
12160                                                ..EditorStyle::default()
12161                                            },
12162                                        ))
12163                                        .into_any_element()
12164                                }
12165                            }),
12166                            priority: 0,
12167                        }],
12168                        Some(Autoscroll::fit()),
12169                        cx,
12170                    )[0];
12171                    this.pending_rename = Some(RenameState {
12172                        range,
12173                        old_name,
12174                        editor: rename_editor,
12175                        block_id,
12176                    });
12177                })?;
12178            }
12179
12180            Ok(())
12181        }))
12182    }
12183
12184    pub fn confirm_rename(
12185        &mut self,
12186        _: &ConfirmRename,
12187        window: &mut Window,
12188        cx: &mut Context<Self>,
12189    ) -> Option<Task<Result<()>>> {
12190        let rename = self.take_rename(false, window, cx)?;
12191        let workspace = self.workspace()?.downgrade();
12192        let (buffer, start) = self
12193            .buffer
12194            .read(cx)
12195            .text_anchor_for_position(rename.range.start, cx)?;
12196        let (end_buffer, _) = self
12197            .buffer
12198            .read(cx)
12199            .text_anchor_for_position(rename.range.end, cx)?;
12200        if buffer != end_buffer {
12201            return None;
12202        }
12203
12204        let old_name = rename.old_name;
12205        let new_name = rename.editor.read(cx).text(cx);
12206
12207        let rename = self.semantics_provider.as_ref()?.perform_rename(
12208            &buffer,
12209            start,
12210            new_name.clone(),
12211            cx,
12212        )?;
12213
12214        Some(cx.spawn_in(window, |editor, mut cx| async move {
12215            let project_transaction = rename.await?;
12216            Self::open_project_transaction(
12217                &editor,
12218                workspace,
12219                project_transaction,
12220                format!("Rename: {}{}", old_name, new_name),
12221                cx.clone(),
12222            )
12223            .await?;
12224
12225            editor.update(&mut cx, |editor, cx| {
12226                editor.refresh_document_highlights(cx);
12227            })?;
12228            Ok(())
12229        }))
12230    }
12231
12232    fn take_rename(
12233        &mut self,
12234        moving_cursor: bool,
12235        window: &mut Window,
12236        cx: &mut Context<Self>,
12237    ) -> Option<RenameState> {
12238        let rename = self.pending_rename.take()?;
12239        if rename.editor.focus_handle(cx).is_focused(window) {
12240            window.focus(&self.focus_handle);
12241        }
12242
12243        self.remove_blocks(
12244            [rename.block_id].into_iter().collect(),
12245            Some(Autoscroll::fit()),
12246            cx,
12247        );
12248        self.clear_highlights::<Rename>(cx);
12249        self.show_local_selections = true;
12250
12251        if moving_cursor {
12252            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12253                editor.selections.newest::<usize>(cx).head()
12254            });
12255
12256            // Update the selection to match the position of the selection inside
12257            // the rename editor.
12258            let snapshot = self.buffer.read(cx).read(cx);
12259            let rename_range = rename.range.to_offset(&snapshot);
12260            let cursor_in_editor = snapshot
12261                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12262                .min(rename_range.end);
12263            drop(snapshot);
12264
12265            self.change_selections(None, window, cx, |s| {
12266                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12267            });
12268        } else {
12269            self.refresh_document_highlights(cx);
12270        }
12271
12272        Some(rename)
12273    }
12274
12275    pub fn pending_rename(&self) -> Option<&RenameState> {
12276        self.pending_rename.as_ref()
12277    }
12278
12279    fn format(
12280        &mut self,
12281        _: &Format,
12282        window: &mut Window,
12283        cx: &mut Context<Self>,
12284    ) -> Option<Task<Result<()>>> {
12285        let project = match &self.project {
12286            Some(project) => project.clone(),
12287            None => return None,
12288        };
12289
12290        Some(self.perform_format(
12291            project,
12292            FormatTrigger::Manual,
12293            FormatTarget::Buffers,
12294            window,
12295            cx,
12296        ))
12297    }
12298
12299    fn format_selections(
12300        &mut self,
12301        _: &FormatSelections,
12302        window: &mut Window,
12303        cx: &mut Context<Self>,
12304    ) -> Option<Task<Result<()>>> {
12305        let project = match &self.project {
12306            Some(project) => project.clone(),
12307            None => return None,
12308        };
12309
12310        let ranges = self
12311            .selections
12312            .all_adjusted(cx)
12313            .into_iter()
12314            .map(|selection| selection.range())
12315            .collect_vec();
12316
12317        Some(self.perform_format(
12318            project,
12319            FormatTrigger::Manual,
12320            FormatTarget::Ranges(ranges),
12321            window,
12322            cx,
12323        ))
12324    }
12325
12326    fn perform_format(
12327        &mut self,
12328        project: Entity<Project>,
12329        trigger: FormatTrigger,
12330        target: FormatTarget,
12331        window: &mut Window,
12332        cx: &mut Context<Self>,
12333    ) -> Task<Result<()>> {
12334        let buffer = self.buffer.clone();
12335        let (buffers, target) = match target {
12336            FormatTarget::Buffers => {
12337                let mut buffers = buffer.read(cx).all_buffers();
12338                if trigger == FormatTrigger::Save {
12339                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
12340                }
12341                (buffers, LspFormatTarget::Buffers)
12342            }
12343            FormatTarget::Ranges(selection_ranges) => {
12344                let multi_buffer = buffer.read(cx);
12345                let snapshot = multi_buffer.read(cx);
12346                let mut buffers = HashSet::default();
12347                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12348                    BTreeMap::new();
12349                for selection_range in selection_ranges {
12350                    for (buffer, buffer_range, _) in
12351                        snapshot.range_to_buffer_ranges(selection_range)
12352                    {
12353                        let buffer_id = buffer.remote_id();
12354                        let start = buffer.anchor_before(buffer_range.start);
12355                        let end = buffer.anchor_after(buffer_range.end);
12356                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12357                        buffer_id_to_ranges
12358                            .entry(buffer_id)
12359                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12360                            .or_insert_with(|| vec![start..end]);
12361                    }
12362                }
12363                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12364            }
12365        };
12366
12367        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12368        let format = project.update(cx, |project, cx| {
12369            project.format(buffers, target, true, trigger, cx)
12370        });
12371
12372        cx.spawn_in(window, |_, mut cx| async move {
12373            let transaction = futures::select_biased! {
12374                () = timeout => {
12375                    log::warn!("timed out waiting for formatting");
12376                    None
12377                }
12378                transaction = format.log_err().fuse() => transaction,
12379            };
12380
12381            buffer
12382                .update(&mut cx, |buffer, cx| {
12383                    if let Some(transaction) = transaction {
12384                        if !buffer.is_singleton() {
12385                            buffer.push_transaction(&transaction.0, cx);
12386                        }
12387                    }
12388
12389                    cx.notify();
12390                })
12391                .ok();
12392
12393            Ok(())
12394        })
12395    }
12396
12397    fn restart_language_server(
12398        &mut self,
12399        _: &RestartLanguageServer,
12400        _: &mut Window,
12401        cx: &mut Context<Self>,
12402    ) {
12403        if let Some(project) = self.project.clone() {
12404            self.buffer.update(cx, |multi_buffer, cx| {
12405                project.update(cx, |project, cx| {
12406                    project.restart_language_servers_for_buffers(
12407                        multi_buffer.all_buffers().into_iter().collect(),
12408                        cx,
12409                    );
12410                });
12411            })
12412        }
12413    }
12414
12415    fn cancel_language_server_work(
12416        workspace: &mut Workspace,
12417        _: &actions::CancelLanguageServerWork,
12418        _: &mut Window,
12419        cx: &mut Context<Workspace>,
12420    ) {
12421        let project = workspace.project();
12422        let buffers = workspace
12423            .active_item(cx)
12424            .and_then(|item| item.act_as::<Editor>(cx))
12425            .map_or(HashSet::default(), |editor| {
12426                editor.read(cx).buffer.read(cx).all_buffers()
12427            });
12428        project.update(cx, |project, cx| {
12429            project.cancel_language_server_work_for_buffers(buffers, cx);
12430        });
12431    }
12432
12433    fn show_character_palette(
12434        &mut self,
12435        _: &ShowCharacterPalette,
12436        window: &mut Window,
12437        _: &mut Context<Self>,
12438    ) {
12439        window.show_character_palette();
12440    }
12441
12442    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12443        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12444            let buffer = self.buffer.read(cx).snapshot(cx);
12445            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12446            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12447            let is_valid = buffer
12448                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12449                .any(|entry| {
12450                    entry.diagnostic.is_primary
12451                        && !entry.range.is_empty()
12452                        && entry.range.start == primary_range_start
12453                        && entry.diagnostic.message == active_diagnostics.primary_message
12454                });
12455
12456            if is_valid != active_diagnostics.is_valid {
12457                active_diagnostics.is_valid = is_valid;
12458                let mut new_styles = HashMap::default();
12459                for (block_id, diagnostic) in &active_diagnostics.blocks {
12460                    new_styles.insert(
12461                        *block_id,
12462                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
12463                    );
12464                }
12465                self.display_map.update(cx, |display_map, _cx| {
12466                    display_map.replace_blocks(new_styles)
12467                });
12468            }
12469        }
12470    }
12471
12472    fn activate_diagnostics(
12473        &mut self,
12474        buffer_id: BufferId,
12475        group_id: usize,
12476        window: &mut Window,
12477        cx: &mut Context<Self>,
12478    ) {
12479        self.dismiss_diagnostics(cx);
12480        let snapshot = self.snapshot(window, cx);
12481        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12482            let buffer = self.buffer.read(cx).snapshot(cx);
12483
12484            let mut primary_range = None;
12485            let mut primary_message = None;
12486            let diagnostic_group = buffer
12487                .diagnostic_group(buffer_id, group_id)
12488                .filter_map(|entry| {
12489                    let start = entry.range.start;
12490                    let end = entry.range.end;
12491                    if snapshot.is_line_folded(MultiBufferRow(start.row))
12492                        && (start.row == end.row
12493                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
12494                    {
12495                        return None;
12496                    }
12497                    if entry.diagnostic.is_primary {
12498                        primary_range = Some(entry.range.clone());
12499                        primary_message = Some(entry.diagnostic.message.clone());
12500                    }
12501                    Some(entry)
12502                })
12503                .collect::<Vec<_>>();
12504            let primary_range = primary_range?;
12505            let primary_message = primary_message?;
12506
12507            let blocks = display_map
12508                .insert_blocks(
12509                    diagnostic_group.iter().map(|entry| {
12510                        let diagnostic = entry.diagnostic.clone();
12511                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12512                        BlockProperties {
12513                            style: BlockStyle::Fixed,
12514                            placement: BlockPlacement::Below(
12515                                buffer.anchor_after(entry.range.start),
12516                            ),
12517                            height: message_height,
12518                            render: diagnostic_block_renderer(diagnostic, None, true, true),
12519                            priority: 0,
12520                        }
12521                    }),
12522                    cx,
12523                )
12524                .into_iter()
12525                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12526                .collect();
12527
12528            Some(ActiveDiagnosticGroup {
12529                primary_range: buffer.anchor_before(primary_range.start)
12530                    ..buffer.anchor_after(primary_range.end),
12531                primary_message,
12532                group_id,
12533                blocks,
12534                is_valid: true,
12535            })
12536        });
12537    }
12538
12539    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12540        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12541            self.display_map.update(cx, |display_map, cx| {
12542                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12543            });
12544            cx.notify();
12545        }
12546    }
12547
12548    /// Disable inline diagnostics rendering for this editor.
12549    pub fn disable_inline_diagnostics(&mut self) {
12550        self.inline_diagnostics_enabled = false;
12551        self.inline_diagnostics_update = Task::ready(());
12552        self.inline_diagnostics.clear();
12553    }
12554
12555    pub fn inline_diagnostics_enabled(&self) -> bool {
12556        self.inline_diagnostics_enabled
12557    }
12558
12559    pub fn show_inline_diagnostics(&self) -> bool {
12560        self.show_inline_diagnostics
12561    }
12562
12563    pub fn toggle_inline_diagnostics(
12564        &mut self,
12565        _: &ToggleInlineDiagnostics,
12566        window: &mut Window,
12567        cx: &mut Context<'_, Editor>,
12568    ) {
12569        self.show_inline_diagnostics = !self.show_inline_diagnostics;
12570        self.refresh_inline_diagnostics(false, window, cx);
12571    }
12572
12573    fn refresh_inline_diagnostics(
12574        &mut self,
12575        debounce: bool,
12576        window: &mut Window,
12577        cx: &mut Context<Self>,
12578    ) {
12579        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12580            self.inline_diagnostics_update = Task::ready(());
12581            self.inline_diagnostics.clear();
12582            return;
12583        }
12584
12585        let debounce_ms = ProjectSettings::get_global(cx)
12586            .diagnostics
12587            .inline
12588            .update_debounce_ms;
12589        let debounce = if debounce && debounce_ms > 0 {
12590            Some(Duration::from_millis(debounce_ms))
12591        } else {
12592            None
12593        };
12594        self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12595            if let Some(debounce) = debounce {
12596                cx.background_executor().timer(debounce).await;
12597            }
12598            let Some(snapshot) = editor
12599                .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12600                .ok()
12601            else {
12602                return;
12603            };
12604
12605            let new_inline_diagnostics = cx
12606                .background_spawn(async move {
12607                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12608                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12609                        let message = diagnostic_entry
12610                            .diagnostic
12611                            .message
12612                            .split_once('\n')
12613                            .map(|(line, _)| line)
12614                            .map(SharedString::new)
12615                            .unwrap_or_else(|| {
12616                                SharedString::from(diagnostic_entry.diagnostic.message)
12617                            });
12618                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12619                        let (Ok(i) | Err(i)) = inline_diagnostics
12620                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12621                        inline_diagnostics.insert(
12622                            i,
12623                            (
12624                                start_anchor,
12625                                InlineDiagnostic {
12626                                    message,
12627                                    group_id: diagnostic_entry.diagnostic.group_id,
12628                                    start: diagnostic_entry.range.start.to_point(&snapshot),
12629                                    is_primary: diagnostic_entry.diagnostic.is_primary,
12630                                    severity: diagnostic_entry.diagnostic.severity,
12631                                },
12632                            ),
12633                        );
12634                    }
12635                    inline_diagnostics
12636                })
12637                .await;
12638
12639            editor
12640                .update(&mut cx, |editor, cx| {
12641                    editor.inline_diagnostics = new_inline_diagnostics;
12642                    cx.notify();
12643                })
12644                .ok();
12645        });
12646    }
12647
12648    pub fn set_selections_from_remote(
12649        &mut self,
12650        selections: Vec<Selection<Anchor>>,
12651        pending_selection: Option<Selection<Anchor>>,
12652        window: &mut Window,
12653        cx: &mut Context<Self>,
12654    ) {
12655        let old_cursor_position = self.selections.newest_anchor().head();
12656        self.selections.change_with(cx, |s| {
12657            s.select_anchors(selections);
12658            if let Some(pending_selection) = pending_selection {
12659                s.set_pending(pending_selection, SelectMode::Character);
12660            } else {
12661                s.clear_pending();
12662            }
12663        });
12664        self.selections_did_change(false, &old_cursor_position, true, window, cx);
12665    }
12666
12667    fn push_to_selection_history(&mut self) {
12668        self.selection_history.push(SelectionHistoryEntry {
12669            selections: self.selections.disjoint_anchors(),
12670            select_next_state: self.select_next_state.clone(),
12671            select_prev_state: self.select_prev_state.clone(),
12672            add_selections_state: self.add_selections_state.clone(),
12673        });
12674    }
12675
12676    pub fn transact(
12677        &mut self,
12678        window: &mut Window,
12679        cx: &mut Context<Self>,
12680        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12681    ) -> Option<TransactionId> {
12682        self.start_transaction_at(Instant::now(), window, cx);
12683        update(self, window, cx);
12684        self.end_transaction_at(Instant::now(), cx)
12685    }
12686
12687    pub fn start_transaction_at(
12688        &mut self,
12689        now: Instant,
12690        window: &mut Window,
12691        cx: &mut Context<Self>,
12692    ) {
12693        self.end_selection(window, cx);
12694        if let Some(tx_id) = self
12695            .buffer
12696            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12697        {
12698            self.selection_history
12699                .insert_transaction(tx_id, self.selections.disjoint_anchors());
12700            cx.emit(EditorEvent::TransactionBegun {
12701                transaction_id: tx_id,
12702            })
12703        }
12704    }
12705
12706    pub fn end_transaction_at(
12707        &mut self,
12708        now: Instant,
12709        cx: &mut Context<Self>,
12710    ) -> Option<TransactionId> {
12711        if let Some(transaction_id) = self
12712            .buffer
12713            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12714        {
12715            if let Some((_, end_selections)) =
12716                self.selection_history.transaction_mut(transaction_id)
12717            {
12718                *end_selections = Some(self.selections.disjoint_anchors());
12719            } else {
12720                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12721            }
12722
12723            cx.emit(EditorEvent::Edited { transaction_id });
12724            Some(transaction_id)
12725        } else {
12726            None
12727        }
12728    }
12729
12730    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12731        if self.selection_mark_mode {
12732            self.change_selections(None, window, cx, |s| {
12733                s.move_with(|_, sel| {
12734                    sel.collapse_to(sel.head(), SelectionGoal::None);
12735                });
12736            })
12737        }
12738        self.selection_mark_mode = true;
12739        cx.notify();
12740    }
12741
12742    pub fn swap_selection_ends(
12743        &mut self,
12744        _: &actions::SwapSelectionEnds,
12745        window: &mut Window,
12746        cx: &mut Context<Self>,
12747    ) {
12748        self.change_selections(None, window, cx, |s| {
12749            s.move_with(|_, sel| {
12750                if sel.start != sel.end {
12751                    sel.reversed = !sel.reversed
12752                }
12753            });
12754        });
12755        self.request_autoscroll(Autoscroll::newest(), cx);
12756        cx.notify();
12757    }
12758
12759    pub fn toggle_fold(
12760        &mut self,
12761        _: &actions::ToggleFold,
12762        window: &mut Window,
12763        cx: &mut Context<Self>,
12764    ) {
12765        if self.is_singleton(cx) {
12766            let selection = self.selections.newest::<Point>(cx);
12767
12768            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12769            let range = if selection.is_empty() {
12770                let point = selection.head().to_display_point(&display_map);
12771                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12772                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12773                    .to_point(&display_map);
12774                start..end
12775            } else {
12776                selection.range()
12777            };
12778            if display_map.folds_in_range(range).next().is_some() {
12779                self.unfold_lines(&Default::default(), window, cx)
12780            } else {
12781                self.fold(&Default::default(), window, cx)
12782            }
12783        } else {
12784            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12785            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12786                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12787                .map(|(snapshot, _, _)| snapshot.remote_id())
12788                .collect();
12789
12790            for buffer_id in buffer_ids {
12791                if self.is_buffer_folded(buffer_id, cx) {
12792                    self.unfold_buffer(buffer_id, cx);
12793                } else {
12794                    self.fold_buffer(buffer_id, cx);
12795                }
12796            }
12797        }
12798    }
12799
12800    pub fn toggle_fold_recursive(
12801        &mut self,
12802        _: &actions::ToggleFoldRecursive,
12803        window: &mut Window,
12804        cx: &mut Context<Self>,
12805    ) {
12806        let selection = self.selections.newest::<Point>(cx);
12807
12808        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12809        let range = if selection.is_empty() {
12810            let point = selection.head().to_display_point(&display_map);
12811            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12812            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12813                .to_point(&display_map);
12814            start..end
12815        } else {
12816            selection.range()
12817        };
12818        if display_map.folds_in_range(range).next().is_some() {
12819            self.unfold_recursive(&Default::default(), window, cx)
12820        } else {
12821            self.fold_recursive(&Default::default(), window, cx)
12822        }
12823    }
12824
12825    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12826        if self.is_singleton(cx) {
12827            let mut to_fold = Vec::new();
12828            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12829            let selections = self.selections.all_adjusted(cx);
12830
12831            for selection in selections {
12832                let range = selection.range().sorted();
12833                let buffer_start_row = range.start.row;
12834
12835                if range.start.row != range.end.row {
12836                    let mut found = false;
12837                    let mut row = range.start.row;
12838                    while row <= range.end.row {
12839                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12840                        {
12841                            found = true;
12842                            row = crease.range().end.row + 1;
12843                            to_fold.push(crease);
12844                        } else {
12845                            row += 1
12846                        }
12847                    }
12848                    if found {
12849                        continue;
12850                    }
12851                }
12852
12853                for row in (0..=range.start.row).rev() {
12854                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12855                        if crease.range().end.row >= buffer_start_row {
12856                            to_fold.push(crease);
12857                            if row <= range.start.row {
12858                                break;
12859                            }
12860                        }
12861                    }
12862                }
12863            }
12864
12865            self.fold_creases(to_fold, true, window, cx);
12866        } else {
12867            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12868
12869            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12870                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12871                .map(|(snapshot, _, _)| snapshot.remote_id())
12872                .collect();
12873            for buffer_id in buffer_ids {
12874                self.fold_buffer(buffer_id, cx);
12875            }
12876        }
12877    }
12878
12879    fn fold_at_level(
12880        &mut self,
12881        fold_at: &FoldAtLevel,
12882        window: &mut Window,
12883        cx: &mut Context<Self>,
12884    ) {
12885        if !self.buffer.read(cx).is_singleton() {
12886            return;
12887        }
12888
12889        let fold_at_level = fold_at.0;
12890        let snapshot = self.buffer.read(cx).snapshot(cx);
12891        let mut to_fold = Vec::new();
12892        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12893
12894        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12895            while start_row < end_row {
12896                match self
12897                    .snapshot(window, cx)
12898                    .crease_for_buffer_row(MultiBufferRow(start_row))
12899                {
12900                    Some(crease) => {
12901                        let nested_start_row = crease.range().start.row + 1;
12902                        let nested_end_row = crease.range().end.row;
12903
12904                        if current_level < fold_at_level {
12905                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12906                        } else if current_level == fold_at_level {
12907                            to_fold.push(crease);
12908                        }
12909
12910                        start_row = nested_end_row + 1;
12911                    }
12912                    None => start_row += 1,
12913                }
12914            }
12915        }
12916
12917        self.fold_creases(to_fold, true, window, cx);
12918    }
12919
12920    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12921        if self.buffer.read(cx).is_singleton() {
12922            let mut fold_ranges = Vec::new();
12923            let snapshot = self.buffer.read(cx).snapshot(cx);
12924
12925            for row in 0..snapshot.max_row().0 {
12926                if let Some(foldable_range) = self
12927                    .snapshot(window, cx)
12928                    .crease_for_buffer_row(MultiBufferRow(row))
12929                {
12930                    fold_ranges.push(foldable_range);
12931                }
12932            }
12933
12934            self.fold_creases(fold_ranges, true, window, cx);
12935        } else {
12936            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12937                editor
12938                    .update_in(&mut cx, |editor, _, cx| {
12939                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12940                            editor.fold_buffer(buffer_id, cx);
12941                        }
12942                    })
12943                    .ok();
12944            });
12945        }
12946    }
12947
12948    pub fn fold_function_bodies(
12949        &mut self,
12950        _: &actions::FoldFunctionBodies,
12951        window: &mut Window,
12952        cx: &mut Context<Self>,
12953    ) {
12954        let snapshot = self.buffer.read(cx).snapshot(cx);
12955
12956        let ranges = snapshot
12957            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12958            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12959            .collect::<Vec<_>>();
12960
12961        let creases = ranges
12962            .into_iter()
12963            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12964            .collect();
12965
12966        self.fold_creases(creases, true, window, cx);
12967    }
12968
12969    pub fn fold_recursive(
12970        &mut self,
12971        _: &actions::FoldRecursive,
12972        window: &mut Window,
12973        cx: &mut Context<Self>,
12974    ) {
12975        let mut to_fold = Vec::new();
12976        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12977        let selections = self.selections.all_adjusted(cx);
12978
12979        for selection in selections {
12980            let range = selection.range().sorted();
12981            let buffer_start_row = range.start.row;
12982
12983            if range.start.row != range.end.row {
12984                let mut found = false;
12985                for row in range.start.row..=range.end.row {
12986                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12987                        found = true;
12988                        to_fold.push(crease);
12989                    }
12990                }
12991                if found {
12992                    continue;
12993                }
12994            }
12995
12996            for row in (0..=range.start.row).rev() {
12997                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12998                    if crease.range().end.row >= buffer_start_row {
12999                        to_fold.push(crease);
13000                    } else {
13001                        break;
13002                    }
13003                }
13004            }
13005        }
13006
13007        self.fold_creases(to_fold, true, window, cx);
13008    }
13009
13010    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13011        let buffer_row = fold_at.buffer_row;
13012        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13013
13014        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13015            let autoscroll = self
13016                .selections
13017                .all::<Point>(cx)
13018                .iter()
13019                .any(|selection| crease.range().overlaps(&selection.range()));
13020
13021            self.fold_creases(vec![crease], autoscroll, window, cx);
13022        }
13023    }
13024
13025    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13026        if self.is_singleton(cx) {
13027            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13028            let buffer = &display_map.buffer_snapshot;
13029            let selections = self.selections.all::<Point>(cx);
13030            let ranges = selections
13031                .iter()
13032                .map(|s| {
13033                    let range = s.display_range(&display_map).sorted();
13034                    let mut start = range.start.to_point(&display_map);
13035                    let mut end = range.end.to_point(&display_map);
13036                    start.column = 0;
13037                    end.column = buffer.line_len(MultiBufferRow(end.row));
13038                    start..end
13039                })
13040                .collect::<Vec<_>>();
13041
13042            self.unfold_ranges(&ranges, true, true, cx);
13043        } else {
13044            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13045            let buffer_ids: HashSet<_> = multi_buffer_snapshot
13046                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
13047                .map(|(snapshot, _, _)| snapshot.remote_id())
13048                .collect();
13049            for buffer_id in buffer_ids {
13050                self.unfold_buffer(buffer_id, cx);
13051            }
13052        }
13053    }
13054
13055    pub fn unfold_recursive(
13056        &mut self,
13057        _: &UnfoldRecursive,
13058        _window: &mut Window,
13059        cx: &mut Context<Self>,
13060    ) {
13061        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13062        let selections = self.selections.all::<Point>(cx);
13063        let ranges = selections
13064            .iter()
13065            .map(|s| {
13066                let mut range = s.display_range(&display_map).sorted();
13067                *range.start.column_mut() = 0;
13068                *range.end.column_mut() = display_map.line_len(range.end.row());
13069                let start = range.start.to_point(&display_map);
13070                let end = range.end.to_point(&display_map);
13071                start..end
13072            })
13073            .collect::<Vec<_>>();
13074
13075        self.unfold_ranges(&ranges, true, true, cx);
13076    }
13077
13078    pub fn unfold_at(
13079        &mut self,
13080        unfold_at: &UnfoldAt,
13081        _window: &mut Window,
13082        cx: &mut Context<Self>,
13083    ) {
13084        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13085
13086        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13087            ..Point::new(
13088                unfold_at.buffer_row.0,
13089                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13090            );
13091
13092        let autoscroll = self
13093            .selections
13094            .all::<Point>(cx)
13095            .iter()
13096            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13097
13098        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13099    }
13100
13101    pub fn unfold_all(
13102        &mut self,
13103        _: &actions::UnfoldAll,
13104        _window: &mut Window,
13105        cx: &mut Context<Self>,
13106    ) {
13107        if self.buffer.read(cx).is_singleton() {
13108            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13109            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13110        } else {
13111            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13112                editor
13113                    .update(&mut cx, |editor, cx| {
13114                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13115                            editor.unfold_buffer(buffer_id, cx);
13116                        }
13117                    })
13118                    .ok();
13119            });
13120        }
13121    }
13122
13123    pub fn fold_selected_ranges(
13124        &mut self,
13125        _: &FoldSelectedRanges,
13126        window: &mut Window,
13127        cx: &mut Context<Self>,
13128    ) {
13129        let selections = self.selections.all::<Point>(cx);
13130        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13131        let line_mode = self.selections.line_mode;
13132        let ranges = selections
13133            .into_iter()
13134            .map(|s| {
13135                if line_mode {
13136                    let start = Point::new(s.start.row, 0);
13137                    let end = Point::new(
13138                        s.end.row,
13139                        display_map
13140                            .buffer_snapshot
13141                            .line_len(MultiBufferRow(s.end.row)),
13142                    );
13143                    Crease::simple(start..end, display_map.fold_placeholder.clone())
13144                } else {
13145                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13146                }
13147            })
13148            .collect::<Vec<_>>();
13149        self.fold_creases(ranges, true, window, cx);
13150    }
13151
13152    pub fn fold_ranges<T: ToOffset + Clone>(
13153        &mut self,
13154        ranges: Vec<Range<T>>,
13155        auto_scroll: bool,
13156        window: &mut Window,
13157        cx: &mut Context<Self>,
13158    ) {
13159        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13160        let ranges = ranges
13161            .into_iter()
13162            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13163            .collect::<Vec<_>>();
13164        self.fold_creases(ranges, auto_scroll, window, cx);
13165    }
13166
13167    pub fn fold_creases<T: ToOffset + Clone>(
13168        &mut self,
13169        creases: Vec<Crease<T>>,
13170        auto_scroll: bool,
13171        window: &mut Window,
13172        cx: &mut Context<Self>,
13173    ) {
13174        if creases.is_empty() {
13175            return;
13176        }
13177
13178        let mut buffers_affected = HashSet::default();
13179        let multi_buffer = self.buffer().read(cx);
13180        for crease in &creases {
13181            if let Some((_, buffer, _)) =
13182                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13183            {
13184                buffers_affected.insert(buffer.read(cx).remote_id());
13185            };
13186        }
13187
13188        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13189
13190        if auto_scroll {
13191            self.request_autoscroll(Autoscroll::fit(), cx);
13192        }
13193
13194        cx.notify();
13195
13196        if let Some(active_diagnostics) = self.active_diagnostics.take() {
13197            // Clear diagnostics block when folding a range that contains it.
13198            let snapshot = self.snapshot(window, cx);
13199            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13200                drop(snapshot);
13201                self.active_diagnostics = Some(active_diagnostics);
13202                self.dismiss_diagnostics(cx);
13203            } else {
13204                self.active_diagnostics = Some(active_diagnostics);
13205            }
13206        }
13207
13208        self.scrollbar_marker_state.dirty = true;
13209    }
13210
13211    /// Removes any folds whose ranges intersect any of the given ranges.
13212    pub fn unfold_ranges<T: ToOffset + Clone>(
13213        &mut self,
13214        ranges: &[Range<T>],
13215        inclusive: bool,
13216        auto_scroll: bool,
13217        cx: &mut Context<Self>,
13218    ) {
13219        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13220            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13221        });
13222    }
13223
13224    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13225        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13226            return;
13227        }
13228        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13229        self.display_map
13230            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
13231        cx.emit(EditorEvent::BufferFoldToggled {
13232            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13233            folded: true,
13234        });
13235        cx.notify();
13236    }
13237
13238    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13239        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13240            return;
13241        }
13242        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13243        self.display_map.update(cx, |display_map, cx| {
13244            display_map.unfold_buffer(buffer_id, cx);
13245        });
13246        cx.emit(EditorEvent::BufferFoldToggled {
13247            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13248            folded: false,
13249        });
13250        cx.notify();
13251    }
13252
13253    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13254        self.display_map.read(cx).is_buffer_folded(buffer)
13255    }
13256
13257    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13258        self.display_map.read(cx).folded_buffers()
13259    }
13260
13261    /// Removes any folds with the given ranges.
13262    pub fn remove_folds_with_type<T: ToOffset + Clone>(
13263        &mut self,
13264        ranges: &[Range<T>],
13265        type_id: TypeId,
13266        auto_scroll: bool,
13267        cx: &mut Context<Self>,
13268    ) {
13269        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13270            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13271        });
13272    }
13273
13274    fn remove_folds_with<T: ToOffset + Clone>(
13275        &mut self,
13276        ranges: &[Range<T>],
13277        auto_scroll: bool,
13278        cx: &mut Context<Self>,
13279        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13280    ) {
13281        if ranges.is_empty() {
13282            return;
13283        }
13284
13285        let mut buffers_affected = HashSet::default();
13286        let multi_buffer = self.buffer().read(cx);
13287        for range in ranges {
13288            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13289                buffers_affected.insert(buffer.read(cx).remote_id());
13290            };
13291        }
13292
13293        self.display_map.update(cx, update);
13294
13295        if auto_scroll {
13296            self.request_autoscroll(Autoscroll::fit(), cx);
13297        }
13298
13299        cx.notify();
13300        self.scrollbar_marker_state.dirty = true;
13301        self.active_indent_guides_state.dirty = true;
13302    }
13303
13304    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13305        self.display_map.read(cx).fold_placeholder.clone()
13306    }
13307
13308    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13309        self.buffer.update(cx, |buffer, cx| {
13310            buffer.set_all_diff_hunks_expanded(cx);
13311        });
13312    }
13313
13314    pub fn expand_all_diff_hunks(
13315        &mut self,
13316        _: &ExpandAllDiffHunks,
13317        _window: &mut Window,
13318        cx: &mut Context<Self>,
13319    ) {
13320        self.buffer.update(cx, |buffer, cx| {
13321            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13322        });
13323    }
13324
13325    pub fn toggle_selected_diff_hunks(
13326        &mut self,
13327        _: &ToggleSelectedDiffHunks,
13328        _window: &mut Window,
13329        cx: &mut Context<Self>,
13330    ) {
13331        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13332        self.toggle_diff_hunks_in_ranges(ranges, cx);
13333    }
13334
13335    pub fn diff_hunks_in_ranges<'a>(
13336        &'a self,
13337        ranges: &'a [Range<Anchor>],
13338        buffer: &'a MultiBufferSnapshot,
13339    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13340        ranges.iter().flat_map(move |range| {
13341            let end_excerpt_id = range.end.excerpt_id;
13342            let range = range.to_point(buffer);
13343            let mut peek_end = range.end;
13344            if range.end.row < buffer.max_row().0 {
13345                peek_end = Point::new(range.end.row + 1, 0);
13346            }
13347            buffer
13348                .diff_hunks_in_range(range.start..peek_end)
13349                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13350        })
13351    }
13352
13353    pub fn has_stageable_diff_hunks_in_ranges(
13354        &self,
13355        ranges: &[Range<Anchor>],
13356        snapshot: &MultiBufferSnapshot,
13357    ) -> bool {
13358        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13359        hunks.any(|hunk| hunk.secondary_status != DiffHunkSecondaryStatus::None)
13360    }
13361
13362    pub fn toggle_staged_selected_diff_hunks(
13363        &mut self,
13364        _: &::git::ToggleStaged,
13365        _window: &mut Window,
13366        cx: &mut Context<Self>,
13367    ) {
13368        let snapshot = self.buffer.read(cx).snapshot(cx);
13369        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13370        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13371        self.stage_or_unstage_diff_hunks(stage, &ranges, cx);
13372    }
13373
13374    pub fn stage_and_next(
13375        &mut self,
13376        _: &::git::StageAndNext,
13377        window: &mut Window,
13378        cx: &mut Context<Self>,
13379    ) {
13380        self.do_stage_or_unstage_and_next(true, window, cx);
13381    }
13382
13383    pub fn unstage_and_next(
13384        &mut self,
13385        _: &::git::UnstageAndNext,
13386        window: &mut Window,
13387        cx: &mut Context<Self>,
13388    ) {
13389        self.do_stage_or_unstage_and_next(false, window, cx);
13390    }
13391
13392    pub fn stage_or_unstage_diff_hunks(
13393        &mut self,
13394        stage: bool,
13395        ranges: &[Range<Anchor>],
13396        cx: &mut Context<Self>,
13397    ) {
13398        let snapshot = self.buffer.read(cx).snapshot(cx);
13399        let Some(project) = &self.project else {
13400            return;
13401        };
13402
13403        let chunk_by = self
13404            .diff_hunks_in_ranges(&ranges, &snapshot)
13405            .chunk_by(|hunk| hunk.buffer_id);
13406        for (buffer_id, hunks) in &chunk_by {
13407            Self::do_stage_or_unstage(project, stage, buffer_id, hunks, &snapshot, cx);
13408        }
13409    }
13410
13411    fn do_stage_or_unstage_and_next(
13412        &mut self,
13413        stage: bool,
13414        window: &mut Window,
13415        cx: &mut Context<Self>,
13416    ) {
13417        let mut ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13418        if ranges.iter().any(|range| range.start != range.end) {
13419            self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13420            return;
13421        }
13422
13423        if !self.buffer().read(cx).is_singleton() {
13424            if let Some((excerpt_id, buffer, range)) = self.active_excerpt(cx) {
13425                if buffer.read(cx).is_empty() {
13426                    let buffer = buffer.read(cx);
13427                    let Some(file) = buffer.file() else {
13428                        return;
13429                    };
13430                    let project_path = project::ProjectPath {
13431                        worktree_id: file.worktree_id(cx),
13432                        path: file.path().clone(),
13433                    };
13434                    let Some(project) = self.project.as_ref() else {
13435                        return;
13436                    };
13437                    let project = project.read(cx);
13438
13439                    let Some(repo) = project.git_store().read(cx).active_repository() else {
13440                        return;
13441                    };
13442
13443                    repo.update(cx, |repo, cx| {
13444                        let Some(repo_path) = repo.project_path_to_repo_path(&project_path) else {
13445                            return;
13446                        };
13447                        let Some(status) = repo.repository_entry.status_for_path(&repo_path) else {
13448                            return;
13449                        };
13450                        if stage && status.status == FileStatus::Untracked {
13451                            repo.stage_entries(vec![repo_path], cx)
13452                                .detach_and_log_err(cx);
13453                            return;
13454                        }
13455                    })
13456                }
13457                ranges = vec![multi_buffer::Anchor::range_in_buffer(
13458                    excerpt_id,
13459                    buffer.read(cx).remote_id(),
13460                    range,
13461                )];
13462                self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13463                let snapshot = self.buffer().read(cx).snapshot(cx);
13464                let mut point = ranges.last().unwrap().end.to_point(&snapshot);
13465                if point.row < snapshot.max_row().0 {
13466                    point.row += 1;
13467                    point.column = 0;
13468                    point = snapshot.clip_point(point, Bias::Right);
13469                    self.change_selections(Some(Autoscroll::top_relative(6)), window, cx, |s| {
13470                        s.select_ranges([point..point]);
13471                    })
13472                }
13473                return;
13474            }
13475        }
13476        self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13477        self.go_to_next_hunk(&Default::default(), window, cx);
13478    }
13479
13480    fn do_stage_or_unstage(
13481        project: &Entity<Project>,
13482        stage: bool,
13483        buffer_id: BufferId,
13484        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13485        snapshot: &MultiBufferSnapshot,
13486        cx: &mut App,
13487    ) {
13488        let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
13489            log::debug!("no buffer for id");
13490            return;
13491        };
13492        let buffer_snapshot = buffer.read(cx).snapshot();
13493        let file_exists = buffer_snapshot
13494            .file()
13495            .is_some_and(|file| file.disk_state().exists());
13496        let Some((repo, path)) = project
13497            .read(cx)
13498            .repository_and_path_for_buffer_id(buffer_id, cx)
13499        else {
13500            log::debug!("no git repo for buffer id");
13501            return;
13502        };
13503        let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
13504            log::debug!("no diff for buffer id");
13505            return;
13506        };
13507
13508        let new_index_text = if !stage && diff.is_single_insertion || stage && !file_exists {
13509            log::debug!("removing from index");
13510            None
13511        } else {
13512            diff.new_secondary_text_for_stage_or_unstage(
13513                stage,
13514                hunks.filter_map(|hunk| {
13515                    if stage && hunk.secondary_status == DiffHunkSecondaryStatus::None {
13516                        return None;
13517                    } else if !stage
13518                        && hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
13519                    {
13520                        return None;
13521                    }
13522                    Some((hunk.buffer_range.clone(), hunk.diff_base_byte_range.clone()))
13523                }),
13524                &buffer_snapshot,
13525                cx,
13526            )
13527        };
13528
13529        if file_exists {
13530            let buffer_store = project.read(cx).buffer_store().clone();
13531            buffer_store
13532                .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
13533                .detach_and_log_err(cx);
13534        }
13535
13536        cx.background_spawn(
13537            repo.read(cx)
13538                .set_index_text(&path, new_index_text.map(|rope| rope.to_string()))
13539                .log_err(),
13540        )
13541        .detach();
13542    }
13543
13544    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13545        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13546        self.buffer
13547            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13548    }
13549
13550    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13551        self.buffer.update(cx, |buffer, cx| {
13552            let ranges = vec![Anchor::min()..Anchor::max()];
13553            if !buffer.all_diff_hunks_expanded()
13554                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13555            {
13556                buffer.collapse_diff_hunks(ranges, cx);
13557                true
13558            } else {
13559                false
13560            }
13561        })
13562    }
13563
13564    fn toggle_diff_hunks_in_ranges(
13565        &mut self,
13566        ranges: Vec<Range<Anchor>>,
13567        cx: &mut Context<'_, Editor>,
13568    ) {
13569        self.buffer.update(cx, |buffer, cx| {
13570            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13571            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13572        })
13573    }
13574
13575    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13576        self.buffer.update(cx, |buffer, cx| {
13577            let snapshot = buffer.snapshot(cx);
13578            let excerpt_id = range.end.excerpt_id;
13579            let point_range = range.to_point(&snapshot);
13580            let expand = !buffer.single_hunk_is_expanded(range, cx);
13581            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13582        })
13583    }
13584
13585    pub(crate) fn apply_all_diff_hunks(
13586        &mut self,
13587        _: &ApplyAllDiffHunks,
13588        window: &mut Window,
13589        cx: &mut Context<Self>,
13590    ) {
13591        let buffers = self.buffer.read(cx).all_buffers();
13592        for branch_buffer in buffers {
13593            branch_buffer.update(cx, |branch_buffer, cx| {
13594                branch_buffer.merge_into_base(Vec::new(), cx);
13595            });
13596        }
13597
13598        if let Some(project) = self.project.clone() {
13599            self.save(true, project, window, cx).detach_and_log_err(cx);
13600        }
13601    }
13602
13603    pub(crate) fn apply_selected_diff_hunks(
13604        &mut self,
13605        _: &ApplyDiffHunk,
13606        window: &mut Window,
13607        cx: &mut Context<Self>,
13608    ) {
13609        let snapshot = self.snapshot(window, cx);
13610        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
13611        let mut ranges_by_buffer = HashMap::default();
13612        self.transact(window, cx, |editor, _window, cx| {
13613            for hunk in hunks {
13614                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13615                    ranges_by_buffer
13616                        .entry(buffer.clone())
13617                        .or_insert_with(Vec::new)
13618                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13619                }
13620            }
13621
13622            for (buffer, ranges) in ranges_by_buffer {
13623                buffer.update(cx, |buffer, cx| {
13624                    buffer.merge_into_base(ranges, cx);
13625                });
13626            }
13627        });
13628
13629        if let Some(project) = self.project.clone() {
13630            self.save(true, project, window, cx).detach_and_log_err(cx);
13631        }
13632    }
13633
13634    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13635        if hovered != self.gutter_hovered {
13636            self.gutter_hovered = hovered;
13637            cx.notify();
13638        }
13639    }
13640
13641    pub fn insert_blocks(
13642        &mut self,
13643        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13644        autoscroll: Option<Autoscroll>,
13645        cx: &mut Context<Self>,
13646    ) -> Vec<CustomBlockId> {
13647        let blocks = self
13648            .display_map
13649            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13650        if let Some(autoscroll) = autoscroll {
13651            self.request_autoscroll(autoscroll, cx);
13652        }
13653        cx.notify();
13654        blocks
13655    }
13656
13657    pub fn resize_blocks(
13658        &mut self,
13659        heights: HashMap<CustomBlockId, u32>,
13660        autoscroll: Option<Autoscroll>,
13661        cx: &mut Context<Self>,
13662    ) {
13663        self.display_map
13664            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13665        if let Some(autoscroll) = autoscroll {
13666            self.request_autoscroll(autoscroll, cx);
13667        }
13668        cx.notify();
13669    }
13670
13671    pub fn replace_blocks(
13672        &mut self,
13673        renderers: HashMap<CustomBlockId, RenderBlock>,
13674        autoscroll: Option<Autoscroll>,
13675        cx: &mut Context<Self>,
13676    ) {
13677        self.display_map
13678            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13679        if let Some(autoscroll) = autoscroll {
13680            self.request_autoscroll(autoscroll, cx);
13681        }
13682        cx.notify();
13683    }
13684
13685    pub fn remove_blocks(
13686        &mut self,
13687        block_ids: HashSet<CustomBlockId>,
13688        autoscroll: Option<Autoscroll>,
13689        cx: &mut Context<Self>,
13690    ) {
13691        self.display_map.update(cx, |display_map, cx| {
13692            display_map.remove_blocks(block_ids, cx)
13693        });
13694        if let Some(autoscroll) = autoscroll {
13695            self.request_autoscroll(autoscroll, cx);
13696        }
13697        cx.notify();
13698    }
13699
13700    pub fn row_for_block(
13701        &self,
13702        block_id: CustomBlockId,
13703        cx: &mut Context<Self>,
13704    ) -> Option<DisplayRow> {
13705        self.display_map
13706            .update(cx, |map, cx| map.row_for_block(block_id, cx))
13707    }
13708
13709    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13710        self.focused_block = Some(focused_block);
13711    }
13712
13713    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13714        self.focused_block.take()
13715    }
13716
13717    pub fn insert_creases(
13718        &mut self,
13719        creases: impl IntoIterator<Item = Crease<Anchor>>,
13720        cx: &mut Context<Self>,
13721    ) -> Vec<CreaseId> {
13722        self.display_map
13723            .update(cx, |map, cx| map.insert_creases(creases, cx))
13724    }
13725
13726    pub fn remove_creases(
13727        &mut self,
13728        ids: impl IntoIterator<Item = CreaseId>,
13729        cx: &mut Context<Self>,
13730    ) {
13731        self.display_map
13732            .update(cx, |map, cx| map.remove_creases(ids, cx));
13733    }
13734
13735    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13736        self.display_map
13737            .update(cx, |map, cx| map.snapshot(cx))
13738            .longest_row()
13739    }
13740
13741    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13742        self.display_map
13743            .update(cx, |map, cx| map.snapshot(cx))
13744            .max_point()
13745    }
13746
13747    pub fn text(&self, cx: &App) -> String {
13748        self.buffer.read(cx).read(cx).text()
13749    }
13750
13751    pub fn is_empty(&self, cx: &App) -> bool {
13752        self.buffer.read(cx).read(cx).is_empty()
13753    }
13754
13755    pub fn text_option(&self, cx: &App) -> Option<String> {
13756        let text = self.text(cx);
13757        let text = text.trim();
13758
13759        if text.is_empty() {
13760            return None;
13761        }
13762
13763        Some(text.to_string())
13764    }
13765
13766    pub fn set_text(
13767        &mut self,
13768        text: impl Into<Arc<str>>,
13769        window: &mut Window,
13770        cx: &mut Context<Self>,
13771    ) {
13772        self.transact(window, cx, |this, _, cx| {
13773            this.buffer
13774                .read(cx)
13775                .as_singleton()
13776                .expect("you can only call set_text on editors for singleton buffers")
13777                .update(cx, |buffer, cx| buffer.set_text(text, cx));
13778        });
13779    }
13780
13781    pub fn display_text(&self, cx: &mut App) -> String {
13782        self.display_map
13783            .update(cx, |map, cx| map.snapshot(cx))
13784            .text()
13785    }
13786
13787    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
13788        let mut wrap_guides = smallvec::smallvec![];
13789
13790        if self.show_wrap_guides == Some(false) {
13791            return wrap_guides;
13792        }
13793
13794        let settings = self.buffer.read(cx).settings_at(0, cx);
13795        if settings.show_wrap_guides {
13796            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
13797                wrap_guides.push((soft_wrap as usize, true));
13798            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
13799                wrap_guides.push((soft_wrap as usize, true));
13800            }
13801            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
13802        }
13803
13804        wrap_guides
13805    }
13806
13807    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
13808        let settings = self.buffer.read(cx).settings_at(0, cx);
13809        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
13810        match mode {
13811            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
13812                SoftWrap::None
13813            }
13814            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13815            language_settings::SoftWrap::PreferredLineLength => {
13816                SoftWrap::Column(settings.preferred_line_length)
13817            }
13818            language_settings::SoftWrap::Bounded => {
13819                SoftWrap::Bounded(settings.preferred_line_length)
13820            }
13821        }
13822    }
13823
13824    pub fn set_soft_wrap_mode(
13825        &mut self,
13826        mode: language_settings::SoftWrap,
13827
13828        cx: &mut Context<Self>,
13829    ) {
13830        self.soft_wrap_mode_override = Some(mode);
13831        cx.notify();
13832    }
13833
13834    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13835        self.text_style_refinement = Some(style);
13836    }
13837
13838    /// called by the Element so we know what style we were most recently rendered with.
13839    pub(crate) fn set_style(
13840        &mut self,
13841        style: EditorStyle,
13842        window: &mut Window,
13843        cx: &mut Context<Self>,
13844    ) {
13845        let rem_size = window.rem_size();
13846        self.display_map.update(cx, |map, cx| {
13847            map.set_font(
13848                style.text.font(),
13849                style.text.font_size.to_pixels(rem_size),
13850                cx,
13851            )
13852        });
13853        self.style = Some(style);
13854    }
13855
13856    pub fn style(&self) -> Option<&EditorStyle> {
13857        self.style.as_ref()
13858    }
13859
13860    // Called by the element. This method is not designed to be called outside of the editor
13861    // element's layout code because it does not notify when rewrapping is computed synchronously.
13862    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13863        self.display_map
13864            .update(cx, |map, cx| map.set_wrap_width(width, cx))
13865    }
13866
13867    pub fn set_soft_wrap(&mut self) {
13868        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13869    }
13870
13871    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13872        if self.soft_wrap_mode_override.is_some() {
13873            self.soft_wrap_mode_override.take();
13874        } else {
13875            let soft_wrap = match self.soft_wrap_mode(cx) {
13876                SoftWrap::GitDiff => return,
13877                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13878                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13879                    language_settings::SoftWrap::None
13880                }
13881            };
13882            self.soft_wrap_mode_override = Some(soft_wrap);
13883        }
13884        cx.notify();
13885    }
13886
13887    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13888        let Some(workspace) = self.workspace() else {
13889            return;
13890        };
13891        let fs = workspace.read(cx).app_state().fs.clone();
13892        let current_show = TabBarSettings::get_global(cx).show;
13893        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13894            setting.show = Some(!current_show);
13895        });
13896    }
13897
13898    pub fn toggle_indent_guides(
13899        &mut self,
13900        _: &ToggleIndentGuides,
13901        _: &mut Window,
13902        cx: &mut Context<Self>,
13903    ) {
13904        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13905            self.buffer
13906                .read(cx)
13907                .settings_at(0, cx)
13908                .indent_guides
13909                .enabled
13910        });
13911        self.show_indent_guides = Some(!currently_enabled);
13912        cx.notify();
13913    }
13914
13915    fn should_show_indent_guides(&self) -> Option<bool> {
13916        self.show_indent_guides
13917    }
13918
13919    pub fn toggle_line_numbers(
13920        &mut self,
13921        _: &ToggleLineNumbers,
13922        _: &mut Window,
13923        cx: &mut Context<Self>,
13924    ) {
13925        let mut editor_settings = EditorSettings::get_global(cx).clone();
13926        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13927        EditorSettings::override_global(editor_settings, cx);
13928    }
13929
13930    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13931        self.use_relative_line_numbers
13932            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13933    }
13934
13935    pub fn toggle_relative_line_numbers(
13936        &mut self,
13937        _: &ToggleRelativeLineNumbers,
13938        _: &mut Window,
13939        cx: &mut Context<Self>,
13940    ) {
13941        let is_relative = self.should_use_relative_line_numbers(cx);
13942        self.set_relative_line_number(Some(!is_relative), cx)
13943    }
13944
13945    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13946        self.use_relative_line_numbers = is_relative;
13947        cx.notify();
13948    }
13949
13950    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13951        self.show_gutter = show_gutter;
13952        cx.notify();
13953    }
13954
13955    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13956        self.show_scrollbars = show_scrollbars;
13957        cx.notify();
13958    }
13959
13960    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13961        self.show_line_numbers = Some(show_line_numbers);
13962        cx.notify();
13963    }
13964
13965    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13966        self.show_git_diff_gutter = Some(show_git_diff_gutter);
13967        cx.notify();
13968    }
13969
13970    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13971        self.show_code_actions = Some(show_code_actions);
13972        cx.notify();
13973    }
13974
13975    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13976        self.show_runnables = Some(show_runnables);
13977        cx.notify();
13978    }
13979
13980    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13981        if self.display_map.read(cx).masked != masked {
13982            self.display_map.update(cx, |map, _| map.masked = masked);
13983        }
13984        cx.notify()
13985    }
13986
13987    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13988        self.show_wrap_guides = Some(show_wrap_guides);
13989        cx.notify();
13990    }
13991
13992    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13993        self.show_indent_guides = Some(show_indent_guides);
13994        cx.notify();
13995    }
13996
13997    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13998        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13999            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14000                if let Some(dir) = file.abs_path(cx).parent() {
14001                    return Some(dir.to_owned());
14002                }
14003            }
14004
14005            if let Some(project_path) = buffer.read(cx).project_path(cx) {
14006                return Some(project_path.path.to_path_buf());
14007            }
14008        }
14009
14010        None
14011    }
14012
14013    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14014        self.active_excerpt(cx)?
14015            .1
14016            .read(cx)
14017            .file()
14018            .and_then(|f| f.as_local())
14019    }
14020
14021    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14022        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14023            let buffer = buffer.read(cx);
14024            if let Some(project_path) = buffer.project_path(cx) {
14025                let project = self.project.as_ref()?.read(cx);
14026                project.absolute_path(&project_path, cx)
14027            } else {
14028                buffer
14029                    .file()
14030                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14031            }
14032        })
14033    }
14034
14035    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14036        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14037            let project_path = buffer.read(cx).project_path(cx)?;
14038            let project = self.project.as_ref()?.read(cx);
14039            let entry = project.entry_for_path(&project_path, cx)?;
14040            let path = entry.path.to_path_buf();
14041            Some(path)
14042        })
14043    }
14044
14045    pub fn reveal_in_finder(
14046        &mut self,
14047        _: &RevealInFileManager,
14048        _window: &mut Window,
14049        cx: &mut Context<Self>,
14050    ) {
14051        if let Some(target) = self.target_file(cx) {
14052            cx.reveal_path(&target.abs_path(cx));
14053        }
14054    }
14055
14056    pub fn copy_path(
14057        &mut self,
14058        _: &zed_actions::workspace::CopyPath,
14059        _window: &mut Window,
14060        cx: &mut Context<Self>,
14061    ) {
14062        if let Some(path) = self.target_file_abs_path(cx) {
14063            if let Some(path) = path.to_str() {
14064                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14065            }
14066        }
14067    }
14068
14069    pub fn copy_relative_path(
14070        &mut self,
14071        _: &zed_actions::workspace::CopyRelativePath,
14072        _window: &mut Window,
14073        cx: &mut Context<Self>,
14074    ) {
14075        if let Some(path) = self.target_file_path(cx) {
14076            if let Some(path) = path.to_str() {
14077                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14078            }
14079        }
14080    }
14081
14082    pub fn copy_file_name_without_extension(
14083        &mut self,
14084        _: &CopyFileNameWithoutExtension,
14085        _: &mut Window,
14086        cx: &mut Context<Self>,
14087    ) {
14088        if let Some(file) = self.target_file(cx) {
14089            if let Some(file_stem) = file.path().file_stem() {
14090                if let Some(name) = file_stem.to_str() {
14091                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14092                }
14093            }
14094        }
14095    }
14096
14097    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14098        if let Some(file) = self.target_file(cx) {
14099            if let Some(file_name) = file.path().file_name() {
14100                if let Some(name) = file_name.to_str() {
14101                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14102                }
14103            }
14104        }
14105    }
14106
14107    pub fn toggle_git_blame(
14108        &mut self,
14109        _: &ToggleGitBlame,
14110        window: &mut Window,
14111        cx: &mut Context<Self>,
14112    ) {
14113        self.show_git_blame_gutter = !self.show_git_blame_gutter;
14114
14115        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14116            self.start_git_blame(true, window, cx);
14117        }
14118
14119        cx.notify();
14120    }
14121
14122    pub fn toggle_git_blame_inline(
14123        &mut self,
14124        _: &ToggleGitBlameInline,
14125        window: &mut Window,
14126        cx: &mut Context<Self>,
14127    ) {
14128        self.toggle_git_blame_inline_internal(true, window, cx);
14129        cx.notify();
14130    }
14131
14132    pub fn git_blame_inline_enabled(&self) -> bool {
14133        self.git_blame_inline_enabled
14134    }
14135
14136    pub fn toggle_selection_menu(
14137        &mut self,
14138        _: &ToggleSelectionMenu,
14139        _: &mut Window,
14140        cx: &mut Context<Self>,
14141    ) {
14142        self.show_selection_menu = self
14143            .show_selection_menu
14144            .map(|show_selections_menu| !show_selections_menu)
14145            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14146
14147        cx.notify();
14148    }
14149
14150    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14151        self.show_selection_menu
14152            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14153    }
14154
14155    fn start_git_blame(
14156        &mut self,
14157        user_triggered: bool,
14158        window: &mut Window,
14159        cx: &mut Context<Self>,
14160    ) {
14161        if let Some(project) = self.project.as_ref() {
14162            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14163                return;
14164            };
14165
14166            if buffer.read(cx).file().is_none() {
14167                return;
14168            }
14169
14170            let focused = self.focus_handle(cx).contains_focused(window, cx);
14171
14172            let project = project.clone();
14173            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14174            self.blame_subscription =
14175                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14176            self.blame = Some(blame);
14177        }
14178    }
14179
14180    fn toggle_git_blame_inline_internal(
14181        &mut self,
14182        user_triggered: bool,
14183        window: &mut Window,
14184        cx: &mut Context<Self>,
14185    ) {
14186        if self.git_blame_inline_enabled {
14187            self.git_blame_inline_enabled = false;
14188            self.show_git_blame_inline = false;
14189            self.show_git_blame_inline_delay_task.take();
14190        } else {
14191            self.git_blame_inline_enabled = true;
14192            self.start_git_blame_inline(user_triggered, window, cx);
14193        }
14194
14195        cx.notify();
14196    }
14197
14198    fn start_git_blame_inline(
14199        &mut self,
14200        user_triggered: bool,
14201        window: &mut Window,
14202        cx: &mut Context<Self>,
14203    ) {
14204        self.start_git_blame(user_triggered, window, cx);
14205
14206        if ProjectSettings::get_global(cx)
14207            .git
14208            .inline_blame_delay()
14209            .is_some()
14210        {
14211            self.start_inline_blame_timer(window, cx);
14212        } else {
14213            self.show_git_blame_inline = true
14214        }
14215    }
14216
14217    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14218        self.blame.as_ref()
14219    }
14220
14221    pub fn show_git_blame_gutter(&self) -> bool {
14222        self.show_git_blame_gutter
14223    }
14224
14225    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14226        self.show_git_blame_gutter && self.has_blame_entries(cx)
14227    }
14228
14229    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14230        self.show_git_blame_inline
14231            && (self.focus_handle.is_focused(window)
14232                || self
14233                    .git_blame_inline_tooltip
14234                    .as_ref()
14235                    .and_then(|t| t.upgrade())
14236                    .is_some())
14237            && !self.newest_selection_head_on_empty_line(cx)
14238            && self.has_blame_entries(cx)
14239    }
14240
14241    fn has_blame_entries(&self, cx: &App) -> bool {
14242        self.blame()
14243            .map_or(false, |blame| blame.read(cx).has_generated_entries())
14244    }
14245
14246    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14247        let cursor_anchor = self.selections.newest_anchor().head();
14248
14249        let snapshot = self.buffer.read(cx).snapshot(cx);
14250        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14251
14252        snapshot.line_len(buffer_row) == 0
14253    }
14254
14255    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14256        let buffer_and_selection = maybe!({
14257            let selection = self.selections.newest::<Point>(cx);
14258            let selection_range = selection.range();
14259
14260            let multi_buffer = self.buffer().read(cx);
14261            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14262            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14263
14264            let (buffer, range, _) = if selection.reversed {
14265                buffer_ranges.first()
14266            } else {
14267                buffer_ranges.last()
14268            }?;
14269
14270            let selection = text::ToPoint::to_point(&range.start, &buffer).row
14271                ..text::ToPoint::to_point(&range.end, &buffer).row;
14272            Some((
14273                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14274                selection,
14275            ))
14276        });
14277
14278        let Some((buffer, selection)) = buffer_and_selection else {
14279            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14280        };
14281
14282        let Some(project) = self.project.as_ref() else {
14283            return Task::ready(Err(anyhow!("editor does not have project")));
14284        };
14285
14286        project.update(cx, |project, cx| {
14287            project.get_permalink_to_line(&buffer, selection, cx)
14288        })
14289    }
14290
14291    pub fn copy_permalink_to_line(
14292        &mut self,
14293        _: &CopyPermalinkToLine,
14294        window: &mut Window,
14295        cx: &mut Context<Self>,
14296    ) {
14297        let permalink_task = self.get_permalink_to_line(cx);
14298        let workspace = self.workspace();
14299
14300        cx.spawn_in(window, |_, mut cx| async move {
14301            match permalink_task.await {
14302                Ok(permalink) => {
14303                    cx.update(|_, cx| {
14304                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14305                    })
14306                    .ok();
14307                }
14308                Err(err) => {
14309                    let message = format!("Failed to copy permalink: {err}");
14310
14311                    Err::<(), anyhow::Error>(err).log_err();
14312
14313                    if let Some(workspace) = workspace {
14314                        workspace
14315                            .update_in(&mut cx, |workspace, _, cx| {
14316                                struct CopyPermalinkToLine;
14317
14318                                workspace.show_toast(
14319                                    Toast::new(
14320                                        NotificationId::unique::<CopyPermalinkToLine>(),
14321                                        message,
14322                                    ),
14323                                    cx,
14324                                )
14325                            })
14326                            .ok();
14327                    }
14328                }
14329            }
14330        })
14331        .detach();
14332    }
14333
14334    pub fn copy_file_location(
14335        &mut self,
14336        _: &CopyFileLocation,
14337        _: &mut Window,
14338        cx: &mut Context<Self>,
14339    ) {
14340        let selection = self.selections.newest::<Point>(cx).start.row + 1;
14341        if let Some(file) = self.target_file(cx) {
14342            if let Some(path) = file.path().to_str() {
14343                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14344            }
14345        }
14346    }
14347
14348    pub fn open_permalink_to_line(
14349        &mut self,
14350        _: &OpenPermalinkToLine,
14351        window: &mut Window,
14352        cx: &mut Context<Self>,
14353    ) {
14354        let permalink_task = self.get_permalink_to_line(cx);
14355        let workspace = self.workspace();
14356
14357        cx.spawn_in(window, |_, mut cx| async move {
14358            match permalink_task.await {
14359                Ok(permalink) => {
14360                    cx.update(|_, cx| {
14361                        cx.open_url(permalink.as_ref());
14362                    })
14363                    .ok();
14364                }
14365                Err(err) => {
14366                    let message = format!("Failed to open permalink: {err}");
14367
14368                    Err::<(), anyhow::Error>(err).log_err();
14369
14370                    if let Some(workspace) = workspace {
14371                        workspace
14372                            .update(&mut cx, |workspace, cx| {
14373                                struct OpenPermalinkToLine;
14374
14375                                workspace.show_toast(
14376                                    Toast::new(
14377                                        NotificationId::unique::<OpenPermalinkToLine>(),
14378                                        message,
14379                                    ),
14380                                    cx,
14381                                )
14382                            })
14383                            .ok();
14384                    }
14385                }
14386            }
14387        })
14388        .detach();
14389    }
14390
14391    pub fn insert_uuid_v4(
14392        &mut self,
14393        _: &InsertUuidV4,
14394        window: &mut Window,
14395        cx: &mut Context<Self>,
14396    ) {
14397        self.insert_uuid(UuidVersion::V4, window, cx);
14398    }
14399
14400    pub fn insert_uuid_v7(
14401        &mut self,
14402        _: &InsertUuidV7,
14403        window: &mut Window,
14404        cx: &mut Context<Self>,
14405    ) {
14406        self.insert_uuid(UuidVersion::V7, window, cx);
14407    }
14408
14409    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14410        self.transact(window, cx, |this, window, cx| {
14411            let edits = this
14412                .selections
14413                .all::<Point>(cx)
14414                .into_iter()
14415                .map(|selection| {
14416                    let uuid = match version {
14417                        UuidVersion::V4 => uuid::Uuid::new_v4(),
14418                        UuidVersion::V7 => uuid::Uuid::now_v7(),
14419                    };
14420
14421                    (selection.range(), uuid.to_string())
14422                });
14423            this.edit(edits, cx);
14424            this.refresh_inline_completion(true, false, window, cx);
14425        });
14426    }
14427
14428    pub fn open_selections_in_multibuffer(
14429        &mut self,
14430        _: &OpenSelectionsInMultibuffer,
14431        window: &mut Window,
14432        cx: &mut Context<Self>,
14433    ) {
14434        let multibuffer = self.buffer.read(cx);
14435
14436        let Some(buffer) = multibuffer.as_singleton() else {
14437            return;
14438        };
14439
14440        let Some(workspace) = self.workspace() else {
14441            return;
14442        };
14443
14444        let locations = self
14445            .selections
14446            .disjoint_anchors()
14447            .iter()
14448            .map(|range| Location {
14449                buffer: buffer.clone(),
14450                range: range.start.text_anchor..range.end.text_anchor,
14451            })
14452            .collect::<Vec<_>>();
14453
14454        let title = multibuffer.title(cx).to_string();
14455
14456        cx.spawn_in(window, |_, mut cx| async move {
14457            workspace.update_in(&mut cx, |workspace, window, cx| {
14458                Self::open_locations_in_multibuffer(
14459                    workspace,
14460                    locations,
14461                    format!("Selections for '{title}'"),
14462                    false,
14463                    MultibufferSelectionMode::All,
14464                    window,
14465                    cx,
14466                );
14467            })
14468        })
14469        .detach();
14470    }
14471
14472    /// Adds a row highlight for the given range. If a row has multiple highlights, the
14473    /// last highlight added will be used.
14474    ///
14475    /// If the range ends at the beginning of a line, then that line will not be highlighted.
14476    pub fn highlight_rows<T: 'static>(
14477        &mut self,
14478        range: Range<Anchor>,
14479        color: Hsla,
14480        should_autoscroll: bool,
14481        cx: &mut Context<Self>,
14482    ) {
14483        let snapshot = self.buffer().read(cx).snapshot(cx);
14484        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14485        let ix = row_highlights.binary_search_by(|highlight| {
14486            Ordering::Equal
14487                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14488                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14489        });
14490
14491        if let Err(mut ix) = ix {
14492            let index = post_inc(&mut self.highlight_order);
14493
14494            // If this range intersects with the preceding highlight, then merge it with
14495            // the preceding highlight. Otherwise insert a new highlight.
14496            let mut merged = false;
14497            if ix > 0 {
14498                let prev_highlight = &mut row_highlights[ix - 1];
14499                if prev_highlight
14500                    .range
14501                    .end
14502                    .cmp(&range.start, &snapshot)
14503                    .is_ge()
14504                {
14505                    ix -= 1;
14506                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14507                        prev_highlight.range.end = range.end;
14508                    }
14509                    merged = true;
14510                    prev_highlight.index = index;
14511                    prev_highlight.color = color;
14512                    prev_highlight.should_autoscroll = should_autoscroll;
14513                }
14514            }
14515
14516            if !merged {
14517                row_highlights.insert(
14518                    ix,
14519                    RowHighlight {
14520                        range: range.clone(),
14521                        index,
14522                        color,
14523                        should_autoscroll,
14524                    },
14525                );
14526            }
14527
14528            // If any of the following highlights intersect with this one, merge them.
14529            while let Some(next_highlight) = row_highlights.get(ix + 1) {
14530                let highlight = &row_highlights[ix];
14531                if next_highlight
14532                    .range
14533                    .start
14534                    .cmp(&highlight.range.end, &snapshot)
14535                    .is_le()
14536                {
14537                    if next_highlight
14538                        .range
14539                        .end
14540                        .cmp(&highlight.range.end, &snapshot)
14541                        .is_gt()
14542                    {
14543                        row_highlights[ix].range.end = next_highlight.range.end;
14544                    }
14545                    row_highlights.remove(ix + 1);
14546                } else {
14547                    break;
14548                }
14549            }
14550        }
14551    }
14552
14553    /// Remove any highlighted row ranges of the given type that intersect the
14554    /// given ranges.
14555    pub fn remove_highlighted_rows<T: 'static>(
14556        &mut self,
14557        ranges_to_remove: Vec<Range<Anchor>>,
14558        cx: &mut Context<Self>,
14559    ) {
14560        let snapshot = self.buffer().read(cx).snapshot(cx);
14561        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14562        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14563        row_highlights.retain(|highlight| {
14564            while let Some(range_to_remove) = ranges_to_remove.peek() {
14565                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14566                    Ordering::Less | Ordering::Equal => {
14567                        ranges_to_remove.next();
14568                    }
14569                    Ordering::Greater => {
14570                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14571                            Ordering::Less | Ordering::Equal => {
14572                                return false;
14573                            }
14574                            Ordering::Greater => break,
14575                        }
14576                    }
14577                }
14578            }
14579
14580            true
14581        })
14582    }
14583
14584    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14585    pub fn clear_row_highlights<T: 'static>(&mut self) {
14586        self.highlighted_rows.remove(&TypeId::of::<T>());
14587    }
14588
14589    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14590    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14591        self.highlighted_rows
14592            .get(&TypeId::of::<T>())
14593            .map_or(&[] as &[_], |vec| vec.as_slice())
14594            .iter()
14595            .map(|highlight| (highlight.range.clone(), highlight.color))
14596    }
14597
14598    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14599    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14600    /// Allows to ignore certain kinds of highlights.
14601    pub fn highlighted_display_rows(
14602        &self,
14603        window: &mut Window,
14604        cx: &mut App,
14605    ) -> BTreeMap<DisplayRow, Background> {
14606        let snapshot = self.snapshot(window, cx);
14607        let mut used_highlight_orders = HashMap::default();
14608        self.highlighted_rows
14609            .iter()
14610            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14611            .fold(
14612                BTreeMap::<DisplayRow, Background>::new(),
14613                |mut unique_rows, highlight| {
14614                    let start = highlight.range.start.to_display_point(&snapshot);
14615                    let end = highlight.range.end.to_display_point(&snapshot);
14616                    let start_row = start.row().0;
14617                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14618                        && end.column() == 0
14619                    {
14620                        end.row().0.saturating_sub(1)
14621                    } else {
14622                        end.row().0
14623                    };
14624                    for row in start_row..=end_row {
14625                        let used_index =
14626                            used_highlight_orders.entry(row).or_insert(highlight.index);
14627                        if highlight.index >= *used_index {
14628                            *used_index = highlight.index;
14629                            unique_rows.insert(DisplayRow(row), highlight.color.into());
14630                        }
14631                    }
14632                    unique_rows
14633                },
14634            )
14635    }
14636
14637    pub fn highlighted_display_row_for_autoscroll(
14638        &self,
14639        snapshot: &DisplaySnapshot,
14640    ) -> Option<DisplayRow> {
14641        self.highlighted_rows
14642            .values()
14643            .flat_map(|highlighted_rows| highlighted_rows.iter())
14644            .filter_map(|highlight| {
14645                if highlight.should_autoscroll {
14646                    Some(highlight.range.start.to_display_point(snapshot).row())
14647                } else {
14648                    None
14649                }
14650            })
14651            .min()
14652    }
14653
14654    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14655        self.highlight_background::<SearchWithinRange>(
14656            ranges,
14657            |colors| colors.editor_document_highlight_read_background,
14658            cx,
14659        )
14660    }
14661
14662    pub fn set_breadcrumb_header(&mut self, new_header: String) {
14663        self.breadcrumb_header = Some(new_header);
14664    }
14665
14666    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14667        self.clear_background_highlights::<SearchWithinRange>(cx);
14668    }
14669
14670    pub fn highlight_background<T: 'static>(
14671        &mut self,
14672        ranges: &[Range<Anchor>],
14673        color_fetcher: fn(&ThemeColors) -> Hsla,
14674        cx: &mut Context<Self>,
14675    ) {
14676        self.background_highlights
14677            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14678        self.scrollbar_marker_state.dirty = true;
14679        cx.notify();
14680    }
14681
14682    pub fn clear_background_highlights<T: 'static>(
14683        &mut self,
14684        cx: &mut Context<Self>,
14685    ) -> Option<BackgroundHighlight> {
14686        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14687        if !text_highlights.1.is_empty() {
14688            self.scrollbar_marker_state.dirty = true;
14689            cx.notify();
14690        }
14691        Some(text_highlights)
14692    }
14693
14694    pub fn highlight_gutter<T: 'static>(
14695        &mut self,
14696        ranges: &[Range<Anchor>],
14697        color_fetcher: fn(&App) -> Hsla,
14698        cx: &mut Context<Self>,
14699    ) {
14700        self.gutter_highlights
14701            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14702        cx.notify();
14703    }
14704
14705    pub fn clear_gutter_highlights<T: 'static>(
14706        &mut self,
14707        cx: &mut Context<Self>,
14708    ) -> Option<GutterHighlight> {
14709        cx.notify();
14710        self.gutter_highlights.remove(&TypeId::of::<T>())
14711    }
14712
14713    #[cfg(feature = "test-support")]
14714    pub fn all_text_background_highlights(
14715        &self,
14716        window: &mut Window,
14717        cx: &mut Context<Self>,
14718    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14719        let snapshot = self.snapshot(window, cx);
14720        let buffer = &snapshot.buffer_snapshot;
14721        let start = buffer.anchor_before(0);
14722        let end = buffer.anchor_after(buffer.len());
14723        let theme = cx.theme().colors();
14724        self.background_highlights_in_range(start..end, &snapshot, theme)
14725    }
14726
14727    #[cfg(feature = "test-support")]
14728    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14729        let snapshot = self.buffer().read(cx).snapshot(cx);
14730
14731        let highlights = self
14732            .background_highlights
14733            .get(&TypeId::of::<items::BufferSearchHighlights>());
14734
14735        if let Some((_color, ranges)) = highlights {
14736            ranges
14737                .iter()
14738                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14739                .collect_vec()
14740        } else {
14741            vec![]
14742        }
14743    }
14744
14745    fn document_highlights_for_position<'a>(
14746        &'a self,
14747        position: Anchor,
14748        buffer: &'a MultiBufferSnapshot,
14749    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
14750        let read_highlights = self
14751            .background_highlights
14752            .get(&TypeId::of::<DocumentHighlightRead>())
14753            .map(|h| &h.1);
14754        let write_highlights = self
14755            .background_highlights
14756            .get(&TypeId::of::<DocumentHighlightWrite>())
14757            .map(|h| &h.1);
14758        let left_position = position.bias_left(buffer);
14759        let right_position = position.bias_right(buffer);
14760        read_highlights
14761            .into_iter()
14762            .chain(write_highlights)
14763            .flat_map(move |ranges| {
14764                let start_ix = match ranges.binary_search_by(|probe| {
14765                    let cmp = probe.end.cmp(&left_position, buffer);
14766                    if cmp.is_ge() {
14767                        Ordering::Greater
14768                    } else {
14769                        Ordering::Less
14770                    }
14771                }) {
14772                    Ok(i) | Err(i) => i,
14773                };
14774
14775                ranges[start_ix..]
14776                    .iter()
14777                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
14778            })
14779    }
14780
14781    pub fn has_background_highlights<T: 'static>(&self) -> bool {
14782        self.background_highlights
14783            .get(&TypeId::of::<T>())
14784            .map_or(false, |(_, highlights)| !highlights.is_empty())
14785    }
14786
14787    pub fn background_highlights_in_range(
14788        &self,
14789        search_range: Range<Anchor>,
14790        display_snapshot: &DisplaySnapshot,
14791        theme: &ThemeColors,
14792    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14793        let mut results = Vec::new();
14794        for (color_fetcher, ranges) in self.background_highlights.values() {
14795            let color = color_fetcher(theme);
14796            let start_ix = match ranges.binary_search_by(|probe| {
14797                let cmp = probe
14798                    .end
14799                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14800                if cmp.is_gt() {
14801                    Ordering::Greater
14802                } else {
14803                    Ordering::Less
14804                }
14805            }) {
14806                Ok(i) | Err(i) => i,
14807            };
14808            for range in &ranges[start_ix..] {
14809                if range
14810                    .start
14811                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14812                    .is_ge()
14813                {
14814                    break;
14815                }
14816
14817                let start = range.start.to_display_point(display_snapshot);
14818                let end = range.end.to_display_point(display_snapshot);
14819                results.push((start..end, color))
14820            }
14821        }
14822        results
14823    }
14824
14825    pub fn background_highlight_row_ranges<T: 'static>(
14826        &self,
14827        search_range: Range<Anchor>,
14828        display_snapshot: &DisplaySnapshot,
14829        count: usize,
14830    ) -> Vec<RangeInclusive<DisplayPoint>> {
14831        let mut results = Vec::new();
14832        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14833            return vec![];
14834        };
14835
14836        let start_ix = match ranges.binary_search_by(|probe| {
14837            let cmp = probe
14838                .end
14839                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14840            if cmp.is_gt() {
14841                Ordering::Greater
14842            } else {
14843                Ordering::Less
14844            }
14845        }) {
14846            Ok(i) | Err(i) => i,
14847        };
14848        let mut push_region = |start: Option<Point>, end: Option<Point>| {
14849            if let (Some(start_display), Some(end_display)) = (start, end) {
14850                results.push(
14851                    start_display.to_display_point(display_snapshot)
14852                        ..=end_display.to_display_point(display_snapshot),
14853                );
14854            }
14855        };
14856        let mut start_row: Option<Point> = None;
14857        let mut end_row: Option<Point> = None;
14858        if ranges.len() > count {
14859            return Vec::new();
14860        }
14861        for range in &ranges[start_ix..] {
14862            if range
14863                .start
14864                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14865                .is_ge()
14866            {
14867                break;
14868            }
14869            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14870            if let Some(current_row) = &end_row {
14871                if end.row == current_row.row {
14872                    continue;
14873                }
14874            }
14875            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14876            if start_row.is_none() {
14877                assert_eq!(end_row, None);
14878                start_row = Some(start);
14879                end_row = Some(end);
14880                continue;
14881            }
14882            if let Some(current_end) = end_row.as_mut() {
14883                if start.row > current_end.row + 1 {
14884                    push_region(start_row, end_row);
14885                    start_row = Some(start);
14886                    end_row = Some(end);
14887                } else {
14888                    // Merge two hunks.
14889                    *current_end = end;
14890                }
14891            } else {
14892                unreachable!();
14893            }
14894        }
14895        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14896        push_region(start_row, end_row);
14897        results
14898    }
14899
14900    pub fn gutter_highlights_in_range(
14901        &self,
14902        search_range: Range<Anchor>,
14903        display_snapshot: &DisplaySnapshot,
14904        cx: &App,
14905    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14906        let mut results = Vec::new();
14907        for (color_fetcher, ranges) in self.gutter_highlights.values() {
14908            let color = color_fetcher(cx);
14909            let start_ix = match ranges.binary_search_by(|probe| {
14910                let cmp = probe
14911                    .end
14912                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14913                if cmp.is_gt() {
14914                    Ordering::Greater
14915                } else {
14916                    Ordering::Less
14917                }
14918            }) {
14919                Ok(i) | Err(i) => i,
14920            };
14921            for range in &ranges[start_ix..] {
14922                if range
14923                    .start
14924                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14925                    .is_ge()
14926                {
14927                    break;
14928                }
14929
14930                let start = range.start.to_display_point(display_snapshot);
14931                let end = range.end.to_display_point(display_snapshot);
14932                results.push((start..end, color))
14933            }
14934        }
14935        results
14936    }
14937
14938    /// Get the text ranges corresponding to the redaction query
14939    pub fn redacted_ranges(
14940        &self,
14941        search_range: Range<Anchor>,
14942        display_snapshot: &DisplaySnapshot,
14943        cx: &App,
14944    ) -> Vec<Range<DisplayPoint>> {
14945        display_snapshot
14946            .buffer_snapshot
14947            .redacted_ranges(search_range, |file| {
14948                if let Some(file) = file {
14949                    file.is_private()
14950                        && EditorSettings::get(
14951                            Some(SettingsLocation {
14952                                worktree_id: file.worktree_id(cx),
14953                                path: file.path().as_ref(),
14954                            }),
14955                            cx,
14956                        )
14957                        .redact_private_values
14958                } else {
14959                    false
14960                }
14961            })
14962            .map(|range| {
14963                range.start.to_display_point(display_snapshot)
14964                    ..range.end.to_display_point(display_snapshot)
14965            })
14966            .collect()
14967    }
14968
14969    pub fn highlight_text<T: 'static>(
14970        &mut self,
14971        ranges: Vec<Range<Anchor>>,
14972        style: HighlightStyle,
14973        cx: &mut Context<Self>,
14974    ) {
14975        self.display_map.update(cx, |map, _| {
14976            map.highlight_text(TypeId::of::<T>(), ranges, style)
14977        });
14978        cx.notify();
14979    }
14980
14981    pub(crate) fn highlight_inlays<T: 'static>(
14982        &mut self,
14983        highlights: Vec<InlayHighlight>,
14984        style: HighlightStyle,
14985        cx: &mut Context<Self>,
14986    ) {
14987        self.display_map.update(cx, |map, _| {
14988            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14989        });
14990        cx.notify();
14991    }
14992
14993    pub fn text_highlights<'a, T: 'static>(
14994        &'a self,
14995        cx: &'a App,
14996    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14997        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14998    }
14999
15000    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15001        let cleared = self
15002            .display_map
15003            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15004        if cleared {
15005            cx.notify();
15006        }
15007    }
15008
15009    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15010        (self.read_only(cx) || self.blink_manager.read(cx).visible())
15011            && self.focus_handle.is_focused(window)
15012    }
15013
15014    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15015        self.show_cursor_when_unfocused = is_enabled;
15016        cx.notify();
15017    }
15018
15019    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15020        cx.notify();
15021    }
15022
15023    fn on_buffer_event(
15024        &mut self,
15025        multibuffer: &Entity<MultiBuffer>,
15026        event: &multi_buffer::Event,
15027        window: &mut Window,
15028        cx: &mut Context<Self>,
15029    ) {
15030        match event {
15031            multi_buffer::Event::Edited {
15032                singleton_buffer_edited,
15033                edited_buffer: buffer_edited,
15034            } => {
15035                self.scrollbar_marker_state.dirty = true;
15036                self.active_indent_guides_state.dirty = true;
15037                self.refresh_active_diagnostics(cx);
15038                self.refresh_code_actions(window, cx);
15039                if self.has_active_inline_completion() {
15040                    self.update_visible_inline_completion(window, cx);
15041                }
15042                if let Some(buffer) = buffer_edited {
15043                    let buffer_id = buffer.read(cx).remote_id();
15044                    if !self.registered_buffers.contains_key(&buffer_id) {
15045                        if let Some(project) = self.project.as_ref() {
15046                            project.update(cx, |project, cx| {
15047                                self.registered_buffers.insert(
15048                                    buffer_id,
15049                                    project.register_buffer_with_language_servers(&buffer, cx),
15050                                );
15051                            })
15052                        }
15053                    }
15054                }
15055                cx.emit(EditorEvent::BufferEdited);
15056                cx.emit(SearchEvent::MatchesInvalidated);
15057                if *singleton_buffer_edited {
15058                    if let Some(project) = &self.project {
15059                        #[allow(clippy::mutable_key_type)]
15060                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15061                            multibuffer
15062                                .all_buffers()
15063                                .into_iter()
15064                                .filter_map(|buffer| {
15065                                    buffer.update(cx, |buffer, cx| {
15066                                        let language = buffer.language()?;
15067                                        let should_discard = project.update(cx, |project, cx| {
15068                                            project.is_local()
15069                                                && !project.has_language_servers_for(buffer, cx)
15070                                        });
15071                                        should_discard.not().then_some(language.clone())
15072                                    })
15073                                })
15074                                .collect::<HashSet<_>>()
15075                        });
15076                        if !languages_affected.is_empty() {
15077                            self.refresh_inlay_hints(
15078                                InlayHintRefreshReason::BufferEdited(languages_affected),
15079                                cx,
15080                            );
15081                        }
15082                    }
15083                }
15084
15085                let Some(project) = &self.project else { return };
15086                let (telemetry, is_via_ssh) = {
15087                    let project = project.read(cx);
15088                    let telemetry = project.client().telemetry().clone();
15089                    let is_via_ssh = project.is_via_ssh();
15090                    (telemetry, is_via_ssh)
15091                };
15092                refresh_linked_ranges(self, window, cx);
15093                telemetry.log_edit_event("editor", is_via_ssh);
15094            }
15095            multi_buffer::Event::ExcerptsAdded {
15096                buffer,
15097                predecessor,
15098                excerpts,
15099            } => {
15100                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15101                let buffer_id = buffer.read(cx).remote_id();
15102                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15103                    if let Some(project) = &self.project {
15104                        get_uncommitted_diff_for_buffer(
15105                            project,
15106                            [buffer.clone()],
15107                            self.buffer.clone(),
15108                            cx,
15109                        )
15110                        .detach();
15111                    }
15112                }
15113                cx.emit(EditorEvent::ExcerptsAdded {
15114                    buffer: buffer.clone(),
15115                    predecessor: *predecessor,
15116                    excerpts: excerpts.clone(),
15117                });
15118                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15119            }
15120            multi_buffer::Event::ExcerptsRemoved { ids } => {
15121                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15122                let buffer = self.buffer.read(cx);
15123                self.registered_buffers
15124                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15125                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15126            }
15127            multi_buffer::Event::ExcerptsEdited { ids } => {
15128                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
15129            }
15130            multi_buffer::Event::ExcerptsExpanded { ids } => {
15131                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15132                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15133            }
15134            multi_buffer::Event::Reparsed(buffer_id) => {
15135                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15136
15137                cx.emit(EditorEvent::Reparsed(*buffer_id));
15138            }
15139            multi_buffer::Event::DiffHunksToggled => {
15140                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15141            }
15142            multi_buffer::Event::LanguageChanged(buffer_id) => {
15143                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15144                cx.emit(EditorEvent::Reparsed(*buffer_id));
15145                cx.notify();
15146            }
15147            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15148            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15149            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15150                cx.emit(EditorEvent::TitleChanged)
15151            }
15152            // multi_buffer::Event::DiffBaseChanged => {
15153            //     self.scrollbar_marker_state.dirty = true;
15154            //     cx.emit(EditorEvent::DiffBaseChanged);
15155            //     cx.notify();
15156            // }
15157            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15158            multi_buffer::Event::DiagnosticsUpdated => {
15159                self.refresh_active_diagnostics(cx);
15160                self.refresh_inline_diagnostics(true, window, cx);
15161                self.scrollbar_marker_state.dirty = true;
15162                cx.notify();
15163            }
15164            _ => {}
15165        };
15166    }
15167
15168    fn on_display_map_changed(
15169        &mut self,
15170        _: Entity<DisplayMap>,
15171        _: &mut Window,
15172        cx: &mut Context<Self>,
15173    ) {
15174        cx.notify();
15175    }
15176
15177    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15178        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15179        self.update_edit_prediction_settings(cx);
15180        self.refresh_inline_completion(true, false, window, cx);
15181        self.refresh_inlay_hints(
15182            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15183                self.selections.newest_anchor().head(),
15184                &self.buffer.read(cx).snapshot(cx),
15185                cx,
15186            )),
15187            cx,
15188        );
15189
15190        let old_cursor_shape = self.cursor_shape;
15191
15192        {
15193            let editor_settings = EditorSettings::get_global(cx);
15194            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15195            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15196            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15197        }
15198
15199        if old_cursor_shape != self.cursor_shape {
15200            cx.emit(EditorEvent::CursorShapeChanged);
15201        }
15202
15203        let project_settings = ProjectSettings::get_global(cx);
15204        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15205
15206        if self.mode == EditorMode::Full {
15207            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15208            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15209            if self.show_inline_diagnostics != show_inline_diagnostics {
15210                self.show_inline_diagnostics = show_inline_diagnostics;
15211                self.refresh_inline_diagnostics(false, window, cx);
15212            }
15213
15214            if self.git_blame_inline_enabled != inline_blame_enabled {
15215                self.toggle_git_blame_inline_internal(false, window, cx);
15216            }
15217        }
15218
15219        cx.notify();
15220    }
15221
15222    pub fn set_searchable(&mut self, searchable: bool) {
15223        self.searchable = searchable;
15224    }
15225
15226    pub fn searchable(&self) -> bool {
15227        self.searchable
15228    }
15229
15230    fn open_proposed_changes_editor(
15231        &mut self,
15232        _: &OpenProposedChangesEditor,
15233        window: &mut Window,
15234        cx: &mut Context<Self>,
15235    ) {
15236        let Some(workspace) = self.workspace() else {
15237            cx.propagate();
15238            return;
15239        };
15240
15241        let selections = self.selections.all::<usize>(cx);
15242        let multi_buffer = self.buffer.read(cx);
15243        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15244        let mut new_selections_by_buffer = HashMap::default();
15245        for selection in selections {
15246            for (buffer, range, _) in
15247                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15248            {
15249                let mut range = range.to_point(buffer);
15250                range.start.column = 0;
15251                range.end.column = buffer.line_len(range.end.row);
15252                new_selections_by_buffer
15253                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15254                    .or_insert(Vec::new())
15255                    .push(range)
15256            }
15257        }
15258
15259        let proposed_changes_buffers = new_selections_by_buffer
15260            .into_iter()
15261            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15262            .collect::<Vec<_>>();
15263        let proposed_changes_editor = cx.new(|cx| {
15264            ProposedChangesEditor::new(
15265                "Proposed changes",
15266                proposed_changes_buffers,
15267                self.project.clone(),
15268                window,
15269                cx,
15270            )
15271        });
15272
15273        window.defer(cx, move |window, cx| {
15274            workspace.update(cx, |workspace, cx| {
15275                workspace.active_pane().update(cx, |pane, cx| {
15276                    pane.add_item(
15277                        Box::new(proposed_changes_editor),
15278                        true,
15279                        true,
15280                        None,
15281                        window,
15282                        cx,
15283                    );
15284                });
15285            });
15286        });
15287    }
15288
15289    pub fn open_excerpts_in_split(
15290        &mut self,
15291        _: &OpenExcerptsSplit,
15292        window: &mut Window,
15293        cx: &mut Context<Self>,
15294    ) {
15295        self.open_excerpts_common(None, true, window, cx)
15296    }
15297
15298    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15299        self.open_excerpts_common(None, false, window, cx)
15300    }
15301
15302    fn open_excerpts_common(
15303        &mut self,
15304        jump_data: Option<JumpData>,
15305        split: bool,
15306        window: &mut Window,
15307        cx: &mut Context<Self>,
15308    ) {
15309        let Some(workspace) = self.workspace() else {
15310            cx.propagate();
15311            return;
15312        };
15313
15314        if self.buffer.read(cx).is_singleton() {
15315            cx.propagate();
15316            return;
15317        }
15318
15319        let mut new_selections_by_buffer = HashMap::default();
15320        match &jump_data {
15321            Some(JumpData::MultiBufferPoint {
15322                excerpt_id,
15323                position,
15324                anchor,
15325                line_offset_from_top,
15326            }) => {
15327                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15328                if let Some(buffer) = multi_buffer_snapshot
15329                    .buffer_id_for_excerpt(*excerpt_id)
15330                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15331                {
15332                    let buffer_snapshot = buffer.read(cx).snapshot();
15333                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15334                        language::ToPoint::to_point(anchor, &buffer_snapshot)
15335                    } else {
15336                        buffer_snapshot.clip_point(*position, Bias::Left)
15337                    };
15338                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15339                    new_selections_by_buffer.insert(
15340                        buffer,
15341                        (
15342                            vec![jump_to_offset..jump_to_offset],
15343                            Some(*line_offset_from_top),
15344                        ),
15345                    );
15346                }
15347            }
15348            Some(JumpData::MultiBufferRow {
15349                row,
15350                line_offset_from_top,
15351            }) => {
15352                let point = MultiBufferPoint::new(row.0, 0);
15353                if let Some((buffer, buffer_point, _)) =
15354                    self.buffer.read(cx).point_to_buffer_point(point, cx)
15355                {
15356                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15357                    new_selections_by_buffer
15358                        .entry(buffer)
15359                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
15360                        .0
15361                        .push(buffer_offset..buffer_offset)
15362                }
15363            }
15364            None => {
15365                let selections = self.selections.all::<usize>(cx);
15366                let multi_buffer = self.buffer.read(cx);
15367                for selection in selections {
15368                    for (snapshot, range, _, anchor) in multi_buffer
15369                        .snapshot(cx)
15370                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15371                    {
15372                        if let Some(anchor) = anchor {
15373                            // selection is in a deleted hunk
15374                            let Some(buffer_id) = anchor.buffer_id else {
15375                                continue;
15376                            };
15377                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15378                                continue;
15379                            };
15380                            let offset = text::ToOffset::to_offset(
15381                                &anchor.text_anchor,
15382                                &buffer_handle.read(cx).snapshot(),
15383                            );
15384                            let range = offset..offset;
15385                            new_selections_by_buffer
15386                                .entry(buffer_handle)
15387                                .or_insert((Vec::new(), None))
15388                                .0
15389                                .push(range)
15390                        } else {
15391                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15392                            else {
15393                                continue;
15394                            };
15395                            new_selections_by_buffer
15396                                .entry(buffer_handle)
15397                                .or_insert((Vec::new(), None))
15398                                .0
15399                                .push(range)
15400                        }
15401                    }
15402                }
15403            }
15404        }
15405
15406        if new_selections_by_buffer.is_empty() {
15407            return;
15408        }
15409
15410        // We defer the pane interaction because we ourselves are a workspace item
15411        // and activating a new item causes the pane to call a method on us reentrantly,
15412        // which panics if we're on the stack.
15413        window.defer(cx, move |window, cx| {
15414            workspace.update(cx, |workspace, cx| {
15415                let pane = if split {
15416                    workspace.adjacent_pane(window, cx)
15417                } else {
15418                    workspace.active_pane().clone()
15419                };
15420
15421                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15422                    let editor = buffer
15423                        .read(cx)
15424                        .file()
15425                        .is_none()
15426                        .then(|| {
15427                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15428                            // so `workspace.open_project_item` will never find them, always opening a new editor.
15429                            // Instead, we try to activate the existing editor in the pane first.
15430                            let (editor, pane_item_index) =
15431                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
15432                                    let editor = item.downcast::<Editor>()?;
15433                                    let singleton_buffer =
15434                                        editor.read(cx).buffer().read(cx).as_singleton()?;
15435                                    if singleton_buffer == buffer {
15436                                        Some((editor, i))
15437                                    } else {
15438                                        None
15439                                    }
15440                                })?;
15441                            pane.update(cx, |pane, cx| {
15442                                pane.activate_item(pane_item_index, true, true, window, cx)
15443                            });
15444                            Some(editor)
15445                        })
15446                        .flatten()
15447                        .unwrap_or_else(|| {
15448                            workspace.open_project_item::<Self>(
15449                                pane.clone(),
15450                                buffer,
15451                                true,
15452                                true,
15453                                window,
15454                                cx,
15455                            )
15456                        });
15457
15458                    editor.update(cx, |editor, cx| {
15459                        let autoscroll = match scroll_offset {
15460                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15461                            None => Autoscroll::newest(),
15462                        };
15463                        let nav_history = editor.nav_history.take();
15464                        editor.change_selections(Some(autoscroll), window, cx, |s| {
15465                            s.select_ranges(ranges);
15466                        });
15467                        editor.nav_history = nav_history;
15468                    });
15469                }
15470            })
15471        });
15472    }
15473
15474    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15475        let snapshot = self.buffer.read(cx).read(cx);
15476        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15477        Some(
15478            ranges
15479                .iter()
15480                .map(move |range| {
15481                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15482                })
15483                .collect(),
15484        )
15485    }
15486
15487    fn selection_replacement_ranges(
15488        &self,
15489        range: Range<OffsetUtf16>,
15490        cx: &mut App,
15491    ) -> Vec<Range<OffsetUtf16>> {
15492        let selections = self.selections.all::<OffsetUtf16>(cx);
15493        let newest_selection = selections
15494            .iter()
15495            .max_by_key(|selection| selection.id)
15496            .unwrap();
15497        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15498        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15499        let snapshot = self.buffer.read(cx).read(cx);
15500        selections
15501            .into_iter()
15502            .map(|mut selection| {
15503                selection.start.0 =
15504                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
15505                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15506                snapshot.clip_offset_utf16(selection.start, Bias::Left)
15507                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15508            })
15509            .collect()
15510    }
15511
15512    fn report_editor_event(
15513        &self,
15514        event_type: &'static str,
15515        file_extension: Option<String>,
15516        cx: &App,
15517    ) {
15518        if cfg!(any(test, feature = "test-support")) {
15519            return;
15520        }
15521
15522        let Some(project) = &self.project else { return };
15523
15524        // If None, we are in a file without an extension
15525        let file = self
15526            .buffer
15527            .read(cx)
15528            .as_singleton()
15529            .and_then(|b| b.read(cx).file());
15530        let file_extension = file_extension.or(file
15531            .as_ref()
15532            .and_then(|file| Path::new(file.file_name(cx)).extension())
15533            .and_then(|e| e.to_str())
15534            .map(|a| a.to_string()));
15535
15536        let vim_mode = cx
15537            .global::<SettingsStore>()
15538            .raw_user_settings()
15539            .get("vim_mode")
15540            == Some(&serde_json::Value::Bool(true));
15541
15542        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15543        let copilot_enabled = edit_predictions_provider
15544            == language::language_settings::EditPredictionProvider::Copilot;
15545        let copilot_enabled_for_language = self
15546            .buffer
15547            .read(cx)
15548            .settings_at(0, cx)
15549            .show_edit_predictions;
15550
15551        let project = project.read(cx);
15552        telemetry::event!(
15553            event_type,
15554            file_extension,
15555            vim_mode,
15556            copilot_enabled,
15557            copilot_enabled_for_language,
15558            edit_predictions_provider,
15559            is_via_ssh = project.is_via_ssh(),
15560        );
15561    }
15562
15563    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15564    /// with each line being an array of {text, highlight} objects.
15565    fn copy_highlight_json(
15566        &mut self,
15567        _: &CopyHighlightJson,
15568        window: &mut Window,
15569        cx: &mut Context<Self>,
15570    ) {
15571        #[derive(Serialize)]
15572        struct Chunk<'a> {
15573            text: String,
15574            highlight: Option<&'a str>,
15575        }
15576
15577        let snapshot = self.buffer.read(cx).snapshot(cx);
15578        let range = self
15579            .selected_text_range(false, window, cx)
15580            .and_then(|selection| {
15581                if selection.range.is_empty() {
15582                    None
15583                } else {
15584                    Some(selection.range)
15585                }
15586            })
15587            .unwrap_or_else(|| 0..snapshot.len());
15588
15589        let chunks = snapshot.chunks(range, true);
15590        let mut lines = Vec::new();
15591        let mut line: VecDeque<Chunk> = VecDeque::new();
15592
15593        let Some(style) = self.style.as_ref() else {
15594            return;
15595        };
15596
15597        for chunk in chunks {
15598            let highlight = chunk
15599                .syntax_highlight_id
15600                .and_then(|id| id.name(&style.syntax));
15601            let mut chunk_lines = chunk.text.split('\n').peekable();
15602            while let Some(text) = chunk_lines.next() {
15603                let mut merged_with_last_token = false;
15604                if let Some(last_token) = line.back_mut() {
15605                    if last_token.highlight == highlight {
15606                        last_token.text.push_str(text);
15607                        merged_with_last_token = true;
15608                    }
15609                }
15610
15611                if !merged_with_last_token {
15612                    line.push_back(Chunk {
15613                        text: text.into(),
15614                        highlight,
15615                    });
15616                }
15617
15618                if chunk_lines.peek().is_some() {
15619                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
15620                        line.pop_front();
15621                    }
15622                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
15623                        line.pop_back();
15624                    }
15625
15626                    lines.push(mem::take(&mut line));
15627                }
15628            }
15629        }
15630
15631        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15632            return;
15633        };
15634        cx.write_to_clipboard(ClipboardItem::new_string(lines));
15635    }
15636
15637    pub fn open_context_menu(
15638        &mut self,
15639        _: &OpenContextMenu,
15640        window: &mut Window,
15641        cx: &mut Context<Self>,
15642    ) {
15643        self.request_autoscroll(Autoscroll::newest(), cx);
15644        let position = self.selections.newest_display(cx).start;
15645        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15646    }
15647
15648    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15649        &self.inlay_hint_cache
15650    }
15651
15652    pub fn replay_insert_event(
15653        &mut self,
15654        text: &str,
15655        relative_utf16_range: Option<Range<isize>>,
15656        window: &mut Window,
15657        cx: &mut Context<Self>,
15658    ) {
15659        if !self.input_enabled {
15660            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15661            return;
15662        }
15663        if let Some(relative_utf16_range) = relative_utf16_range {
15664            let selections = self.selections.all::<OffsetUtf16>(cx);
15665            self.change_selections(None, window, cx, |s| {
15666                let new_ranges = selections.into_iter().map(|range| {
15667                    let start = OffsetUtf16(
15668                        range
15669                            .head()
15670                            .0
15671                            .saturating_add_signed(relative_utf16_range.start),
15672                    );
15673                    let end = OffsetUtf16(
15674                        range
15675                            .head()
15676                            .0
15677                            .saturating_add_signed(relative_utf16_range.end),
15678                    );
15679                    start..end
15680                });
15681                s.select_ranges(new_ranges);
15682            });
15683        }
15684
15685        self.handle_input(text, window, cx);
15686    }
15687
15688    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15689        let Some(provider) = self.semantics_provider.as_ref() else {
15690            return false;
15691        };
15692
15693        let mut supports = false;
15694        self.buffer().update(cx, |this, cx| {
15695            this.for_each_buffer(|buffer| {
15696                supports |= provider.supports_inlay_hints(buffer, cx);
15697            });
15698        });
15699
15700        supports
15701    }
15702
15703    pub fn is_focused(&self, window: &Window) -> bool {
15704        self.focus_handle.is_focused(window)
15705    }
15706
15707    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15708        cx.emit(EditorEvent::Focused);
15709
15710        if let Some(descendant) = self
15711            .last_focused_descendant
15712            .take()
15713            .and_then(|descendant| descendant.upgrade())
15714        {
15715            window.focus(&descendant);
15716        } else {
15717            if let Some(blame) = self.blame.as_ref() {
15718                blame.update(cx, GitBlame::focus)
15719            }
15720
15721            self.blink_manager.update(cx, BlinkManager::enable);
15722            self.show_cursor_names(window, cx);
15723            self.buffer.update(cx, |buffer, cx| {
15724                buffer.finalize_last_transaction(cx);
15725                if self.leader_peer_id.is_none() {
15726                    buffer.set_active_selections(
15727                        &self.selections.disjoint_anchors(),
15728                        self.selections.line_mode,
15729                        self.cursor_shape,
15730                        cx,
15731                    );
15732                }
15733            });
15734        }
15735    }
15736
15737    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15738        cx.emit(EditorEvent::FocusedIn)
15739    }
15740
15741    fn handle_focus_out(
15742        &mut self,
15743        event: FocusOutEvent,
15744        _window: &mut Window,
15745        _cx: &mut Context<Self>,
15746    ) {
15747        if event.blurred != self.focus_handle {
15748            self.last_focused_descendant = Some(event.blurred);
15749        }
15750    }
15751
15752    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15753        self.blink_manager.update(cx, BlinkManager::disable);
15754        self.buffer
15755            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
15756
15757        if let Some(blame) = self.blame.as_ref() {
15758            blame.update(cx, GitBlame::blur)
15759        }
15760        if !self.hover_state.focused(window, cx) {
15761            hide_hover(self, cx);
15762        }
15763        if !self
15764            .context_menu
15765            .borrow()
15766            .as_ref()
15767            .is_some_and(|context_menu| context_menu.focused(window, cx))
15768        {
15769            self.hide_context_menu(window, cx);
15770        }
15771        self.discard_inline_completion(false, cx);
15772        cx.emit(EditorEvent::Blurred);
15773        cx.notify();
15774    }
15775
15776    pub fn register_action<A: Action>(
15777        &mut self,
15778        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
15779    ) -> Subscription {
15780        let id = self.next_editor_action_id.post_inc();
15781        let listener = Arc::new(listener);
15782        self.editor_actions.borrow_mut().insert(
15783            id,
15784            Box::new(move |window, _| {
15785                let listener = listener.clone();
15786                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
15787                    let action = action.downcast_ref().unwrap();
15788                    if phase == DispatchPhase::Bubble {
15789                        listener(action, window, cx)
15790                    }
15791                })
15792            }),
15793        );
15794
15795        let editor_actions = self.editor_actions.clone();
15796        Subscription::new(move || {
15797            editor_actions.borrow_mut().remove(&id);
15798        })
15799    }
15800
15801    pub fn file_header_size(&self) -> u32 {
15802        FILE_HEADER_HEIGHT
15803    }
15804
15805    pub fn revert(
15806        &mut self,
15807        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
15808        window: &mut Window,
15809        cx: &mut Context<Self>,
15810    ) {
15811        self.buffer().update(cx, |multi_buffer, cx| {
15812            for (buffer_id, changes) in revert_changes {
15813                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
15814                    buffer.update(cx, |buffer, cx| {
15815                        buffer.edit(
15816                            changes.into_iter().map(|(range, text)| {
15817                                (range, text.to_string().map(Arc::<str>::from))
15818                            }),
15819                            None,
15820                            cx,
15821                        );
15822                    });
15823                }
15824            }
15825        });
15826        self.change_selections(None, window, cx, |selections| selections.refresh());
15827    }
15828
15829    pub fn to_pixel_point(
15830        &self,
15831        source: multi_buffer::Anchor,
15832        editor_snapshot: &EditorSnapshot,
15833        window: &mut Window,
15834    ) -> Option<gpui::Point<Pixels>> {
15835        let source_point = source.to_display_point(editor_snapshot);
15836        self.display_to_pixel_point(source_point, editor_snapshot, window)
15837    }
15838
15839    pub fn display_to_pixel_point(
15840        &self,
15841        source: DisplayPoint,
15842        editor_snapshot: &EditorSnapshot,
15843        window: &mut Window,
15844    ) -> Option<gpui::Point<Pixels>> {
15845        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15846        let text_layout_details = self.text_layout_details(window);
15847        let scroll_top = text_layout_details
15848            .scroll_anchor
15849            .scroll_position(editor_snapshot)
15850            .y;
15851
15852        if source.row().as_f32() < scroll_top.floor() {
15853            return None;
15854        }
15855        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15856        let source_y = line_height * (source.row().as_f32() - scroll_top);
15857        Some(gpui::Point::new(source_x, source_y))
15858    }
15859
15860    pub fn has_visible_completions_menu(&self) -> bool {
15861        !self.edit_prediction_preview_is_active()
15862            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15863                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15864            })
15865    }
15866
15867    pub fn register_addon<T: Addon>(&mut self, instance: T) {
15868        self.addons
15869            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15870    }
15871
15872    pub fn unregister_addon<T: Addon>(&mut self) {
15873        self.addons.remove(&std::any::TypeId::of::<T>());
15874    }
15875
15876    pub fn addon<T: Addon>(&self) -> Option<&T> {
15877        let type_id = std::any::TypeId::of::<T>();
15878        self.addons
15879            .get(&type_id)
15880            .and_then(|item| item.to_any().downcast_ref::<T>())
15881    }
15882
15883    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15884        let text_layout_details = self.text_layout_details(window);
15885        let style = &text_layout_details.editor_style;
15886        let font_id = window.text_system().resolve_font(&style.text.font());
15887        let font_size = style.text.font_size.to_pixels(window.rem_size());
15888        let line_height = style.text.line_height_in_pixels(window.rem_size());
15889        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15890
15891        gpui::Size::new(em_width, line_height)
15892    }
15893
15894    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15895        self.load_diff_task.clone()
15896    }
15897
15898    fn read_selections_from_db(
15899        &mut self,
15900        item_id: u64,
15901        workspace_id: WorkspaceId,
15902        window: &mut Window,
15903        cx: &mut Context<Editor>,
15904    ) {
15905        if !self.is_singleton(cx)
15906            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15907        {
15908            return;
15909        }
15910        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15911            return;
15912        };
15913        if selections.is_empty() {
15914            return;
15915        }
15916
15917        let snapshot = self.buffer.read(cx).snapshot(cx);
15918        self.change_selections(None, window, cx, |s| {
15919            s.select_ranges(selections.into_iter().map(|(start, end)| {
15920                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15921            }));
15922        });
15923    }
15924}
15925
15926fn insert_extra_newline_brackets(
15927    buffer: &MultiBufferSnapshot,
15928    range: Range<usize>,
15929    language: &language::LanguageScope,
15930) -> bool {
15931    let leading_whitespace_len = buffer
15932        .reversed_chars_at(range.start)
15933        .take_while(|c| c.is_whitespace() && *c != '\n')
15934        .map(|c| c.len_utf8())
15935        .sum::<usize>();
15936    let trailing_whitespace_len = buffer
15937        .chars_at(range.end)
15938        .take_while(|c| c.is_whitespace() && *c != '\n')
15939        .map(|c| c.len_utf8())
15940        .sum::<usize>();
15941    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
15942
15943    language.brackets().any(|(pair, enabled)| {
15944        let pair_start = pair.start.trim_end();
15945        let pair_end = pair.end.trim_start();
15946
15947        enabled
15948            && pair.newline
15949            && buffer.contains_str_at(range.end, pair_end)
15950            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
15951    })
15952}
15953
15954fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
15955    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
15956        [(buffer, range, _)] => (*buffer, range.clone()),
15957        _ => return false,
15958    };
15959    let pair = {
15960        let mut result: Option<BracketMatch> = None;
15961
15962        for pair in buffer
15963            .all_bracket_ranges(range.clone())
15964            .filter(move |pair| {
15965                pair.open_range.start <= range.start && pair.close_range.end >= range.end
15966            })
15967        {
15968            let len = pair.close_range.end - pair.open_range.start;
15969
15970            if let Some(existing) = &result {
15971                let existing_len = existing.close_range.end - existing.open_range.start;
15972                if len > existing_len {
15973                    continue;
15974                }
15975            }
15976
15977            result = Some(pair);
15978        }
15979
15980        result
15981    };
15982    let Some(pair) = pair else {
15983        return false;
15984    };
15985    pair.newline_only
15986        && buffer
15987            .chars_for_range(pair.open_range.end..range.start)
15988            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
15989            .all(|c| c.is_whitespace() && c != '\n')
15990}
15991
15992fn get_uncommitted_diff_for_buffer(
15993    project: &Entity<Project>,
15994    buffers: impl IntoIterator<Item = Entity<Buffer>>,
15995    buffer: Entity<MultiBuffer>,
15996    cx: &mut App,
15997) -> Task<()> {
15998    let mut tasks = Vec::new();
15999    project.update(cx, |project, cx| {
16000        for buffer in buffers {
16001            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16002        }
16003    });
16004    cx.spawn(|mut cx| async move {
16005        let diffs = futures::future::join_all(tasks).await;
16006        buffer
16007            .update(&mut cx, |buffer, cx| {
16008                for diff in diffs.into_iter().flatten() {
16009                    buffer.add_diff(diff, cx);
16010                }
16011            })
16012            .ok();
16013    })
16014}
16015
16016fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16017    let tab_size = tab_size.get() as usize;
16018    let mut width = offset;
16019
16020    for ch in text.chars() {
16021        width += if ch == '\t' {
16022            tab_size - (width % tab_size)
16023        } else {
16024            1
16025        };
16026    }
16027
16028    width - offset
16029}
16030
16031#[cfg(test)]
16032mod tests {
16033    use super::*;
16034
16035    #[test]
16036    fn test_string_size_with_expanded_tabs() {
16037        let nz = |val| NonZeroU32::new(val).unwrap();
16038        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16039        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16040        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16041        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16042        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16043        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16044        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16045        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16046    }
16047}
16048
16049/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16050struct WordBreakingTokenizer<'a> {
16051    input: &'a str,
16052}
16053
16054impl<'a> WordBreakingTokenizer<'a> {
16055    fn new(input: &'a str) -> Self {
16056        Self { input }
16057    }
16058}
16059
16060fn is_char_ideographic(ch: char) -> bool {
16061    use unicode_script::Script::*;
16062    use unicode_script::UnicodeScript;
16063    matches!(ch.script(), Han | Tangut | Yi)
16064}
16065
16066fn is_grapheme_ideographic(text: &str) -> bool {
16067    text.chars().any(is_char_ideographic)
16068}
16069
16070fn is_grapheme_whitespace(text: &str) -> bool {
16071    text.chars().any(|x| x.is_whitespace())
16072}
16073
16074fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16075    text.chars().next().map_or(false, |ch| {
16076        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16077    })
16078}
16079
16080#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16081struct WordBreakToken<'a> {
16082    token: &'a str,
16083    grapheme_len: usize,
16084    is_whitespace: bool,
16085}
16086
16087impl<'a> Iterator for WordBreakingTokenizer<'a> {
16088    /// Yields a span, the count of graphemes in the token, and whether it was
16089    /// whitespace. Note that it also breaks at word boundaries.
16090    type Item = WordBreakToken<'a>;
16091
16092    fn next(&mut self) -> Option<Self::Item> {
16093        use unicode_segmentation::UnicodeSegmentation;
16094        if self.input.is_empty() {
16095            return None;
16096        }
16097
16098        let mut iter = self.input.graphemes(true).peekable();
16099        let mut offset = 0;
16100        let mut graphemes = 0;
16101        if let Some(first_grapheme) = iter.next() {
16102            let is_whitespace = is_grapheme_whitespace(first_grapheme);
16103            offset += first_grapheme.len();
16104            graphemes += 1;
16105            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16106                if let Some(grapheme) = iter.peek().copied() {
16107                    if should_stay_with_preceding_ideograph(grapheme) {
16108                        offset += grapheme.len();
16109                        graphemes += 1;
16110                    }
16111                }
16112            } else {
16113                let mut words = self.input[offset..].split_word_bound_indices().peekable();
16114                let mut next_word_bound = words.peek().copied();
16115                if next_word_bound.map_or(false, |(i, _)| i == 0) {
16116                    next_word_bound = words.next();
16117                }
16118                while let Some(grapheme) = iter.peek().copied() {
16119                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
16120                        break;
16121                    };
16122                    if is_grapheme_whitespace(grapheme) != is_whitespace {
16123                        break;
16124                    };
16125                    offset += grapheme.len();
16126                    graphemes += 1;
16127                    iter.next();
16128                }
16129            }
16130            let token = &self.input[..offset];
16131            self.input = &self.input[offset..];
16132            if is_whitespace {
16133                Some(WordBreakToken {
16134                    token: " ",
16135                    grapheme_len: 1,
16136                    is_whitespace: true,
16137                })
16138            } else {
16139                Some(WordBreakToken {
16140                    token,
16141                    grapheme_len: graphemes,
16142                    is_whitespace: false,
16143                })
16144            }
16145        } else {
16146            None
16147        }
16148    }
16149}
16150
16151#[test]
16152fn test_word_breaking_tokenizer() {
16153    let tests: &[(&str, &[(&str, usize, bool)])] = &[
16154        ("", &[]),
16155        ("  ", &[(" ", 1, true)]),
16156        ("Ʒ", &[("Ʒ", 1, false)]),
16157        ("Ǽ", &[("Ǽ", 1, false)]),
16158        ("", &[("", 1, false)]),
16159        ("⋑⋑", &[("⋑⋑", 2, false)]),
16160        (
16161            "原理,进而",
16162            &[
16163                ("", 1, false),
16164                ("理,", 2, false),
16165                ("", 1, false),
16166                ("", 1, false),
16167            ],
16168        ),
16169        (
16170            "hello world",
16171            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16172        ),
16173        (
16174            "hello, world",
16175            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16176        ),
16177        (
16178            "  hello world",
16179            &[
16180                (" ", 1, true),
16181                ("hello", 5, false),
16182                (" ", 1, true),
16183                ("world", 5, false),
16184            ],
16185        ),
16186        (
16187            "这是什么 \n 钢笔",
16188            &[
16189                ("", 1, false),
16190                ("", 1, false),
16191                ("", 1, false),
16192                ("", 1, false),
16193                (" ", 1, true),
16194                ("", 1, false),
16195                ("", 1, false),
16196            ],
16197        ),
16198        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16199    ];
16200
16201    for (input, result) in tests {
16202        assert_eq!(
16203            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16204            result
16205                .iter()
16206                .copied()
16207                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16208                    token,
16209                    grapheme_len,
16210                    is_whitespace,
16211                })
16212                .collect::<Vec<_>>()
16213        );
16214    }
16215}
16216
16217fn wrap_with_prefix(
16218    line_prefix: String,
16219    unwrapped_text: String,
16220    wrap_column: usize,
16221    tab_size: NonZeroU32,
16222) -> String {
16223    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16224    let mut wrapped_text = String::new();
16225    let mut current_line = line_prefix.clone();
16226
16227    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16228    let mut current_line_len = line_prefix_len;
16229    for WordBreakToken {
16230        token,
16231        grapheme_len,
16232        is_whitespace,
16233    } in tokenizer
16234    {
16235        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16236            wrapped_text.push_str(current_line.trim_end());
16237            wrapped_text.push('\n');
16238            current_line.truncate(line_prefix.len());
16239            current_line_len = line_prefix_len;
16240            if !is_whitespace {
16241                current_line.push_str(token);
16242                current_line_len += grapheme_len;
16243            }
16244        } else if !is_whitespace {
16245            current_line.push_str(token);
16246            current_line_len += grapheme_len;
16247        } else if current_line_len != line_prefix_len {
16248            current_line.push(' ');
16249            current_line_len += 1;
16250        }
16251    }
16252
16253    if !current_line.is_empty() {
16254        wrapped_text.push_str(&current_line);
16255    }
16256    wrapped_text
16257}
16258
16259#[test]
16260fn test_wrap_with_prefix() {
16261    assert_eq!(
16262        wrap_with_prefix(
16263            "# ".to_string(),
16264            "abcdefg".to_string(),
16265            4,
16266            NonZeroU32::new(4).unwrap()
16267        ),
16268        "# abcdefg"
16269    );
16270    assert_eq!(
16271        wrap_with_prefix(
16272            "".to_string(),
16273            "\thello world".to_string(),
16274            8,
16275            NonZeroU32::new(4).unwrap()
16276        ),
16277        "hello\nworld"
16278    );
16279    assert_eq!(
16280        wrap_with_prefix(
16281            "// ".to_string(),
16282            "xx \nyy zz aa bb cc".to_string(),
16283            12,
16284            NonZeroU32::new(4).unwrap()
16285        ),
16286        "// xx yy zz\n// aa bb cc"
16287    );
16288    assert_eq!(
16289        wrap_with_prefix(
16290            String::new(),
16291            "这是什么 \n 钢笔".to_string(),
16292            3,
16293            NonZeroU32::new(4).unwrap()
16294        ),
16295        "这是什\n么 钢\n"
16296    );
16297}
16298
16299pub trait CollaborationHub {
16300    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16301    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16302    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16303}
16304
16305impl CollaborationHub for Entity<Project> {
16306    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16307        self.read(cx).collaborators()
16308    }
16309
16310    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16311        self.read(cx).user_store().read(cx).participant_indices()
16312    }
16313
16314    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16315        let this = self.read(cx);
16316        let user_ids = this.collaborators().values().map(|c| c.user_id);
16317        this.user_store().read_with(cx, |user_store, cx| {
16318            user_store.participant_names(user_ids, cx)
16319        })
16320    }
16321}
16322
16323pub trait SemanticsProvider {
16324    fn hover(
16325        &self,
16326        buffer: &Entity<Buffer>,
16327        position: text::Anchor,
16328        cx: &mut App,
16329    ) -> Option<Task<Vec<project::Hover>>>;
16330
16331    fn inlay_hints(
16332        &self,
16333        buffer_handle: Entity<Buffer>,
16334        range: Range<text::Anchor>,
16335        cx: &mut App,
16336    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16337
16338    fn resolve_inlay_hint(
16339        &self,
16340        hint: InlayHint,
16341        buffer_handle: Entity<Buffer>,
16342        server_id: LanguageServerId,
16343        cx: &mut App,
16344    ) -> Option<Task<anyhow::Result<InlayHint>>>;
16345
16346    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16347
16348    fn document_highlights(
16349        &self,
16350        buffer: &Entity<Buffer>,
16351        position: text::Anchor,
16352        cx: &mut App,
16353    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16354
16355    fn definitions(
16356        &self,
16357        buffer: &Entity<Buffer>,
16358        position: text::Anchor,
16359        kind: GotoDefinitionKind,
16360        cx: &mut App,
16361    ) -> Option<Task<Result<Vec<LocationLink>>>>;
16362
16363    fn range_for_rename(
16364        &self,
16365        buffer: &Entity<Buffer>,
16366        position: text::Anchor,
16367        cx: &mut App,
16368    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16369
16370    fn perform_rename(
16371        &self,
16372        buffer: &Entity<Buffer>,
16373        position: text::Anchor,
16374        new_name: String,
16375        cx: &mut App,
16376    ) -> Option<Task<Result<ProjectTransaction>>>;
16377}
16378
16379pub trait CompletionProvider {
16380    fn completions(
16381        &self,
16382        buffer: &Entity<Buffer>,
16383        buffer_position: text::Anchor,
16384        trigger: CompletionContext,
16385        window: &mut Window,
16386        cx: &mut Context<Editor>,
16387    ) -> Task<Result<Vec<Completion>>>;
16388
16389    fn resolve_completions(
16390        &self,
16391        buffer: Entity<Buffer>,
16392        completion_indices: Vec<usize>,
16393        completions: Rc<RefCell<Box<[Completion]>>>,
16394        cx: &mut Context<Editor>,
16395    ) -> Task<Result<bool>>;
16396
16397    fn apply_additional_edits_for_completion(
16398        &self,
16399        _buffer: Entity<Buffer>,
16400        _completions: Rc<RefCell<Box<[Completion]>>>,
16401        _completion_index: usize,
16402        _push_to_history: bool,
16403        _cx: &mut Context<Editor>,
16404    ) -> Task<Result<Option<language::Transaction>>> {
16405        Task::ready(Ok(None))
16406    }
16407
16408    fn is_completion_trigger(
16409        &self,
16410        buffer: &Entity<Buffer>,
16411        position: language::Anchor,
16412        text: &str,
16413        trigger_in_words: bool,
16414        cx: &mut Context<Editor>,
16415    ) -> bool;
16416
16417    fn sort_completions(&self) -> bool {
16418        true
16419    }
16420}
16421
16422pub trait CodeActionProvider {
16423    fn id(&self) -> Arc<str>;
16424
16425    fn code_actions(
16426        &self,
16427        buffer: &Entity<Buffer>,
16428        range: Range<text::Anchor>,
16429        window: &mut Window,
16430        cx: &mut App,
16431    ) -> Task<Result<Vec<CodeAction>>>;
16432
16433    fn apply_code_action(
16434        &self,
16435        buffer_handle: Entity<Buffer>,
16436        action: CodeAction,
16437        excerpt_id: ExcerptId,
16438        push_to_history: bool,
16439        window: &mut Window,
16440        cx: &mut App,
16441    ) -> Task<Result<ProjectTransaction>>;
16442}
16443
16444impl CodeActionProvider for Entity<Project> {
16445    fn id(&self) -> Arc<str> {
16446        "project".into()
16447    }
16448
16449    fn code_actions(
16450        &self,
16451        buffer: &Entity<Buffer>,
16452        range: Range<text::Anchor>,
16453        _window: &mut Window,
16454        cx: &mut App,
16455    ) -> Task<Result<Vec<CodeAction>>> {
16456        self.update(cx, |project, cx| {
16457            project.code_actions(buffer, range, None, cx)
16458        })
16459    }
16460
16461    fn apply_code_action(
16462        &self,
16463        buffer_handle: Entity<Buffer>,
16464        action: CodeAction,
16465        _excerpt_id: ExcerptId,
16466        push_to_history: bool,
16467        _window: &mut Window,
16468        cx: &mut App,
16469    ) -> Task<Result<ProjectTransaction>> {
16470        self.update(cx, |project, cx| {
16471            project.apply_code_action(buffer_handle, action, push_to_history, cx)
16472        })
16473    }
16474}
16475
16476fn snippet_completions(
16477    project: &Project,
16478    buffer: &Entity<Buffer>,
16479    buffer_position: text::Anchor,
16480    cx: &mut App,
16481) -> Task<Result<Vec<Completion>>> {
16482    let language = buffer.read(cx).language_at(buffer_position);
16483    let language_name = language.as_ref().map(|language| language.lsp_id());
16484    let snippet_store = project.snippets().read(cx);
16485    let snippets = snippet_store.snippets_for(language_name, cx);
16486
16487    if snippets.is_empty() {
16488        return Task::ready(Ok(vec![]));
16489    }
16490    let snapshot = buffer.read(cx).text_snapshot();
16491    let chars: String = snapshot
16492        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16493        .collect();
16494
16495    let scope = language.map(|language| language.default_scope());
16496    let executor = cx.background_executor().clone();
16497
16498    cx.background_spawn(async move {
16499        let classifier = CharClassifier::new(scope).for_completion(true);
16500        let mut last_word = chars
16501            .chars()
16502            .take_while(|c| classifier.is_word(*c))
16503            .collect::<String>();
16504        last_word = last_word.chars().rev().collect();
16505
16506        if last_word.is_empty() {
16507            return Ok(vec![]);
16508        }
16509
16510        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16511        let to_lsp = |point: &text::Anchor| {
16512            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16513            point_to_lsp(end)
16514        };
16515        let lsp_end = to_lsp(&buffer_position);
16516
16517        let candidates = snippets
16518            .iter()
16519            .enumerate()
16520            .flat_map(|(ix, snippet)| {
16521                snippet
16522                    .prefix
16523                    .iter()
16524                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16525            })
16526            .collect::<Vec<StringMatchCandidate>>();
16527
16528        let mut matches = fuzzy::match_strings(
16529            &candidates,
16530            &last_word,
16531            last_word.chars().any(|c| c.is_uppercase()),
16532            100,
16533            &Default::default(),
16534            executor,
16535        )
16536        .await;
16537
16538        // Remove all candidates where the query's start does not match the start of any word in the candidate
16539        if let Some(query_start) = last_word.chars().next() {
16540            matches.retain(|string_match| {
16541                split_words(&string_match.string).any(|word| {
16542                    // Check that the first codepoint of the word as lowercase matches the first
16543                    // codepoint of the query as lowercase
16544                    word.chars()
16545                        .flat_map(|codepoint| codepoint.to_lowercase())
16546                        .zip(query_start.to_lowercase())
16547                        .all(|(word_cp, query_cp)| word_cp == query_cp)
16548                })
16549            });
16550        }
16551
16552        let matched_strings = matches
16553            .into_iter()
16554            .map(|m| m.string)
16555            .collect::<HashSet<_>>();
16556
16557        let result: Vec<Completion> = snippets
16558            .into_iter()
16559            .filter_map(|snippet| {
16560                let matching_prefix = snippet
16561                    .prefix
16562                    .iter()
16563                    .find(|prefix| matched_strings.contains(*prefix))?;
16564                let start = as_offset - last_word.len();
16565                let start = snapshot.anchor_before(start);
16566                let range = start..buffer_position;
16567                let lsp_start = to_lsp(&start);
16568                let lsp_range = lsp::Range {
16569                    start: lsp_start,
16570                    end: lsp_end,
16571                };
16572                Some(Completion {
16573                    old_range: range,
16574                    new_text: snippet.body.clone(),
16575                    resolved: false,
16576                    label: CodeLabel {
16577                        text: matching_prefix.clone(),
16578                        runs: vec![],
16579                        filter_range: 0..matching_prefix.len(),
16580                    },
16581                    server_id: LanguageServerId(usize::MAX),
16582                    documentation: snippet
16583                        .description
16584                        .clone()
16585                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
16586                    lsp_completion: lsp::CompletionItem {
16587                        label: snippet.prefix.first().unwrap().clone(),
16588                        kind: Some(CompletionItemKind::SNIPPET),
16589                        label_details: snippet.description.as_ref().map(|description| {
16590                            lsp::CompletionItemLabelDetails {
16591                                detail: Some(description.clone()),
16592                                description: None,
16593                            }
16594                        }),
16595                        insert_text_format: Some(InsertTextFormat::SNIPPET),
16596                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16597                            lsp::InsertReplaceEdit {
16598                                new_text: snippet.body.clone(),
16599                                insert: lsp_range,
16600                                replace: lsp_range,
16601                            },
16602                        )),
16603                        filter_text: Some(snippet.body.clone()),
16604                        sort_text: Some(char::MAX.to_string()),
16605                        ..Default::default()
16606                    },
16607                    confirm: None,
16608                })
16609            })
16610            .collect();
16611
16612        Ok(result)
16613    })
16614}
16615
16616impl CompletionProvider for Entity<Project> {
16617    fn completions(
16618        &self,
16619        buffer: &Entity<Buffer>,
16620        buffer_position: text::Anchor,
16621        options: CompletionContext,
16622        _window: &mut Window,
16623        cx: &mut Context<Editor>,
16624    ) -> Task<Result<Vec<Completion>>> {
16625        self.update(cx, |project, cx| {
16626            let snippets = snippet_completions(project, buffer, buffer_position, cx);
16627            let project_completions = project.completions(buffer, buffer_position, options, cx);
16628            cx.background_spawn(async move {
16629                let mut completions = project_completions.await?;
16630                let snippets_completions = snippets.await?;
16631                completions.extend(snippets_completions);
16632                Ok(completions)
16633            })
16634        })
16635    }
16636
16637    fn resolve_completions(
16638        &self,
16639        buffer: Entity<Buffer>,
16640        completion_indices: Vec<usize>,
16641        completions: Rc<RefCell<Box<[Completion]>>>,
16642        cx: &mut Context<Editor>,
16643    ) -> Task<Result<bool>> {
16644        self.update(cx, |project, cx| {
16645            project.lsp_store().update(cx, |lsp_store, cx| {
16646                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16647            })
16648        })
16649    }
16650
16651    fn apply_additional_edits_for_completion(
16652        &self,
16653        buffer: Entity<Buffer>,
16654        completions: Rc<RefCell<Box<[Completion]>>>,
16655        completion_index: usize,
16656        push_to_history: bool,
16657        cx: &mut Context<Editor>,
16658    ) -> Task<Result<Option<language::Transaction>>> {
16659        self.update(cx, |project, cx| {
16660            project.lsp_store().update(cx, |lsp_store, cx| {
16661                lsp_store.apply_additional_edits_for_completion(
16662                    buffer,
16663                    completions,
16664                    completion_index,
16665                    push_to_history,
16666                    cx,
16667                )
16668            })
16669        })
16670    }
16671
16672    fn is_completion_trigger(
16673        &self,
16674        buffer: &Entity<Buffer>,
16675        position: language::Anchor,
16676        text: &str,
16677        trigger_in_words: bool,
16678        cx: &mut Context<Editor>,
16679    ) -> bool {
16680        let mut chars = text.chars();
16681        let char = if let Some(char) = chars.next() {
16682            char
16683        } else {
16684            return false;
16685        };
16686        if chars.next().is_some() {
16687            return false;
16688        }
16689
16690        let buffer = buffer.read(cx);
16691        let snapshot = buffer.snapshot();
16692        if !snapshot.settings_at(position, cx).show_completions_on_input {
16693            return false;
16694        }
16695        let classifier = snapshot.char_classifier_at(position).for_completion(true);
16696        if trigger_in_words && classifier.is_word(char) {
16697            return true;
16698        }
16699
16700        buffer.completion_triggers().contains(text)
16701    }
16702}
16703
16704impl SemanticsProvider for Entity<Project> {
16705    fn hover(
16706        &self,
16707        buffer: &Entity<Buffer>,
16708        position: text::Anchor,
16709        cx: &mut App,
16710    ) -> Option<Task<Vec<project::Hover>>> {
16711        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
16712    }
16713
16714    fn document_highlights(
16715        &self,
16716        buffer: &Entity<Buffer>,
16717        position: text::Anchor,
16718        cx: &mut App,
16719    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
16720        Some(self.update(cx, |project, cx| {
16721            project.document_highlights(buffer, position, cx)
16722        }))
16723    }
16724
16725    fn definitions(
16726        &self,
16727        buffer: &Entity<Buffer>,
16728        position: text::Anchor,
16729        kind: GotoDefinitionKind,
16730        cx: &mut App,
16731    ) -> Option<Task<Result<Vec<LocationLink>>>> {
16732        Some(self.update(cx, |project, cx| match kind {
16733            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
16734            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
16735            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
16736            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
16737        }))
16738    }
16739
16740    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
16741        // TODO: make this work for remote projects
16742        self.update(cx, |this, cx| {
16743            buffer.update(cx, |buffer, cx| {
16744                this.any_language_server_supports_inlay_hints(buffer, cx)
16745            })
16746        })
16747    }
16748
16749    fn inlay_hints(
16750        &self,
16751        buffer_handle: Entity<Buffer>,
16752        range: Range<text::Anchor>,
16753        cx: &mut App,
16754    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
16755        Some(self.update(cx, |project, cx| {
16756            project.inlay_hints(buffer_handle, range, cx)
16757        }))
16758    }
16759
16760    fn resolve_inlay_hint(
16761        &self,
16762        hint: InlayHint,
16763        buffer_handle: Entity<Buffer>,
16764        server_id: LanguageServerId,
16765        cx: &mut App,
16766    ) -> Option<Task<anyhow::Result<InlayHint>>> {
16767        Some(self.update(cx, |project, cx| {
16768            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
16769        }))
16770    }
16771
16772    fn range_for_rename(
16773        &self,
16774        buffer: &Entity<Buffer>,
16775        position: text::Anchor,
16776        cx: &mut App,
16777    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
16778        Some(self.update(cx, |project, cx| {
16779            let buffer = buffer.clone();
16780            let task = project.prepare_rename(buffer.clone(), position, cx);
16781            cx.spawn(|_, mut cx| async move {
16782                Ok(match task.await? {
16783                    PrepareRenameResponse::Success(range) => Some(range),
16784                    PrepareRenameResponse::InvalidPosition => None,
16785                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
16786                        // Fallback on using TreeSitter info to determine identifier range
16787                        buffer.update(&mut cx, |buffer, _| {
16788                            let snapshot = buffer.snapshot();
16789                            let (range, kind) = snapshot.surrounding_word(position);
16790                            if kind != Some(CharKind::Word) {
16791                                return None;
16792                            }
16793                            Some(
16794                                snapshot.anchor_before(range.start)
16795                                    ..snapshot.anchor_after(range.end),
16796                            )
16797                        })?
16798                    }
16799                })
16800            })
16801        }))
16802    }
16803
16804    fn perform_rename(
16805        &self,
16806        buffer: &Entity<Buffer>,
16807        position: text::Anchor,
16808        new_name: String,
16809        cx: &mut App,
16810    ) -> Option<Task<Result<ProjectTransaction>>> {
16811        Some(self.update(cx, |project, cx| {
16812            project.perform_rename(buffer.clone(), position, new_name, cx)
16813        }))
16814    }
16815}
16816
16817fn inlay_hint_settings(
16818    location: Anchor,
16819    snapshot: &MultiBufferSnapshot,
16820    cx: &mut Context<Editor>,
16821) -> InlayHintSettings {
16822    let file = snapshot.file_at(location);
16823    let language = snapshot.language_at(location).map(|l| l.name());
16824    language_settings(language, file, cx).inlay_hints
16825}
16826
16827fn consume_contiguous_rows(
16828    contiguous_row_selections: &mut Vec<Selection<Point>>,
16829    selection: &Selection<Point>,
16830    display_map: &DisplaySnapshot,
16831    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
16832) -> (MultiBufferRow, MultiBufferRow) {
16833    contiguous_row_selections.push(selection.clone());
16834    let start_row = MultiBufferRow(selection.start.row);
16835    let mut end_row = ending_row(selection, display_map);
16836
16837    while let Some(next_selection) = selections.peek() {
16838        if next_selection.start.row <= end_row.0 {
16839            end_row = ending_row(next_selection, display_map);
16840            contiguous_row_selections.push(selections.next().unwrap().clone());
16841        } else {
16842            break;
16843        }
16844    }
16845    (start_row, end_row)
16846}
16847
16848fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
16849    if next_selection.end.column > 0 || next_selection.is_empty() {
16850        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
16851    } else {
16852        MultiBufferRow(next_selection.end.row)
16853    }
16854}
16855
16856impl EditorSnapshot {
16857    pub fn remote_selections_in_range<'a>(
16858        &'a self,
16859        range: &'a Range<Anchor>,
16860        collaboration_hub: &dyn CollaborationHub,
16861        cx: &'a App,
16862    ) -> impl 'a + Iterator<Item = RemoteSelection> {
16863        let participant_names = collaboration_hub.user_names(cx);
16864        let participant_indices = collaboration_hub.user_participant_indices(cx);
16865        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
16866        let collaborators_by_replica_id = collaborators_by_peer_id
16867            .iter()
16868            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
16869            .collect::<HashMap<_, _>>();
16870        self.buffer_snapshot
16871            .selections_in_range(range, false)
16872            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
16873                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
16874                let participant_index = participant_indices.get(&collaborator.user_id).copied();
16875                let user_name = participant_names.get(&collaborator.user_id).cloned();
16876                Some(RemoteSelection {
16877                    replica_id,
16878                    selection,
16879                    cursor_shape,
16880                    line_mode,
16881                    participant_index,
16882                    peer_id: collaborator.peer_id,
16883                    user_name,
16884                })
16885            })
16886    }
16887
16888    pub fn hunks_for_ranges(
16889        &self,
16890        ranges: impl Iterator<Item = Range<Point>>,
16891    ) -> Vec<MultiBufferDiffHunk> {
16892        let mut hunks = Vec::new();
16893        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
16894            HashMap::default();
16895        for query_range in ranges {
16896            let query_rows =
16897                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
16898            for hunk in self.buffer_snapshot.diff_hunks_in_range(
16899                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
16900            ) {
16901                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
16902                // when the caret is just above or just below the deleted hunk.
16903                let allow_adjacent = hunk.status().is_deleted();
16904                let related_to_selection = if allow_adjacent {
16905                    hunk.row_range.overlaps(&query_rows)
16906                        || hunk.row_range.start == query_rows.end
16907                        || hunk.row_range.end == query_rows.start
16908                } else {
16909                    hunk.row_range.overlaps(&query_rows)
16910                };
16911                if related_to_selection {
16912                    if !processed_buffer_rows
16913                        .entry(hunk.buffer_id)
16914                        .or_default()
16915                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16916                    {
16917                        continue;
16918                    }
16919                    hunks.push(hunk);
16920                }
16921            }
16922        }
16923
16924        hunks
16925    }
16926
16927    fn display_diff_hunks_for_rows<'a>(
16928        &'a self,
16929        display_rows: Range<DisplayRow>,
16930        folded_buffers: &'a HashSet<BufferId>,
16931    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
16932        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
16933        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
16934
16935        self.buffer_snapshot
16936            .diff_hunks_in_range(buffer_start..buffer_end)
16937            .filter_map(|hunk| {
16938                if folded_buffers.contains(&hunk.buffer_id) {
16939                    return None;
16940                }
16941
16942                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
16943                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
16944
16945                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
16946                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
16947
16948                let display_hunk = if hunk_display_start.column() != 0 {
16949                    DisplayDiffHunk::Folded {
16950                        display_row: hunk_display_start.row(),
16951                    }
16952                } else {
16953                    let mut end_row = hunk_display_end.row();
16954                    if hunk_display_end.column() > 0 {
16955                        end_row.0 += 1;
16956                    }
16957                    DisplayDiffHunk::Unfolded {
16958                        status: hunk.status(),
16959                        diff_base_byte_range: hunk.diff_base_byte_range,
16960                        display_row_range: hunk_display_start.row()..end_row,
16961                        multi_buffer_range: Anchor::range_in_buffer(
16962                            hunk.excerpt_id,
16963                            hunk.buffer_id,
16964                            hunk.buffer_range,
16965                        ),
16966                    }
16967                };
16968
16969                Some(display_hunk)
16970            })
16971    }
16972
16973    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16974        self.display_snapshot.buffer_snapshot.language_at(position)
16975    }
16976
16977    pub fn is_focused(&self) -> bool {
16978        self.is_focused
16979    }
16980
16981    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16982        self.placeholder_text.as_ref()
16983    }
16984
16985    pub fn scroll_position(&self) -> gpui::Point<f32> {
16986        self.scroll_anchor.scroll_position(&self.display_snapshot)
16987    }
16988
16989    fn gutter_dimensions(
16990        &self,
16991        font_id: FontId,
16992        font_size: Pixels,
16993        max_line_number_width: Pixels,
16994        cx: &App,
16995    ) -> Option<GutterDimensions> {
16996        if !self.show_gutter {
16997            return None;
16998        }
16999
17000        let descent = cx.text_system().descent(font_id, font_size);
17001        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17002        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17003
17004        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17005            matches!(
17006                ProjectSettings::get_global(cx).git.git_gutter,
17007                Some(GitGutterSetting::TrackedFiles)
17008            )
17009        });
17010        let gutter_settings = EditorSettings::get_global(cx).gutter;
17011        let show_line_numbers = self
17012            .show_line_numbers
17013            .unwrap_or(gutter_settings.line_numbers);
17014        let line_gutter_width = if show_line_numbers {
17015            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17016            let min_width_for_number_on_gutter = em_advance * 4.0;
17017            max_line_number_width.max(min_width_for_number_on_gutter)
17018        } else {
17019            0.0.into()
17020        };
17021
17022        let show_code_actions = self
17023            .show_code_actions
17024            .unwrap_or(gutter_settings.code_actions);
17025
17026        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17027
17028        let git_blame_entries_width =
17029            self.git_blame_gutter_max_author_length
17030                .map(|max_author_length| {
17031                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17032
17033                    /// The number of characters to dedicate to gaps and margins.
17034                    const SPACING_WIDTH: usize = 4;
17035
17036                    let max_char_count = max_author_length
17037                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17038                        + ::git::SHORT_SHA_LENGTH
17039                        + MAX_RELATIVE_TIMESTAMP.len()
17040                        + SPACING_WIDTH;
17041
17042                    em_advance * max_char_count
17043                });
17044
17045        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17046        left_padding += if show_code_actions || show_runnables {
17047            em_width * 3.0
17048        } else if show_git_gutter && show_line_numbers {
17049            em_width * 2.0
17050        } else if show_git_gutter || show_line_numbers {
17051            em_width
17052        } else {
17053            px(0.)
17054        };
17055
17056        let right_padding = if gutter_settings.folds && show_line_numbers {
17057            em_width * 4.0
17058        } else if gutter_settings.folds {
17059            em_width * 3.0
17060        } else if show_line_numbers {
17061            em_width
17062        } else {
17063            px(0.)
17064        };
17065
17066        Some(GutterDimensions {
17067            left_padding,
17068            right_padding,
17069            width: line_gutter_width + left_padding + right_padding,
17070            margin: -descent,
17071            git_blame_entries_width,
17072        })
17073    }
17074
17075    pub fn render_crease_toggle(
17076        &self,
17077        buffer_row: MultiBufferRow,
17078        row_contains_cursor: bool,
17079        editor: Entity<Editor>,
17080        window: &mut Window,
17081        cx: &mut App,
17082    ) -> Option<AnyElement> {
17083        let folded = self.is_line_folded(buffer_row);
17084        let mut is_foldable = false;
17085
17086        if let Some(crease) = self
17087            .crease_snapshot
17088            .query_row(buffer_row, &self.buffer_snapshot)
17089        {
17090            is_foldable = true;
17091            match crease {
17092                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17093                    if let Some(render_toggle) = render_toggle {
17094                        let toggle_callback =
17095                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17096                                if folded {
17097                                    editor.update(cx, |editor, cx| {
17098                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17099                                    });
17100                                } else {
17101                                    editor.update(cx, |editor, cx| {
17102                                        editor.unfold_at(
17103                                            &crate::UnfoldAt { buffer_row },
17104                                            window,
17105                                            cx,
17106                                        )
17107                                    });
17108                                }
17109                            });
17110                        return Some((render_toggle)(
17111                            buffer_row,
17112                            folded,
17113                            toggle_callback,
17114                            window,
17115                            cx,
17116                        ));
17117                    }
17118                }
17119            }
17120        }
17121
17122        is_foldable |= self.starts_indent(buffer_row);
17123
17124        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17125            Some(
17126                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17127                    .toggle_state(folded)
17128                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17129                        if folded {
17130                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17131                        } else {
17132                            this.fold_at(&FoldAt { buffer_row }, window, cx);
17133                        }
17134                    }))
17135                    .into_any_element(),
17136            )
17137        } else {
17138            None
17139        }
17140    }
17141
17142    pub fn render_crease_trailer(
17143        &self,
17144        buffer_row: MultiBufferRow,
17145        window: &mut Window,
17146        cx: &mut App,
17147    ) -> Option<AnyElement> {
17148        let folded = self.is_line_folded(buffer_row);
17149        if let Crease::Inline { render_trailer, .. } = self
17150            .crease_snapshot
17151            .query_row(buffer_row, &self.buffer_snapshot)?
17152        {
17153            let render_trailer = render_trailer.as_ref()?;
17154            Some(render_trailer(buffer_row, folded, window, cx))
17155        } else {
17156            None
17157        }
17158    }
17159}
17160
17161impl Deref for EditorSnapshot {
17162    type Target = DisplaySnapshot;
17163
17164    fn deref(&self) -> &Self::Target {
17165        &self.display_snapshot
17166    }
17167}
17168
17169#[derive(Clone, Debug, PartialEq, Eq)]
17170pub enum EditorEvent {
17171    InputIgnored {
17172        text: Arc<str>,
17173    },
17174    InputHandled {
17175        utf16_range_to_replace: Option<Range<isize>>,
17176        text: Arc<str>,
17177    },
17178    ExcerptsAdded {
17179        buffer: Entity<Buffer>,
17180        predecessor: ExcerptId,
17181        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17182    },
17183    ExcerptsRemoved {
17184        ids: Vec<ExcerptId>,
17185    },
17186    BufferFoldToggled {
17187        ids: Vec<ExcerptId>,
17188        folded: bool,
17189    },
17190    ExcerptsEdited {
17191        ids: Vec<ExcerptId>,
17192    },
17193    ExcerptsExpanded {
17194        ids: Vec<ExcerptId>,
17195    },
17196    BufferEdited,
17197    Edited {
17198        transaction_id: clock::Lamport,
17199    },
17200    Reparsed(BufferId),
17201    Focused,
17202    FocusedIn,
17203    Blurred,
17204    DirtyChanged,
17205    Saved,
17206    TitleChanged,
17207    DiffBaseChanged,
17208    SelectionsChanged {
17209        local: bool,
17210    },
17211    ScrollPositionChanged {
17212        local: bool,
17213        autoscroll: bool,
17214    },
17215    Closed,
17216    TransactionUndone {
17217        transaction_id: clock::Lamport,
17218    },
17219    TransactionBegun {
17220        transaction_id: clock::Lamport,
17221    },
17222    Reloaded,
17223    CursorShapeChanged,
17224}
17225
17226impl EventEmitter<EditorEvent> for Editor {}
17227
17228impl Focusable for Editor {
17229    fn focus_handle(&self, _cx: &App) -> FocusHandle {
17230        self.focus_handle.clone()
17231    }
17232}
17233
17234impl Render for Editor {
17235    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
17236        let settings = ThemeSettings::get_global(cx);
17237
17238        let mut text_style = match self.mode {
17239            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17240                color: cx.theme().colors().editor_foreground,
17241                font_family: settings.ui_font.family.clone(),
17242                font_features: settings.ui_font.features.clone(),
17243                font_fallbacks: settings.ui_font.fallbacks.clone(),
17244                font_size: rems(0.875).into(),
17245                font_weight: settings.ui_font.weight,
17246                line_height: relative(settings.buffer_line_height.value()),
17247                ..Default::default()
17248            },
17249            EditorMode::Full => TextStyle {
17250                color: cx.theme().colors().editor_foreground,
17251                font_family: settings.buffer_font.family.clone(),
17252                font_features: settings.buffer_font.features.clone(),
17253                font_fallbacks: settings.buffer_font.fallbacks.clone(),
17254                font_size: settings.buffer_font_size(cx).into(),
17255                font_weight: settings.buffer_font.weight,
17256                line_height: relative(settings.buffer_line_height.value()),
17257                ..Default::default()
17258            },
17259        };
17260        if let Some(text_style_refinement) = &self.text_style_refinement {
17261            text_style.refine(text_style_refinement)
17262        }
17263
17264        let background = match self.mode {
17265            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17266            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17267            EditorMode::Full => cx.theme().colors().editor_background,
17268        };
17269
17270        EditorElement::new(
17271            &cx.entity(),
17272            EditorStyle {
17273                background,
17274                local_player: cx.theme().players().local(),
17275                text: text_style,
17276                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17277                syntax: cx.theme().syntax().clone(),
17278                status: cx.theme().status().clone(),
17279                inlay_hints_style: make_inlay_hints_style(cx),
17280                inline_completion_styles: make_suggestion_styles(cx),
17281                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17282            },
17283        )
17284    }
17285}
17286
17287impl EntityInputHandler for Editor {
17288    fn text_for_range(
17289        &mut self,
17290        range_utf16: Range<usize>,
17291        adjusted_range: &mut Option<Range<usize>>,
17292        _: &mut Window,
17293        cx: &mut Context<Self>,
17294    ) -> Option<String> {
17295        let snapshot = self.buffer.read(cx).read(cx);
17296        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17297        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17298        if (start.0..end.0) != range_utf16 {
17299            adjusted_range.replace(start.0..end.0);
17300        }
17301        Some(snapshot.text_for_range(start..end).collect())
17302    }
17303
17304    fn selected_text_range(
17305        &mut self,
17306        ignore_disabled_input: bool,
17307        _: &mut Window,
17308        cx: &mut Context<Self>,
17309    ) -> Option<UTF16Selection> {
17310        // Prevent the IME menu from appearing when holding down an alphabetic key
17311        // while input is disabled.
17312        if !ignore_disabled_input && !self.input_enabled {
17313            return None;
17314        }
17315
17316        let selection = self.selections.newest::<OffsetUtf16>(cx);
17317        let range = selection.range();
17318
17319        Some(UTF16Selection {
17320            range: range.start.0..range.end.0,
17321            reversed: selection.reversed,
17322        })
17323    }
17324
17325    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17326        let snapshot = self.buffer.read(cx).read(cx);
17327        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17328        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17329    }
17330
17331    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17332        self.clear_highlights::<InputComposition>(cx);
17333        self.ime_transaction.take();
17334    }
17335
17336    fn replace_text_in_range(
17337        &mut self,
17338        range_utf16: Option<Range<usize>>,
17339        text: &str,
17340        window: &mut Window,
17341        cx: &mut Context<Self>,
17342    ) {
17343        if !self.input_enabled {
17344            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17345            return;
17346        }
17347
17348        self.transact(window, cx, |this, window, cx| {
17349            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17350                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17351                Some(this.selection_replacement_ranges(range_utf16, cx))
17352            } else {
17353                this.marked_text_ranges(cx)
17354            };
17355
17356            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17357                let newest_selection_id = this.selections.newest_anchor().id;
17358                this.selections
17359                    .all::<OffsetUtf16>(cx)
17360                    .iter()
17361                    .zip(ranges_to_replace.iter())
17362                    .find_map(|(selection, range)| {
17363                        if selection.id == newest_selection_id {
17364                            Some(
17365                                (range.start.0 as isize - selection.head().0 as isize)
17366                                    ..(range.end.0 as isize - selection.head().0 as isize),
17367                            )
17368                        } else {
17369                            None
17370                        }
17371                    })
17372            });
17373
17374            cx.emit(EditorEvent::InputHandled {
17375                utf16_range_to_replace: range_to_replace,
17376                text: text.into(),
17377            });
17378
17379            if let Some(new_selected_ranges) = new_selected_ranges {
17380                this.change_selections(None, window, cx, |selections| {
17381                    selections.select_ranges(new_selected_ranges)
17382                });
17383                this.backspace(&Default::default(), window, cx);
17384            }
17385
17386            this.handle_input(text, window, cx);
17387        });
17388
17389        if let Some(transaction) = self.ime_transaction {
17390            self.buffer.update(cx, |buffer, cx| {
17391                buffer.group_until_transaction(transaction, cx);
17392            });
17393        }
17394
17395        self.unmark_text(window, cx);
17396    }
17397
17398    fn replace_and_mark_text_in_range(
17399        &mut self,
17400        range_utf16: Option<Range<usize>>,
17401        text: &str,
17402        new_selected_range_utf16: Option<Range<usize>>,
17403        window: &mut Window,
17404        cx: &mut Context<Self>,
17405    ) {
17406        if !self.input_enabled {
17407            return;
17408        }
17409
17410        let transaction = self.transact(window, cx, |this, window, cx| {
17411            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17412                let snapshot = this.buffer.read(cx).read(cx);
17413                if let Some(relative_range_utf16) = range_utf16.as_ref() {
17414                    for marked_range in &mut marked_ranges {
17415                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17416                        marked_range.start.0 += relative_range_utf16.start;
17417                        marked_range.start =
17418                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17419                        marked_range.end =
17420                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17421                    }
17422                }
17423                Some(marked_ranges)
17424            } else if let Some(range_utf16) = range_utf16 {
17425                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17426                Some(this.selection_replacement_ranges(range_utf16, cx))
17427            } else {
17428                None
17429            };
17430
17431            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17432                let newest_selection_id = this.selections.newest_anchor().id;
17433                this.selections
17434                    .all::<OffsetUtf16>(cx)
17435                    .iter()
17436                    .zip(ranges_to_replace.iter())
17437                    .find_map(|(selection, range)| {
17438                        if selection.id == newest_selection_id {
17439                            Some(
17440                                (range.start.0 as isize - selection.head().0 as isize)
17441                                    ..(range.end.0 as isize - selection.head().0 as isize),
17442                            )
17443                        } else {
17444                            None
17445                        }
17446                    })
17447            });
17448
17449            cx.emit(EditorEvent::InputHandled {
17450                utf16_range_to_replace: range_to_replace,
17451                text: text.into(),
17452            });
17453
17454            if let Some(ranges) = ranges_to_replace {
17455                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17456            }
17457
17458            let marked_ranges = {
17459                let snapshot = this.buffer.read(cx).read(cx);
17460                this.selections
17461                    .disjoint_anchors()
17462                    .iter()
17463                    .map(|selection| {
17464                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17465                    })
17466                    .collect::<Vec<_>>()
17467            };
17468
17469            if text.is_empty() {
17470                this.unmark_text(window, cx);
17471            } else {
17472                this.highlight_text::<InputComposition>(
17473                    marked_ranges.clone(),
17474                    HighlightStyle {
17475                        underline: Some(UnderlineStyle {
17476                            thickness: px(1.),
17477                            color: None,
17478                            wavy: false,
17479                        }),
17480                        ..Default::default()
17481                    },
17482                    cx,
17483                );
17484            }
17485
17486            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17487            let use_autoclose = this.use_autoclose;
17488            let use_auto_surround = this.use_auto_surround;
17489            this.set_use_autoclose(false);
17490            this.set_use_auto_surround(false);
17491            this.handle_input(text, window, cx);
17492            this.set_use_autoclose(use_autoclose);
17493            this.set_use_auto_surround(use_auto_surround);
17494
17495            if let Some(new_selected_range) = new_selected_range_utf16 {
17496                let snapshot = this.buffer.read(cx).read(cx);
17497                let new_selected_ranges = marked_ranges
17498                    .into_iter()
17499                    .map(|marked_range| {
17500                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17501                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17502                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17503                        snapshot.clip_offset_utf16(new_start, Bias::Left)
17504                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17505                    })
17506                    .collect::<Vec<_>>();
17507
17508                drop(snapshot);
17509                this.change_selections(None, window, cx, |selections| {
17510                    selections.select_ranges(new_selected_ranges)
17511                });
17512            }
17513        });
17514
17515        self.ime_transaction = self.ime_transaction.or(transaction);
17516        if let Some(transaction) = self.ime_transaction {
17517            self.buffer.update(cx, |buffer, cx| {
17518                buffer.group_until_transaction(transaction, cx);
17519            });
17520        }
17521
17522        if self.text_highlights::<InputComposition>(cx).is_none() {
17523            self.ime_transaction.take();
17524        }
17525    }
17526
17527    fn bounds_for_range(
17528        &mut self,
17529        range_utf16: Range<usize>,
17530        element_bounds: gpui::Bounds<Pixels>,
17531        window: &mut Window,
17532        cx: &mut Context<Self>,
17533    ) -> Option<gpui::Bounds<Pixels>> {
17534        let text_layout_details = self.text_layout_details(window);
17535        let gpui::Size {
17536            width: em_width,
17537            height: line_height,
17538        } = self.character_size(window);
17539
17540        let snapshot = self.snapshot(window, cx);
17541        let scroll_position = snapshot.scroll_position();
17542        let scroll_left = scroll_position.x * em_width;
17543
17544        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17545        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17546            + self.gutter_dimensions.width
17547            + self.gutter_dimensions.margin;
17548        let y = line_height * (start.row().as_f32() - scroll_position.y);
17549
17550        Some(Bounds {
17551            origin: element_bounds.origin + point(x, y),
17552            size: size(em_width, line_height),
17553        })
17554    }
17555
17556    fn character_index_for_point(
17557        &mut self,
17558        point: gpui::Point<Pixels>,
17559        _window: &mut Window,
17560        _cx: &mut Context<Self>,
17561    ) -> Option<usize> {
17562        let position_map = self.last_position_map.as_ref()?;
17563        if !position_map.text_hitbox.contains(&point) {
17564            return None;
17565        }
17566        let display_point = position_map.point_for_position(point).previous_valid;
17567        let anchor = position_map
17568            .snapshot
17569            .display_point_to_anchor(display_point, Bias::Left);
17570        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17571        Some(utf16_offset.0)
17572    }
17573}
17574
17575trait SelectionExt {
17576    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17577    fn spanned_rows(
17578        &self,
17579        include_end_if_at_line_start: bool,
17580        map: &DisplaySnapshot,
17581    ) -> Range<MultiBufferRow>;
17582}
17583
17584impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17585    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17586        let start = self
17587            .start
17588            .to_point(&map.buffer_snapshot)
17589            .to_display_point(map);
17590        let end = self
17591            .end
17592            .to_point(&map.buffer_snapshot)
17593            .to_display_point(map);
17594        if self.reversed {
17595            end..start
17596        } else {
17597            start..end
17598        }
17599    }
17600
17601    fn spanned_rows(
17602        &self,
17603        include_end_if_at_line_start: bool,
17604        map: &DisplaySnapshot,
17605    ) -> Range<MultiBufferRow> {
17606        let start = self.start.to_point(&map.buffer_snapshot);
17607        let mut end = self.end.to_point(&map.buffer_snapshot);
17608        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17609            end.row -= 1;
17610        }
17611
17612        let buffer_start = map.prev_line_boundary(start).0;
17613        let buffer_end = map.next_line_boundary(end).0;
17614        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17615    }
17616}
17617
17618impl<T: InvalidationRegion> InvalidationStack<T> {
17619    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17620    where
17621        S: Clone + ToOffset,
17622    {
17623        while let Some(region) = self.last() {
17624            let all_selections_inside_invalidation_ranges =
17625                if selections.len() == region.ranges().len() {
17626                    selections
17627                        .iter()
17628                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17629                        .all(|(selection, invalidation_range)| {
17630                            let head = selection.head().to_offset(buffer);
17631                            invalidation_range.start <= head && invalidation_range.end >= head
17632                        })
17633                } else {
17634                    false
17635                };
17636
17637            if all_selections_inside_invalidation_ranges {
17638                break;
17639            } else {
17640                self.pop();
17641            }
17642        }
17643    }
17644}
17645
17646impl<T> Default for InvalidationStack<T> {
17647    fn default() -> Self {
17648        Self(Default::default())
17649    }
17650}
17651
17652impl<T> Deref for InvalidationStack<T> {
17653    type Target = Vec<T>;
17654
17655    fn deref(&self) -> &Self::Target {
17656        &self.0
17657    }
17658}
17659
17660impl<T> DerefMut for InvalidationStack<T> {
17661    fn deref_mut(&mut self) -> &mut Self::Target {
17662        &mut self.0
17663    }
17664}
17665
17666impl InvalidationRegion for SnippetState {
17667    fn ranges(&self) -> &[Range<Anchor>] {
17668        &self.ranges[self.active_index]
17669    }
17670}
17671
17672pub fn diagnostic_block_renderer(
17673    diagnostic: Diagnostic,
17674    max_message_rows: Option<u8>,
17675    allow_closing: bool,
17676    _is_valid: bool,
17677) -> RenderBlock {
17678    let (text_without_backticks, code_ranges) =
17679        highlight_diagnostic_message(&diagnostic, max_message_rows);
17680
17681    Arc::new(move |cx: &mut BlockContext| {
17682        let group_id: SharedString = cx.block_id.to_string().into();
17683
17684        let mut text_style = cx.window.text_style().clone();
17685        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17686        let theme_settings = ThemeSettings::get_global(cx);
17687        text_style.font_family = theme_settings.buffer_font.family.clone();
17688        text_style.font_style = theme_settings.buffer_font.style;
17689        text_style.font_features = theme_settings.buffer_font.features.clone();
17690        text_style.font_weight = theme_settings.buffer_font.weight;
17691
17692        let multi_line_diagnostic = diagnostic.message.contains('\n');
17693
17694        let buttons = |diagnostic: &Diagnostic| {
17695            if multi_line_diagnostic {
17696                v_flex()
17697            } else {
17698                h_flex()
17699            }
17700            .when(allow_closing, |div| {
17701                div.children(diagnostic.is_primary.then(|| {
17702                    IconButton::new("close-block", IconName::XCircle)
17703                        .icon_color(Color::Muted)
17704                        .size(ButtonSize::Compact)
17705                        .style(ButtonStyle::Transparent)
17706                        .visible_on_hover(group_id.clone())
17707                        .on_click(move |_click, window, cx| {
17708                            window.dispatch_action(Box::new(Cancel), cx)
17709                        })
17710                        .tooltip(|window, cx| {
17711                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
17712                        })
17713                }))
17714            })
17715            .child(
17716                IconButton::new("copy-block", IconName::Copy)
17717                    .icon_color(Color::Muted)
17718                    .size(ButtonSize::Compact)
17719                    .style(ButtonStyle::Transparent)
17720                    .visible_on_hover(group_id.clone())
17721                    .on_click({
17722                        let message = diagnostic.message.clone();
17723                        move |_click, _, cx| {
17724                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
17725                        }
17726                    })
17727                    .tooltip(Tooltip::text("Copy diagnostic message")),
17728            )
17729        };
17730
17731        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
17732            AvailableSpace::min_size(),
17733            cx.window,
17734            cx.app,
17735        );
17736
17737        h_flex()
17738            .id(cx.block_id)
17739            .group(group_id.clone())
17740            .relative()
17741            .size_full()
17742            .block_mouse_down()
17743            .pl(cx.gutter_dimensions.width)
17744            .w(cx.max_width - cx.gutter_dimensions.full_width())
17745            .child(
17746                div()
17747                    .flex()
17748                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
17749                    .flex_shrink(),
17750            )
17751            .child(buttons(&diagnostic))
17752            .child(div().flex().flex_shrink_0().child(
17753                StyledText::new(text_without_backticks.clone()).with_highlights(
17754                    &text_style,
17755                    code_ranges.iter().map(|range| {
17756                        (
17757                            range.clone(),
17758                            HighlightStyle {
17759                                font_weight: Some(FontWeight::BOLD),
17760                                ..Default::default()
17761                            },
17762                        )
17763                    }),
17764                ),
17765            ))
17766            .into_any_element()
17767    })
17768}
17769
17770fn inline_completion_edit_text(
17771    current_snapshot: &BufferSnapshot,
17772    edits: &[(Range<Anchor>, String)],
17773    edit_preview: &EditPreview,
17774    include_deletions: bool,
17775    cx: &App,
17776) -> HighlightedText {
17777    let edits = edits
17778        .iter()
17779        .map(|(anchor, text)| {
17780            (
17781                anchor.start.text_anchor..anchor.end.text_anchor,
17782                text.clone(),
17783            )
17784        })
17785        .collect::<Vec<_>>();
17786
17787    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
17788}
17789
17790pub fn highlight_diagnostic_message(
17791    diagnostic: &Diagnostic,
17792    mut max_message_rows: Option<u8>,
17793) -> (SharedString, Vec<Range<usize>>) {
17794    let mut text_without_backticks = String::new();
17795    let mut code_ranges = Vec::new();
17796
17797    if let Some(source) = &diagnostic.source {
17798        text_without_backticks.push_str(source);
17799        code_ranges.push(0..source.len());
17800        text_without_backticks.push_str(": ");
17801    }
17802
17803    let mut prev_offset = 0;
17804    let mut in_code_block = false;
17805    let has_row_limit = max_message_rows.is_some();
17806    let mut newline_indices = diagnostic
17807        .message
17808        .match_indices('\n')
17809        .filter(|_| has_row_limit)
17810        .map(|(ix, _)| ix)
17811        .fuse()
17812        .peekable();
17813
17814    for (quote_ix, _) in diagnostic
17815        .message
17816        .match_indices('`')
17817        .chain([(diagnostic.message.len(), "")])
17818    {
17819        let mut first_newline_ix = None;
17820        let mut last_newline_ix = None;
17821        while let Some(newline_ix) = newline_indices.peek() {
17822            if *newline_ix < quote_ix {
17823                if first_newline_ix.is_none() {
17824                    first_newline_ix = Some(*newline_ix);
17825                }
17826                last_newline_ix = Some(*newline_ix);
17827
17828                if let Some(rows_left) = &mut max_message_rows {
17829                    if *rows_left == 0 {
17830                        break;
17831                    } else {
17832                        *rows_left -= 1;
17833                    }
17834                }
17835                let _ = newline_indices.next();
17836            } else {
17837                break;
17838            }
17839        }
17840        let prev_len = text_without_backticks.len();
17841        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
17842        text_without_backticks.push_str(new_text);
17843        if in_code_block {
17844            code_ranges.push(prev_len..text_without_backticks.len());
17845        }
17846        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
17847        in_code_block = !in_code_block;
17848        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
17849            text_without_backticks.push_str("...");
17850            break;
17851        }
17852    }
17853
17854    (text_without_backticks.into(), code_ranges)
17855}
17856
17857fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
17858    match severity {
17859        DiagnosticSeverity::ERROR => colors.error,
17860        DiagnosticSeverity::WARNING => colors.warning,
17861        DiagnosticSeverity::INFORMATION => colors.info,
17862        DiagnosticSeverity::HINT => colors.info,
17863        _ => colors.ignored,
17864    }
17865}
17866
17867pub fn styled_runs_for_code_label<'a>(
17868    label: &'a CodeLabel,
17869    syntax_theme: &'a theme::SyntaxTheme,
17870) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
17871    let fade_out = HighlightStyle {
17872        fade_out: Some(0.35),
17873        ..Default::default()
17874    };
17875
17876    let mut prev_end = label.filter_range.end;
17877    label
17878        .runs
17879        .iter()
17880        .enumerate()
17881        .flat_map(move |(ix, (range, highlight_id))| {
17882            let style = if let Some(style) = highlight_id.style(syntax_theme) {
17883                style
17884            } else {
17885                return Default::default();
17886            };
17887            let mut muted_style = style;
17888            muted_style.highlight(fade_out);
17889
17890            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
17891            if range.start >= label.filter_range.end {
17892                if range.start > prev_end {
17893                    runs.push((prev_end..range.start, fade_out));
17894                }
17895                runs.push((range.clone(), muted_style));
17896            } else if range.end <= label.filter_range.end {
17897                runs.push((range.clone(), style));
17898            } else {
17899                runs.push((range.start..label.filter_range.end, style));
17900                runs.push((label.filter_range.end..range.end, muted_style));
17901            }
17902            prev_end = cmp::max(prev_end, range.end);
17903
17904            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
17905                runs.push((prev_end..label.text.len(), fade_out));
17906            }
17907
17908            runs
17909        })
17910}
17911
17912pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
17913    let mut prev_index = 0;
17914    let mut prev_codepoint: Option<char> = None;
17915    text.char_indices()
17916        .chain([(text.len(), '\0')])
17917        .filter_map(move |(index, codepoint)| {
17918            let prev_codepoint = prev_codepoint.replace(codepoint)?;
17919            let is_boundary = index == text.len()
17920                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
17921                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
17922            if is_boundary {
17923                let chunk = &text[prev_index..index];
17924                prev_index = index;
17925                Some(chunk)
17926            } else {
17927                None
17928            }
17929        })
17930}
17931
17932pub trait RangeToAnchorExt: Sized {
17933    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
17934
17935    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
17936        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
17937        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
17938    }
17939}
17940
17941impl<T: ToOffset> RangeToAnchorExt for Range<T> {
17942    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
17943        let start_offset = self.start.to_offset(snapshot);
17944        let end_offset = self.end.to_offset(snapshot);
17945        if start_offset == end_offset {
17946            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
17947        } else {
17948            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
17949        }
17950    }
17951}
17952
17953pub trait RowExt {
17954    fn as_f32(&self) -> f32;
17955
17956    fn next_row(&self) -> Self;
17957
17958    fn previous_row(&self) -> Self;
17959
17960    fn minus(&self, other: Self) -> u32;
17961}
17962
17963impl RowExt for DisplayRow {
17964    fn as_f32(&self) -> f32 {
17965        self.0 as f32
17966    }
17967
17968    fn next_row(&self) -> Self {
17969        Self(self.0 + 1)
17970    }
17971
17972    fn previous_row(&self) -> Self {
17973        Self(self.0.saturating_sub(1))
17974    }
17975
17976    fn minus(&self, other: Self) -> u32 {
17977        self.0 - other.0
17978    }
17979}
17980
17981impl RowExt for MultiBufferRow {
17982    fn as_f32(&self) -> f32 {
17983        self.0 as f32
17984    }
17985
17986    fn next_row(&self) -> Self {
17987        Self(self.0 + 1)
17988    }
17989
17990    fn previous_row(&self) -> Self {
17991        Self(self.0.saturating_sub(1))
17992    }
17993
17994    fn minus(&self, other: Self) -> u32 {
17995        self.0 - other.0
17996    }
17997}
17998
17999trait RowRangeExt {
18000    type Row;
18001
18002    fn len(&self) -> usize;
18003
18004    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18005}
18006
18007impl RowRangeExt for Range<MultiBufferRow> {
18008    type Row = MultiBufferRow;
18009
18010    fn len(&self) -> usize {
18011        (self.end.0 - self.start.0) as usize
18012    }
18013
18014    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18015        (self.start.0..self.end.0).map(MultiBufferRow)
18016    }
18017}
18018
18019impl RowRangeExt for Range<DisplayRow> {
18020    type Row = DisplayRow;
18021
18022    fn len(&self) -> usize {
18023        (self.end.0 - self.start.0) as usize
18024    }
18025
18026    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18027        (self.start.0..self.end.0).map(DisplayRow)
18028    }
18029}
18030
18031/// If select range has more than one line, we
18032/// just point the cursor to range.start.
18033fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18034    if range.start.row == range.end.row {
18035        range
18036    } else {
18037        range.start..range.start
18038    }
18039}
18040pub struct KillRing(ClipboardItem);
18041impl Global for KillRing {}
18042
18043const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18044
18045fn all_edits_insertions_or_deletions(
18046    edits: &Vec<(Range<Anchor>, String)>,
18047    snapshot: &MultiBufferSnapshot,
18048) -> bool {
18049    let mut all_insertions = true;
18050    let mut all_deletions = true;
18051
18052    for (range, new_text) in edits.iter() {
18053        let range_is_empty = range.to_offset(&snapshot).is_empty();
18054        let text_is_empty = new_text.is_empty();
18055
18056        if range_is_empty != text_is_empty {
18057            if range_is_empty {
18058                all_deletions = false;
18059            } else {
18060                all_insertions = false;
18061            }
18062        } else {
18063            return false;
18064        }
18065
18066        if !all_insertions && !all_deletions {
18067            return false;
18068        }
18069    }
18070    all_insertions || all_deletions
18071}