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;
   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::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{
   71    future::{self, Shared},
   72    FutureExt,
   73};
   74use fuzzy::StringMatchCandidate;
   75
   76use ::git::Restore;
   77use code_context_menus::{
   78    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   79    CompletionsMenu, ContextMenuOrigin,
   80};
   81use git::blame::GitBlame;
   82use gpui::{
   83    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   84    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   85    ClipboardEntry, ClipboardItem, Context, DispatchPhase, 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, DiskState,
  106    EditPredictionsMode, EditPreview, HighlightedText, IndentKind, IndentSize, Language,
  107    OffsetRangeExt, Point, 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 std::iter::Peekable;
  117use task::{ResolvedTask, TaskTemplate, TaskVariables};
  118
  119use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  120pub use lsp::CompletionContext;
  121use lsp::{
  122    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  123    LanguageServerId, LanguageServerName,
  124};
  125
  126use language::BufferSnapshot;
  127use movement::TextLayoutDetails;
  128pub use multi_buffer::{
  129    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  130    ToOffset, ToPoint,
  131};
  132use multi_buffer::{
  133    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  134    ToOffsetUtf16,
  135};
  136use project::{
  137    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  138    project_settings::{GitGutterSetting, ProjectSettings},
  139    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  140    PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  141};
  142use rand::prelude::*;
  143use rpc::{proto::*, ErrorExt};
  144use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  145use selections_collection::{
  146    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  147};
  148use serde::{Deserialize, Serialize};
  149use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  150use smallvec::SmallVec;
  151use snippet::Snippet;
  152use std::{
  153    any::TypeId,
  154    borrow::Cow,
  155    cell::RefCell,
  156    cmp::{self, Ordering, Reverse},
  157    mem,
  158    num::NonZeroU32,
  159    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  160    path::{Path, PathBuf},
  161    rc::Rc,
  162    sync::Arc,
  163    time::{Duration, Instant},
  164};
  165pub use sum_tree::Bias;
  166use sum_tree::TreeMap;
  167use text::{BufferId, OffsetUtf16, Rope};
  168use theme::{
  169    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  170    ThemeColors, ThemeSettings,
  171};
  172use ui::{
  173    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  174    Tooltip,
  175};
  176use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  177use workspace::{
  178    item::{ItemHandle, PreviewTabsSettings},
  179    ItemId, RestoreOnStartupBehavior,
  180};
  181use workspace::{
  182    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  183    WorkspaceSettings,
  184};
  185use workspace::{
  186    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  187};
  188use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  189
  190use crate::hover_links::{find_url, find_url_from_range};
  191use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  192
  193pub const FILE_HEADER_HEIGHT: u32 = 2;
  194pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  195pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  196pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  197const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  198const MAX_LINE_LEN: usize = 1024;
  199const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  200const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  201pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  202#[doc(hidden)]
  203pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  204
  205pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  206pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  207
  208pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  209pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  210
  211const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  212    alt: true,
  213    shift: true,
  214    control: false,
  215    platform: false,
  216    function: false,
  217};
  218
  219#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  220pub enum InlayId {
  221    InlineCompletion(usize),
  222    Hint(usize),
  223}
  224
  225impl InlayId {
  226    fn id(&self) -> usize {
  227        match self {
  228            Self::InlineCompletion(id) => *id,
  229            Self::Hint(id) => *id,
  230        }
  231    }
  232}
  233
  234enum DocumentHighlightRead {}
  235enum DocumentHighlightWrite {}
  236enum InputComposition {}
  237enum SelectedTextHighlight {}
  238
  239#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  240pub enum Navigated {
  241    Yes,
  242    No,
  243}
  244
  245impl Navigated {
  246    pub fn from_bool(yes: bool) -> Navigated {
  247        if yes {
  248            Navigated::Yes
  249        } else {
  250            Navigated::No
  251        }
  252    }
  253}
  254
  255pub fn init_settings(cx: &mut App) {
  256    EditorSettings::register(cx);
  257}
  258
  259pub fn init(cx: &mut App) {
  260    init_settings(cx);
  261
  262    workspace::register_project_item::<Editor>(cx);
  263    workspace::FollowableViewRegistry::register::<Editor>(cx);
  264    workspace::register_serializable_item::<Editor>(cx);
  265
  266    cx.observe_new(
  267        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  268            workspace.register_action(Editor::new_file);
  269            workspace.register_action(Editor::new_file_vertical);
  270            workspace.register_action(Editor::new_file_horizontal);
  271            workspace.register_action(Editor::cancel_language_server_work);
  272        },
  273    )
  274    .detach();
  275
  276    cx.on_action(move |_: &workspace::NewFile, cx| {
  277        let app_state = workspace::AppState::global(cx);
  278        if let Some(app_state) = app_state.upgrade() {
  279            workspace::open_new(
  280                Default::default(),
  281                app_state,
  282                cx,
  283                |workspace, window, cx| {
  284                    Editor::new_file(workspace, &Default::default(), window, cx)
  285                },
  286            )
  287            .detach();
  288        }
  289    });
  290    cx.on_action(move |_: &workspace::NewWindow, 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                    cx.activate(true);
  299                    Editor::new_file(workspace, &Default::default(), window, cx)
  300                },
  301            )
  302            .detach();
  303        }
  304    });
  305}
  306
  307pub struct SearchWithinRange;
  308
  309trait InvalidationRegion {
  310    fn ranges(&self) -> &[Range<Anchor>];
  311}
  312
  313#[derive(Clone, Debug, PartialEq)]
  314pub enum SelectPhase {
  315    Begin {
  316        position: DisplayPoint,
  317        add: bool,
  318        click_count: usize,
  319    },
  320    BeginColumnar {
  321        position: DisplayPoint,
  322        reset: bool,
  323        goal_column: u32,
  324    },
  325    Extend {
  326        position: DisplayPoint,
  327        click_count: usize,
  328    },
  329    Update {
  330        position: DisplayPoint,
  331        goal_column: u32,
  332        scroll_delta: gpui::Point<f32>,
  333    },
  334    End,
  335}
  336
  337#[derive(Clone, Debug)]
  338pub enum SelectMode {
  339    Character,
  340    Word(Range<Anchor>),
  341    Line(Range<Anchor>),
  342    All,
  343}
  344
  345#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  346pub enum EditorMode {
  347    SingleLine { auto_width: bool },
  348    AutoHeight { max_lines: usize },
  349    Full,
  350}
  351
  352#[derive(Copy, Clone, Debug)]
  353pub enum SoftWrap {
  354    /// Prefer not to wrap at all.
  355    ///
  356    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  357    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  358    GitDiff,
  359    /// Prefer a single line generally, unless an overly long line is encountered.
  360    None,
  361    /// Soft wrap lines that exceed the editor width.
  362    EditorWidth,
  363    /// Soft wrap lines at the preferred line length.
  364    Column(u32),
  365    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  366    Bounded(u32),
  367}
  368
  369#[derive(Clone)]
  370pub struct EditorStyle {
  371    pub background: Hsla,
  372    pub local_player: PlayerColor,
  373    pub text: TextStyle,
  374    pub scrollbar_width: Pixels,
  375    pub syntax: Arc<SyntaxTheme>,
  376    pub status: StatusColors,
  377    pub inlay_hints_style: HighlightStyle,
  378    pub inline_completion_styles: InlineCompletionStyles,
  379    pub unnecessary_code_fade: f32,
  380}
  381
  382impl Default for EditorStyle {
  383    fn default() -> Self {
  384        Self {
  385            background: Hsla::default(),
  386            local_player: PlayerColor::default(),
  387            text: TextStyle::default(),
  388            scrollbar_width: Pixels::default(),
  389            syntax: Default::default(),
  390            // HACK: Status colors don't have a real default.
  391            // We should look into removing the status colors from the editor
  392            // style and retrieve them directly from the theme.
  393            status: StatusColors::dark(),
  394            inlay_hints_style: HighlightStyle::default(),
  395            inline_completion_styles: InlineCompletionStyles {
  396                insertion: HighlightStyle::default(),
  397                whitespace: HighlightStyle::default(),
  398            },
  399            unnecessary_code_fade: Default::default(),
  400        }
  401    }
  402}
  403
  404pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  405    let show_background = language_settings::language_settings(None, None, cx)
  406        .inlay_hints
  407        .show_background;
  408
  409    HighlightStyle {
  410        color: Some(cx.theme().status().hint),
  411        background_color: show_background.then(|| cx.theme().status().hint_background),
  412        ..HighlightStyle::default()
  413    }
  414}
  415
  416pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  417    InlineCompletionStyles {
  418        insertion: HighlightStyle {
  419            color: Some(cx.theme().status().predictive),
  420            ..HighlightStyle::default()
  421        },
  422        whitespace: HighlightStyle {
  423            background_color: Some(cx.theme().status().created_background),
  424            ..HighlightStyle::default()
  425        },
  426    }
  427}
  428
  429type CompletionId = usize;
  430
  431pub(crate) enum EditDisplayMode {
  432    TabAccept,
  433    DiffPopover,
  434    Inline,
  435}
  436
  437enum InlineCompletion {
  438    Edit {
  439        edits: Vec<(Range<Anchor>, String)>,
  440        edit_preview: Option<EditPreview>,
  441        display_mode: EditDisplayMode,
  442        snapshot: BufferSnapshot,
  443    },
  444    Move {
  445        target: Anchor,
  446        snapshot: BufferSnapshot,
  447    },
  448}
  449
  450struct InlineCompletionState {
  451    inlay_ids: Vec<InlayId>,
  452    completion: InlineCompletion,
  453    completion_id: Option<SharedString>,
  454    invalidation_range: Range<Anchor>,
  455}
  456
  457enum EditPredictionSettings {
  458    Disabled,
  459    Enabled {
  460        show_in_menu: bool,
  461        preview_requires_modifier: bool,
  462    },
  463}
  464
  465enum InlineCompletionHighlight {}
  466
  467#[derive(Debug, Clone)]
  468struct InlineDiagnostic {
  469    message: SharedString,
  470    group_id: usize,
  471    is_primary: bool,
  472    start: Point,
  473    severity: DiagnosticSeverity,
  474}
  475
  476pub enum MenuInlineCompletionsPolicy {
  477    Never,
  478    ByProvider,
  479}
  480
  481pub enum EditPredictionPreview {
  482    /// Modifier is not pressed
  483    Inactive,
  484    /// Modifier pressed
  485    Active {
  486        previous_scroll_position: Option<ScrollAnchor>,
  487    },
  488}
  489
  490#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  491struct EditorActionId(usize);
  492
  493impl EditorActionId {
  494    pub fn post_inc(&mut self) -> Self {
  495        let answer = self.0;
  496
  497        *self = Self(answer + 1);
  498
  499        Self(answer)
  500    }
  501}
  502
  503// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  504// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  505
  506type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  507type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  508
  509#[derive(Default)]
  510struct ScrollbarMarkerState {
  511    scrollbar_size: Size<Pixels>,
  512    dirty: bool,
  513    markers: Arc<[PaintQuad]>,
  514    pending_refresh: Option<Task<Result<()>>>,
  515}
  516
  517impl ScrollbarMarkerState {
  518    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  519        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  520    }
  521}
  522
  523#[derive(Clone, Debug)]
  524struct RunnableTasks {
  525    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  526    offset: MultiBufferOffset,
  527    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  528    column: u32,
  529    // Values of all named captures, including those starting with '_'
  530    extra_variables: HashMap<String, String>,
  531    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  532    context_range: Range<BufferOffset>,
  533}
  534
  535impl RunnableTasks {
  536    fn resolve<'a>(
  537        &'a self,
  538        cx: &'a task::TaskContext,
  539    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  540        self.templates.iter().filter_map(|(kind, template)| {
  541            template
  542                .resolve_task(&kind.to_id_base(), cx)
  543                .map(|task| (kind.clone(), task))
  544        })
  545    }
  546}
  547
  548#[derive(Clone)]
  549struct ResolvedTasks {
  550    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  551    position: Anchor,
  552}
  553#[derive(Copy, Clone, Debug)]
  554struct MultiBufferOffset(usize);
  555#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  556struct BufferOffset(usize);
  557
  558// Addons allow storing per-editor state in other crates (e.g. Vim)
  559pub trait Addon: 'static {
  560    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  561
  562    fn render_buffer_header_controls(
  563        &self,
  564        _: &ExcerptInfo,
  565        _: &Window,
  566        _: &App,
  567    ) -> Option<AnyElement> {
  568        None
  569    }
  570
  571    fn to_any(&self) -> &dyn std::any::Any;
  572}
  573
  574#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  575pub enum IsVimMode {
  576    Yes,
  577    No,
  578}
  579
  580/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  581///
  582/// See the [module level documentation](self) for more information.
  583pub struct Editor {
  584    focus_handle: FocusHandle,
  585    last_focused_descendant: Option<WeakFocusHandle>,
  586    /// The text buffer being edited
  587    buffer: Entity<MultiBuffer>,
  588    /// Map of how text in the buffer should be displayed.
  589    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  590    pub display_map: Entity<DisplayMap>,
  591    pub selections: SelectionsCollection,
  592    pub scroll_manager: ScrollManager,
  593    /// When inline assist editors are linked, they all render cursors because
  594    /// typing enters text into each of them, even the ones that aren't focused.
  595    pub(crate) show_cursor_when_unfocused: bool,
  596    columnar_selection_tail: Option<Anchor>,
  597    add_selections_state: Option<AddSelectionsState>,
  598    select_next_state: Option<SelectNextState>,
  599    select_prev_state: Option<SelectNextState>,
  600    selection_history: SelectionHistory,
  601    autoclose_regions: Vec<AutocloseRegion>,
  602    snippet_stack: InvalidationStack<SnippetState>,
  603    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  604    ime_transaction: Option<TransactionId>,
  605    active_diagnostics: Option<ActiveDiagnosticGroup>,
  606    show_inline_diagnostics: bool,
  607    inline_diagnostics_update: Task<()>,
  608    inline_diagnostics_enabled: bool,
  609    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  610    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  611
  612    // TODO: make this a access method
  613    pub project: Option<Entity<Project>>,
  614    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  615    completion_provider: Option<Box<dyn CompletionProvider>>,
  616    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  617    blink_manager: Entity<BlinkManager>,
  618    show_cursor_names: bool,
  619    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  620    pub show_local_selections: bool,
  621    mode: EditorMode,
  622    show_breadcrumbs: bool,
  623    show_gutter: bool,
  624    show_scrollbars: bool,
  625    show_line_numbers: Option<bool>,
  626    use_relative_line_numbers: Option<bool>,
  627    show_git_diff_gutter: Option<bool>,
  628    show_code_actions: Option<bool>,
  629    show_runnables: Option<bool>,
  630    show_wrap_guides: Option<bool>,
  631    show_indent_guides: Option<bool>,
  632    placeholder_text: Option<Arc<str>>,
  633    highlight_order: usize,
  634    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  635    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  636    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  637    scrollbar_marker_state: ScrollbarMarkerState,
  638    active_indent_guides_state: ActiveIndentGuidesState,
  639    nav_history: Option<ItemNavHistory>,
  640    context_menu: RefCell<Option<CodeContextMenu>>,
  641    mouse_context_menu: Option<MouseContextMenu>,
  642    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  643    signature_help_state: SignatureHelpState,
  644    auto_signature_help: Option<bool>,
  645    find_all_references_task_sources: Vec<Anchor>,
  646    next_completion_id: CompletionId,
  647    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  648    code_actions_task: Option<Task<Result<()>>>,
  649    selection_highlight_task: Option<Task<()>>,
  650    document_highlights_task: Option<Task<()>>,
  651    linked_editing_range_task: Option<Task<Option<()>>>,
  652    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  653    pending_rename: Option<RenameState>,
  654    searchable: bool,
  655    cursor_shape: CursorShape,
  656    current_line_highlight: Option<CurrentLineHighlight>,
  657    collapse_matches: bool,
  658    autoindent_mode: Option<AutoindentMode>,
  659    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  660    input_enabled: bool,
  661    use_modal_editing: bool,
  662    read_only: bool,
  663    leader_peer_id: Option<PeerId>,
  664    remote_id: Option<ViewId>,
  665    hover_state: HoverState,
  666    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  667    gutter_hovered: bool,
  668    hovered_link_state: Option<HoveredLinkState>,
  669    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  670    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  671    active_inline_completion: Option<InlineCompletionState>,
  672    /// Used to prevent flickering as the user types while the menu is open
  673    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  674    edit_prediction_settings: EditPredictionSettings,
  675    inline_completions_hidden_for_vim_mode: bool,
  676    show_inline_completions_override: Option<bool>,
  677    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  678    edit_prediction_preview: EditPredictionPreview,
  679    edit_prediction_cursor_on_leading_whitespace: bool,
  680    edit_prediction_requires_modifier_in_leading_space: bool,
  681    inlay_hint_cache: InlayHintCache,
  682    next_inlay_id: usize,
  683    _subscriptions: Vec<Subscription>,
  684    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  685    gutter_dimensions: GutterDimensions,
  686    style: Option<EditorStyle>,
  687    text_style_refinement: Option<TextStyleRefinement>,
  688    next_editor_action_id: EditorActionId,
  689    editor_actions:
  690        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  691    use_autoclose: bool,
  692    use_auto_surround: bool,
  693    auto_replace_emoji_shortcode: bool,
  694    show_git_blame_gutter: bool,
  695    show_git_blame_inline: bool,
  696    show_git_blame_inline_delay_task: Option<Task<()>>,
  697    git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
  698    distinguish_unstaged_diff_hunks: bool,
  699    git_blame_inline_enabled: bool,
  700    serialize_dirty_buffers: bool,
  701    show_selection_menu: Option<bool>,
  702    blame: Option<Entity<GitBlame>>,
  703    blame_subscription: Option<Subscription>,
  704    custom_context_menu: Option<
  705        Box<
  706            dyn 'static
  707                + Fn(
  708                    &mut Self,
  709                    DisplayPoint,
  710                    &mut Window,
  711                    &mut Context<Self>,
  712                ) -> Option<Entity<ui::ContextMenu>>,
  713        >,
  714    >,
  715    last_bounds: Option<Bounds<Pixels>>,
  716    last_position_map: Option<Rc<PositionMap>>,
  717    expect_bounds_change: Option<Bounds<Pixels>>,
  718    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  719    tasks_update_task: Option<Task<()>>,
  720    in_project_search: bool,
  721    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  722    breadcrumb_header: Option<String>,
  723    focused_block: Option<FocusedBlock>,
  724    next_scroll_position: NextScrollCursorCenterTopBottom,
  725    addons: HashMap<TypeId, Box<dyn Addon>>,
  726    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  727    load_diff_task: Option<Shared<Task<()>>>,
  728    selection_mark_mode: bool,
  729    toggle_fold_multiple_buffers: Task<()>,
  730    _scroll_cursor_center_top_bottom_task: Task<()>,
  731    serialize_selections: Task<()>,
  732    mouse_cursor_hidden: bool,
  733    hide_mouse_while_typing: bool,
  734}
  735
  736#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  737enum NextScrollCursorCenterTopBottom {
  738    #[default]
  739    Center,
  740    Top,
  741    Bottom,
  742}
  743
  744impl NextScrollCursorCenterTopBottom {
  745    fn next(&self) -> Self {
  746        match self {
  747            Self::Center => Self::Top,
  748            Self::Top => Self::Bottom,
  749            Self::Bottom => Self::Center,
  750        }
  751    }
  752}
  753
  754#[derive(Clone)]
  755pub struct EditorSnapshot {
  756    pub mode: EditorMode,
  757    show_gutter: bool,
  758    show_line_numbers: Option<bool>,
  759    show_git_diff_gutter: Option<bool>,
  760    show_code_actions: Option<bool>,
  761    show_runnables: Option<bool>,
  762    git_blame_gutter_max_author_length: Option<usize>,
  763    pub display_snapshot: DisplaySnapshot,
  764    pub placeholder_text: Option<Arc<str>>,
  765    is_focused: bool,
  766    scroll_anchor: ScrollAnchor,
  767    ongoing_scroll: OngoingScroll,
  768    current_line_highlight: CurrentLineHighlight,
  769    gutter_hovered: bool,
  770}
  771
  772const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  773
  774#[derive(Default, Debug, Clone, Copy)]
  775pub struct GutterDimensions {
  776    pub left_padding: Pixels,
  777    pub right_padding: Pixels,
  778    pub width: Pixels,
  779    pub margin: Pixels,
  780    pub git_blame_entries_width: Option<Pixels>,
  781}
  782
  783impl GutterDimensions {
  784    /// The full width of the space taken up by the gutter.
  785    pub fn full_width(&self) -> Pixels {
  786        self.margin + self.width
  787    }
  788
  789    /// The width of the space reserved for the fold indicators,
  790    /// use alongside 'justify_end' and `gutter_width` to
  791    /// right align content with the line numbers
  792    pub fn fold_area_width(&self) -> Pixels {
  793        self.margin + self.right_padding
  794    }
  795}
  796
  797#[derive(Debug)]
  798pub struct RemoteSelection {
  799    pub replica_id: ReplicaId,
  800    pub selection: Selection<Anchor>,
  801    pub cursor_shape: CursorShape,
  802    pub peer_id: PeerId,
  803    pub line_mode: bool,
  804    pub participant_index: Option<ParticipantIndex>,
  805    pub user_name: Option<SharedString>,
  806}
  807
  808#[derive(Clone, Debug)]
  809struct SelectionHistoryEntry {
  810    selections: Arc<[Selection<Anchor>]>,
  811    select_next_state: Option<SelectNextState>,
  812    select_prev_state: Option<SelectNextState>,
  813    add_selections_state: Option<AddSelectionsState>,
  814}
  815
  816enum SelectionHistoryMode {
  817    Normal,
  818    Undoing,
  819    Redoing,
  820}
  821
  822#[derive(Clone, PartialEq, Eq, Hash)]
  823struct HoveredCursor {
  824    replica_id: u16,
  825    selection_id: usize,
  826}
  827
  828impl Default for SelectionHistoryMode {
  829    fn default() -> Self {
  830        Self::Normal
  831    }
  832}
  833
  834#[derive(Default)]
  835struct SelectionHistory {
  836    #[allow(clippy::type_complexity)]
  837    selections_by_transaction:
  838        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  839    mode: SelectionHistoryMode,
  840    undo_stack: VecDeque<SelectionHistoryEntry>,
  841    redo_stack: VecDeque<SelectionHistoryEntry>,
  842}
  843
  844impl SelectionHistory {
  845    fn insert_transaction(
  846        &mut self,
  847        transaction_id: TransactionId,
  848        selections: Arc<[Selection<Anchor>]>,
  849    ) {
  850        self.selections_by_transaction
  851            .insert(transaction_id, (selections, None));
  852    }
  853
  854    #[allow(clippy::type_complexity)]
  855    fn transaction(
  856        &self,
  857        transaction_id: TransactionId,
  858    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  859        self.selections_by_transaction.get(&transaction_id)
  860    }
  861
  862    #[allow(clippy::type_complexity)]
  863    fn transaction_mut(
  864        &mut self,
  865        transaction_id: TransactionId,
  866    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  867        self.selections_by_transaction.get_mut(&transaction_id)
  868    }
  869
  870    fn push(&mut self, entry: SelectionHistoryEntry) {
  871        if !entry.selections.is_empty() {
  872            match self.mode {
  873                SelectionHistoryMode::Normal => {
  874                    self.push_undo(entry);
  875                    self.redo_stack.clear();
  876                }
  877                SelectionHistoryMode::Undoing => self.push_redo(entry),
  878                SelectionHistoryMode::Redoing => self.push_undo(entry),
  879            }
  880        }
  881    }
  882
  883    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  884        if self
  885            .undo_stack
  886            .back()
  887            .map_or(true, |e| e.selections != entry.selections)
  888        {
  889            self.undo_stack.push_back(entry);
  890            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  891                self.undo_stack.pop_front();
  892            }
  893        }
  894    }
  895
  896    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  897        if self
  898            .redo_stack
  899            .back()
  900            .map_or(true, |e| e.selections != entry.selections)
  901        {
  902            self.redo_stack.push_back(entry);
  903            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  904                self.redo_stack.pop_front();
  905            }
  906        }
  907    }
  908}
  909
  910struct RowHighlight {
  911    index: usize,
  912    range: Range<Anchor>,
  913    color: Hsla,
  914    should_autoscroll: bool,
  915}
  916
  917#[derive(Clone, Debug)]
  918struct AddSelectionsState {
  919    above: bool,
  920    stack: Vec<usize>,
  921}
  922
  923#[derive(Clone)]
  924struct SelectNextState {
  925    query: AhoCorasick,
  926    wordwise: bool,
  927    done: bool,
  928}
  929
  930impl std::fmt::Debug for SelectNextState {
  931    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  932        f.debug_struct(std::any::type_name::<Self>())
  933            .field("wordwise", &self.wordwise)
  934            .field("done", &self.done)
  935            .finish()
  936    }
  937}
  938
  939#[derive(Debug)]
  940struct AutocloseRegion {
  941    selection_id: usize,
  942    range: Range<Anchor>,
  943    pair: BracketPair,
  944}
  945
  946#[derive(Debug)]
  947struct SnippetState {
  948    ranges: Vec<Vec<Range<Anchor>>>,
  949    active_index: usize,
  950    choices: Vec<Option<Vec<String>>>,
  951}
  952
  953#[doc(hidden)]
  954pub struct RenameState {
  955    pub range: Range<Anchor>,
  956    pub old_name: Arc<str>,
  957    pub editor: Entity<Editor>,
  958    block_id: CustomBlockId,
  959}
  960
  961struct InvalidationStack<T>(Vec<T>);
  962
  963struct RegisteredInlineCompletionProvider {
  964    provider: Arc<dyn InlineCompletionProviderHandle>,
  965    _subscription: Subscription,
  966}
  967
  968#[derive(Debug)]
  969struct ActiveDiagnosticGroup {
  970    primary_range: Range<Anchor>,
  971    primary_message: String,
  972    group_id: usize,
  973    blocks: HashMap<CustomBlockId, Diagnostic>,
  974    is_valid: bool,
  975}
  976
  977#[derive(Serialize, Deserialize, Clone, Debug)]
  978pub struct ClipboardSelection {
  979    /// The number of bytes in this selection.
  980    pub len: usize,
  981    /// Whether this was a full-line selection.
  982    pub is_entire_line: bool,
  983    /// The column where this selection originally started.
  984    pub start_column: u32,
  985}
  986
  987#[derive(Debug)]
  988pub(crate) struct NavigationData {
  989    cursor_anchor: Anchor,
  990    cursor_position: Point,
  991    scroll_anchor: ScrollAnchor,
  992    scroll_top_row: u32,
  993}
  994
  995#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  996pub enum GotoDefinitionKind {
  997    Symbol,
  998    Declaration,
  999    Type,
 1000    Implementation,
 1001}
 1002
 1003#[derive(Debug, Clone)]
 1004enum InlayHintRefreshReason {
 1005    Toggle(bool),
 1006    SettingsChange(InlayHintSettings),
 1007    NewLinesShown,
 1008    BufferEdited(HashSet<Arc<Language>>),
 1009    RefreshRequested,
 1010    ExcerptsRemoved(Vec<ExcerptId>),
 1011}
 1012
 1013impl InlayHintRefreshReason {
 1014    fn description(&self) -> &'static str {
 1015        match self {
 1016            Self::Toggle(_) => "toggle",
 1017            Self::SettingsChange(_) => "settings change",
 1018            Self::NewLinesShown => "new lines shown",
 1019            Self::BufferEdited(_) => "buffer edited",
 1020            Self::RefreshRequested => "refresh requested",
 1021            Self::ExcerptsRemoved(_) => "excerpts removed",
 1022        }
 1023    }
 1024}
 1025
 1026pub enum FormatTarget {
 1027    Buffers,
 1028    Ranges(Vec<Range<MultiBufferPoint>>),
 1029}
 1030
 1031pub(crate) struct FocusedBlock {
 1032    id: BlockId,
 1033    focus_handle: WeakFocusHandle,
 1034}
 1035
 1036#[derive(Clone)]
 1037enum JumpData {
 1038    MultiBufferRow {
 1039        row: MultiBufferRow,
 1040        line_offset_from_top: u32,
 1041    },
 1042    MultiBufferPoint {
 1043        excerpt_id: ExcerptId,
 1044        position: Point,
 1045        anchor: text::Anchor,
 1046        line_offset_from_top: u32,
 1047    },
 1048}
 1049
 1050pub enum MultibufferSelectionMode {
 1051    First,
 1052    All,
 1053}
 1054
 1055impl Editor {
 1056    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1057        let buffer = cx.new(|cx| Buffer::local("", cx));
 1058        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1059        Self::new(
 1060            EditorMode::SingleLine { auto_width: false },
 1061            buffer,
 1062            None,
 1063            false,
 1064            window,
 1065            cx,
 1066        )
 1067    }
 1068
 1069    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1070        let buffer = cx.new(|cx| Buffer::local("", cx));
 1071        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1072        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1073    }
 1074
 1075    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1076        let buffer = cx.new(|cx| Buffer::local("", cx));
 1077        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1078        Self::new(
 1079            EditorMode::SingleLine { auto_width: true },
 1080            buffer,
 1081            None,
 1082            false,
 1083            window,
 1084            cx,
 1085        )
 1086    }
 1087
 1088    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1089        let buffer = cx.new(|cx| Buffer::local("", cx));
 1090        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1091        Self::new(
 1092            EditorMode::AutoHeight { max_lines },
 1093            buffer,
 1094            None,
 1095            false,
 1096            window,
 1097            cx,
 1098        )
 1099    }
 1100
 1101    pub fn for_buffer(
 1102        buffer: Entity<Buffer>,
 1103        project: Option<Entity<Project>>,
 1104        window: &mut Window,
 1105        cx: &mut Context<Self>,
 1106    ) -> Self {
 1107        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1108        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1109    }
 1110
 1111    pub fn for_multibuffer(
 1112        buffer: Entity<MultiBuffer>,
 1113        project: Option<Entity<Project>>,
 1114        show_excerpt_controls: bool,
 1115        window: &mut Window,
 1116        cx: &mut Context<Self>,
 1117    ) -> Self {
 1118        Self::new(
 1119            EditorMode::Full,
 1120            buffer,
 1121            project,
 1122            show_excerpt_controls,
 1123            window,
 1124            cx,
 1125        )
 1126    }
 1127
 1128    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1129        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1130        let mut clone = Self::new(
 1131            self.mode,
 1132            self.buffer.clone(),
 1133            self.project.clone(),
 1134            show_excerpt_controls,
 1135            window,
 1136            cx,
 1137        );
 1138        self.display_map.update(cx, |display_map, cx| {
 1139            let snapshot = display_map.snapshot(cx);
 1140            clone.display_map.update(cx, |display_map, cx| {
 1141                display_map.set_state(&snapshot, cx);
 1142            });
 1143        });
 1144        clone.selections.clone_state(&self.selections);
 1145        clone.scroll_manager.clone_state(&self.scroll_manager);
 1146        clone.searchable = self.searchable;
 1147        clone
 1148    }
 1149
 1150    pub fn new(
 1151        mode: EditorMode,
 1152        buffer: Entity<MultiBuffer>,
 1153        project: Option<Entity<Project>>,
 1154        show_excerpt_controls: bool,
 1155        window: &mut Window,
 1156        cx: &mut Context<Self>,
 1157    ) -> Self {
 1158        let style = window.text_style();
 1159        let font_size = style.font_size.to_pixels(window.rem_size());
 1160        let editor = cx.entity().downgrade();
 1161        let fold_placeholder = FoldPlaceholder {
 1162            constrain_width: true,
 1163            render: Arc::new(move |fold_id, fold_range, cx| {
 1164                let editor = editor.clone();
 1165                div()
 1166                    .id(fold_id)
 1167                    .bg(cx.theme().colors().ghost_element_background)
 1168                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1169                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1170                    .rounded_sm()
 1171                    .size_full()
 1172                    .cursor_pointer()
 1173                    .child("")
 1174                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1175                    .on_click(move |_, _window, cx| {
 1176                        editor
 1177                            .update(cx, |editor, cx| {
 1178                                editor.unfold_ranges(
 1179                                    &[fold_range.start..fold_range.end],
 1180                                    true,
 1181                                    false,
 1182                                    cx,
 1183                                );
 1184                                cx.stop_propagation();
 1185                            })
 1186                            .ok();
 1187                    })
 1188                    .into_any()
 1189            }),
 1190            merge_adjacent: true,
 1191            ..Default::default()
 1192        };
 1193        let display_map = cx.new(|cx| {
 1194            DisplayMap::new(
 1195                buffer.clone(),
 1196                style.font(),
 1197                font_size,
 1198                None,
 1199                show_excerpt_controls,
 1200                FILE_HEADER_HEIGHT,
 1201                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1202                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1203                fold_placeholder,
 1204                cx,
 1205            )
 1206        });
 1207
 1208        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1209
 1210        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1211
 1212        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1213            .then(|| language_settings::SoftWrap::None);
 1214
 1215        let mut project_subscriptions = Vec::new();
 1216        if mode == EditorMode::Full {
 1217            if let Some(project) = project.as_ref() {
 1218                if buffer.read(cx).is_singleton() {
 1219                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1220                        cx.emit(EditorEvent::TitleChanged);
 1221                    }));
 1222                }
 1223                project_subscriptions.push(cx.subscribe_in(
 1224                    project,
 1225                    window,
 1226                    |editor, _, event, window, cx| {
 1227                        if let project::Event::RefreshInlayHints = event {
 1228                            editor
 1229                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1230                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1231                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1232                                let focus_handle = editor.focus_handle(cx);
 1233                                if focus_handle.is_focused(window) {
 1234                                    let snapshot = buffer.read(cx).snapshot();
 1235                                    for (range, snippet) in snippet_edits {
 1236                                        let editor_range =
 1237                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1238                                        editor
 1239                                            .insert_snippet(
 1240                                                &[editor_range],
 1241                                                snippet.clone(),
 1242                                                window,
 1243                                                cx,
 1244                                            )
 1245                                            .ok();
 1246                                    }
 1247                                }
 1248                            }
 1249                        }
 1250                    },
 1251                ));
 1252                if let Some(task_inventory) = project
 1253                    .read(cx)
 1254                    .task_store()
 1255                    .read(cx)
 1256                    .task_inventory()
 1257                    .cloned()
 1258                {
 1259                    project_subscriptions.push(cx.observe_in(
 1260                        &task_inventory,
 1261                        window,
 1262                        |editor, _, window, cx| {
 1263                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1264                        },
 1265                    ));
 1266                }
 1267            }
 1268        }
 1269
 1270        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1271
 1272        let inlay_hint_settings =
 1273            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1274        let focus_handle = cx.focus_handle();
 1275        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1276            .detach();
 1277        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1278            .detach();
 1279        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1280            .detach();
 1281        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1282            .detach();
 1283
 1284        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1285            Some(false)
 1286        } else {
 1287            None
 1288        };
 1289
 1290        let mut code_action_providers = Vec::new();
 1291        let mut load_uncommitted_diff = None;
 1292        if let Some(project) = project.clone() {
 1293            load_uncommitted_diff = Some(
 1294                get_uncommitted_diff_for_buffer(
 1295                    &project,
 1296                    buffer.read(cx).all_buffers(),
 1297                    buffer.clone(),
 1298                    cx,
 1299                )
 1300                .shared(),
 1301            );
 1302            code_action_providers.push(Rc::new(project) as Rc<_>);
 1303        }
 1304
 1305        let mut this = Self {
 1306            focus_handle,
 1307            show_cursor_when_unfocused: false,
 1308            last_focused_descendant: None,
 1309            buffer: buffer.clone(),
 1310            display_map: display_map.clone(),
 1311            selections,
 1312            scroll_manager: ScrollManager::new(cx),
 1313            columnar_selection_tail: None,
 1314            add_selections_state: None,
 1315            select_next_state: None,
 1316            select_prev_state: None,
 1317            selection_history: Default::default(),
 1318            autoclose_regions: Default::default(),
 1319            snippet_stack: Default::default(),
 1320            select_larger_syntax_node_stack: Vec::new(),
 1321            ime_transaction: Default::default(),
 1322            active_diagnostics: None,
 1323            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1324            inline_diagnostics_update: Task::ready(()),
 1325            inline_diagnostics: Vec::new(),
 1326            soft_wrap_mode_override,
 1327            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1328            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1329            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1330            project,
 1331            blink_manager: blink_manager.clone(),
 1332            show_local_selections: true,
 1333            show_scrollbars: true,
 1334            mode,
 1335            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1336            show_gutter: mode == EditorMode::Full,
 1337            show_line_numbers: None,
 1338            use_relative_line_numbers: None,
 1339            show_git_diff_gutter: None,
 1340            show_code_actions: None,
 1341            show_runnables: None,
 1342            show_wrap_guides: None,
 1343            show_indent_guides,
 1344            placeholder_text: None,
 1345            highlight_order: 0,
 1346            highlighted_rows: HashMap::default(),
 1347            background_highlights: Default::default(),
 1348            gutter_highlights: TreeMap::default(),
 1349            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1350            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1351            nav_history: None,
 1352            context_menu: RefCell::new(None),
 1353            mouse_context_menu: None,
 1354            completion_tasks: Default::default(),
 1355            signature_help_state: SignatureHelpState::default(),
 1356            auto_signature_help: None,
 1357            find_all_references_task_sources: Vec::new(),
 1358            next_completion_id: 0,
 1359            next_inlay_id: 0,
 1360            code_action_providers,
 1361            available_code_actions: Default::default(),
 1362            code_actions_task: Default::default(),
 1363            selection_highlight_task: Default::default(),
 1364            document_highlights_task: Default::default(),
 1365            linked_editing_range_task: Default::default(),
 1366            pending_rename: Default::default(),
 1367            searchable: true,
 1368            cursor_shape: EditorSettings::get_global(cx)
 1369                .cursor_shape
 1370                .unwrap_or_default(),
 1371            current_line_highlight: None,
 1372            autoindent_mode: Some(AutoindentMode::EachLine),
 1373            collapse_matches: false,
 1374            workspace: None,
 1375            input_enabled: true,
 1376            use_modal_editing: mode == EditorMode::Full,
 1377            read_only: false,
 1378            use_autoclose: true,
 1379            use_auto_surround: true,
 1380            auto_replace_emoji_shortcode: false,
 1381            leader_peer_id: None,
 1382            remote_id: None,
 1383            hover_state: Default::default(),
 1384            pending_mouse_down: None,
 1385            hovered_link_state: Default::default(),
 1386            edit_prediction_provider: None,
 1387            active_inline_completion: None,
 1388            stale_inline_completion_in_menu: None,
 1389            edit_prediction_preview: EditPredictionPreview::Inactive,
 1390            inline_diagnostics_enabled: mode == EditorMode::Full,
 1391            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1392
 1393            gutter_hovered: false,
 1394            pixel_position_of_newest_cursor: None,
 1395            last_bounds: None,
 1396            last_position_map: None,
 1397            expect_bounds_change: None,
 1398            gutter_dimensions: GutterDimensions::default(),
 1399            style: None,
 1400            show_cursor_names: false,
 1401            hovered_cursors: Default::default(),
 1402            next_editor_action_id: EditorActionId::default(),
 1403            editor_actions: Rc::default(),
 1404            inline_completions_hidden_for_vim_mode: false,
 1405            show_inline_completions_override: None,
 1406            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1407            edit_prediction_settings: EditPredictionSettings::Disabled,
 1408            edit_prediction_cursor_on_leading_whitespace: false,
 1409            edit_prediction_requires_modifier_in_leading_space: true,
 1410            custom_context_menu: None,
 1411            show_git_blame_gutter: false,
 1412            show_git_blame_inline: false,
 1413            distinguish_unstaged_diff_hunks: false,
 1414            show_selection_menu: None,
 1415            show_git_blame_inline_delay_task: None,
 1416            git_blame_inline_tooltip: None,
 1417            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1418            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1419                .session
 1420                .restore_unsaved_buffers,
 1421            blame: None,
 1422            blame_subscription: None,
 1423            tasks: Default::default(),
 1424            _subscriptions: vec![
 1425                cx.observe(&buffer, Self::on_buffer_changed),
 1426                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1427                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1428                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1429                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1430                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1431                cx.observe_window_activation(window, |editor, window, cx| {
 1432                    let active = window.is_window_active();
 1433                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1434                        if active {
 1435                            blink_manager.enable(cx);
 1436                        } else {
 1437                            blink_manager.disable(cx);
 1438                        }
 1439                    });
 1440                }),
 1441            ],
 1442            tasks_update_task: None,
 1443            linked_edit_ranges: Default::default(),
 1444            in_project_search: false,
 1445            previous_search_ranges: None,
 1446            breadcrumb_header: None,
 1447            focused_block: None,
 1448            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1449            addons: HashMap::default(),
 1450            registered_buffers: HashMap::default(),
 1451            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1452            selection_mark_mode: false,
 1453            toggle_fold_multiple_buffers: Task::ready(()),
 1454            serialize_selections: Task::ready(()),
 1455            text_style_refinement: None,
 1456            load_diff_task: load_uncommitted_diff,
 1457            mouse_cursor_hidden: false,
 1458            hide_mouse_while_typing: EditorSettings::get_global(cx)
 1459                .hide_mouse_while_typing
 1460                .unwrap_or(true),
 1461        };
 1462        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1463        this._subscriptions.extend(project_subscriptions);
 1464
 1465        this.end_selection(window, cx);
 1466        this.scroll_manager.show_scrollbar(window, cx);
 1467
 1468        if mode == EditorMode::Full {
 1469            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1470            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1471
 1472            if this.git_blame_inline_enabled {
 1473                this.git_blame_inline_enabled = true;
 1474                this.start_git_blame_inline(false, window, cx);
 1475            }
 1476
 1477            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1478                if let Some(project) = this.project.as_ref() {
 1479                    let handle = project.update(cx, |project, cx| {
 1480                        project.register_buffer_with_language_servers(&buffer, cx)
 1481                    });
 1482                    this.registered_buffers
 1483                        .insert(buffer.read(cx).remote_id(), handle);
 1484                }
 1485            }
 1486        }
 1487
 1488        this.report_editor_event("Editor Opened", None, cx);
 1489        this
 1490    }
 1491
 1492    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1493        self.mouse_context_menu
 1494            .as_ref()
 1495            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1496    }
 1497
 1498    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1499        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1500    }
 1501
 1502    fn key_context_internal(
 1503        &self,
 1504        has_active_edit_prediction: bool,
 1505        window: &Window,
 1506        cx: &App,
 1507    ) -> KeyContext {
 1508        let mut key_context = KeyContext::new_with_defaults();
 1509        key_context.add("Editor");
 1510        let mode = match self.mode {
 1511            EditorMode::SingleLine { .. } => "single_line",
 1512            EditorMode::AutoHeight { .. } => "auto_height",
 1513            EditorMode::Full => "full",
 1514        };
 1515
 1516        if EditorSettings::jupyter_enabled(cx) {
 1517            key_context.add("jupyter");
 1518        }
 1519
 1520        key_context.set("mode", mode);
 1521        if self.pending_rename.is_some() {
 1522            key_context.add("renaming");
 1523        }
 1524
 1525        match self.context_menu.borrow().as_ref() {
 1526            Some(CodeContextMenu::Completions(_)) => {
 1527                key_context.add("menu");
 1528                key_context.add("showing_completions");
 1529            }
 1530            Some(CodeContextMenu::CodeActions(_)) => {
 1531                key_context.add("menu");
 1532                key_context.add("showing_code_actions")
 1533            }
 1534            None => {}
 1535        }
 1536
 1537        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1538        if !self.focus_handle(cx).contains_focused(window, cx)
 1539            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1540        {
 1541            for addon in self.addons.values() {
 1542                addon.extend_key_context(&mut key_context, cx)
 1543            }
 1544        }
 1545
 1546        if let Some(extension) = self
 1547            .buffer
 1548            .read(cx)
 1549            .as_singleton()
 1550            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1551        {
 1552            key_context.set("extension", extension.to_string());
 1553        }
 1554
 1555        if has_active_edit_prediction {
 1556            if self.edit_prediction_in_conflict() {
 1557                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1558            } else {
 1559                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1560                key_context.add("copilot_suggestion");
 1561            }
 1562        }
 1563
 1564        if self.selection_mark_mode {
 1565            key_context.add("selection_mode");
 1566        }
 1567
 1568        key_context
 1569    }
 1570
 1571    pub fn edit_prediction_in_conflict(&self) -> bool {
 1572        if !self.show_edit_predictions_in_menu() {
 1573            return false;
 1574        }
 1575
 1576        let showing_completions = self
 1577            .context_menu
 1578            .borrow()
 1579            .as_ref()
 1580            .map_or(false, |context| {
 1581                matches!(context, CodeContextMenu::Completions(_))
 1582            });
 1583
 1584        showing_completions
 1585            || self.edit_prediction_requires_modifier()
 1586            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1587            // bindings to insert tab characters.
 1588            || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
 1589    }
 1590
 1591    pub fn accept_edit_prediction_keybind(
 1592        &self,
 1593        window: &Window,
 1594        cx: &App,
 1595    ) -> AcceptEditPredictionBinding {
 1596        let key_context = self.key_context_internal(true, window, cx);
 1597        let in_conflict = self.edit_prediction_in_conflict();
 1598
 1599        AcceptEditPredictionBinding(
 1600            window
 1601                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1602                .into_iter()
 1603                .filter(|binding| {
 1604                    !in_conflict
 1605                        || binding
 1606                            .keystrokes()
 1607                            .first()
 1608                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1609                })
 1610                .rev()
 1611                .min_by_key(|binding| {
 1612                    binding
 1613                        .keystrokes()
 1614                        .first()
 1615                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1616                }),
 1617        )
 1618    }
 1619
 1620    pub fn new_file(
 1621        workspace: &mut Workspace,
 1622        _: &workspace::NewFile,
 1623        window: &mut Window,
 1624        cx: &mut Context<Workspace>,
 1625    ) {
 1626        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1627            "Failed to create buffer",
 1628            window,
 1629            cx,
 1630            |e, _, _| match e.error_code() {
 1631                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1632                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1633                e.error_tag("required").unwrap_or("the latest version")
 1634            )),
 1635                _ => None,
 1636            },
 1637        );
 1638    }
 1639
 1640    pub fn new_in_workspace(
 1641        workspace: &mut Workspace,
 1642        window: &mut Window,
 1643        cx: &mut Context<Workspace>,
 1644    ) -> Task<Result<Entity<Editor>>> {
 1645        let project = workspace.project().clone();
 1646        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1647
 1648        cx.spawn_in(window, |workspace, mut cx| async move {
 1649            let buffer = create.await?;
 1650            workspace.update_in(&mut cx, |workspace, window, cx| {
 1651                let editor =
 1652                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1653                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1654                editor
 1655            })
 1656        })
 1657    }
 1658
 1659    fn new_file_vertical(
 1660        workspace: &mut Workspace,
 1661        _: &workspace::NewFileSplitVertical,
 1662        window: &mut Window,
 1663        cx: &mut Context<Workspace>,
 1664    ) {
 1665        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1666    }
 1667
 1668    fn new_file_horizontal(
 1669        workspace: &mut Workspace,
 1670        _: &workspace::NewFileSplitHorizontal,
 1671        window: &mut Window,
 1672        cx: &mut Context<Workspace>,
 1673    ) {
 1674        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1675    }
 1676
 1677    fn new_file_in_direction(
 1678        workspace: &mut Workspace,
 1679        direction: SplitDirection,
 1680        window: &mut Window,
 1681        cx: &mut Context<Workspace>,
 1682    ) {
 1683        let project = workspace.project().clone();
 1684        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1685
 1686        cx.spawn_in(window, |workspace, mut cx| async move {
 1687            let buffer = create.await?;
 1688            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1689                workspace.split_item(
 1690                    direction,
 1691                    Box::new(
 1692                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1693                    ),
 1694                    window,
 1695                    cx,
 1696                )
 1697            })?;
 1698            anyhow::Ok(())
 1699        })
 1700        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1701            match e.error_code() {
 1702                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1703                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1704                e.error_tag("required").unwrap_or("the latest version")
 1705            )),
 1706                _ => None,
 1707            }
 1708        });
 1709    }
 1710
 1711    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1712        self.leader_peer_id
 1713    }
 1714
 1715    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1716        &self.buffer
 1717    }
 1718
 1719    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1720        self.workspace.as_ref()?.0.upgrade()
 1721    }
 1722
 1723    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1724        self.buffer().read(cx).title(cx)
 1725    }
 1726
 1727    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1728        let git_blame_gutter_max_author_length = self
 1729            .render_git_blame_gutter(cx)
 1730            .then(|| {
 1731                if let Some(blame) = self.blame.as_ref() {
 1732                    let max_author_length =
 1733                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1734                    Some(max_author_length)
 1735                } else {
 1736                    None
 1737                }
 1738            })
 1739            .flatten();
 1740
 1741        EditorSnapshot {
 1742            mode: self.mode,
 1743            show_gutter: self.show_gutter,
 1744            show_line_numbers: self.show_line_numbers,
 1745            show_git_diff_gutter: self.show_git_diff_gutter,
 1746            show_code_actions: self.show_code_actions,
 1747            show_runnables: self.show_runnables,
 1748            git_blame_gutter_max_author_length,
 1749            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1750            scroll_anchor: self.scroll_manager.anchor(),
 1751            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1752            placeholder_text: self.placeholder_text.clone(),
 1753            is_focused: self.focus_handle.is_focused(window),
 1754            current_line_highlight: self
 1755                .current_line_highlight
 1756                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1757            gutter_hovered: self.gutter_hovered,
 1758        }
 1759    }
 1760
 1761    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1762        self.buffer.read(cx).language_at(point, cx)
 1763    }
 1764
 1765    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1766        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1767    }
 1768
 1769    pub fn active_excerpt(
 1770        &self,
 1771        cx: &App,
 1772    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1773        self.buffer
 1774            .read(cx)
 1775            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1776    }
 1777
 1778    pub fn mode(&self) -> EditorMode {
 1779        self.mode
 1780    }
 1781
 1782    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1783        self.collaboration_hub.as_deref()
 1784    }
 1785
 1786    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1787        self.collaboration_hub = Some(hub);
 1788    }
 1789
 1790    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1791        self.in_project_search = in_project_search;
 1792    }
 1793
 1794    pub fn set_custom_context_menu(
 1795        &mut self,
 1796        f: impl 'static
 1797            + Fn(
 1798                &mut Self,
 1799                DisplayPoint,
 1800                &mut Window,
 1801                &mut Context<Self>,
 1802            ) -> Option<Entity<ui::ContextMenu>>,
 1803    ) {
 1804        self.custom_context_menu = Some(Box::new(f))
 1805    }
 1806
 1807    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1808        self.completion_provider = provider;
 1809    }
 1810
 1811    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1812        self.semantics_provider.clone()
 1813    }
 1814
 1815    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1816        self.semantics_provider = provider;
 1817    }
 1818
 1819    pub fn set_edit_prediction_provider<T>(
 1820        &mut self,
 1821        provider: Option<Entity<T>>,
 1822        window: &mut Window,
 1823        cx: &mut Context<Self>,
 1824    ) where
 1825        T: EditPredictionProvider,
 1826    {
 1827        self.edit_prediction_provider =
 1828            provider.map(|provider| RegisteredInlineCompletionProvider {
 1829                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1830                    if this.focus_handle.is_focused(window) {
 1831                        this.update_visible_inline_completion(window, cx);
 1832                    }
 1833                }),
 1834                provider: Arc::new(provider),
 1835            });
 1836        self.refresh_inline_completion(false, false, window, cx);
 1837    }
 1838
 1839    pub fn placeholder_text(&self) -> Option<&str> {
 1840        self.placeholder_text.as_deref()
 1841    }
 1842
 1843    pub fn set_placeholder_text(
 1844        &mut self,
 1845        placeholder_text: impl Into<Arc<str>>,
 1846        cx: &mut Context<Self>,
 1847    ) {
 1848        let placeholder_text = Some(placeholder_text.into());
 1849        if self.placeholder_text != placeholder_text {
 1850            self.placeholder_text = placeholder_text;
 1851            cx.notify();
 1852        }
 1853    }
 1854
 1855    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1856        self.cursor_shape = cursor_shape;
 1857
 1858        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1859        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1860
 1861        cx.notify();
 1862    }
 1863
 1864    pub fn set_current_line_highlight(
 1865        &mut self,
 1866        current_line_highlight: Option<CurrentLineHighlight>,
 1867    ) {
 1868        self.current_line_highlight = current_line_highlight;
 1869    }
 1870
 1871    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1872        self.collapse_matches = collapse_matches;
 1873    }
 1874
 1875    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1876        let buffers = self.buffer.read(cx).all_buffers();
 1877        let Some(project) = self.project.as_ref() else {
 1878            return;
 1879        };
 1880        project.update(cx, |project, cx| {
 1881            for buffer in buffers {
 1882                self.registered_buffers
 1883                    .entry(buffer.read(cx).remote_id())
 1884                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1885            }
 1886        })
 1887    }
 1888
 1889    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1890        if self.collapse_matches {
 1891            return range.start..range.start;
 1892        }
 1893        range.clone()
 1894    }
 1895
 1896    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1897        if self.display_map.read(cx).clip_at_line_ends != clip {
 1898            self.display_map
 1899                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1900        }
 1901    }
 1902
 1903    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1904        self.input_enabled = input_enabled;
 1905    }
 1906
 1907    pub fn set_inline_completions_hidden_for_vim_mode(
 1908        &mut self,
 1909        hidden: bool,
 1910        window: &mut Window,
 1911        cx: &mut Context<Self>,
 1912    ) {
 1913        if hidden != self.inline_completions_hidden_for_vim_mode {
 1914            self.inline_completions_hidden_for_vim_mode = hidden;
 1915            if hidden {
 1916                self.update_visible_inline_completion(window, cx);
 1917            } else {
 1918                self.refresh_inline_completion(true, false, window, cx);
 1919            }
 1920        }
 1921    }
 1922
 1923    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1924        self.menu_inline_completions_policy = value;
 1925    }
 1926
 1927    pub fn set_autoindent(&mut self, autoindent: bool) {
 1928        if autoindent {
 1929            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1930        } else {
 1931            self.autoindent_mode = None;
 1932        }
 1933    }
 1934
 1935    pub fn read_only(&self, cx: &App) -> bool {
 1936        self.read_only || self.buffer.read(cx).read_only()
 1937    }
 1938
 1939    pub fn set_read_only(&mut self, read_only: bool) {
 1940        self.read_only = read_only;
 1941    }
 1942
 1943    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1944        self.use_autoclose = autoclose;
 1945    }
 1946
 1947    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1948        self.use_auto_surround = auto_surround;
 1949    }
 1950
 1951    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1952        self.auto_replace_emoji_shortcode = auto_replace;
 1953    }
 1954
 1955    pub fn toggle_inline_completions(
 1956        &mut self,
 1957        _: &ToggleEditPrediction,
 1958        window: &mut Window,
 1959        cx: &mut Context<Self>,
 1960    ) {
 1961        if self.show_inline_completions_override.is_some() {
 1962            self.set_show_edit_predictions(None, window, cx);
 1963        } else {
 1964            let show_edit_predictions = !self.edit_predictions_enabled();
 1965            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1966        }
 1967    }
 1968
 1969    pub fn set_show_edit_predictions(
 1970        &mut self,
 1971        show_edit_predictions: Option<bool>,
 1972        window: &mut Window,
 1973        cx: &mut Context<Self>,
 1974    ) {
 1975        self.show_inline_completions_override = show_edit_predictions;
 1976
 1977        if let Some(false) = show_edit_predictions {
 1978            self.discard_inline_completion(false, cx);
 1979        } else {
 1980            self.refresh_inline_completion(false, true, window, cx);
 1981        }
 1982    }
 1983
 1984    fn inline_completions_disabled_in_scope(
 1985        &self,
 1986        buffer: &Entity<Buffer>,
 1987        buffer_position: language::Anchor,
 1988        cx: &App,
 1989    ) -> bool {
 1990        let snapshot = buffer.read(cx).snapshot();
 1991        let settings = snapshot.settings_at(buffer_position, cx);
 1992
 1993        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1994            return false;
 1995        };
 1996
 1997        scope.override_name().map_or(false, |scope_name| {
 1998            settings
 1999                .edit_predictions_disabled_in
 2000                .iter()
 2001                .any(|s| s == scope_name)
 2002        })
 2003    }
 2004
 2005    pub fn set_use_modal_editing(&mut self, to: bool) {
 2006        self.use_modal_editing = to;
 2007    }
 2008
 2009    pub fn use_modal_editing(&self) -> bool {
 2010        self.use_modal_editing
 2011    }
 2012
 2013    fn selections_did_change(
 2014        &mut self,
 2015        local: bool,
 2016        old_cursor_position: &Anchor,
 2017        show_completions: bool,
 2018        window: &mut Window,
 2019        cx: &mut Context<Self>,
 2020    ) {
 2021        window.invalidate_character_coordinates();
 2022
 2023        // Copy selections to primary selection buffer
 2024        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2025        if local {
 2026            let selections = self.selections.all::<usize>(cx);
 2027            let buffer_handle = self.buffer.read(cx).read(cx);
 2028
 2029            let mut text = String::new();
 2030            for (index, selection) in selections.iter().enumerate() {
 2031                let text_for_selection = buffer_handle
 2032                    .text_for_range(selection.start..selection.end)
 2033                    .collect::<String>();
 2034
 2035                text.push_str(&text_for_selection);
 2036                if index != selections.len() - 1 {
 2037                    text.push('\n');
 2038                }
 2039            }
 2040
 2041            if !text.is_empty() {
 2042                cx.write_to_primary(ClipboardItem::new_string(text));
 2043            }
 2044        }
 2045
 2046        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2047            self.buffer.update(cx, |buffer, cx| {
 2048                buffer.set_active_selections(
 2049                    &self.selections.disjoint_anchors(),
 2050                    self.selections.line_mode,
 2051                    self.cursor_shape,
 2052                    cx,
 2053                )
 2054            });
 2055        }
 2056        let display_map = self
 2057            .display_map
 2058            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2059        let buffer = &display_map.buffer_snapshot;
 2060        self.add_selections_state = None;
 2061        self.select_next_state = None;
 2062        self.select_prev_state = None;
 2063        self.select_larger_syntax_node_stack.clear();
 2064        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2065        self.snippet_stack
 2066            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2067        self.take_rename(false, window, cx);
 2068
 2069        let new_cursor_position = self.selections.newest_anchor().head();
 2070
 2071        self.push_to_nav_history(
 2072            *old_cursor_position,
 2073            Some(new_cursor_position.to_point(buffer)),
 2074            cx,
 2075        );
 2076
 2077        if local {
 2078            let new_cursor_position = self.selections.newest_anchor().head();
 2079            let mut context_menu = self.context_menu.borrow_mut();
 2080            let completion_menu = match context_menu.as_ref() {
 2081                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2082                _ => {
 2083                    *context_menu = None;
 2084                    None
 2085                }
 2086            };
 2087            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2088                if !self.registered_buffers.contains_key(&buffer_id) {
 2089                    if let Some(project) = self.project.as_ref() {
 2090                        project.update(cx, |project, cx| {
 2091                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2092                                return;
 2093                            };
 2094                            self.registered_buffers.insert(
 2095                                buffer_id,
 2096                                project.register_buffer_with_language_servers(&buffer, cx),
 2097                            );
 2098                        })
 2099                    }
 2100                }
 2101            }
 2102
 2103            if let Some(completion_menu) = completion_menu {
 2104                let cursor_position = new_cursor_position.to_offset(buffer);
 2105                let (word_range, kind) =
 2106                    buffer.surrounding_word(completion_menu.initial_position, true);
 2107                if kind == Some(CharKind::Word)
 2108                    && word_range.to_inclusive().contains(&cursor_position)
 2109                {
 2110                    let mut completion_menu = completion_menu.clone();
 2111                    drop(context_menu);
 2112
 2113                    let query = Self::completion_query(buffer, cursor_position);
 2114                    cx.spawn(move |this, mut cx| async move {
 2115                        completion_menu
 2116                            .filter(query.as_deref(), cx.background_executor().clone())
 2117                            .await;
 2118
 2119                        this.update(&mut cx, |this, cx| {
 2120                            let mut context_menu = this.context_menu.borrow_mut();
 2121                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2122                            else {
 2123                                return;
 2124                            };
 2125
 2126                            if menu.id > completion_menu.id {
 2127                                return;
 2128                            }
 2129
 2130                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2131                            drop(context_menu);
 2132                            cx.notify();
 2133                        })
 2134                    })
 2135                    .detach();
 2136
 2137                    if show_completions {
 2138                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2139                    }
 2140                } else {
 2141                    drop(context_menu);
 2142                    self.hide_context_menu(window, cx);
 2143                }
 2144            } else {
 2145                drop(context_menu);
 2146            }
 2147
 2148            hide_hover(self, cx);
 2149
 2150            if old_cursor_position.to_display_point(&display_map).row()
 2151                != new_cursor_position.to_display_point(&display_map).row()
 2152            {
 2153                self.available_code_actions.take();
 2154            }
 2155            self.refresh_code_actions(window, cx);
 2156            self.refresh_document_highlights(cx);
 2157            self.refresh_selected_text_highlights(window, cx);
 2158            refresh_matching_bracket_highlights(self, window, cx);
 2159            self.update_visible_inline_completion(window, cx);
 2160            self.edit_prediction_requires_modifier_in_leading_space = true;
 2161            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2162            if self.git_blame_inline_enabled {
 2163                self.start_inline_blame_timer(window, cx);
 2164            }
 2165        }
 2166
 2167        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2168        cx.emit(EditorEvent::SelectionsChanged { local });
 2169
 2170        let selections = &self.selections.disjoint;
 2171        if selections.len() == 1 {
 2172            cx.emit(SearchEvent::ActiveMatchChanged)
 2173        }
 2174        if local
 2175            && self.is_singleton(cx)
 2176            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2177        {
 2178            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2179                let background_executor = cx.background_executor().clone();
 2180                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2181                let snapshot = self.buffer().read(cx).snapshot(cx);
 2182                let selections = selections.clone();
 2183                self.serialize_selections = cx.background_spawn(async move {
 2184                    background_executor.timer(Duration::from_millis(100)).await;
 2185                    let selections = selections
 2186                        .iter()
 2187                        .map(|selection| {
 2188                            (
 2189                                selection.start.to_offset(&snapshot),
 2190                                selection.end.to_offset(&snapshot),
 2191                            )
 2192                        })
 2193                        .collect();
 2194                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2195                        .await
 2196                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2197                        .log_err();
 2198                });
 2199            }
 2200        }
 2201
 2202        cx.notify();
 2203    }
 2204
 2205    pub fn change_selections<R>(
 2206        &mut self,
 2207        autoscroll: Option<Autoscroll>,
 2208        window: &mut Window,
 2209        cx: &mut Context<Self>,
 2210        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2211    ) -> R {
 2212        self.change_selections_inner(autoscroll, true, window, cx, change)
 2213    }
 2214
 2215    fn change_selections_inner<R>(
 2216        &mut self,
 2217        autoscroll: Option<Autoscroll>,
 2218        request_completions: bool,
 2219        window: &mut Window,
 2220        cx: &mut Context<Self>,
 2221        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2222    ) -> R {
 2223        let old_cursor_position = self.selections.newest_anchor().head();
 2224        self.push_to_selection_history();
 2225
 2226        let (changed, result) = self.selections.change_with(cx, change);
 2227
 2228        if changed {
 2229            if let Some(autoscroll) = autoscroll {
 2230                self.request_autoscroll(autoscroll, cx);
 2231            }
 2232            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2233
 2234            if self.should_open_signature_help_automatically(
 2235                &old_cursor_position,
 2236                self.signature_help_state.backspace_pressed(),
 2237                cx,
 2238            ) {
 2239                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2240            }
 2241            self.signature_help_state.set_backspace_pressed(false);
 2242        }
 2243
 2244        result
 2245    }
 2246
 2247    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2248    where
 2249        I: IntoIterator<Item = (Range<S>, T)>,
 2250        S: ToOffset,
 2251        T: Into<Arc<str>>,
 2252    {
 2253        if self.read_only(cx) {
 2254            return;
 2255        }
 2256
 2257        self.buffer
 2258            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2259    }
 2260
 2261    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2262    where
 2263        I: IntoIterator<Item = (Range<S>, T)>,
 2264        S: ToOffset,
 2265        T: Into<Arc<str>>,
 2266    {
 2267        if self.read_only(cx) {
 2268            return;
 2269        }
 2270
 2271        self.buffer.update(cx, |buffer, cx| {
 2272            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2273        });
 2274    }
 2275
 2276    pub fn edit_with_block_indent<I, S, T>(
 2277        &mut self,
 2278        edits: I,
 2279        original_start_columns: Vec<u32>,
 2280        cx: &mut Context<Self>,
 2281    ) where
 2282        I: IntoIterator<Item = (Range<S>, T)>,
 2283        S: ToOffset,
 2284        T: Into<Arc<str>>,
 2285    {
 2286        if self.read_only(cx) {
 2287            return;
 2288        }
 2289
 2290        self.buffer.update(cx, |buffer, cx| {
 2291            buffer.edit(
 2292                edits,
 2293                Some(AutoindentMode::Block {
 2294                    original_start_columns,
 2295                }),
 2296                cx,
 2297            )
 2298        });
 2299    }
 2300
 2301    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2302        self.hide_context_menu(window, cx);
 2303
 2304        match phase {
 2305            SelectPhase::Begin {
 2306                position,
 2307                add,
 2308                click_count,
 2309            } => self.begin_selection(position, add, click_count, window, cx),
 2310            SelectPhase::BeginColumnar {
 2311                position,
 2312                goal_column,
 2313                reset,
 2314            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2315            SelectPhase::Extend {
 2316                position,
 2317                click_count,
 2318            } => self.extend_selection(position, click_count, window, cx),
 2319            SelectPhase::Update {
 2320                position,
 2321                goal_column,
 2322                scroll_delta,
 2323            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2324            SelectPhase::End => self.end_selection(window, cx),
 2325        }
 2326    }
 2327
 2328    fn extend_selection(
 2329        &mut self,
 2330        position: DisplayPoint,
 2331        click_count: usize,
 2332        window: &mut Window,
 2333        cx: &mut Context<Self>,
 2334    ) {
 2335        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2336        let tail = self.selections.newest::<usize>(cx).tail();
 2337        self.begin_selection(position, false, click_count, window, cx);
 2338
 2339        let position = position.to_offset(&display_map, Bias::Left);
 2340        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2341
 2342        let mut pending_selection = self
 2343            .selections
 2344            .pending_anchor()
 2345            .expect("extend_selection not called with pending selection");
 2346        if position >= tail {
 2347            pending_selection.start = tail_anchor;
 2348        } else {
 2349            pending_selection.end = tail_anchor;
 2350            pending_selection.reversed = true;
 2351        }
 2352
 2353        let mut pending_mode = self.selections.pending_mode().unwrap();
 2354        match &mut pending_mode {
 2355            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2356            _ => {}
 2357        }
 2358
 2359        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2360            s.set_pending(pending_selection, pending_mode)
 2361        });
 2362    }
 2363
 2364    fn begin_selection(
 2365        &mut self,
 2366        position: DisplayPoint,
 2367        add: bool,
 2368        click_count: usize,
 2369        window: &mut Window,
 2370        cx: &mut Context<Self>,
 2371    ) {
 2372        if !self.focus_handle.is_focused(window) {
 2373            self.last_focused_descendant = None;
 2374            window.focus(&self.focus_handle);
 2375        }
 2376
 2377        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2378        let buffer = &display_map.buffer_snapshot;
 2379        let newest_selection = self.selections.newest_anchor().clone();
 2380        let position = display_map.clip_point(position, Bias::Left);
 2381
 2382        let start;
 2383        let end;
 2384        let mode;
 2385        let mut auto_scroll;
 2386        match click_count {
 2387            1 => {
 2388                start = buffer.anchor_before(position.to_point(&display_map));
 2389                end = start;
 2390                mode = SelectMode::Character;
 2391                auto_scroll = true;
 2392            }
 2393            2 => {
 2394                let range = movement::surrounding_word(&display_map, position);
 2395                start = buffer.anchor_before(range.start.to_point(&display_map));
 2396                end = buffer.anchor_before(range.end.to_point(&display_map));
 2397                mode = SelectMode::Word(start..end);
 2398                auto_scroll = true;
 2399            }
 2400            3 => {
 2401                let position = display_map
 2402                    .clip_point(position, Bias::Left)
 2403                    .to_point(&display_map);
 2404                let line_start = display_map.prev_line_boundary(position).0;
 2405                let next_line_start = buffer.clip_point(
 2406                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2407                    Bias::Left,
 2408                );
 2409                start = buffer.anchor_before(line_start);
 2410                end = buffer.anchor_before(next_line_start);
 2411                mode = SelectMode::Line(start..end);
 2412                auto_scroll = true;
 2413            }
 2414            _ => {
 2415                start = buffer.anchor_before(0);
 2416                end = buffer.anchor_before(buffer.len());
 2417                mode = SelectMode::All;
 2418                auto_scroll = false;
 2419            }
 2420        }
 2421        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2422
 2423        let point_to_delete: Option<usize> = {
 2424            let selected_points: Vec<Selection<Point>> =
 2425                self.selections.disjoint_in_range(start..end, cx);
 2426
 2427            if !add || click_count > 1 {
 2428                None
 2429            } else if !selected_points.is_empty() {
 2430                Some(selected_points[0].id)
 2431            } else {
 2432                let clicked_point_already_selected =
 2433                    self.selections.disjoint.iter().find(|selection| {
 2434                        selection.start.to_point(buffer) == start.to_point(buffer)
 2435                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2436                    });
 2437
 2438                clicked_point_already_selected.map(|selection| selection.id)
 2439            }
 2440        };
 2441
 2442        let selections_count = self.selections.count();
 2443
 2444        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2445            if let Some(point_to_delete) = point_to_delete {
 2446                s.delete(point_to_delete);
 2447
 2448                if selections_count == 1 {
 2449                    s.set_pending_anchor_range(start..end, mode);
 2450                }
 2451            } else {
 2452                if !add {
 2453                    s.clear_disjoint();
 2454                } else if click_count > 1 {
 2455                    s.delete(newest_selection.id)
 2456                }
 2457
 2458                s.set_pending_anchor_range(start..end, mode);
 2459            }
 2460        });
 2461    }
 2462
 2463    fn begin_columnar_selection(
 2464        &mut self,
 2465        position: DisplayPoint,
 2466        goal_column: u32,
 2467        reset: bool,
 2468        window: &mut Window,
 2469        cx: &mut Context<Self>,
 2470    ) {
 2471        if !self.focus_handle.is_focused(window) {
 2472            self.last_focused_descendant = None;
 2473            window.focus(&self.focus_handle);
 2474        }
 2475
 2476        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2477
 2478        if reset {
 2479            let pointer_position = display_map
 2480                .buffer_snapshot
 2481                .anchor_before(position.to_point(&display_map));
 2482
 2483            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2484                s.clear_disjoint();
 2485                s.set_pending_anchor_range(
 2486                    pointer_position..pointer_position,
 2487                    SelectMode::Character,
 2488                );
 2489            });
 2490        }
 2491
 2492        let tail = self.selections.newest::<Point>(cx).tail();
 2493        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2494
 2495        if !reset {
 2496            self.select_columns(
 2497                tail.to_display_point(&display_map),
 2498                position,
 2499                goal_column,
 2500                &display_map,
 2501                window,
 2502                cx,
 2503            );
 2504        }
 2505    }
 2506
 2507    fn update_selection(
 2508        &mut self,
 2509        position: DisplayPoint,
 2510        goal_column: u32,
 2511        scroll_delta: gpui::Point<f32>,
 2512        window: &mut Window,
 2513        cx: &mut Context<Self>,
 2514    ) {
 2515        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2516
 2517        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2518            let tail = tail.to_display_point(&display_map);
 2519            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2520        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2521            let buffer = self.buffer.read(cx).snapshot(cx);
 2522            let head;
 2523            let tail;
 2524            let mode = self.selections.pending_mode().unwrap();
 2525            match &mode {
 2526                SelectMode::Character => {
 2527                    head = position.to_point(&display_map);
 2528                    tail = pending.tail().to_point(&buffer);
 2529                }
 2530                SelectMode::Word(original_range) => {
 2531                    let original_display_range = original_range.start.to_display_point(&display_map)
 2532                        ..original_range.end.to_display_point(&display_map);
 2533                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2534                        ..original_display_range.end.to_point(&display_map);
 2535                    if movement::is_inside_word(&display_map, position)
 2536                        || original_display_range.contains(&position)
 2537                    {
 2538                        let word_range = movement::surrounding_word(&display_map, position);
 2539                        if word_range.start < original_display_range.start {
 2540                            head = word_range.start.to_point(&display_map);
 2541                        } else {
 2542                            head = word_range.end.to_point(&display_map);
 2543                        }
 2544                    } else {
 2545                        head = position.to_point(&display_map);
 2546                    }
 2547
 2548                    if head <= original_buffer_range.start {
 2549                        tail = original_buffer_range.end;
 2550                    } else {
 2551                        tail = original_buffer_range.start;
 2552                    }
 2553                }
 2554                SelectMode::Line(original_range) => {
 2555                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2556
 2557                    let position = display_map
 2558                        .clip_point(position, Bias::Left)
 2559                        .to_point(&display_map);
 2560                    let line_start = display_map.prev_line_boundary(position).0;
 2561                    let next_line_start = buffer.clip_point(
 2562                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2563                        Bias::Left,
 2564                    );
 2565
 2566                    if line_start < original_range.start {
 2567                        head = line_start
 2568                    } else {
 2569                        head = next_line_start
 2570                    }
 2571
 2572                    if head <= original_range.start {
 2573                        tail = original_range.end;
 2574                    } else {
 2575                        tail = original_range.start;
 2576                    }
 2577                }
 2578                SelectMode::All => {
 2579                    return;
 2580                }
 2581            };
 2582
 2583            if head < tail {
 2584                pending.start = buffer.anchor_before(head);
 2585                pending.end = buffer.anchor_before(tail);
 2586                pending.reversed = true;
 2587            } else {
 2588                pending.start = buffer.anchor_before(tail);
 2589                pending.end = buffer.anchor_before(head);
 2590                pending.reversed = false;
 2591            }
 2592
 2593            self.change_selections(None, window, cx, |s| {
 2594                s.set_pending(pending, mode);
 2595            });
 2596        } else {
 2597            log::error!("update_selection dispatched with no pending selection");
 2598            return;
 2599        }
 2600
 2601        self.apply_scroll_delta(scroll_delta, window, cx);
 2602        cx.notify();
 2603    }
 2604
 2605    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2606        self.columnar_selection_tail.take();
 2607        if self.selections.pending_anchor().is_some() {
 2608            let selections = self.selections.all::<usize>(cx);
 2609            self.change_selections(None, window, cx, |s| {
 2610                s.select(selections);
 2611                s.clear_pending();
 2612            });
 2613        }
 2614    }
 2615
 2616    fn select_columns(
 2617        &mut self,
 2618        tail: DisplayPoint,
 2619        head: DisplayPoint,
 2620        goal_column: u32,
 2621        display_map: &DisplaySnapshot,
 2622        window: &mut Window,
 2623        cx: &mut Context<Self>,
 2624    ) {
 2625        let start_row = cmp::min(tail.row(), head.row());
 2626        let end_row = cmp::max(tail.row(), head.row());
 2627        let start_column = cmp::min(tail.column(), goal_column);
 2628        let end_column = cmp::max(tail.column(), goal_column);
 2629        let reversed = start_column < tail.column();
 2630
 2631        let selection_ranges = (start_row.0..=end_row.0)
 2632            .map(DisplayRow)
 2633            .filter_map(|row| {
 2634                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2635                    let start = display_map
 2636                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2637                        .to_point(display_map);
 2638                    let end = display_map
 2639                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2640                        .to_point(display_map);
 2641                    if reversed {
 2642                        Some(end..start)
 2643                    } else {
 2644                        Some(start..end)
 2645                    }
 2646                } else {
 2647                    None
 2648                }
 2649            })
 2650            .collect::<Vec<_>>();
 2651
 2652        self.change_selections(None, window, cx, |s| {
 2653            s.select_ranges(selection_ranges);
 2654        });
 2655        cx.notify();
 2656    }
 2657
 2658    pub fn has_pending_nonempty_selection(&self) -> bool {
 2659        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2660            Some(Selection { start, end, .. }) => start != end,
 2661            None => false,
 2662        };
 2663
 2664        pending_nonempty_selection
 2665            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2666    }
 2667
 2668    pub fn has_pending_selection(&self) -> bool {
 2669        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2670    }
 2671
 2672    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2673        self.selection_mark_mode = false;
 2674
 2675        if self.clear_expanded_diff_hunks(cx) {
 2676            cx.notify();
 2677            return;
 2678        }
 2679        if self.dismiss_menus_and_popups(true, window, cx) {
 2680            return;
 2681        }
 2682
 2683        if self.mode == EditorMode::Full
 2684            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2685        {
 2686            return;
 2687        }
 2688
 2689        cx.propagate();
 2690    }
 2691
 2692    pub fn dismiss_menus_and_popups(
 2693        &mut self,
 2694        is_user_requested: bool,
 2695        window: &mut Window,
 2696        cx: &mut Context<Self>,
 2697    ) -> bool {
 2698        if self.take_rename(false, window, cx).is_some() {
 2699            return true;
 2700        }
 2701
 2702        if hide_hover(self, cx) {
 2703            return true;
 2704        }
 2705
 2706        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2707            return true;
 2708        }
 2709
 2710        if self.hide_context_menu(window, cx).is_some() {
 2711            return true;
 2712        }
 2713
 2714        if self.mouse_context_menu.take().is_some() {
 2715            return true;
 2716        }
 2717
 2718        if is_user_requested && self.discard_inline_completion(true, cx) {
 2719            return true;
 2720        }
 2721
 2722        if self.snippet_stack.pop().is_some() {
 2723            return true;
 2724        }
 2725
 2726        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2727            self.dismiss_diagnostics(cx);
 2728            return true;
 2729        }
 2730
 2731        false
 2732    }
 2733
 2734    fn linked_editing_ranges_for(
 2735        &self,
 2736        selection: Range<text::Anchor>,
 2737        cx: &App,
 2738    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2739        if self.linked_edit_ranges.is_empty() {
 2740            return None;
 2741        }
 2742        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2743            selection.end.buffer_id.and_then(|end_buffer_id| {
 2744                if selection.start.buffer_id != Some(end_buffer_id) {
 2745                    return None;
 2746                }
 2747                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2748                let snapshot = buffer.read(cx).snapshot();
 2749                self.linked_edit_ranges
 2750                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2751                    .map(|ranges| (ranges, snapshot, buffer))
 2752            })?;
 2753        use text::ToOffset as TO;
 2754        // find offset from the start of current range to current cursor position
 2755        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2756
 2757        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2758        let start_difference = start_offset - start_byte_offset;
 2759        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2760        let end_difference = end_offset - start_byte_offset;
 2761        // Current range has associated linked ranges.
 2762        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2763        for range in linked_ranges.iter() {
 2764            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2765            let end_offset = start_offset + end_difference;
 2766            let start_offset = start_offset + start_difference;
 2767            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2768                continue;
 2769            }
 2770            if self.selections.disjoint_anchor_ranges().any(|s| {
 2771                if s.start.buffer_id != selection.start.buffer_id
 2772                    || s.end.buffer_id != selection.end.buffer_id
 2773                {
 2774                    return false;
 2775                }
 2776                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2777                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2778            }) {
 2779                continue;
 2780            }
 2781            let start = buffer_snapshot.anchor_after(start_offset);
 2782            let end = buffer_snapshot.anchor_after(end_offset);
 2783            linked_edits
 2784                .entry(buffer.clone())
 2785                .or_default()
 2786                .push(start..end);
 2787        }
 2788        Some(linked_edits)
 2789    }
 2790
 2791    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2792        let text: Arc<str> = text.into();
 2793
 2794        if self.read_only(cx) {
 2795            return;
 2796        }
 2797
 2798        self.mouse_cursor_hidden = self.hide_mouse_while_typing;
 2799
 2800        let selections = self.selections.all_adjusted(cx);
 2801        let mut bracket_inserted = false;
 2802        let mut edits = Vec::new();
 2803        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2804        let mut new_selections = Vec::with_capacity(selections.len());
 2805        let mut new_autoclose_regions = Vec::new();
 2806        let snapshot = self.buffer.read(cx).read(cx);
 2807
 2808        for (selection, autoclose_region) in
 2809            self.selections_with_autoclose_regions(selections, &snapshot)
 2810        {
 2811            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2812                // Determine if the inserted text matches the opening or closing
 2813                // bracket of any of this language's bracket pairs.
 2814                let mut bracket_pair = None;
 2815                let mut is_bracket_pair_start = false;
 2816                let mut is_bracket_pair_end = false;
 2817                if !text.is_empty() {
 2818                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2819                    //  and they are removing the character that triggered IME popup.
 2820                    for (pair, enabled) in scope.brackets() {
 2821                        if !pair.close && !pair.surround {
 2822                            continue;
 2823                        }
 2824
 2825                        if enabled && pair.start.ends_with(text.as_ref()) {
 2826                            let prefix_len = pair.start.len() - text.len();
 2827                            let preceding_text_matches_prefix = prefix_len == 0
 2828                                || (selection.start.column >= (prefix_len as u32)
 2829                                    && snapshot.contains_str_at(
 2830                                        Point::new(
 2831                                            selection.start.row,
 2832                                            selection.start.column - (prefix_len as u32),
 2833                                        ),
 2834                                        &pair.start[..prefix_len],
 2835                                    ));
 2836                            if preceding_text_matches_prefix {
 2837                                bracket_pair = Some(pair.clone());
 2838                                is_bracket_pair_start = true;
 2839                                break;
 2840                            }
 2841                        }
 2842                        if pair.end.as_str() == text.as_ref() {
 2843                            bracket_pair = Some(pair.clone());
 2844                            is_bracket_pair_end = true;
 2845                            break;
 2846                        }
 2847                    }
 2848                }
 2849
 2850                if let Some(bracket_pair) = bracket_pair {
 2851                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2852                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2853                    let auto_surround =
 2854                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2855                    if selection.is_empty() {
 2856                        if is_bracket_pair_start {
 2857                            // If the inserted text is a suffix of an opening bracket and the
 2858                            // selection is preceded by the rest of the opening bracket, then
 2859                            // insert the closing bracket.
 2860                            let following_text_allows_autoclose = snapshot
 2861                                .chars_at(selection.start)
 2862                                .next()
 2863                                .map_or(true, |c| scope.should_autoclose_before(c));
 2864
 2865                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2866                                && bracket_pair.start.len() == 1
 2867                            {
 2868                                let target = bracket_pair.start.chars().next().unwrap();
 2869                                let current_line_count = snapshot
 2870                                    .reversed_chars_at(selection.start)
 2871                                    .take_while(|&c| c != '\n')
 2872                                    .filter(|&c| c == target)
 2873                                    .count();
 2874                                current_line_count % 2 == 1
 2875                            } else {
 2876                                false
 2877                            };
 2878
 2879                            if autoclose
 2880                                && bracket_pair.close
 2881                                && following_text_allows_autoclose
 2882                                && !is_closing_quote
 2883                            {
 2884                                let anchor = snapshot.anchor_before(selection.end);
 2885                                new_selections.push((selection.map(|_| anchor), text.len()));
 2886                                new_autoclose_regions.push((
 2887                                    anchor,
 2888                                    text.len(),
 2889                                    selection.id,
 2890                                    bracket_pair.clone(),
 2891                                ));
 2892                                edits.push((
 2893                                    selection.range(),
 2894                                    format!("{}{}", text, bracket_pair.end).into(),
 2895                                ));
 2896                                bracket_inserted = true;
 2897                                continue;
 2898                            }
 2899                        }
 2900
 2901                        if let Some(region) = autoclose_region {
 2902                            // If the selection is followed by an auto-inserted closing bracket,
 2903                            // then don't insert that closing bracket again; just move the selection
 2904                            // past the closing bracket.
 2905                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2906                                && text.as_ref() == region.pair.end.as_str();
 2907                            if should_skip {
 2908                                let anchor = snapshot.anchor_after(selection.end);
 2909                                new_selections
 2910                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2911                                continue;
 2912                            }
 2913                        }
 2914
 2915                        let always_treat_brackets_as_autoclosed = snapshot
 2916                            .settings_at(selection.start, cx)
 2917                            .always_treat_brackets_as_autoclosed;
 2918                        if always_treat_brackets_as_autoclosed
 2919                            && is_bracket_pair_end
 2920                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2921                        {
 2922                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2923                            // and the inserted text is a closing bracket and the selection is followed
 2924                            // by the closing bracket then move the selection past the closing bracket.
 2925                            let anchor = snapshot.anchor_after(selection.end);
 2926                            new_selections.push((selection.map(|_| anchor), text.len()));
 2927                            continue;
 2928                        }
 2929                    }
 2930                    // If an opening bracket is 1 character long and is typed while
 2931                    // text is selected, then surround that text with the bracket pair.
 2932                    else if auto_surround
 2933                        && bracket_pair.surround
 2934                        && is_bracket_pair_start
 2935                        && bracket_pair.start.chars().count() == 1
 2936                    {
 2937                        edits.push((selection.start..selection.start, text.clone()));
 2938                        edits.push((
 2939                            selection.end..selection.end,
 2940                            bracket_pair.end.as_str().into(),
 2941                        ));
 2942                        bracket_inserted = true;
 2943                        new_selections.push((
 2944                            Selection {
 2945                                id: selection.id,
 2946                                start: snapshot.anchor_after(selection.start),
 2947                                end: snapshot.anchor_before(selection.end),
 2948                                reversed: selection.reversed,
 2949                                goal: selection.goal,
 2950                            },
 2951                            0,
 2952                        ));
 2953                        continue;
 2954                    }
 2955                }
 2956            }
 2957
 2958            if self.auto_replace_emoji_shortcode
 2959                && selection.is_empty()
 2960                && text.as_ref().ends_with(':')
 2961            {
 2962                if let Some(possible_emoji_short_code) =
 2963                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2964                {
 2965                    if !possible_emoji_short_code.is_empty() {
 2966                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2967                            let emoji_shortcode_start = Point::new(
 2968                                selection.start.row,
 2969                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2970                            );
 2971
 2972                            // Remove shortcode from buffer
 2973                            edits.push((
 2974                                emoji_shortcode_start..selection.start,
 2975                                "".to_string().into(),
 2976                            ));
 2977                            new_selections.push((
 2978                                Selection {
 2979                                    id: selection.id,
 2980                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2981                                    end: snapshot.anchor_before(selection.start),
 2982                                    reversed: selection.reversed,
 2983                                    goal: selection.goal,
 2984                                },
 2985                                0,
 2986                            ));
 2987
 2988                            // Insert emoji
 2989                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2990                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2991                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2992
 2993                            continue;
 2994                        }
 2995                    }
 2996                }
 2997            }
 2998
 2999            // If not handling any auto-close operation, then just replace the selected
 3000            // text with the given input and move the selection to the end of the
 3001            // newly inserted text.
 3002            let anchor = snapshot.anchor_after(selection.end);
 3003            if !self.linked_edit_ranges.is_empty() {
 3004                let start_anchor = snapshot.anchor_before(selection.start);
 3005
 3006                let is_word_char = text.chars().next().map_or(true, |char| {
 3007                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3008                    classifier.is_word(char)
 3009                });
 3010
 3011                if is_word_char {
 3012                    if let Some(ranges) = self
 3013                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3014                    {
 3015                        for (buffer, edits) in ranges {
 3016                            linked_edits
 3017                                .entry(buffer.clone())
 3018                                .or_default()
 3019                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3020                        }
 3021                    }
 3022                }
 3023            }
 3024
 3025            new_selections.push((selection.map(|_| anchor), 0));
 3026            edits.push((selection.start..selection.end, text.clone()));
 3027        }
 3028
 3029        drop(snapshot);
 3030
 3031        self.transact(window, cx, |this, window, cx| {
 3032            this.buffer.update(cx, |buffer, cx| {
 3033                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3034            });
 3035            for (buffer, edits) in linked_edits {
 3036                buffer.update(cx, |buffer, cx| {
 3037                    let snapshot = buffer.snapshot();
 3038                    let edits = edits
 3039                        .into_iter()
 3040                        .map(|(range, text)| {
 3041                            use text::ToPoint as TP;
 3042                            let end_point = TP::to_point(&range.end, &snapshot);
 3043                            let start_point = TP::to_point(&range.start, &snapshot);
 3044                            (start_point..end_point, text)
 3045                        })
 3046                        .sorted_by_key(|(range, _)| range.start)
 3047                        .collect::<Vec<_>>();
 3048                    buffer.edit(edits, None, cx);
 3049                })
 3050            }
 3051            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3052            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3053            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3054            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3055                .zip(new_selection_deltas)
 3056                .map(|(selection, delta)| Selection {
 3057                    id: selection.id,
 3058                    start: selection.start + delta,
 3059                    end: selection.end + delta,
 3060                    reversed: selection.reversed,
 3061                    goal: SelectionGoal::None,
 3062                })
 3063                .collect::<Vec<_>>();
 3064
 3065            let mut i = 0;
 3066            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3067                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3068                let start = map.buffer_snapshot.anchor_before(position);
 3069                let end = map.buffer_snapshot.anchor_after(position);
 3070                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3071                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3072                        Ordering::Less => i += 1,
 3073                        Ordering::Greater => break,
 3074                        Ordering::Equal => {
 3075                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3076                                Ordering::Less => i += 1,
 3077                                Ordering::Equal => break,
 3078                                Ordering::Greater => break,
 3079                            }
 3080                        }
 3081                    }
 3082                }
 3083                this.autoclose_regions.insert(
 3084                    i,
 3085                    AutocloseRegion {
 3086                        selection_id,
 3087                        range: start..end,
 3088                        pair,
 3089                    },
 3090                );
 3091            }
 3092
 3093            let had_active_inline_completion = this.has_active_inline_completion();
 3094            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3095                s.select(new_selections)
 3096            });
 3097
 3098            if !bracket_inserted {
 3099                if let Some(on_type_format_task) =
 3100                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3101                {
 3102                    on_type_format_task.detach_and_log_err(cx);
 3103                }
 3104            }
 3105
 3106            let editor_settings = EditorSettings::get_global(cx);
 3107            if bracket_inserted
 3108                && (editor_settings.auto_signature_help
 3109                    || editor_settings.show_signature_help_after_edits)
 3110            {
 3111                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3112            }
 3113
 3114            let trigger_in_words =
 3115                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3116            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3117            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3118            this.refresh_inline_completion(true, false, window, cx);
 3119        });
 3120    }
 3121
 3122    fn find_possible_emoji_shortcode_at_position(
 3123        snapshot: &MultiBufferSnapshot,
 3124        position: Point,
 3125    ) -> Option<String> {
 3126        let mut chars = Vec::new();
 3127        let mut found_colon = false;
 3128        for char in snapshot.reversed_chars_at(position).take(100) {
 3129            // Found a possible emoji shortcode in the middle of the buffer
 3130            if found_colon {
 3131                if char.is_whitespace() {
 3132                    chars.reverse();
 3133                    return Some(chars.iter().collect());
 3134                }
 3135                // If the previous character is not a whitespace, we are in the middle of a word
 3136                // and we only want to complete the shortcode if the word is made up of other emojis
 3137                let mut containing_word = String::new();
 3138                for ch in snapshot
 3139                    .reversed_chars_at(position)
 3140                    .skip(chars.len() + 1)
 3141                    .take(100)
 3142                {
 3143                    if ch.is_whitespace() {
 3144                        break;
 3145                    }
 3146                    containing_word.push(ch);
 3147                }
 3148                let containing_word = containing_word.chars().rev().collect::<String>();
 3149                if util::word_consists_of_emojis(containing_word.as_str()) {
 3150                    chars.reverse();
 3151                    return Some(chars.iter().collect());
 3152                }
 3153            }
 3154
 3155            if char.is_whitespace() || !char.is_ascii() {
 3156                return None;
 3157            }
 3158            if char == ':' {
 3159                found_colon = true;
 3160            } else {
 3161                chars.push(char);
 3162            }
 3163        }
 3164        // Found a possible emoji shortcode at the beginning of the buffer
 3165        chars.reverse();
 3166        Some(chars.iter().collect())
 3167    }
 3168
 3169    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3170        self.transact(window, cx, |this, window, cx| {
 3171            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3172                let selections = this.selections.all::<usize>(cx);
 3173                let multi_buffer = this.buffer.read(cx);
 3174                let buffer = multi_buffer.snapshot(cx);
 3175                selections
 3176                    .iter()
 3177                    .map(|selection| {
 3178                        let start_point = selection.start.to_point(&buffer);
 3179                        let mut indent =
 3180                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3181                        indent.len = cmp::min(indent.len, start_point.column);
 3182                        let start = selection.start;
 3183                        let end = selection.end;
 3184                        let selection_is_empty = start == end;
 3185                        let language_scope = buffer.language_scope_at(start);
 3186                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3187                            &language_scope
 3188                        {
 3189                            let insert_extra_newline =
 3190                                insert_extra_newline_brackets(&buffer, start..end, language)
 3191                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3192
 3193                            // Comment extension on newline is allowed only for cursor selections
 3194                            let comment_delimiter = maybe!({
 3195                                if !selection_is_empty {
 3196                                    return None;
 3197                                }
 3198
 3199                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3200                                    return None;
 3201                                }
 3202
 3203                                let delimiters = language.line_comment_prefixes();
 3204                                let max_len_of_delimiter =
 3205                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3206                                let (snapshot, range) =
 3207                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3208
 3209                                let mut index_of_first_non_whitespace = 0;
 3210                                let comment_candidate = snapshot
 3211                                    .chars_for_range(range)
 3212                                    .skip_while(|c| {
 3213                                        let should_skip = c.is_whitespace();
 3214                                        if should_skip {
 3215                                            index_of_first_non_whitespace += 1;
 3216                                        }
 3217                                        should_skip
 3218                                    })
 3219                                    .take(max_len_of_delimiter)
 3220                                    .collect::<String>();
 3221                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3222                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3223                                })?;
 3224                                let cursor_is_placed_after_comment_marker =
 3225                                    index_of_first_non_whitespace + comment_prefix.len()
 3226                                        <= start_point.column as usize;
 3227                                if cursor_is_placed_after_comment_marker {
 3228                                    Some(comment_prefix.clone())
 3229                                } else {
 3230                                    None
 3231                                }
 3232                            });
 3233                            (comment_delimiter, insert_extra_newline)
 3234                        } else {
 3235                            (None, false)
 3236                        };
 3237
 3238                        let capacity_for_delimiter = comment_delimiter
 3239                            .as_deref()
 3240                            .map(str::len)
 3241                            .unwrap_or_default();
 3242                        let mut new_text =
 3243                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3244                        new_text.push('\n');
 3245                        new_text.extend(indent.chars());
 3246                        if let Some(delimiter) = &comment_delimiter {
 3247                            new_text.push_str(delimiter);
 3248                        }
 3249                        if insert_extra_newline {
 3250                            new_text = new_text.repeat(2);
 3251                        }
 3252
 3253                        let anchor = buffer.anchor_after(end);
 3254                        let new_selection = selection.map(|_| anchor);
 3255                        (
 3256                            (start..end, new_text),
 3257                            (insert_extra_newline, new_selection),
 3258                        )
 3259                    })
 3260                    .unzip()
 3261            };
 3262
 3263            this.edit_with_autoindent(edits, cx);
 3264            let buffer = this.buffer.read(cx).snapshot(cx);
 3265            let new_selections = selection_fixup_info
 3266                .into_iter()
 3267                .map(|(extra_newline_inserted, new_selection)| {
 3268                    let mut cursor = new_selection.end.to_point(&buffer);
 3269                    if extra_newline_inserted {
 3270                        cursor.row -= 1;
 3271                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3272                    }
 3273                    new_selection.map(|_| cursor)
 3274                })
 3275                .collect();
 3276
 3277            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3278                s.select(new_selections)
 3279            });
 3280            this.refresh_inline_completion(true, false, window, cx);
 3281        });
 3282    }
 3283
 3284    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3285        let buffer = self.buffer.read(cx);
 3286        let snapshot = buffer.snapshot(cx);
 3287
 3288        let mut edits = Vec::new();
 3289        let mut rows = Vec::new();
 3290
 3291        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3292            let cursor = selection.head();
 3293            let row = cursor.row;
 3294
 3295            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3296
 3297            let newline = "\n".to_string();
 3298            edits.push((start_of_line..start_of_line, newline));
 3299
 3300            rows.push(row + rows_inserted as u32);
 3301        }
 3302
 3303        self.transact(window, cx, |editor, window, cx| {
 3304            editor.edit(edits, cx);
 3305
 3306            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3307                let mut index = 0;
 3308                s.move_cursors_with(|map, _, _| {
 3309                    let row = rows[index];
 3310                    index += 1;
 3311
 3312                    let point = Point::new(row, 0);
 3313                    let boundary = map.next_line_boundary(point).1;
 3314                    let clipped = map.clip_point(boundary, Bias::Left);
 3315
 3316                    (clipped, SelectionGoal::None)
 3317                });
 3318            });
 3319
 3320            let mut indent_edits = Vec::new();
 3321            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3322            for row in rows {
 3323                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3324                for (row, indent) in indents {
 3325                    if indent.len == 0 {
 3326                        continue;
 3327                    }
 3328
 3329                    let text = match indent.kind {
 3330                        IndentKind::Space => " ".repeat(indent.len as usize),
 3331                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3332                    };
 3333                    let point = Point::new(row.0, 0);
 3334                    indent_edits.push((point..point, text));
 3335                }
 3336            }
 3337            editor.edit(indent_edits, cx);
 3338        });
 3339    }
 3340
 3341    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3342        let buffer = self.buffer.read(cx);
 3343        let snapshot = buffer.snapshot(cx);
 3344
 3345        let mut edits = Vec::new();
 3346        let mut rows = Vec::new();
 3347        let mut rows_inserted = 0;
 3348
 3349        for selection in self.selections.all_adjusted(cx) {
 3350            let cursor = selection.head();
 3351            let row = cursor.row;
 3352
 3353            let point = Point::new(row + 1, 0);
 3354            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3355
 3356            let newline = "\n".to_string();
 3357            edits.push((start_of_line..start_of_line, newline));
 3358
 3359            rows_inserted += 1;
 3360            rows.push(row + rows_inserted);
 3361        }
 3362
 3363        self.transact(window, cx, |editor, window, cx| {
 3364            editor.edit(edits, cx);
 3365
 3366            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3367                let mut index = 0;
 3368                s.move_cursors_with(|map, _, _| {
 3369                    let row = rows[index];
 3370                    index += 1;
 3371
 3372                    let point = Point::new(row, 0);
 3373                    let boundary = map.next_line_boundary(point).1;
 3374                    let clipped = map.clip_point(boundary, Bias::Left);
 3375
 3376                    (clipped, SelectionGoal::None)
 3377                });
 3378            });
 3379
 3380            let mut indent_edits = Vec::new();
 3381            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3382            for row in rows {
 3383                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3384                for (row, indent) in indents {
 3385                    if indent.len == 0 {
 3386                        continue;
 3387                    }
 3388
 3389                    let text = match indent.kind {
 3390                        IndentKind::Space => " ".repeat(indent.len as usize),
 3391                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3392                    };
 3393                    let point = Point::new(row.0, 0);
 3394                    indent_edits.push((point..point, text));
 3395                }
 3396            }
 3397            editor.edit(indent_edits, cx);
 3398        });
 3399    }
 3400
 3401    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3402        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3403            original_start_columns: Vec::new(),
 3404        });
 3405        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3406    }
 3407
 3408    fn insert_with_autoindent_mode(
 3409        &mut self,
 3410        text: &str,
 3411        autoindent_mode: Option<AutoindentMode>,
 3412        window: &mut Window,
 3413        cx: &mut Context<Self>,
 3414    ) {
 3415        if self.read_only(cx) {
 3416            return;
 3417        }
 3418
 3419        let text: Arc<str> = text.into();
 3420        self.transact(window, cx, |this, window, cx| {
 3421            let old_selections = this.selections.all_adjusted(cx);
 3422            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3423                let anchors = {
 3424                    let snapshot = buffer.read(cx);
 3425                    old_selections
 3426                        .iter()
 3427                        .map(|s| {
 3428                            let anchor = snapshot.anchor_after(s.head());
 3429                            s.map(|_| anchor)
 3430                        })
 3431                        .collect::<Vec<_>>()
 3432                };
 3433                buffer.edit(
 3434                    old_selections
 3435                        .iter()
 3436                        .map(|s| (s.start..s.end, text.clone())),
 3437                    autoindent_mode,
 3438                    cx,
 3439                );
 3440                anchors
 3441            });
 3442
 3443            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3444                s.select_anchors(selection_anchors);
 3445            });
 3446
 3447            cx.notify();
 3448        });
 3449    }
 3450
 3451    fn trigger_completion_on_input(
 3452        &mut self,
 3453        text: &str,
 3454        trigger_in_words: bool,
 3455        window: &mut Window,
 3456        cx: &mut Context<Self>,
 3457    ) {
 3458        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3459            self.show_completions(
 3460                &ShowCompletions {
 3461                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3462                },
 3463                window,
 3464                cx,
 3465            );
 3466        } else {
 3467            self.hide_context_menu(window, cx);
 3468        }
 3469    }
 3470
 3471    fn is_completion_trigger(
 3472        &self,
 3473        text: &str,
 3474        trigger_in_words: bool,
 3475        cx: &mut Context<Self>,
 3476    ) -> bool {
 3477        let position = self.selections.newest_anchor().head();
 3478        let multibuffer = self.buffer.read(cx);
 3479        let Some(buffer) = position
 3480            .buffer_id
 3481            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3482        else {
 3483            return false;
 3484        };
 3485
 3486        if let Some(completion_provider) = &self.completion_provider {
 3487            completion_provider.is_completion_trigger(
 3488                &buffer,
 3489                position.text_anchor,
 3490                text,
 3491                trigger_in_words,
 3492                cx,
 3493            )
 3494        } else {
 3495            false
 3496        }
 3497    }
 3498
 3499    /// If any empty selections is touching the start of its innermost containing autoclose
 3500    /// region, expand it to select the brackets.
 3501    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3502        let selections = self.selections.all::<usize>(cx);
 3503        let buffer = self.buffer.read(cx).read(cx);
 3504        let new_selections = self
 3505            .selections_with_autoclose_regions(selections, &buffer)
 3506            .map(|(mut selection, region)| {
 3507                if !selection.is_empty() {
 3508                    return selection;
 3509                }
 3510
 3511                if let Some(region) = region {
 3512                    let mut range = region.range.to_offset(&buffer);
 3513                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3514                        range.start -= region.pair.start.len();
 3515                        if buffer.contains_str_at(range.start, &region.pair.start)
 3516                            && buffer.contains_str_at(range.end, &region.pair.end)
 3517                        {
 3518                            range.end += region.pair.end.len();
 3519                            selection.start = range.start;
 3520                            selection.end = range.end;
 3521
 3522                            return selection;
 3523                        }
 3524                    }
 3525                }
 3526
 3527                let always_treat_brackets_as_autoclosed = buffer
 3528                    .settings_at(selection.start, cx)
 3529                    .always_treat_brackets_as_autoclosed;
 3530
 3531                if !always_treat_brackets_as_autoclosed {
 3532                    return selection;
 3533                }
 3534
 3535                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3536                    for (pair, enabled) in scope.brackets() {
 3537                        if !enabled || !pair.close {
 3538                            continue;
 3539                        }
 3540
 3541                        if buffer.contains_str_at(selection.start, &pair.end) {
 3542                            let pair_start_len = pair.start.len();
 3543                            if buffer.contains_str_at(
 3544                                selection.start.saturating_sub(pair_start_len),
 3545                                &pair.start,
 3546                            ) {
 3547                                selection.start -= pair_start_len;
 3548                                selection.end += pair.end.len();
 3549
 3550                                return selection;
 3551                            }
 3552                        }
 3553                    }
 3554                }
 3555
 3556                selection
 3557            })
 3558            .collect();
 3559
 3560        drop(buffer);
 3561        self.change_selections(None, window, cx, |selections| {
 3562            selections.select(new_selections)
 3563        });
 3564    }
 3565
 3566    /// Iterate the given selections, and for each one, find the smallest surrounding
 3567    /// autoclose region. This uses the ordering of the selections and the autoclose
 3568    /// regions to avoid repeated comparisons.
 3569    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3570        &'a self,
 3571        selections: impl IntoIterator<Item = Selection<D>>,
 3572        buffer: &'a MultiBufferSnapshot,
 3573    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3574        let mut i = 0;
 3575        let mut regions = self.autoclose_regions.as_slice();
 3576        selections.into_iter().map(move |selection| {
 3577            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3578
 3579            let mut enclosing = None;
 3580            while let Some(pair_state) = regions.get(i) {
 3581                if pair_state.range.end.to_offset(buffer) < range.start {
 3582                    regions = &regions[i + 1..];
 3583                    i = 0;
 3584                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3585                    break;
 3586                } else {
 3587                    if pair_state.selection_id == selection.id {
 3588                        enclosing = Some(pair_state);
 3589                    }
 3590                    i += 1;
 3591                }
 3592            }
 3593
 3594            (selection, enclosing)
 3595        })
 3596    }
 3597
 3598    /// Remove any autoclose regions that no longer contain their selection.
 3599    fn invalidate_autoclose_regions(
 3600        &mut self,
 3601        mut selections: &[Selection<Anchor>],
 3602        buffer: &MultiBufferSnapshot,
 3603    ) {
 3604        self.autoclose_regions.retain(|state| {
 3605            let mut i = 0;
 3606            while let Some(selection) = selections.get(i) {
 3607                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3608                    selections = &selections[1..];
 3609                    continue;
 3610                }
 3611                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3612                    break;
 3613                }
 3614                if selection.id == state.selection_id {
 3615                    return true;
 3616                } else {
 3617                    i += 1;
 3618                }
 3619            }
 3620            false
 3621        });
 3622    }
 3623
 3624    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3625        let offset = position.to_offset(buffer);
 3626        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3627        if offset > word_range.start && kind == Some(CharKind::Word) {
 3628            Some(
 3629                buffer
 3630                    .text_for_range(word_range.start..offset)
 3631                    .collect::<String>(),
 3632            )
 3633        } else {
 3634            None
 3635        }
 3636    }
 3637
 3638    pub fn toggle_inlay_hints(
 3639        &mut self,
 3640        _: &ToggleInlayHints,
 3641        _: &mut Window,
 3642        cx: &mut Context<Self>,
 3643    ) {
 3644        self.refresh_inlay_hints(
 3645            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3646            cx,
 3647        );
 3648    }
 3649
 3650    pub fn inlay_hints_enabled(&self) -> bool {
 3651        self.inlay_hint_cache.enabled
 3652    }
 3653
 3654    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3655        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3656            return;
 3657        }
 3658
 3659        let reason_description = reason.description();
 3660        let ignore_debounce = matches!(
 3661            reason,
 3662            InlayHintRefreshReason::SettingsChange(_)
 3663                | InlayHintRefreshReason::Toggle(_)
 3664                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3665        );
 3666        let (invalidate_cache, required_languages) = match reason {
 3667            InlayHintRefreshReason::Toggle(enabled) => {
 3668                self.inlay_hint_cache.enabled = enabled;
 3669                if enabled {
 3670                    (InvalidationStrategy::RefreshRequested, None)
 3671                } else {
 3672                    self.inlay_hint_cache.clear();
 3673                    self.splice_inlays(
 3674                        &self
 3675                            .visible_inlay_hints(cx)
 3676                            .iter()
 3677                            .map(|inlay| inlay.id)
 3678                            .collect::<Vec<InlayId>>(),
 3679                        Vec::new(),
 3680                        cx,
 3681                    );
 3682                    return;
 3683                }
 3684            }
 3685            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3686                match self.inlay_hint_cache.update_settings(
 3687                    &self.buffer,
 3688                    new_settings,
 3689                    self.visible_inlay_hints(cx),
 3690                    cx,
 3691                ) {
 3692                    ControlFlow::Break(Some(InlaySplice {
 3693                        to_remove,
 3694                        to_insert,
 3695                    })) => {
 3696                        self.splice_inlays(&to_remove, to_insert, cx);
 3697                        return;
 3698                    }
 3699                    ControlFlow::Break(None) => return,
 3700                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3701                }
 3702            }
 3703            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3704                if let Some(InlaySplice {
 3705                    to_remove,
 3706                    to_insert,
 3707                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3708                {
 3709                    self.splice_inlays(&to_remove, to_insert, cx);
 3710                }
 3711                return;
 3712            }
 3713            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3714            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3715                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3716            }
 3717            InlayHintRefreshReason::RefreshRequested => {
 3718                (InvalidationStrategy::RefreshRequested, None)
 3719            }
 3720        };
 3721
 3722        if let Some(InlaySplice {
 3723            to_remove,
 3724            to_insert,
 3725        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3726            reason_description,
 3727            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3728            invalidate_cache,
 3729            ignore_debounce,
 3730            cx,
 3731        ) {
 3732            self.splice_inlays(&to_remove, to_insert, cx);
 3733        }
 3734    }
 3735
 3736    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3737        self.display_map
 3738            .read(cx)
 3739            .current_inlays()
 3740            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3741            .cloned()
 3742            .collect()
 3743    }
 3744
 3745    pub fn excerpts_for_inlay_hints_query(
 3746        &self,
 3747        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3748        cx: &mut Context<Editor>,
 3749    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3750        let Some(project) = self.project.as_ref() else {
 3751            return HashMap::default();
 3752        };
 3753        let project = project.read(cx);
 3754        let multi_buffer = self.buffer().read(cx);
 3755        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3756        let multi_buffer_visible_start = self
 3757            .scroll_manager
 3758            .anchor()
 3759            .anchor
 3760            .to_point(&multi_buffer_snapshot);
 3761        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3762            multi_buffer_visible_start
 3763                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3764            Bias::Left,
 3765        );
 3766        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3767        multi_buffer_snapshot
 3768            .range_to_buffer_ranges(multi_buffer_visible_range)
 3769            .into_iter()
 3770            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3771            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3772                let buffer_file = project::File::from_dyn(buffer.file())?;
 3773                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3774                let worktree_entry = buffer_worktree
 3775                    .read(cx)
 3776                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3777                if worktree_entry.is_ignored {
 3778                    return None;
 3779                }
 3780
 3781                let language = buffer.language()?;
 3782                if let Some(restrict_to_languages) = restrict_to_languages {
 3783                    if !restrict_to_languages.contains(language) {
 3784                        return None;
 3785                    }
 3786                }
 3787                Some((
 3788                    excerpt_id,
 3789                    (
 3790                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3791                        buffer.version().clone(),
 3792                        excerpt_visible_range,
 3793                    ),
 3794                ))
 3795            })
 3796            .collect()
 3797    }
 3798
 3799    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3800        TextLayoutDetails {
 3801            text_system: window.text_system().clone(),
 3802            editor_style: self.style.clone().unwrap(),
 3803            rem_size: window.rem_size(),
 3804            scroll_anchor: self.scroll_manager.anchor(),
 3805            visible_rows: self.visible_line_count(),
 3806            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3807        }
 3808    }
 3809
 3810    pub fn splice_inlays(
 3811        &self,
 3812        to_remove: &[InlayId],
 3813        to_insert: Vec<Inlay>,
 3814        cx: &mut Context<Self>,
 3815    ) {
 3816        self.display_map.update(cx, |display_map, cx| {
 3817            display_map.splice_inlays(to_remove, to_insert, cx)
 3818        });
 3819        cx.notify();
 3820    }
 3821
 3822    fn trigger_on_type_formatting(
 3823        &self,
 3824        input: String,
 3825        window: &mut Window,
 3826        cx: &mut Context<Self>,
 3827    ) -> Option<Task<Result<()>>> {
 3828        if input.len() != 1 {
 3829            return None;
 3830        }
 3831
 3832        let project = self.project.as_ref()?;
 3833        let position = self.selections.newest_anchor().head();
 3834        let (buffer, buffer_position) = self
 3835            .buffer
 3836            .read(cx)
 3837            .text_anchor_for_position(position, cx)?;
 3838
 3839        let settings = language_settings::language_settings(
 3840            buffer
 3841                .read(cx)
 3842                .language_at(buffer_position)
 3843                .map(|l| l.name()),
 3844            buffer.read(cx).file(),
 3845            cx,
 3846        );
 3847        if !settings.use_on_type_format {
 3848            return None;
 3849        }
 3850
 3851        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3852        // hence we do LSP request & edit on host side only — add formats to host's history.
 3853        let push_to_lsp_host_history = true;
 3854        // If this is not the host, append its history with new edits.
 3855        let push_to_client_history = project.read(cx).is_via_collab();
 3856
 3857        let on_type_formatting = project.update(cx, |project, cx| {
 3858            project.on_type_format(
 3859                buffer.clone(),
 3860                buffer_position,
 3861                input,
 3862                push_to_lsp_host_history,
 3863                cx,
 3864            )
 3865        });
 3866        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3867            if let Some(transaction) = on_type_formatting.await? {
 3868                if push_to_client_history {
 3869                    buffer
 3870                        .update(&mut cx, |buffer, _| {
 3871                            buffer.push_transaction(transaction, Instant::now());
 3872                        })
 3873                        .ok();
 3874                }
 3875                editor.update(&mut cx, |editor, cx| {
 3876                    editor.refresh_document_highlights(cx);
 3877                })?;
 3878            }
 3879            Ok(())
 3880        }))
 3881    }
 3882
 3883    pub fn show_completions(
 3884        &mut self,
 3885        options: &ShowCompletions,
 3886        window: &mut Window,
 3887        cx: &mut Context<Self>,
 3888    ) {
 3889        if self.pending_rename.is_some() {
 3890            return;
 3891        }
 3892
 3893        let Some(provider) = self.completion_provider.as_ref() else {
 3894            return;
 3895        };
 3896
 3897        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3898            return;
 3899        }
 3900
 3901        let position = self.selections.newest_anchor().head();
 3902        if position.diff_base_anchor.is_some() {
 3903            return;
 3904        }
 3905        let (buffer, buffer_position) =
 3906            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3907                output
 3908            } else {
 3909                return;
 3910            };
 3911        let show_completion_documentation = buffer
 3912            .read(cx)
 3913            .snapshot()
 3914            .settings_at(buffer_position, cx)
 3915            .show_completion_documentation;
 3916
 3917        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3918
 3919        let trigger_kind = match &options.trigger {
 3920            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3921                CompletionTriggerKind::TRIGGER_CHARACTER
 3922            }
 3923            _ => CompletionTriggerKind::INVOKED,
 3924        };
 3925        let completion_context = CompletionContext {
 3926            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3927                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3928                    Some(String::from(trigger))
 3929                } else {
 3930                    None
 3931                }
 3932            }),
 3933            trigger_kind,
 3934        };
 3935        let completions =
 3936            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3937        let sort_completions = provider.sort_completions();
 3938
 3939        let id = post_inc(&mut self.next_completion_id);
 3940        let task = cx.spawn_in(window, |editor, mut cx| {
 3941            async move {
 3942                editor.update(&mut cx, |this, _| {
 3943                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3944                })?;
 3945                let completions = completions.await.log_err();
 3946                let menu = if let Some(completions) = completions {
 3947                    let mut menu = CompletionsMenu::new(
 3948                        id,
 3949                        sort_completions,
 3950                        show_completion_documentation,
 3951                        position,
 3952                        buffer.clone(),
 3953                        completions.into(),
 3954                    );
 3955
 3956                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3957                        .await;
 3958
 3959                    menu.visible().then_some(menu)
 3960                } else {
 3961                    None
 3962                };
 3963
 3964                editor.update_in(&mut cx, |editor, window, cx| {
 3965                    match editor.context_menu.borrow().as_ref() {
 3966                        None => {}
 3967                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3968                            if prev_menu.id > id {
 3969                                return;
 3970                            }
 3971                        }
 3972                        _ => return,
 3973                    }
 3974
 3975                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3976                        let mut menu = menu.unwrap();
 3977                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3978
 3979                        *editor.context_menu.borrow_mut() =
 3980                            Some(CodeContextMenu::Completions(menu));
 3981
 3982                        if editor.show_edit_predictions_in_menu() {
 3983                            editor.update_visible_inline_completion(window, cx);
 3984                        } else {
 3985                            editor.discard_inline_completion(false, cx);
 3986                        }
 3987
 3988                        cx.notify();
 3989                    } else if editor.completion_tasks.len() <= 1 {
 3990                        // If there are no more completion tasks and the last menu was
 3991                        // empty, we should hide it.
 3992                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3993                        // If it was already hidden and we don't show inline
 3994                        // completions in the menu, we should also show the
 3995                        // inline-completion when available.
 3996                        if was_hidden && editor.show_edit_predictions_in_menu() {
 3997                            editor.update_visible_inline_completion(window, cx);
 3998                        }
 3999                    }
 4000                })?;
 4001
 4002                Ok::<_, anyhow::Error>(())
 4003            }
 4004            .log_err()
 4005        });
 4006
 4007        self.completion_tasks.push((id, task));
 4008    }
 4009
 4010    pub fn confirm_completion(
 4011        &mut self,
 4012        action: &ConfirmCompletion,
 4013        window: &mut Window,
 4014        cx: &mut Context<Self>,
 4015    ) -> Option<Task<Result<()>>> {
 4016        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4017    }
 4018
 4019    pub fn compose_completion(
 4020        &mut self,
 4021        action: &ComposeCompletion,
 4022        window: &mut Window,
 4023        cx: &mut Context<Self>,
 4024    ) -> Option<Task<Result<()>>> {
 4025        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4026    }
 4027
 4028    fn do_completion(
 4029        &mut self,
 4030        item_ix: Option<usize>,
 4031        intent: CompletionIntent,
 4032        window: &mut Window,
 4033        cx: &mut Context<Editor>,
 4034    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4035        use language::ToOffset as _;
 4036
 4037        let completions_menu =
 4038            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4039                menu
 4040            } else {
 4041                return None;
 4042            };
 4043
 4044        let entries = completions_menu.entries.borrow();
 4045        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4046        if self.show_edit_predictions_in_menu() {
 4047            self.discard_inline_completion(true, cx);
 4048        }
 4049        let candidate_id = mat.candidate_id;
 4050        drop(entries);
 4051
 4052        let buffer_handle = completions_menu.buffer;
 4053        let completion = completions_menu
 4054            .completions
 4055            .borrow()
 4056            .get(candidate_id)?
 4057            .clone();
 4058        cx.stop_propagation();
 4059
 4060        let snippet;
 4061        let text;
 4062
 4063        if completion.is_snippet() {
 4064            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4065            text = snippet.as_ref().unwrap().text.clone();
 4066        } else {
 4067            snippet = None;
 4068            text = completion.new_text.clone();
 4069        };
 4070        let selections = self.selections.all::<usize>(cx);
 4071        let buffer = buffer_handle.read(cx);
 4072        let old_range = completion.old_range.to_offset(buffer);
 4073        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4074
 4075        let newest_selection = self.selections.newest_anchor();
 4076        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4077            return None;
 4078        }
 4079
 4080        let lookbehind = newest_selection
 4081            .start
 4082            .text_anchor
 4083            .to_offset(buffer)
 4084            .saturating_sub(old_range.start);
 4085        let lookahead = old_range
 4086            .end
 4087            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4088        let mut common_prefix_len = old_text
 4089            .bytes()
 4090            .zip(text.bytes())
 4091            .take_while(|(a, b)| a == b)
 4092            .count();
 4093
 4094        let snapshot = self.buffer.read(cx).snapshot(cx);
 4095        let mut range_to_replace: Option<Range<isize>> = None;
 4096        let mut ranges = Vec::new();
 4097        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4098        for selection in &selections {
 4099            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4100                let start = selection.start.saturating_sub(lookbehind);
 4101                let end = selection.end + lookahead;
 4102                if selection.id == newest_selection.id {
 4103                    range_to_replace = Some(
 4104                        ((start + common_prefix_len) as isize - selection.start as isize)
 4105                            ..(end as isize - selection.start as isize),
 4106                    );
 4107                }
 4108                ranges.push(start + common_prefix_len..end);
 4109            } else {
 4110                common_prefix_len = 0;
 4111                ranges.clear();
 4112                ranges.extend(selections.iter().map(|s| {
 4113                    if s.id == newest_selection.id {
 4114                        range_to_replace = Some(
 4115                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4116                                - selection.start as isize
 4117                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4118                                    - selection.start as isize,
 4119                        );
 4120                        old_range.clone()
 4121                    } else {
 4122                        s.start..s.end
 4123                    }
 4124                }));
 4125                break;
 4126            }
 4127            if !self.linked_edit_ranges.is_empty() {
 4128                let start_anchor = snapshot.anchor_before(selection.head());
 4129                let end_anchor = snapshot.anchor_after(selection.tail());
 4130                if let Some(ranges) = self
 4131                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4132                {
 4133                    for (buffer, edits) in ranges {
 4134                        linked_edits.entry(buffer.clone()).or_default().extend(
 4135                            edits
 4136                                .into_iter()
 4137                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4138                        );
 4139                    }
 4140                }
 4141            }
 4142        }
 4143        let text = &text[common_prefix_len..];
 4144
 4145        cx.emit(EditorEvent::InputHandled {
 4146            utf16_range_to_replace: range_to_replace,
 4147            text: text.into(),
 4148        });
 4149
 4150        self.transact(window, cx, |this, window, cx| {
 4151            if let Some(mut snippet) = snippet {
 4152                snippet.text = text.to_string();
 4153                for tabstop in snippet
 4154                    .tabstops
 4155                    .iter_mut()
 4156                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4157                {
 4158                    tabstop.start -= common_prefix_len as isize;
 4159                    tabstop.end -= common_prefix_len as isize;
 4160                }
 4161
 4162                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4163            } else {
 4164                this.buffer.update(cx, |buffer, cx| {
 4165                    buffer.edit(
 4166                        ranges.iter().map(|range| (range.clone(), text)),
 4167                        this.autoindent_mode.clone(),
 4168                        cx,
 4169                    );
 4170                });
 4171            }
 4172            for (buffer, edits) in linked_edits {
 4173                buffer.update(cx, |buffer, cx| {
 4174                    let snapshot = buffer.snapshot();
 4175                    let edits = edits
 4176                        .into_iter()
 4177                        .map(|(range, text)| {
 4178                            use text::ToPoint as TP;
 4179                            let end_point = TP::to_point(&range.end, &snapshot);
 4180                            let start_point = TP::to_point(&range.start, &snapshot);
 4181                            (start_point..end_point, text)
 4182                        })
 4183                        .sorted_by_key(|(range, _)| range.start)
 4184                        .collect::<Vec<_>>();
 4185                    buffer.edit(edits, None, cx);
 4186                })
 4187            }
 4188
 4189            this.refresh_inline_completion(true, false, window, cx);
 4190        });
 4191
 4192        let show_new_completions_on_confirm = completion
 4193            .confirm
 4194            .as_ref()
 4195            .map_or(false, |confirm| confirm(intent, window, cx));
 4196        if show_new_completions_on_confirm {
 4197            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4198        }
 4199
 4200        let provider = self.completion_provider.as_ref()?;
 4201        drop(completion);
 4202        let apply_edits = provider.apply_additional_edits_for_completion(
 4203            buffer_handle,
 4204            completions_menu.completions.clone(),
 4205            candidate_id,
 4206            true,
 4207            cx,
 4208        );
 4209
 4210        let editor_settings = EditorSettings::get_global(cx);
 4211        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4212            // After the code completion is finished, users often want to know what signatures are needed.
 4213            // so we should automatically call signature_help
 4214            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4215        }
 4216
 4217        Some(cx.foreground_executor().spawn(async move {
 4218            apply_edits.await?;
 4219            Ok(())
 4220        }))
 4221    }
 4222
 4223    pub fn toggle_code_actions(
 4224        &mut self,
 4225        action: &ToggleCodeActions,
 4226        window: &mut Window,
 4227        cx: &mut Context<Self>,
 4228    ) {
 4229        let mut context_menu = self.context_menu.borrow_mut();
 4230        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4231            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4232                // Toggle if we're selecting the same one
 4233                *context_menu = None;
 4234                cx.notify();
 4235                return;
 4236            } else {
 4237                // Otherwise, clear it and start a new one
 4238                *context_menu = None;
 4239                cx.notify();
 4240            }
 4241        }
 4242        drop(context_menu);
 4243        let snapshot = self.snapshot(window, cx);
 4244        let deployed_from_indicator = action.deployed_from_indicator;
 4245        let mut task = self.code_actions_task.take();
 4246        let action = action.clone();
 4247        cx.spawn_in(window, |editor, mut cx| async move {
 4248            while let Some(prev_task) = task {
 4249                prev_task.await.log_err();
 4250                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4251            }
 4252
 4253            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4254                if editor.focus_handle.is_focused(window) {
 4255                    let multibuffer_point = action
 4256                        .deployed_from_indicator
 4257                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4258                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4259                    let (buffer, buffer_row) = snapshot
 4260                        .buffer_snapshot
 4261                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4262                        .and_then(|(buffer_snapshot, range)| {
 4263                            editor
 4264                                .buffer
 4265                                .read(cx)
 4266                                .buffer(buffer_snapshot.remote_id())
 4267                                .map(|buffer| (buffer, range.start.row))
 4268                        })?;
 4269                    let (_, code_actions) = editor
 4270                        .available_code_actions
 4271                        .clone()
 4272                        .and_then(|(location, code_actions)| {
 4273                            let snapshot = location.buffer.read(cx).snapshot();
 4274                            let point_range = location.range.to_point(&snapshot);
 4275                            let point_range = point_range.start.row..=point_range.end.row;
 4276                            if point_range.contains(&buffer_row) {
 4277                                Some((location, code_actions))
 4278                            } else {
 4279                                None
 4280                            }
 4281                        })
 4282                        .unzip();
 4283                    let buffer_id = buffer.read(cx).remote_id();
 4284                    let tasks = editor
 4285                        .tasks
 4286                        .get(&(buffer_id, buffer_row))
 4287                        .map(|t| Arc::new(t.to_owned()));
 4288                    if tasks.is_none() && code_actions.is_none() {
 4289                        return None;
 4290                    }
 4291
 4292                    editor.completion_tasks.clear();
 4293                    editor.discard_inline_completion(false, cx);
 4294                    let task_context =
 4295                        tasks
 4296                            .as_ref()
 4297                            .zip(editor.project.clone())
 4298                            .map(|(tasks, project)| {
 4299                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4300                            });
 4301
 4302                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4303                        let task_context = match task_context {
 4304                            Some(task_context) => task_context.await,
 4305                            None => None,
 4306                        };
 4307                        let resolved_tasks =
 4308                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4309                                Rc::new(ResolvedTasks {
 4310                                    templates: tasks.resolve(&task_context).collect(),
 4311                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4312                                        multibuffer_point.row,
 4313                                        tasks.column,
 4314                                    )),
 4315                                })
 4316                            });
 4317                        let spawn_straight_away = resolved_tasks
 4318                            .as_ref()
 4319                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4320                            && code_actions
 4321                                .as_ref()
 4322                                .map_or(true, |actions| actions.is_empty());
 4323                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4324                            *editor.context_menu.borrow_mut() =
 4325                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4326                                    buffer,
 4327                                    actions: CodeActionContents {
 4328                                        tasks: resolved_tasks,
 4329                                        actions: code_actions,
 4330                                    },
 4331                                    selected_item: Default::default(),
 4332                                    scroll_handle: UniformListScrollHandle::default(),
 4333                                    deployed_from_indicator,
 4334                                }));
 4335                            if spawn_straight_away {
 4336                                if let Some(task) = editor.confirm_code_action(
 4337                                    &ConfirmCodeAction { item_ix: Some(0) },
 4338                                    window,
 4339                                    cx,
 4340                                ) {
 4341                                    cx.notify();
 4342                                    return task;
 4343                                }
 4344                            }
 4345                            cx.notify();
 4346                            Task::ready(Ok(()))
 4347                        }) {
 4348                            task.await
 4349                        } else {
 4350                            Ok(())
 4351                        }
 4352                    }))
 4353                } else {
 4354                    Some(Task::ready(Ok(())))
 4355                }
 4356            })?;
 4357            if let Some(task) = spawned_test_task {
 4358                task.await?;
 4359            }
 4360
 4361            Ok::<_, anyhow::Error>(())
 4362        })
 4363        .detach_and_log_err(cx);
 4364    }
 4365
 4366    pub fn confirm_code_action(
 4367        &mut self,
 4368        action: &ConfirmCodeAction,
 4369        window: &mut Window,
 4370        cx: &mut Context<Self>,
 4371    ) -> Option<Task<Result<()>>> {
 4372        let actions_menu =
 4373            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4374                menu
 4375            } else {
 4376                return None;
 4377            };
 4378        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4379        let action = actions_menu.actions.get(action_ix)?;
 4380        let title = action.label();
 4381        let buffer = actions_menu.buffer;
 4382        let workspace = self.workspace()?;
 4383
 4384        match action {
 4385            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4386                workspace.update(cx, |workspace, cx| {
 4387                    workspace::tasks::schedule_resolved_task(
 4388                        workspace,
 4389                        task_source_kind,
 4390                        resolved_task,
 4391                        false,
 4392                        cx,
 4393                    );
 4394
 4395                    Some(Task::ready(Ok(())))
 4396                })
 4397            }
 4398            CodeActionsItem::CodeAction {
 4399                excerpt_id,
 4400                action,
 4401                provider,
 4402            } => {
 4403                let apply_code_action =
 4404                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4405                let workspace = workspace.downgrade();
 4406                Some(cx.spawn_in(window, |editor, cx| async move {
 4407                    let project_transaction = apply_code_action.await?;
 4408                    Self::open_project_transaction(
 4409                        &editor,
 4410                        workspace,
 4411                        project_transaction,
 4412                        title,
 4413                        cx,
 4414                    )
 4415                    .await
 4416                }))
 4417            }
 4418        }
 4419    }
 4420
 4421    pub async fn open_project_transaction(
 4422        this: &WeakEntity<Editor>,
 4423        workspace: WeakEntity<Workspace>,
 4424        transaction: ProjectTransaction,
 4425        title: String,
 4426        mut cx: AsyncWindowContext,
 4427    ) -> Result<()> {
 4428        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4429        cx.update(|_, cx| {
 4430            entries.sort_unstable_by_key(|(buffer, _)| {
 4431                buffer.read(cx).file().map(|f| f.path().clone())
 4432            });
 4433        })?;
 4434
 4435        // If the project transaction's edits are all contained within this editor, then
 4436        // avoid opening a new editor to display them.
 4437
 4438        if let Some((buffer, transaction)) = entries.first() {
 4439            if entries.len() == 1 {
 4440                let excerpt = this.update(&mut cx, |editor, cx| {
 4441                    editor
 4442                        .buffer()
 4443                        .read(cx)
 4444                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4445                })?;
 4446                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4447                    if excerpted_buffer == *buffer {
 4448                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4449                            let excerpt_range = excerpt_range.to_offset(buffer);
 4450                            buffer
 4451                                .edited_ranges_for_transaction::<usize>(transaction)
 4452                                .all(|range| {
 4453                                    excerpt_range.start <= range.start
 4454                                        && excerpt_range.end >= range.end
 4455                                })
 4456                        })?;
 4457
 4458                        if all_edits_within_excerpt {
 4459                            return Ok(());
 4460                        }
 4461                    }
 4462                }
 4463            }
 4464        } else {
 4465            return Ok(());
 4466        }
 4467
 4468        let mut ranges_to_highlight = Vec::new();
 4469        let excerpt_buffer = cx.new(|cx| {
 4470            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4471            for (buffer_handle, transaction) in &entries {
 4472                let buffer = buffer_handle.read(cx);
 4473                ranges_to_highlight.extend(
 4474                    multibuffer.push_excerpts_with_context_lines(
 4475                        buffer_handle.clone(),
 4476                        buffer
 4477                            .edited_ranges_for_transaction::<usize>(transaction)
 4478                            .collect(),
 4479                        DEFAULT_MULTIBUFFER_CONTEXT,
 4480                        cx,
 4481                    ),
 4482                );
 4483            }
 4484            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4485            multibuffer
 4486        })?;
 4487
 4488        workspace.update_in(&mut cx, |workspace, window, cx| {
 4489            let project = workspace.project().clone();
 4490            let editor = cx
 4491                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4492            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4493            editor.update(cx, |editor, cx| {
 4494                editor.highlight_background::<Self>(
 4495                    &ranges_to_highlight,
 4496                    |theme| theme.editor_highlighted_line_background,
 4497                    cx,
 4498                );
 4499            });
 4500        })?;
 4501
 4502        Ok(())
 4503    }
 4504
 4505    pub fn clear_code_action_providers(&mut self) {
 4506        self.code_action_providers.clear();
 4507        self.available_code_actions.take();
 4508    }
 4509
 4510    pub fn add_code_action_provider(
 4511        &mut self,
 4512        provider: Rc<dyn CodeActionProvider>,
 4513        window: &mut Window,
 4514        cx: &mut Context<Self>,
 4515    ) {
 4516        if self
 4517            .code_action_providers
 4518            .iter()
 4519            .any(|existing_provider| existing_provider.id() == provider.id())
 4520        {
 4521            return;
 4522        }
 4523
 4524        self.code_action_providers.push(provider);
 4525        self.refresh_code_actions(window, cx);
 4526    }
 4527
 4528    pub fn remove_code_action_provider(
 4529        &mut self,
 4530        id: Arc<str>,
 4531        window: &mut Window,
 4532        cx: &mut Context<Self>,
 4533    ) {
 4534        self.code_action_providers
 4535            .retain(|provider| provider.id() != id);
 4536        self.refresh_code_actions(window, cx);
 4537    }
 4538
 4539    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4540        let buffer = self.buffer.read(cx);
 4541        let newest_selection = self.selections.newest_anchor().clone();
 4542        if newest_selection.head().diff_base_anchor.is_some() {
 4543            return None;
 4544        }
 4545        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4546        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4547        if start_buffer != end_buffer {
 4548            return None;
 4549        }
 4550
 4551        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4552            cx.background_executor()
 4553                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4554                .await;
 4555
 4556            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4557                let providers = this.code_action_providers.clone();
 4558                let tasks = this
 4559                    .code_action_providers
 4560                    .iter()
 4561                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4562                    .collect::<Vec<_>>();
 4563                (providers, tasks)
 4564            })?;
 4565
 4566            let mut actions = Vec::new();
 4567            for (provider, provider_actions) in
 4568                providers.into_iter().zip(future::join_all(tasks).await)
 4569            {
 4570                if let Some(provider_actions) = provider_actions.log_err() {
 4571                    actions.extend(provider_actions.into_iter().map(|action| {
 4572                        AvailableCodeAction {
 4573                            excerpt_id: newest_selection.start.excerpt_id,
 4574                            action,
 4575                            provider: provider.clone(),
 4576                        }
 4577                    }));
 4578                }
 4579            }
 4580
 4581            this.update(&mut cx, |this, cx| {
 4582                this.available_code_actions = if actions.is_empty() {
 4583                    None
 4584                } else {
 4585                    Some((
 4586                        Location {
 4587                            buffer: start_buffer,
 4588                            range: start..end,
 4589                        },
 4590                        actions.into(),
 4591                    ))
 4592                };
 4593                cx.notify();
 4594            })
 4595        }));
 4596        None
 4597    }
 4598
 4599    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4600        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4601            self.show_git_blame_inline = false;
 4602
 4603            self.show_git_blame_inline_delay_task =
 4604                Some(cx.spawn_in(window, |this, mut cx| async move {
 4605                    cx.background_executor().timer(delay).await;
 4606
 4607                    this.update(&mut cx, |this, cx| {
 4608                        this.show_git_blame_inline = true;
 4609                        cx.notify();
 4610                    })
 4611                    .log_err();
 4612                }));
 4613        }
 4614    }
 4615
 4616    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4617        if self.pending_rename.is_some() {
 4618            return None;
 4619        }
 4620
 4621        let provider = self.semantics_provider.clone()?;
 4622        let buffer = self.buffer.read(cx);
 4623        let newest_selection = self.selections.newest_anchor().clone();
 4624        let cursor_position = newest_selection.head();
 4625        let (cursor_buffer, cursor_buffer_position) =
 4626            buffer.text_anchor_for_position(cursor_position, cx)?;
 4627        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4628        if cursor_buffer != tail_buffer {
 4629            return None;
 4630        }
 4631        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4632        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4633            cx.background_executor()
 4634                .timer(Duration::from_millis(debounce))
 4635                .await;
 4636
 4637            let highlights = if let Some(highlights) = cx
 4638                .update(|cx| {
 4639                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4640                })
 4641                .ok()
 4642                .flatten()
 4643            {
 4644                highlights.await.log_err()
 4645            } else {
 4646                None
 4647            };
 4648
 4649            if let Some(highlights) = highlights {
 4650                this.update(&mut cx, |this, cx| {
 4651                    if this.pending_rename.is_some() {
 4652                        return;
 4653                    }
 4654
 4655                    let buffer_id = cursor_position.buffer_id;
 4656                    let buffer = this.buffer.read(cx);
 4657                    if !buffer
 4658                        .text_anchor_for_position(cursor_position, cx)
 4659                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4660                    {
 4661                        return;
 4662                    }
 4663
 4664                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4665                    let mut write_ranges = Vec::new();
 4666                    let mut read_ranges = Vec::new();
 4667                    for highlight in highlights {
 4668                        for (excerpt_id, excerpt_range) in
 4669                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4670                        {
 4671                            let start = highlight
 4672                                .range
 4673                                .start
 4674                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4675                            let end = highlight
 4676                                .range
 4677                                .end
 4678                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4679                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4680                                continue;
 4681                            }
 4682
 4683                            let range = Anchor {
 4684                                buffer_id,
 4685                                excerpt_id,
 4686                                text_anchor: start,
 4687                                diff_base_anchor: None,
 4688                            }..Anchor {
 4689                                buffer_id,
 4690                                excerpt_id,
 4691                                text_anchor: end,
 4692                                diff_base_anchor: None,
 4693                            };
 4694                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4695                                write_ranges.push(range);
 4696                            } else {
 4697                                read_ranges.push(range);
 4698                            }
 4699                        }
 4700                    }
 4701
 4702                    this.highlight_background::<DocumentHighlightRead>(
 4703                        &read_ranges,
 4704                        |theme| theme.editor_document_highlight_read_background,
 4705                        cx,
 4706                    );
 4707                    this.highlight_background::<DocumentHighlightWrite>(
 4708                        &write_ranges,
 4709                        |theme| theme.editor_document_highlight_write_background,
 4710                        cx,
 4711                    );
 4712                    cx.notify();
 4713                })
 4714                .log_err();
 4715            }
 4716        }));
 4717        None
 4718    }
 4719
 4720    pub fn refresh_selected_text_highlights(
 4721        &mut self,
 4722        window: &mut Window,
 4723        cx: &mut Context<Editor>,
 4724    ) {
 4725        self.selection_highlight_task.take();
 4726        if !EditorSettings::get_global(cx).selection_highlight {
 4727            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4728            return;
 4729        }
 4730        if self.selections.count() != 1 || self.selections.line_mode {
 4731            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4732            return;
 4733        }
 4734        let selection = self.selections.newest::<Point>(cx);
 4735        if selection.is_empty() || selection.start.row != selection.end.row {
 4736            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4737            return;
 4738        }
 4739        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4740        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4741            cx.background_executor()
 4742                .timer(Duration::from_millis(debounce))
 4743                .await;
 4744            let Some(Some(matches_task)) = editor
 4745                .update_in(&mut cx, |editor, _, cx| {
 4746                    if editor.selections.count() != 1 || editor.selections.line_mode {
 4747                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4748                        return None;
 4749                    }
 4750                    let selection = editor.selections.newest::<Point>(cx);
 4751                    if selection.is_empty() || selection.start.row != selection.end.row {
 4752                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4753                        return None;
 4754                    }
 4755                    let buffer = editor.buffer().read(cx).snapshot(cx);
 4756                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 4757                    if query.trim().is_empty() {
 4758                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4759                        return None;
 4760                    }
 4761                    Some(cx.background_spawn(async move {
 4762                        let mut ranges = Vec::new();
 4763                        let selection_anchors = selection.range().to_anchors(&buffer);
 4764                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 4765                            for (search_buffer, search_range, excerpt_id) in
 4766                                buffer.range_to_buffer_ranges(range)
 4767                            {
 4768                                ranges.extend(
 4769                                    project::search::SearchQuery::text(
 4770                                        query.clone(),
 4771                                        false,
 4772                                        false,
 4773                                        false,
 4774                                        Default::default(),
 4775                                        Default::default(),
 4776                                        None,
 4777                                    )
 4778                                    .unwrap()
 4779                                    .search(search_buffer, Some(search_range.clone()))
 4780                                    .await
 4781                                    .into_iter()
 4782                                    .filter_map(
 4783                                        |match_range| {
 4784                                            let start = search_buffer.anchor_after(
 4785                                                search_range.start + match_range.start,
 4786                                            );
 4787                                            let end = search_buffer.anchor_before(
 4788                                                search_range.start + match_range.end,
 4789                                            );
 4790                                            let range = Anchor::range_in_buffer(
 4791                                                excerpt_id,
 4792                                                search_buffer.remote_id(),
 4793                                                start..end,
 4794                                            );
 4795                                            (range != selection_anchors).then_some(range)
 4796                                        },
 4797                                    ),
 4798                                );
 4799                            }
 4800                        }
 4801                        ranges
 4802                    }))
 4803                })
 4804                .log_err()
 4805            else {
 4806                return;
 4807            };
 4808            let matches = matches_task.await;
 4809            editor
 4810                .update_in(&mut cx, |editor, _, cx| {
 4811                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4812                    if !matches.is_empty() {
 4813                        editor.highlight_background::<SelectedTextHighlight>(
 4814                            &matches,
 4815                            |theme| theme.editor_document_highlight_bracket_background,
 4816                            cx,
 4817                        )
 4818                    }
 4819                })
 4820                .log_err();
 4821        }));
 4822    }
 4823
 4824    pub fn refresh_inline_completion(
 4825        &mut self,
 4826        debounce: bool,
 4827        user_requested: bool,
 4828        window: &mut Window,
 4829        cx: &mut Context<Self>,
 4830    ) -> Option<()> {
 4831        let provider = self.edit_prediction_provider()?;
 4832        let cursor = self.selections.newest_anchor().head();
 4833        let (buffer, cursor_buffer_position) =
 4834            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4835
 4836        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4837            self.discard_inline_completion(false, cx);
 4838            return None;
 4839        }
 4840
 4841        if !user_requested
 4842            && (!self.should_show_edit_predictions()
 4843                || !self.is_focused(window)
 4844                || buffer.read(cx).is_empty())
 4845        {
 4846            self.discard_inline_completion(false, cx);
 4847            return None;
 4848        }
 4849
 4850        self.update_visible_inline_completion(window, cx);
 4851        provider.refresh(
 4852            self.project.clone(),
 4853            buffer,
 4854            cursor_buffer_position,
 4855            debounce,
 4856            cx,
 4857        );
 4858        Some(())
 4859    }
 4860
 4861    fn show_edit_predictions_in_menu(&self) -> bool {
 4862        match self.edit_prediction_settings {
 4863            EditPredictionSettings::Disabled => false,
 4864            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4865        }
 4866    }
 4867
 4868    pub fn edit_predictions_enabled(&self) -> bool {
 4869        match self.edit_prediction_settings {
 4870            EditPredictionSettings::Disabled => false,
 4871            EditPredictionSettings::Enabled { .. } => true,
 4872        }
 4873    }
 4874
 4875    fn edit_prediction_requires_modifier(&self) -> bool {
 4876        match self.edit_prediction_settings {
 4877            EditPredictionSettings::Disabled => false,
 4878            EditPredictionSettings::Enabled {
 4879                preview_requires_modifier,
 4880                ..
 4881            } => preview_requires_modifier,
 4882        }
 4883    }
 4884
 4885    fn edit_prediction_settings_at_position(
 4886        &self,
 4887        buffer: &Entity<Buffer>,
 4888        buffer_position: language::Anchor,
 4889        cx: &App,
 4890    ) -> EditPredictionSettings {
 4891        if self.mode != EditorMode::Full
 4892            || !self.show_inline_completions_override.unwrap_or(true)
 4893            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4894        {
 4895            return EditPredictionSettings::Disabled;
 4896        }
 4897
 4898        let buffer = buffer.read(cx);
 4899
 4900        let file = buffer.file();
 4901
 4902        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4903            return EditPredictionSettings::Disabled;
 4904        };
 4905
 4906        let by_provider = matches!(
 4907            self.menu_inline_completions_policy,
 4908            MenuInlineCompletionsPolicy::ByProvider
 4909        );
 4910
 4911        let show_in_menu = by_provider
 4912            && self
 4913                .edit_prediction_provider
 4914                .as_ref()
 4915                .map_or(false, |provider| {
 4916                    provider.provider.show_completions_in_menu()
 4917                });
 4918
 4919        let preview_requires_modifier =
 4920            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4921
 4922        EditPredictionSettings::Enabled {
 4923            show_in_menu,
 4924            preview_requires_modifier,
 4925        }
 4926    }
 4927
 4928    fn should_show_edit_predictions(&self) -> bool {
 4929        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4930    }
 4931
 4932    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4933        matches!(
 4934            self.edit_prediction_preview,
 4935            EditPredictionPreview::Active { .. }
 4936        )
 4937    }
 4938
 4939    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4940        let cursor = self.selections.newest_anchor().head();
 4941        if let Some((buffer, cursor_position)) =
 4942            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4943        {
 4944            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4945        } else {
 4946            false
 4947        }
 4948    }
 4949
 4950    fn inline_completions_enabled_in_buffer(
 4951        &self,
 4952        buffer: &Entity<Buffer>,
 4953        buffer_position: language::Anchor,
 4954        cx: &App,
 4955    ) -> bool {
 4956        maybe!({
 4957            let provider = self.edit_prediction_provider()?;
 4958            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4959                return Some(false);
 4960            }
 4961            let buffer = buffer.read(cx);
 4962            let Some(file) = buffer.file() else {
 4963                return Some(true);
 4964            };
 4965            let settings = all_language_settings(Some(file), cx);
 4966            Some(settings.inline_completions_enabled_for_path(file.path()))
 4967        })
 4968        .unwrap_or(false)
 4969    }
 4970
 4971    fn cycle_inline_completion(
 4972        &mut self,
 4973        direction: Direction,
 4974        window: &mut Window,
 4975        cx: &mut Context<Self>,
 4976    ) -> Option<()> {
 4977        let provider = self.edit_prediction_provider()?;
 4978        let cursor = self.selections.newest_anchor().head();
 4979        let (buffer, cursor_buffer_position) =
 4980            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4981        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 4982            return None;
 4983        }
 4984
 4985        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4986        self.update_visible_inline_completion(window, cx);
 4987
 4988        Some(())
 4989    }
 4990
 4991    pub fn show_inline_completion(
 4992        &mut self,
 4993        _: &ShowEditPrediction,
 4994        window: &mut Window,
 4995        cx: &mut Context<Self>,
 4996    ) {
 4997        if !self.has_active_inline_completion() {
 4998            self.refresh_inline_completion(false, true, window, cx);
 4999            return;
 5000        }
 5001
 5002        self.update_visible_inline_completion(window, cx);
 5003    }
 5004
 5005    pub fn display_cursor_names(
 5006        &mut self,
 5007        _: &DisplayCursorNames,
 5008        window: &mut Window,
 5009        cx: &mut Context<Self>,
 5010    ) {
 5011        self.show_cursor_names(window, cx);
 5012    }
 5013
 5014    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5015        self.show_cursor_names = true;
 5016        cx.notify();
 5017        cx.spawn_in(window, |this, mut cx| async move {
 5018            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5019            this.update(&mut cx, |this, cx| {
 5020                this.show_cursor_names = false;
 5021                cx.notify()
 5022            })
 5023            .ok()
 5024        })
 5025        .detach();
 5026    }
 5027
 5028    pub fn next_edit_prediction(
 5029        &mut self,
 5030        _: &NextEditPrediction,
 5031        window: &mut Window,
 5032        cx: &mut Context<Self>,
 5033    ) {
 5034        if self.has_active_inline_completion() {
 5035            self.cycle_inline_completion(Direction::Next, window, cx);
 5036        } else {
 5037            let is_copilot_disabled = self
 5038                .refresh_inline_completion(false, true, window, cx)
 5039                .is_none();
 5040            if is_copilot_disabled {
 5041                cx.propagate();
 5042            }
 5043        }
 5044    }
 5045
 5046    pub fn previous_edit_prediction(
 5047        &mut self,
 5048        _: &PreviousEditPrediction,
 5049        window: &mut Window,
 5050        cx: &mut Context<Self>,
 5051    ) {
 5052        if self.has_active_inline_completion() {
 5053            self.cycle_inline_completion(Direction::Prev, window, cx);
 5054        } else {
 5055            let is_copilot_disabled = self
 5056                .refresh_inline_completion(false, true, window, cx)
 5057                .is_none();
 5058            if is_copilot_disabled {
 5059                cx.propagate();
 5060            }
 5061        }
 5062    }
 5063
 5064    pub fn accept_edit_prediction(
 5065        &mut self,
 5066        _: &AcceptEditPrediction,
 5067        window: &mut Window,
 5068        cx: &mut Context<Self>,
 5069    ) {
 5070        if self.show_edit_predictions_in_menu() {
 5071            self.hide_context_menu(window, cx);
 5072        }
 5073
 5074        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5075            return;
 5076        };
 5077
 5078        self.report_inline_completion_event(
 5079            active_inline_completion.completion_id.clone(),
 5080            true,
 5081            cx,
 5082        );
 5083
 5084        match &active_inline_completion.completion {
 5085            InlineCompletion::Move { target, .. } => {
 5086                let target = *target;
 5087
 5088                if let Some(position_map) = &self.last_position_map {
 5089                    if position_map
 5090                        .visible_row_range
 5091                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5092                        || !self.edit_prediction_requires_modifier()
 5093                    {
 5094                        self.unfold_ranges(&[target..target], true, false, cx);
 5095                        // Note that this is also done in vim's handler of the Tab action.
 5096                        self.change_selections(
 5097                            Some(Autoscroll::newest()),
 5098                            window,
 5099                            cx,
 5100                            |selections| {
 5101                                selections.select_anchor_ranges([target..target]);
 5102                            },
 5103                        );
 5104                        self.clear_row_highlights::<EditPredictionPreview>();
 5105
 5106                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5107                            previous_scroll_position: None,
 5108                        };
 5109                    } else {
 5110                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5111                            previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
 5112                        };
 5113                        self.highlight_rows::<EditPredictionPreview>(
 5114                            target..target,
 5115                            cx.theme().colors().editor_highlighted_line_background,
 5116                            true,
 5117                            cx,
 5118                        );
 5119                        self.request_autoscroll(Autoscroll::fit(), cx);
 5120                    }
 5121                }
 5122            }
 5123            InlineCompletion::Edit { edits, .. } => {
 5124                if let Some(provider) = self.edit_prediction_provider() {
 5125                    provider.accept(cx);
 5126                }
 5127
 5128                let snapshot = self.buffer.read(cx).snapshot(cx);
 5129                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5130
 5131                self.buffer.update(cx, |buffer, cx| {
 5132                    buffer.edit(edits.iter().cloned(), None, cx)
 5133                });
 5134
 5135                self.change_selections(None, window, cx, |s| {
 5136                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5137                });
 5138
 5139                self.update_visible_inline_completion(window, cx);
 5140                if self.active_inline_completion.is_none() {
 5141                    self.refresh_inline_completion(true, true, window, cx);
 5142                }
 5143
 5144                cx.notify();
 5145            }
 5146        }
 5147
 5148        self.edit_prediction_requires_modifier_in_leading_space = false;
 5149    }
 5150
 5151    pub fn accept_partial_inline_completion(
 5152        &mut self,
 5153        _: &AcceptPartialEditPrediction,
 5154        window: &mut Window,
 5155        cx: &mut Context<Self>,
 5156    ) {
 5157        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5158            return;
 5159        };
 5160        if self.selections.count() != 1 {
 5161            return;
 5162        }
 5163
 5164        self.report_inline_completion_event(
 5165            active_inline_completion.completion_id.clone(),
 5166            true,
 5167            cx,
 5168        );
 5169
 5170        match &active_inline_completion.completion {
 5171            InlineCompletion::Move { target, .. } => {
 5172                let target = *target;
 5173                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5174                    selections.select_anchor_ranges([target..target]);
 5175                });
 5176            }
 5177            InlineCompletion::Edit { edits, .. } => {
 5178                // Find an insertion that starts at the cursor position.
 5179                let snapshot = self.buffer.read(cx).snapshot(cx);
 5180                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5181                let insertion = edits.iter().find_map(|(range, text)| {
 5182                    let range = range.to_offset(&snapshot);
 5183                    if range.is_empty() && range.start == cursor_offset {
 5184                        Some(text)
 5185                    } else {
 5186                        None
 5187                    }
 5188                });
 5189
 5190                if let Some(text) = insertion {
 5191                    let mut partial_completion = text
 5192                        .chars()
 5193                        .by_ref()
 5194                        .take_while(|c| c.is_alphabetic())
 5195                        .collect::<String>();
 5196                    if partial_completion.is_empty() {
 5197                        partial_completion = text
 5198                            .chars()
 5199                            .by_ref()
 5200                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5201                            .collect::<String>();
 5202                    }
 5203
 5204                    cx.emit(EditorEvent::InputHandled {
 5205                        utf16_range_to_replace: None,
 5206                        text: partial_completion.clone().into(),
 5207                    });
 5208
 5209                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5210
 5211                    self.refresh_inline_completion(true, true, window, cx);
 5212                    cx.notify();
 5213                } else {
 5214                    self.accept_edit_prediction(&Default::default(), window, cx);
 5215                }
 5216            }
 5217        }
 5218    }
 5219
 5220    fn discard_inline_completion(
 5221        &mut self,
 5222        should_report_inline_completion_event: bool,
 5223        cx: &mut Context<Self>,
 5224    ) -> bool {
 5225        if should_report_inline_completion_event {
 5226            let completion_id = self
 5227                .active_inline_completion
 5228                .as_ref()
 5229                .and_then(|active_completion| active_completion.completion_id.clone());
 5230
 5231            self.report_inline_completion_event(completion_id, false, cx);
 5232        }
 5233
 5234        if let Some(provider) = self.edit_prediction_provider() {
 5235            provider.discard(cx);
 5236        }
 5237
 5238        self.take_active_inline_completion(cx)
 5239    }
 5240
 5241    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5242        let Some(provider) = self.edit_prediction_provider() else {
 5243            return;
 5244        };
 5245
 5246        let Some((_, buffer, _)) = self
 5247            .buffer
 5248            .read(cx)
 5249            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5250        else {
 5251            return;
 5252        };
 5253
 5254        let extension = buffer
 5255            .read(cx)
 5256            .file()
 5257            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5258
 5259        let event_type = match accepted {
 5260            true => "Edit Prediction Accepted",
 5261            false => "Edit Prediction Discarded",
 5262        };
 5263        telemetry::event!(
 5264            event_type,
 5265            provider = provider.name(),
 5266            prediction_id = id,
 5267            suggestion_accepted = accepted,
 5268            file_extension = extension,
 5269        );
 5270    }
 5271
 5272    pub fn has_active_inline_completion(&self) -> bool {
 5273        self.active_inline_completion.is_some()
 5274    }
 5275
 5276    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5277        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5278            return false;
 5279        };
 5280
 5281        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5282        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5283        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5284        true
 5285    }
 5286
 5287    /// Returns true when we're displaying the edit prediction popover below the cursor
 5288    /// like we are not previewing and the LSP autocomplete menu is visible
 5289    /// or we are in `when_holding_modifier` mode.
 5290    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5291        if self.edit_prediction_preview_is_active()
 5292            || !self.show_edit_predictions_in_menu()
 5293            || !self.edit_predictions_enabled()
 5294        {
 5295            return false;
 5296        }
 5297
 5298        if self.has_visible_completions_menu() {
 5299            return true;
 5300        }
 5301
 5302        has_completion && self.edit_prediction_requires_modifier()
 5303    }
 5304
 5305    fn handle_modifiers_changed(
 5306        &mut self,
 5307        modifiers: Modifiers,
 5308        position_map: &PositionMap,
 5309        window: &mut Window,
 5310        cx: &mut Context<Self>,
 5311    ) {
 5312        if self.show_edit_predictions_in_menu() {
 5313            self.update_edit_prediction_preview(&modifiers, window, cx);
 5314        }
 5315
 5316        self.update_selection_mode(&modifiers, position_map, window, cx);
 5317
 5318        let mouse_position = window.mouse_position();
 5319        if !position_map.text_hitbox.is_hovered(window) {
 5320            return;
 5321        }
 5322
 5323        self.update_hovered_link(
 5324            position_map.point_for_position(mouse_position),
 5325            &position_map.snapshot,
 5326            modifiers,
 5327            window,
 5328            cx,
 5329        )
 5330    }
 5331
 5332    fn update_selection_mode(
 5333        &mut self,
 5334        modifiers: &Modifiers,
 5335        position_map: &PositionMap,
 5336        window: &mut Window,
 5337        cx: &mut Context<Self>,
 5338    ) {
 5339        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5340            return;
 5341        }
 5342
 5343        let mouse_position = window.mouse_position();
 5344        let point_for_position = position_map.point_for_position(mouse_position);
 5345        let position = point_for_position.previous_valid;
 5346
 5347        self.select(
 5348            SelectPhase::BeginColumnar {
 5349                position,
 5350                reset: false,
 5351                goal_column: point_for_position.exact_unclipped.column(),
 5352            },
 5353            window,
 5354            cx,
 5355        );
 5356    }
 5357
 5358    fn update_edit_prediction_preview(
 5359        &mut self,
 5360        modifiers: &Modifiers,
 5361        window: &mut Window,
 5362        cx: &mut Context<Self>,
 5363    ) {
 5364        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5365        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5366            return;
 5367        };
 5368
 5369        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5370            if matches!(
 5371                self.edit_prediction_preview,
 5372                EditPredictionPreview::Inactive
 5373            ) {
 5374                self.edit_prediction_preview = EditPredictionPreview::Active {
 5375                    previous_scroll_position: None,
 5376                };
 5377
 5378                self.update_visible_inline_completion(window, cx);
 5379                cx.notify();
 5380            }
 5381        } else if let EditPredictionPreview::Active {
 5382            previous_scroll_position,
 5383        } = self.edit_prediction_preview
 5384        {
 5385            if let (Some(previous_scroll_position), Some(position_map)) =
 5386                (previous_scroll_position, self.last_position_map.as_ref())
 5387            {
 5388                self.set_scroll_position(
 5389                    previous_scroll_position
 5390                        .scroll_position(&position_map.snapshot.display_snapshot),
 5391                    window,
 5392                    cx,
 5393                );
 5394            }
 5395
 5396            self.edit_prediction_preview = EditPredictionPreview::Inactive;
 5397            self.clear_row_highlights::<EditPredictionPreview>();
 5398            self.update_visible_inline_completion(window, cx);
 5399            cx.notify();
 5400        }
 5401    }
 5402
 5403    fn update_visible_inline_completion(
 5404        &mut self,
 5405        _window: &mut Window,
 5406        cx: &mut Context<Self>,
 5407    ) -> Option<()> {
 5408        let selection = self.selections.newest_anchor();
 5409        let cursor = selection.head();
 5410        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5411        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5412        let excerpt_id = cursor.excerpt_id;
 5413
 5414        let show_in_menu = self.show_edit_predictions_in_menu();
 5415        let completions_menu_has_precedence = !show_in_menu
 5416            && (self.context_menu.borrow().is_some()
 5417                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5418
 5419        if completions_menu_has_precedence
 5420            || !offset_selection.is_empty()
 5421            || self
 5422                .active_inline_completion
 5423                .as_ref()
 5424                .map_or(false, |completion| {
 5425                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5426                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5427                    !invalidation_range.contains(&offset_selection.head())
 5428                })
 5429        {
 5430            self.discard_inline_completion(false, cx);
 5431            return None;
 5432        }
 5433
 5434        self.take_active_inline_completion(cx);
 5435        let Some(provider) = self.edit_prediction_provider() else {
 5436            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5437            return None;
 5438        };
 5439
 5440        let (buffer, cursor_buffer_position) =
 5441            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5442
 5443        self.edit_prediction_settings =
 5444            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5445
 5446        self.edit_prediction_cursor_on_leading_whitespace =
 5447            multibuffer.is_line_whitespace_upto(cursor);
 5448
 5449        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5450        let edits = inline_completion
 5451            .edits
 5452            .into_iter()
 5453            .flat_map(|(range, new_text)| {
 5454                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5455                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5456                Some((start..end, new_text))
 5457            })
 5458            .collect::<Vec<_>>();
 5459        if edits.is_empty() {
 5460            return None;
 5461        }
 5462
 5463        let first_edit_start = edits.first().unwrap().0.start;
 5464        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5465        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5466
 5467        let last_edit_end = edits.last().unwrap().0.end;
 5468        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5469        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5470
 5471        let cursor_row = cursor.to_point(&multibuffer).row;
 5472
 5473        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5474
 5475        let mut inlay_ids = Vec::new();
 5476        let invalidation_row_range;
 5477        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5478            Some(cursor_row..edit_end_row)
 5479        } else if cursor_row > edit_end_row {
 5480            Some(edit_start_row..cursor_row)
 5481        } else {
 5482            None
 5483        };
 5484        let is_move =
 5485            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5486        let completion = if is_move {
 5487            invalidation_row_range =
 5488                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5489            let target = first_edit_start;
 5490            InlineCompletion::Move { target, snapshot }
 5491        } else {
 5492            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5493                && !self.inline_completions_hidden_for_vim_mode;
 5494
 5495            if show_completions_in_buffer {
 5496                if edits
 5497                    .iter()
 5498                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5499                {
 5500                    let mut inlays = Vec::new();
 5501                    for (range, new_text) in &edits {
 5502                        let inlay = Inlay::inline_completion(
 5503                            post_inc(&mut self.next_inlay_id),
 5504                            range.start,
 5505                            new_text.as_str(),
 5506                        );
 5507                        inlay_ids.push(inlay.id);
 5508                        inlays.push(inlay);
 5509                    }
 5510
 5511                    self.splice_inlays(&[], inlays, cx);
 5512                } else {
 5513                    let background_color = cx.theme().status().deleted_background;
 5514                    self.highlight_text::<InlineCompletionHighlight>(
 5515                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5516                        HighlightStyle {
 5517                            background_color: Some(background_color),
 5518                            ..Default::default()
 5519                        },
 5520                        cx,
 5521                    );
 5522                }
 5523            }
 5524
 5525            invalidation_row_range = edit_start_row..edit_end_row;
 5526
 5527            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5528                if provider.show_tab_accept_marker() {
 5529                    EditDisplayMode::TabAccept
 5530                } else {
 5531                    EditDisplayMode::Inline
 5532                }
 5533            } else {
 5534                EditDisplayMode::DiffPopover
 5535            };
 5536
 5537            InlineCompletion::Edit {
 5538                edits,
 5539                edit_preview: inline_completion.edit_preview,
 5540                display_mode,
 5541                snapshot,
 5542            }
 5543        };
 5544
 5545        let invalidation_range = multibuffer
 5546            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5547            ..multibuffer.anchor_after(Point::new(
 5548                invalidation_row_range.end,
 5549                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5550            ));
 5551
 5552        self.stale_inline_completion_in_menu = None;
 5553        self.active_inline_completion = Some(InlineCompletionState {
 5554            inlay_ids,
 5555            completion,
 5556            completion_id: inline_completion.id,
 5557            invalidation_range,
 5558        });
 5559
 5560        cx.notify();
 5561
 5562        Some(())
 5563    }
 5564
 5565    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5566        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5567    }
 5568
 5569    fn render_code_actions_indicator(
 5570        &self,
 5571        _style: &EditorStyle,
 5572        row: DisplayRow,
 5573        is_active: bool,
 5574        cx: &mut Context<Self>,
 5575    ) -> Option<IconButton> {
 5576        if self.available_code_actions.is_some() {
 5577            Some(
 5578                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5579                    .shape(ui::IconButtonShape::Square)
 5580                    .icon_size(IconSize::XSmall)
 5581                    .icon_color(Color::Muted)
 5582                    .toggle_state(is_active)
 5583                    .tooltip({
 5584                        let focus_handle = self.focus_handle.clone();
 5585                        move |window, cx| {
 5586                            Tooltip::for_action_in(
 5587                                "Toggle Code Actions",
 5588                                &ToggleCodeActions {
 5589                                    deployed_from_indicator: None,
 5590                                },
 5591                                &focus_handle,
 5592                                window,
 5593                                cx,
 5594                            )
 5595                        }
 5596                    })
 5597                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5598                        window.focus(&editor.focus_handle(cx));
 5599                        editor.toggle_code_actions(
 5600                            &ToggleCodeActions {
 5601                                deployed_from_indicator: Some(row),
 5602                            },
 5603                            window,
 5604                            cx,
 5605                        );
 5606                    })),
 5607            )
 5608        } else {
 5609            None
 5610        }
 5611    }
 5612
 5613    fn clear_tasks(&mut self) {
 5614        self.tasks.clear()
 5615    }
 5616
 5617    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5618        if self.tasks.insert(key, value).is_some() {
 5619            // This case should hopefully be rare, but just in case...
 5620            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5621        }
 5622    }
 5623
 5624    fn build_tasks_context(
 5625        project: &Entity<Project>,
 5626        buffer: &Entity<Buffer>,
 5627        buffer_row: u32,
 5628        tasks: &Arc<RunnableTasks>,
 5629        cx: &mut Context<Self>,
 5630    ) -> Task<Option<task::TaskContext>> {
 5631        let position = Point::new(buffer_row, tasks.column);
 5632        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5633        let location = Location {
 5634            buffer: buffer.clone(),
 5635            range: range_start..range_start,
 5636        };
 5637        // Fill in the environmental variables from the tree-sitter captures
 5638        let mut captured_task_variables = TaskVariables::default();
 5639        for (capture_name, value) in tasks.extra_variables.clone() {
 5640            captured_task_variables.insert(
 5641                task::VariableName::Custom(capture_name.into()),
 5642                value.clone(),
 5643            );
 5644        }
 5645        project.update(cx, |project, cx| {
 5646            project.task_store().update(cx, |task_store, cx| {
 5647                task_store.task_context_for_location(captured_task_variables, location, cx)
 5648            })
 5649        })
 5650    }
 5651
 5652    pub fn spawn_nearest_task(
 5653        &mut self,
 5654        action: &SpawnNearestTask,
 5655        window: &mut Window,
 5656        cx: &mut Context<Self>,
 5657    ) {
 5658        let Some((workspace, _)) = self.workspace.clone() else {
 5659            return;
 5660        };
 5661        let Some(project) = self.project.clone() else {
 5662            return;
 5663        };
 5664
 5665        // Try to find a closest, enclosing node using tree-sitter that has a
 5666        // task
 5667        let Some((buffer, buffer_row, tasks)) = self
 5668            .find_enclosing_node_task(cx)
 5669            // Or find the task that's closest in row-distance.
 5670            .or_else(|| self.find_closest_task(cx))
 5671        else {
 5672            return;
 5673        };
 5674
 5675        let reveal_strategy = action.reveal;
 5676        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5677        cx.spawn_in(window, |_, mut cx| async move {
 5678            let context = task_context.await?;
 5679            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5680
 5681            let resolved = resolved_task.resolved.as_mut()?;
 5682            resolved.reveal = reveal_strategy;
 5683
 5684            workspace
 5685                .update(&mut cx, |workspace, cx| {
 5686                    workspace::tasks::schedule_resolved_task(
 5687                        workspace,
 5688                        task_source_kind,
 5689                        resolved_task,
 5690                        false,
 5691                        cx,
 5692                    );
 5693                })
 5694                .ok()
 5695        })
 5696        .detach();
 5697    }
 5698
 5699    fn find_closest_task(
 5700        &mut self,
 5701        cx: &mut Context<Self>,
 5702    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5703        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5704
 5705        let ((buffer_id, row), tasks) = self
 5706            .tasks
 5707            .iter()
 5708            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5709
 5710        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5711        let tasks = Arc::new(tasks.to_owned());
 5712        Some((buffer, *row, tasks))
 5713    }
 5714
 5715    fn find_enclosing_node_task(
 5716        &mut self,
 5717        cx: &mut Context<Self>,
 5718    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5719        let snapshot = self.buffer.read(cx).snapshot(cx);
 5720        let offset = self.selections.newest::<usize>(cx).head();
 5721        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5722        let buffer_id = excerpt.buffer().remote_id();
 5723
 5724        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5725        let mut cursor = layer.node().walk();
 5726
 5727        while cursor.goto_first_child_for_byte(offset).is_some() {
 5728            if cursor.node().end_byte() == offset {
 5729                cursor.goto_next_sibling();
 5730            }
 5731        }
 5732
 5733        // Ascend to the smallest ancestor that contains the range and has a task.
 5734        loop {
 5735            let node = cursor.node();
 5736            let node_range = node.byte_range();
 5737            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5738
 5739            // Check if this node contains our offset
 5740            if node_range.start <= offset && node_range.end >= offset {
 5741                // If it contains offset, check for task
 5742                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5743                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5744                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5745                }
 5746            }
 5747
 5748            if !cursor.goto_parent() {
 5749                break;
 5750            }
 5751        }
 5752        None
 5753    }
 5754
 5755    fn render_run_indicator(
 5756        &self,
 5757        _style: &EditorStyle,
 5758        is_active: bool,
 5759        row: DisplayRow,
 5760        cx: &mut Context<Self>,
 5761    ) -> IconButton {
 5762        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5763            .shape(ui::IconButtonShape::Square)
 5764            .icon_size(IconSize::XSmall)
 5765            .icon_color(Color::Muted)
 5766            .toggle_state(is_active)
 5767            .on_click(cx.listener(move |editor, _e, window, cx| {
 5768                window.focus(&editor.focus_handle(cx));
 5769                editor.toggle_code_actions(
 5770                    &ToggleCodeActions {
 5771                        deployed_from_indicator: Some(row),
 5772                    },
 5773                    window,
 5774                    cx,
 5775                );
 5776            }))
 5777    }
 5778
 5779    pub fn context_menu_visible(&self) -> bool {
 5780        !self.edit_prediction_preview_is_active()
 5781            && self
 5782                .context_menu
 5783                .borrow()
 5784                .as_ref()
 5785                .map_or(false, |menu| menu.visible())
 5786    }
 5787
 5788    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5789        self.context_menu
 5790            .borrow()
 5791            .as_ref()
 5792            .map(|menu| menu.origin())
 5793    }
 5794
 5795    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5796        px(30.)
 5797    }
 5798
 5799    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5800        if self.read_only(cx) {
 5801            cx.theme().players().read_only()
 5802        } else {
 5803            self.style.as_ref().unwrap().local_player
 5804        }
 5805    }
 5806
 5807    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 5808        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 5809        let accept_keystroke = accept_binding.keystroke()?;
 5810
 5811        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 5812
 5813        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 5814            Color::Accent
 5815        } else {
 5816            Color::Muted
 5817        };
 5818
 5819        h_flex()
 5820            .px_0p5()
 5821            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 5822            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5823            .text_size(TextSize::XSmall.rems(cx))
 5824            .child(h_flex().children(ui::render_modifiers(
 5825                &accept_keystroke.modifiers,
 5826                PlatformStyle::platform(),
 5827                Some(modifiers_color),
 5828                Some(IconSize::XSmall.rems().into()),
 5829                true,
 5830            )))
 5831            .when(is_platform_style_mac, |parent| {
 5832                parent.child(accept_keystroke.key.clone())
 5833            })
 5834            .when(!is_platform_style_mac, |parent| {
 5835                parent.child(
 5836                    Key::new(
 5837                        util::capitalize(&accept_keystroke.key),
 5838                        Some(Color::Default),
 5839                    )
 5840                    .size(Some(IconSize::XSmall.rems().into())),
 5841                )
 5842            })
 5843            .into()
 5844    }
 5845
 5846    fn render_edit_prediction_line_popover(
 5847        &self,
 5848        label: impl Into<SharedString>,
 5849        icon: Option<IconName>,
 5850        window: &mut Window,
 5851        cx: &App,
 5852    ) -> Option<Div> {
 5853        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 5854
 5855        let result = h_flex()
 5856            .py_0p5()
 5857            .pl_1()
 5858            .pr(padding_right)
 5859            .gap_1()
 5860            .rounded(px(6.))
 5861            .border_1()
 5862            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 5863            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 5864            .shadow_sm()
 5865            .children(self.render_edit_prediction_accept_keybind(window, cx))
 5866            .child(Label::new(label).size(LabelSize::Small))
 5867            .when_some(icon, |element, icon| {
 5868                element.child(
 5869                    div()
 5870                        .mt(px(1.5))
 5871                        .child(Icon::new(icon).size(IconSize::Small)),
 5872                )
 5873            });
 5874
 5875        Some(result)
 5876    }
 5877
 5878    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 5879        let accent_color = cx.theme().colors().text_accent;
 5880        let editor_bg_color = cx.theme().colors().editor_background;
 5881        editor_bg_color.blend(accent_color.opacity(0.1))
 5882    }
 5883
 5884    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 5885        let accent_color = cx.theme().colors().text_accent;
 5886        let editor_bg_color = cx.theme().colors().editor_background;
 5887        editor_bg_color.blend(accent_color.opacity(0.6))
 5888    }
 5889
 5890    #[allow(clippy::too_many_arguments)]
 5891    fn render_edit_prediction_cursor_popover(
 5892        &self,
 5893        min_width: Pixels,
 5894        max_width: Pixels,
 5895        cursor_point: Point,
 5896        style: &EditorStyle,
 5897        accept_keystroke: Option<&gpui::Keystroke>,
 5898        _window: &Window,
 5899        cx: &mut Context<Editor>,
 5900    ) -> Option<AnyElement> {
 5901        let provider = self.edit_prediction_provider.as_ref()?;
 5902
 5903        if provider.provider.needs_terms_acceptance(cx) {
 5904            return Some(
 5905                h_flex()
 5906                    .min_w(min_width)
 5907                    .flex_1()
 5908                    .px_2()
 5909                    .py_1()
 5910                    .gap_3()
 5911                    .elevation_2(cx)
 5912                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5913                    .id("accept-terms")
 5914                    .cursor_pointer()
 5915                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5916                    .on_click(cx.listener(|this, _event, window, cx| {
 5917                        cx.stop_propagation();
 5918                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5919                        window.dispatch_action(
 5920                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5921                            cx,
 5922                        );
 5923                    }))
 5924                    .child(
 5925                        h_flex()
 5926                            .flex_1()
 5927                            .gap_2()
 5928                            .child(Icon::new(IconName::ZedPredict))
 5929                            .child(Label::new("Accept Terms of Service"))
 5930                            .child(div().w_full())
 5931                            .child(
 5932                                Icon::new(IconName::ArrowUpRight)
 5933                                    .color(Color::Muted)
 5934                                    .size(IconSize::Small),
 5935                            )
 5936                            .into_any_element(),
 5937                    )
 5938                    .into_any(),
 5939            );
 5940        }
 5941
 5942        let is_refreshing = provider.provider.is_refreshing(cx);
 5943
 5944        fn pending_completion_container() -> Div {
 5945            h_flex()
 5946                .h_full()
 5947                .flex_1()
 5948                .gap_2()
 5949                .child(Icon::new(IconName::ZedPredict))
 5950        }
 5951
 5952        let completion = match &self.active_inline_completion {
 5953            Some(completion) => match &completion.completion {
 5954                InlineCompletion::Move {
 5955                    target, snapshot, ..
 5956                } if !self.has_visible_completions_menu() => {
 5957                    use text::ToPoint as _;
 5958
 5959                    return Some(
 5960                        h_flex()
 5961                            .px_2()
 5962                            .py_1()
 5963                            .gap_2()
 5964                            .elevation_2(cx)
 5965                            .border_color(cx.theme().colors().border)
 5966                            .rounded(px(6.))
 5967                            .rounded_tl(px(0.))
 5968                            .child(
 5969                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5970                                    Icon::new(IconName::ZedPredictDown)
 5971                                } else {
 5972                                    Icon::new(IconName::ZedPredictUp)
 5973                                },
 5974                            )
 5975                            .child(Label::new("Hold").size(LabelSize::Small))
 5976                            .child(h_flex().children(ui::render_modifiers(
 5977                                &accept_keystroke?.modifiers,
 5978                                PlatformStyle::platform(),
 5979                                Some(Color::Default),
 5980                                Some(IconSize::Small.rems().into()),
 5981                                false,
 5982                            )))
 5983                            .into_any(),
 5984                    );
 5985                }
 5986                _ => self.render_edit_prediction_cursor_popover_preview(
 5987                    completion,
 5988                    cursor_point,
 5989                    style,
 5990                    cx,
 5991                )?,
 5992            },
 5993
 5994            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5995                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5996                    stale_completion,
 5997                    cursor_point,
 5998                    style,
 5999                    cx,
 6000                )?,
 6001
 6002                None => {
 6003                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6004                }
 6005            },
 6006
 6007            None => pending_completion_container().child(Label::new("No Prediction")),
 6008        };
 6009
 6010        let completion = if is_refreshing {
 6011            completion
 6012                .with_animation(
 6013                    "loading-completion",
 6014                    Animation::new(Duration::from_secs(2))
 6015                        .repeat()
 6016                        .with_easing(pulsating_between(0.4, 0.8)),
 6017                    |label, delta| label.opacity(delta),
 6018                )
 6019                .into_any_element()
 6020        } else {
 6021            completion.into_any_element()
 6022        };
 6023
 6024        let has_completion = self.active_inline_completion.is_some();
 6025
 6026        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6027        Some(
 6028            h_flex()
 6029                .min_w(min_width)
 6030                .max_w(max_width)
 6031                .flex_1()
 6032                .elevation_2(cx)
 6033                .border_color(cx.theme().colors().border)
 6034                .child(
 6035                    div()
 6036                        .flex_1()
 6037                        .py_1()
 6038                        .px_2()
 6039                        .overflow_hidden()
 6040                        .child(completion),
 6041                )
 6042                .when_some(accept_keystroke, |el, accept_keystroke| {
 6043                    if !accept_keystroke.modifiers.modified() {
 6044                        return el;
 6045                    }
 6046
 6047                    el.child(
 6048                        h_flex()
 6049                            .h_full()
 6050                            .border_l_1()
 6051                            .rounded_r_lg()
 6052                            .border_color(cx.theme().colors().border)
 6053                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6054                            .gap_1()
 6055                            .py_1()
 6056                            .px_2()
 6057                            .child(
 6058                                h_flex()
 6059                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6060                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6061                                    .child(h_flex().children(ui::render_modifiers(
 6062                                        &accept_keystroke.modifiers,
 6063                                        PlatformStyle::platform(),
 6064                                        Some(if !has_completion {
 6065                                            Color::Muted
 6066                                        } else {
 6067                                            Color::Default
 6068                                        }),
 6069                                        None,
 6070                                        false,
 6071                                    ))),
 6072                            )
 6073                            .child(Label::new("Preview").into_any_element())
 6074                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6075                    )
 6076                })
 6077                .into_any(),
 6078        )
 6079    }
 6080
 6081    fn render_edit_prediction_cursor_popover_preview(
 6082        &self,
 6083        completion: &InlineCompletionState,
 6084        cursor_point: Point,
 6085        style: &EditorStyle,
 6086        cx: &mut Context<Editor>,
 6087    ) -> Option<Div> {
 6088        use text::ToPoint as _;
 6089
 6090        fn render_relative_row_jump(
 6091            prefix: impl Into<String>,
 6092            current_row: u32,
 6093            target_row: u32,
 6094        ) -> Div {
 6095            let (row_diff, arrow) = if target_row < current_row {
 6096                (current_row - target_row, IconName::ArrowUp)
 6097            } else {
 6098                (target_row - current_row, IconName::ArrowDown)
 6099            };
 6100
 6101            h_flex()
 6102                .child(
 6103                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6104                        .color(Color::Muted)
 6105                        .size(LabelSize::Small),
 6106                )
 6107                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6108        }
 6109
 6110        match &completion.completion {
 6111            InlineCompletion::Move {
 6112                target, snapshot, ..
 6113            } => Some(
 6114                h_flex()
 6115                    .px_2()
 6116                    .gap_2()
 6117                    .flex_1()
 6118                    .child(
 6119                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6120                            Icon::new(IconName::ZedPredictDown)
 6121                        } else {
 6122                            Icon::new(IconName::ZedPredictUp)
 6123                        },
 6124                    )
 6125                    .child(Label::new("Jump to Edit")),
 6126            ),
 6127
 6128            InlineCompletion::Edit {
 6129                edits,
 6130                edit_preview,
 6131                snapshot,
 6132                display_mode: _,
 6133            } => {
 6134                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6135
 6136                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6137                    &snapshot,
 6138                    &edits,
 6139                    edit_preview.as_ref()?,
 6140                    true,
 6141                    cx,
 6142                )
 6143                .first_line_preview();
 6144
 6145                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6146                    .with_highlights(&style.text, highlighted_edits.highlights);
 6147
 6148                let preview = h_flex()
 6149                    .gap_1()
 6150                    .min_w_16()
 6151                    .child(styled_text)
 6152                    .when(has_more_lines, |parent| parent.child(""));
 6153
 6154                let left = if first_edit_row != cursor_point.row {
 6155                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6156                        .into_any_element()
 6157                } else {
 6158                    Icon::new(IconName::ZedPredict).into_any_element()
 6159                };
 6160
 6161                Some(
 6162                    h_flex()
 6163                        .h_full()
 6164                        .flex_1()
 6165                        .gap_2()
 6166                        .pr_1()
 6167                        .overflow_x_hidden()
 6168                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6169                        .child(left)
 6170                        .child(preview),
 6171                )
 6172            }
 6173        }
 6174    }
 6175
 6176    fn render_context_menu(
 6177        &self,
 6178        style: &EditorStyle,
 6179        max_height_in_lines: u32,
 6180        y_flipped: bool,
 6181        window: &mut Window,
 6182        cx: &mut Context<Editor>,
 6183    ) -> Option<AnyElement> {
 6184        let menu = self.context_menu.borrow();
 6185        let menu = menu.as_ref()?;
 6186        if !menu.visible() {
 6187            return None;
 6188        };
 6189        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6190    }
 6191
 6192    fn render_context_menu_aside(
 6193        &mut self,
 6194        max_size: Size<Pixels>,
 6195        window: &mut Window,
 6196        cx: &mut Context<Editor>,
 6197    ) -> Option<AnyElement> {
 6198        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 6199            if menu.visible() {
 6200                menu.render_aside(self, max_size, window, cx)
 6201            } else {
 6202                None
 6203            }
 6204        })
 6205    }
 6206
 6207    fn hide_context_menu(
 6208        &mut self,
 6209        window: &mut Window,
 6210        cx: &mut Context<Self>,
 6211    ) -> Option<CodeContextMenu> {
 6212        cx.notify();
 6213        self.completion_tasks.clear();
 6214        let context_menu = self.context_menu.borrow_mut().take();
 6215        self.stale_inline_completion_in_menu.take();
 6216        self.update_visible_inline_completion(window, cx);
 6217        context_menu
 6218    }
 6219
 6220    fn show_snippet_choices(
 6221        &mut self,
 6222        choices: &Vec<String>,
 6223        selection: Range<Anchor>,
 6224        cx: &mut Context<Self>,
 6225    ) {
 6226        if selection.start.buffer_id.is_none() {
 6227            return;
 6228        }
 6229        let buffer_id = selection.start.buffer_id.unwrap();
 6230        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6231        let id = post_inc(&mut self.next_completion_id);
 6232
 6233        if let Some(buffer) = buffer {
 6234            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6235                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6236            ));
 6237        }
 6238    }
 6239
 6240    pub fn insert_snippet(
 6241        &mut self,
 6242        insertion_ranges: &[Range<usize>],
 6243        snippet: Snippet,
 6244        window: &mut Window,
 6245        cx: &mut Context<Self>,
 6246    ) -> Result<()> {
 6247        struct Tabstop<T> {
 6248            is_end_tabstop: bool,
 6249            ranges: Vec<Range<T>>,
 6250            choices: Option<Vec<String>>,
 6251        }
 6252
 6253        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6254            let snippet_text: Arc<str> = snippet.text.clone().into();
 6255            buffer.edit(
 6256                insertion_ranges
 6257                    .iter()
 6258                    .cloned()
 6259                    .map(|range| (range, snippet_text.clone())),
 6260                Some(AutoindentMode::EachLine),
 6261                cx,
 6262            );
 6263
 6264            let snapshot = &*buffer.read(cx);
 6265            let snippet = &snippet;
 6266            snippet
 6267                .tabstops
 6268                .iter()
 6269                .map(|tabstop| {
 6270                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6271                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6272                    });
 6273                    let mut tabstop_ranges = tabstop
 6274                        .ranges
 6275                        .iter()
 6276                        .flat_map(|tabstop_range| {
 6277                            let mut delta = 0_isize;
 6278                            insertion_ranges.iter().map(move |insertion_range| {
 6279                                let insertion_start = insertion_range.start as isize + delta;
 6280                                delta +=
 6281                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6282
 6283                                let start = ((insertion_start + tabstop_range.start) as usize)
 6284                                    .min(snapshot.len());
 6285                                let end = ((insertion_start + tabstop_range.end) as usize)
 6286                                    .min(snapshot.len());
 6287                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6288                            })
 6289                        })
 6290                        .collect::<Vec<_>>();
 6291                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6292
 6293                    Tabstop {
 6294                        is_end_tabstop,
 6295                        ranges: tabstop_ranges,
 6296                        choices: tabstop.choices.clone(),
 6297                    }
 6298                })
 6299                .collect::<Vec<_>>()
 6300        });
 6301        if let Some(tabstop) = tabstops.first() {
 6302            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6303                s.select_ranges(tabstop.ranges.iter().cloned());
 6304            });
 6305
 6306            if let Some(choices) = &tabstop.choices {
 6307                if let Some(selection) = tabstop.ranges.first() {
 6308                    self.show_snippet_choices(choices, selection.clone(), cx)
 6309                }
 6310            }
 6311
 6312            // If we're already at the last tabstop and it's at the end of the snippet,
 6313            // we're done, we don't need to keep the state around.
 6314            if !tabstop.is_end_tabstop {
 6315                let choices = tabstops
 6316                    .iter()
 6317                    .map(|tabstop| tabstop.choices.clone())
 6318                    .collect();
 6319
 6320                let ranges = tabstops
 6321                    .into_iter()
 6322                    .map(|tabstop| tabstop.ranges)
 6323                    .collect::<Vec<_>>();
 6324
 6325                self.snippet_stack.push(SnippetState {
 6326                    active_index: 0,
 6327                    ranges,
 6328                    choices,
 6329                });
 6330            }
 6331
 6332            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6333            if self.autoclose_regions.is_empty() {
 6334                let snapshot = self.buffer.read(cx).snapshot(cx);
 6335                for selection in &mut self.selections.all::<Point>(cx) {
 6336                    let selection_head = selection.head();
 6337                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6338                        continue;
 6339                    };
 6340
 6341                    let mut bracket_pair = None;
 6342                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6343                    let prev_chars = snapshot
 6344                        .reversed_chars_at(selection_head)
 6345                        .collect::<String>();
 6346                    for (pair, enabled) in scope.brackets() {
 6347                        if enabled
 6348                            && pair.close
 6349                            && prev_chars.starts_with(pair.start.as_str())
 6350                            && next_chars.starts_with(pair.end.as_str())
 6351                        {
 6352                            bracket_pair = Some(pair.clone());
 6353                            break;
 6354                        }
 6355                    }
 6356                    if let Some(pair) = bracket_pair {
 6357                        let start = snapshot.anchor_after(selection_head);
 6358                        let end = snapshot.anchor_after(selection_head);
 6359                        self.autoclose_regions.push(AutocloseRegion {
 6360                            selection_id: selection.id,
 6361                            range: start..end,
 6362                            pair,
 6363                        });
 6364                    }
 6365                }
 6366            }
 6367        }
 6368        Ok(())
 6369    }
 6370
 6371    pub fn move_to_next_snippet_tabstop(
 6372        &mut self,
 6373        window: &mut Window,
 6374        cx: &mut Context<Self>,
 6375    ) -> bool {
 6376        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6377    }
 6378
 6379    pub fn move_to_prev_snippet_tabstop(
 6380        &mut self,
 6381        window: &mut Window,
 6382        cx: &mut Context<Self>,
 6383    ) -> bool {
 6384        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6385    }
 6386
 6387    pub fn move_to_snippet_tabstop(
 6388        &mut self,
 6389        bias: Bias,
 6390        window: &mut Window,
 6391        cx: &mut Context<Self>,
 6392    ) -> bool {
 6393        if let Some(mut snippet) = self.snippet_stack.pop() {
 6394            match bias {
 6395                Bias::Left => {
 6396                    if snippet.active_index > 0 {
 6397                        snippet.active_index -= 1;
 6398                    } else {
 6399                        self.snippet_stack.push(snippet);
 6400                        return false;
 6401                    }
 6402                }
 6403                Bias::Right => {
 6404                    if snippet.active_index + 1 < snippet.ranges.len() {
 6405                        snippet.active_index += 1;
 6406                    } else {
 6407                        self.snippet_stack.push(snippet);
 6408                        return false;
 6409                    }
 6410                }
 6411            }
 6412            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6413                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6414                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6415                });
 6416
 6417                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6418                    if let Some(selection) = current_ranges.first() {
 6419                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6420                    }
 6421                }
 6422
 6423                // If snippet state is not at the last tabstop, push it back on the stack
 6424                if snippet.active_index + 1 < snippet.ranges.len() {
 6425                    self.snippet_stack.push(snippet);
 6426                }
 6427                return true;
 6428            }
 6429        }
 6430
 6431        false
 6432    }
 6433
 6434    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6435        self.transact(window, cx, |this, window, cx| {
 6436            this.select_all(&SelectAll, window, cx);
 6437            this.insert("", window, cx);
 6438        });
 6439    }
 6440
 6441    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6442        self.transact(window, cx, |this, window, cx| {
 6443            this.select_autoclose_pair(window, cx);
 6444            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6445            if !this.linked_edit_ranges.is_empty() {
 6446                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6447                let snapshot = this.buffer.read(cx).snapshot(cx);
 6448
 6449                for selection in selections.iter() {
 6450                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6451                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6452                    if selection_start.buffer_id != selection_end.buffer_id {
 6453                        continue;
 6454                    }
 6455                    if let Some(ranges) =
 6456                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6457                    {
 6458                        for (buffer, entries) in ranges {
 6459                            linked_ranges.entry(buffer).or_default().extend(entries);
 6460                        }
 6461                    }
 6462                }
 6463            }
 6464
 6465            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6466            if !this.selections.line_mode {
 6467                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6468                for selection in &mut selections {
 6469                    if selection.is_empty() {
 6470                        let old_head = selection.head();
 6471                        let mut new_head =
 6472                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6473                                .to_point(&display_map);
 6474                        if let Some((buffer, line_buffer_range)) = display_map
 6475                            .buffer_snapshot
 6476                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6477                        {
 6478                            let indent_size =
 6479                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6480                            let indent_len = match indent_size.kind {
 6481                                IndentKind::Space => {
 6482                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6483                                }
 6484                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6485                            };
 6486                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6487                                let indent_len = indent_len.get();
 6488                                new_head = cmp::min(
 6489                                    new_head,
 6490                                    MultiBufferPoint::new(
 6491                                        old_head.row,
 6492                                        ((old_head.column - 1) / indent_len) * indent_len,
 6493                                    ),
 6494                                );
 6495                            }
 6496                        }
 6497
 6498                        selection.set_head(new_head, SelectionGoal::None);
 6499                    }
 6500                }
 6501            }
 6502
 6503            this.signature_help_state.set_backspace_pressed(true);
 6504            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6505                s.select(selections)
 6506            });
 6507            this.insert("", window, cx);
 6508            let empty_str: Arc<str> = Arc::from("");
 6509            for (buffer, edits) in linked_ranges {
 6510                let snapshot = buffer.read(cx).snapshot();
 6511                use text::ToPoint as TP;
 6512
 6513                let edits = edits
 6514                    .into_iter()
 6515                    .map(|range| {
 6516                        let end_point = TP::to_point(&range.end, &snapshot);
 6517                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6518
 6519                        if end_point == start_point {
 6520                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6521                                .saturating_sub(1);
 6522                            start_point =
 6523                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6524                        };
 6525
 6526                        (start_point..end_point, empty_str.clone())
 6527                    })
 6528                    .sorted_by_key(|(range, _)| range.start)
 6529                    .collect::<Vec<_>>();
 6530                buffer.update(cx, |this, cx| {
 6531                    this.edit(edits, None, cx);
 6532                })
 6533            }
 6534            this.refresh_inline_completion(true, false, window, cx);
 6535            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6536        });
 6537    }
 6538
 6539    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6540        self.transact(window, cx, |this, window, cx| {
 6541            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6542                let line_mode = s.line_mode;
 6543                s.move_with(|map, selection| {
 6544                    if selection.is_empty() && !line_mode {
 6545                        let cursor = movement::right(map, selection.head());
 6546                        selection.end = cursor;
 6547                        selection.reversed = true;
 6548                        selection.goal = SelectionGoal::None;
 6549                    }
 6550                })
 6551            });
 6552            this.insert("", window, cx);
 6553            this.refresh_inline_completion(true, false, window, cx);
 6554        });
 6555    }
 6556
 6557    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6558        if self.move_to_prev_snippet_tabstop(window, cx) {
 6559            return;
 6560        }
 6561
 6562        self.outdent(&Outdent, window, cx);
 6563    }
 6564
 6565    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6566        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6567            return;
 6568        }
 6569
 6570        let mut selections = self.selections.all_adjusted(cx);
 6571        let buffer = self.buffer.read(cx);
 6572        let snapshot = buffer.snapshot(cx);
 6573        let rows_iter = selections.iter().map(|s| s.head().row);
 6574        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6575
 6576        let mut edits = Vec::new();
 6577        let mut prev_edited_row = 0;
 6578        let mut row_delta = 0;
 6579        for selection in &mut selections {
 6580            if selection.start.row != prev_edited_row {
 6581                row_delta = 0;
 6582            }
 6583            prev_edited_row = selection.end.row;
 6584
 6585            // If the selection is non-empty, then increase the indentation of the selected lines.
 6586            if !selection.is_empty() {
 6587                row_delta =
 6588                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6589                continue;
 6590            }
 6591
 6592            // If the selection is empty and the cursor is in the leading whitespace before the
 6593            // suggested indentation, then auto-indent the line.
 6594            let cursor = selection.head();
 6595            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6596            if let Some(suggested_indent) =
 6597                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6598            {
 6599                if cursor.column < suggested_indent.len
 6600                    && cursor.column <= current_indent.len
 6601                    && current_indent.len <= suggested_indent.len
 6602                {
 6603                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6604                    selection.end = selection.start;
 6605                    if row_delta == 0 {
 6606                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6607                            cursor.row,
 6608                            current_indent,
 6609                            suggested_indent,
 6610                        ));
 6611                        row_delta = suggested_indent.len - current_indent.len;
 6612                    }
 6613                    continue;
 6614                }
 6615            }
 6616
 6617            // Otherwise, insert a hard or soft tab.
 6618            let settings = buffer.settings_at(cursor, cx);
 6619            let tab_size = if settings.hard_tabs {
 6620                IndentSize::tab()
 6621            } else {
 6622                let tab_size = settings.tab_size.get();
 6623                let char_column = snapshot
 6624                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6625                    .flat_map(str::chars)
 6626                    .count()
 6627                    + row_delta as usize;
 6628                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6629                IndentSize::spaces(chars_to_next_tab_stop)
 6630            };
 6631            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6632            selection.end = selection.start;
 6633            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6634            row_delta += tab_size.len;
 6635        }
 6636
 6637        self.transact(window, cx, |this, window, cx| {
 6638            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6639            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6640                s.select(selections)
 6641            });
 6642            this.refresh_inline_completion(true, false, window, cx);
 6643        });
 6644    }
 6645
 6646    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6647        if self.read_only(cx) {
 6648            return;
 6649        }
 6650        let mut selections = self.selections.all::<Point>(cx);
 6651        let mut prev_edited_row = 0;
 6652        let mut row_delta = 0;
 6653        let mut edits = Vec::new();
 6654        let buffer = self.buffer.read(cx);
 6655        let snapshot = buffer.snapshot(cx);
 6656        for selection in &mut selections {
 6657            if selection.start.row != prev_edited_row {
 6658                row_delta = 0;
 6659            }
 6660            prev_edited_row = selection.end.row;
 6661
 6662            row_delta =
 6663                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6664        }
 6665
 6666        self.transact(window, cx, |this, window, cx| {
 6667            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6668            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6669                s.select(selections)
 6670            });
 6671        });
 6672    }
 6673
 6674    fn indent_selection(
 6675        buffer: &MultiBuffer,
 6676        snapshot: &MultiBufferSnapshot,
 6677        selection: &mut Selection<Point>,
 6678        edits: &mut Vec<(Range<Point>, String)>,
 6679        delta_for_start_row: u32,
 6680        cx: &App,
 6681    ) -> u32 {
 6682        let settings = buffer.settings_at(selection.start, cx);
 6683        let tab_size = settings.tab_size.get();
 6684        let indent_kind = if settings.hard_tabs {
 6685            IndentKind::Tab
 6686        } else {
 6687            IndentKind::Space
 6688        };
 6689        let mut start_row = selection.start.row;
 6690        let mut end_row = selection.end.row + 1;
 6691
 6692        // If a selection ends at the beginning of a line, don't indent
 6693        // that last line.
 6694        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6695            end_row -= 1;
 6696        }
 6697
 6698        // Avoid re-indenting a row that has already been indented by a
 6699        // previous selection, but still update this selection's column
 6700        // to reflect that indentation.
 6701        if delta_for_start_row > 0 {
 6702            start_row += 1;
 6703            selection.start.column += delta_for_start_row;
 6704            if selection.end.row == selection.start.row {
 6705                selection.end.column += delta_for_start_row;
 6706            }
 6707        }
 6708
 6709        let mut delta_for_end_row = 0;
 6710        let has_multiple_rows = start_row + 1 != end_row;
 6711        for row in start_row..end_row {
 6712            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6713            let indent_delta = match (current_indent.kind, indent_kind) {
 6714                (IndentKind::Space, IndentKind::Space) => {
 6715                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6716                    IndentSize::spaces(columns_to_next_tab_stop)
 6717                }
 6718                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6719                (_, IndentKind::Tab) => IndentSize::tab(),
 6720            };
 6721
 6722            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6723                0
 6724            } else {
 6725                selection.start.column
 6726            };
 6727            let row_start = Point::new(row, start);
 6728            edits.push((
 6729                row_start..row_start,
 6730                indent_delta.chars().collect::<String>(),
 6731            ));
 6732
 6733            // Update this selection's endpoints to reflect the indentation.
 6734            if row == selection.start.row {
 6735                selection.start.column += indent_delta.len;
 6736            }
 6737            if row == selection.end.row {
 6738                selection.end.column += indent_delta.len;
 6739                delta_for_end_row = indent_delta.len;
 6740            }
 6741        }
 6742
 6743        if selection.start.row == selection.end.row {
 6744            delta_for_start_row + delta_for_end_row
 6745        } else {
 6746            delta_for_end_row
 6747        }
 6748    }
 6749
 6750    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6751        if self.read_only(cx) {
 6752            return;
 6753        }
 6754        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6755        let selections = self.selections.all::<Point>(cx);
 6756        let mut deletion_ranges = Vec::new();
 6757        let mut last_outdent = None;
 6758        {
 6759            let buffer = self.buffer.read(cx);
 6760            let snapshot = buffer.snapshot(cx);
 6761            for selection in &selections {
 6762                let settings = buffer.settings_at(selection.start, cx);
 6763                let tab_size = settings.tab_size.get();
 6764                let mut rows = selection.spanned_rows(false, &display_map);
 6765
 6766                // Avoid re-outdenting a row that has already been outdented by a
 6767                // previous selection.
 6768                if let Some(last_row) = last_outdent {
 6769                    if last_row == rows.start {
 6770                        rows.start = rows.start.next_row();
 6771                    }
 6772                }
 6773                let has_multiple_rows = rows.len() > 1;
 6774                for row in rows.iter_rows() {
 6775                    let indent_size = snapshot.indent_size_for_line(row);
 6776                    if indent_size.len > 0 {
 6777                        let deletion_len = match indent_size.kind {
 6778                            IndentKind::Space => {
 6779                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6780                                if columns_to_prev_tab_stop == 0 {
 6781                                    tab_size
 6782                                } else {
 6783                                    columns_to_prev_tab_stop
 6784                                }
 6785                            }
 6786                            IndentKind::Tab => 1,
 6787                        };
 6788                        let start = if has_multiple_rows
 6789                            || deletion_len > selection.start.column
 6790                            || indent_size.len < selection.start.column
 6791                        {
 6792                            0
 6793                        } else {
 6794                            selection.start.column - deletion_len
 6795                        };
 6796                        deletion_ranges.push(
 6797                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6798                        );
 6799                        last_outdent = Some(row);
 6800                    }
 6801                }
 6802            }
 6803        }
 6804
 6805        self.transact(window, cx, |this, window, cx| {
 6806            this.buffer.update(cx, |buffer, cx| {
 6807                let empty_str: Arc<str> = Arc::default();
 6808                buffer.edit(
 6809                    deletion_ranges
 6810                        .into_iter()
 6811                        .map(|range| (range, empty_str.clone())),
 6812                    None,
 6813                    cx,
 6814                );
 6815            });
 6816            let selections = this.selections.all::<usize>(cx);
 6817            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6818                s.select(selections)
 6819            });
 6820        });
 6821    }
 6822
 6823    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6824        if self.read_only(cx) {
 6825            return;
 6826        }
 6827        let selections = self
 6828            .selections
 6829            .all::<usize>(cx)
 6830            .into_iter()
 6831            .map(|s| s.range());
 6832
 6833        self.transact(window, cx, |this, window, cx| {
 6834            this.buffer.update(cx, |buffer, cx| {
 6835                buffer.autoindent_ranges(selections, cx);
 6836            });
 6837            let selections = this.selections.all::<usize>(cx);
 6838            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6839                s.select(selections)
 6840            });
 6841        });
 6842    }
 6843
 6844    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6845        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6846        let selections = self.selections.all::<Point>(cx);
 6847
 6848        let mut new_cursors = Vec::new();
 6849        let mut edit_ranges = Vec::new();
 6850        let mut selections = selections.iter().peekable();
 6851        while let Some(selection) = selections.next() {
 6852            let mut rows = selection.spanned_rows(false, &display_map);
 6853            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6854
 6855            // Accumulate contiguous regions of rows that we want to delete.
 6856            while let Some(next_selection) = selections.peek() {
 6857                let next_rows = next_selection.spanned_rows(false, &display_map);
 6858                if next_rows.start <= rows.end {
 6859                    rows.end = next_rows.end;
 6860                    selections.next().unwrap();
 6861                } else {
 6862                    break;
 6863                }
 6864            }
 6865
 6866            let buffer = &display_map.buffer_snapshot;
 6867            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6868            let edit_end;
 6869            let cursor_buffer_row;
 6870            if buffer.max_point().row >= rows.end.0 {
 6871                // If there's a line after the range, delete the \n from the end of the row range
 6872                // and position the cursor on the next line.
 6873                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6874                cursor_buffer_row = rows.end;
 6875            } else {
 6876                // If there isn't a line after the range, delete the \n from the line before the
 6877                // start of the row range and position the cursor there.
 6878                edit_start = edit_start.saturating_sub(1);
 6879                edit_end = buffer.len();
 6880                cursor_buffer_row = rows.start.previous_row();
 6881            }
 6882
 6883            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6884            *cursor.column_mut() =
 6885                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6886
 6887            new_cursors.push((
 6888                selection.id,
 6889                buffer.anchor_after(cursor.to_point(&display_map)),
 6890            ));
 6891            edit_ranges.push(edit_start..edit_end);
 6892        }
 6893
 6894        self.transact(window, cx, |this, window, cx| {
 6895            let buffer = this.buffer.update(cx, |buffer, cx| {
 6896                let empty_str: Arc<str> = Arc::default();
 6897                buffer.edit(
 6898                    edit_ranges
 6899                        .into_iter()
 6900                        .map(|range| (range, empty_str.clone())),
 6901                    None,
 6902                    cx,
 6903                );
 6904                buffer.snapshot(cx)
 6905            });
 6906            let new_selections = new_cursors
 6907                .into_iter()
 6908                .map(|(id, cursor)| {
 6909                    let cursor = cursor.to_point(&buffer);
 6910                    Selection {
 6911                        id,
 6912                        start: cursor,
 6913                        end: cursor,
 6914                        reversed: false,
 6915                        goal: SelectionGoal::None,
 6916                    }
 6917                })
 6918                .collect();
 6919
 6920            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6921                s.select(new_selections);
 6922            });
 6923        });
 6924    }
 6925
 6926    pub fn join_lines_impl(
 6927        &mut self,
 6928        insert_whitespace: bool,
 6929        window: &mut Window,
 6930        cx: &mut Context<Self>,
 6931    ) {
 6932        if self.read_only(cx) {
 6933            return;
 6934        }
 6935        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6936        for selection in self.selections.all::<Point>(cx) {
 6937            let start = MultiBufferRow(selection.start.row);
 6938            // Treat single line selections as if they include the next line. Otherwise this action
 6939            // would do nothing for single line selections individual cursors.
 6940            let end = if selection.start.row == selection.end.row {
 6941                MultiBufferRow(selection.start.row + 1)
 6942            } else {
 6943                MultiBufferRow(selection.end.row)
 6944            };
 6945
 6946            if let Some(last_row_range) = row_ranges.last_mut() {
 6947                if start <= last_row_range.end {
 6948                    last_row_range.end = end;
 6949                    continue;
 6950                }
 6951            }
 6952            row_ranges.push(start..end);
 6953        }
 6954
 6955        let snapshot = self.buffer.read(cx).snapshot(cx);
 6956        let mut cursor_positions = Vec::new();
 6957        for row_range in &row_ranges {
 6958            let anchor = snapshot.anchor_before(Point::new(
 6959                row_range.end.previous_row().0,
 6960                snapshot.line_len(row_range.end.previous_row()),
 6961            ));
 6962            cursor_positions.push(anchor..anchor);
 6963        }
 6964
 6965        self.transact(window, cx, |this, window, cx| {
 6966            for row_range in row_ranges.into_iter().rev() {
 6967                for row in row_range.iter_rows().rev() {
 6968                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6969                    let next_line_row = row.next_row();
 6970                    let indent = snapshot.indent_size_for_line(next_line_row);
 6971                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6972
 6973                    let replace =
 6974                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6975                            " "
 6976                        } else {
 6977                            ""
 6978                        };
 6979
 6980                    this.buffer.update(cx, |buffer, cx| {
 6981                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6982                    });
 6983                }
 6984            }
 6985
 6986            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6987                s.select_anchor_ranges(cursor_positions)
 6988            });
 6989        });
 6990    }
 6991
 6992    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6993        self.join_lines_impl(true, window, cx);
 6994    }
 6995
 6996    pub fn sort_lines_case_sensitive(
 6997        &mut self,
 6998        _: &SortLinesCaseSensitive,
 6999        window: &mut Window,
 7000        cx: &mut Context<Self>,
 7001    ) {
 7002        self.manipulate_lines(window, cx, |lines| lines.sort())
 7003    }
 7004
 7005    pub fn sort_lines_case_insensitive(
 7006        &mut self,
 7007        _: &SortLinesCaseInsensitive,
 7008        window: &mut Window,
 7009        cx: &mut Context<Self>,
 7010    ) {
 7011        self.manipulate_lines(window, cx, |lines| {
 7012            lines.sort_by_key(|line| line.to_lowercase())
 7013        })
 7014    }
 7015
 7016    pub fn unique_lines_case_insensitive(
 7017        &mut self,
 7018        _: &UniqueLinesCaseInsensitive,
 7019        window: &mut Window,
 7020        cx: &mut Context<Self>,
 7021    ) {
 7022        self.manipulate_lines(window, cx, |lines| {
 7023            let mut seen = HashSet::default();
 7024            lines.retain(|line| seen.insert(line.to_lowercase()));
 7025        })
 7026    }
 7027
 7028    pub fn unique_lines_case_sensitive(
 7029        &mut self,
 7030        _: &UniqueLinesCaseSensitive,
 7031        window: &mut Window,
 7032        cx: &mut Context<Self>,
 7033    ) {
 7034        self.manipulate_lines(window, cx, |lines| {
 7035            let mut seen = HashSet::default();
 7036            lines.retain(|line| seen.insert(*line));
 7037        })
 7038    }
 7039
 7040    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7041        let Some(project) = self.project.clone() else {
 7042            return;
 7043        };
 7044        self.reload(project, window, cx)
 7045            .detach_and_notify_err(window, cx);
 7046    }
 7047
 7048    pub fn restore_file(
 7049        &mut self,
 7050        _: &::git::RestoreFile,
 7051        window: &mut Window,
 7052        cx: &mut Context<Self>,
 7053    ) {
 7054        let mut buffer_ids = HashSet::default();
 7055        let snapshot = self.buffer().read(cx).snapshot(cx);
 7056        for selection in self.selections.all::<usize>(cx) {
 7057            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 7058        }
 7059
 7060        let buffer = self.buffer().read(cx);
 7061        let ranges = buffer_ids
 7062            .into_iter()
 7063            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 7064            .collect::<Vec<_>>();
 7065
 7066        self.restore_hunks_in_ranges(ranges, window, cx);
 7067    }
 7068
 7069    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 7070        let selections = self
 7071            .selections
 7072            .all(cx)
 7073            .into_iter()
 7074            .map(|s| s.range())
 7075            .collect();
 7076        self.restore_hunks_in_ranges(selections, window, cx);
 7077    }
 7078
 7079    fn restore_hunks_in_ranges(
 7080        &mut self,
 7081        ranges: Vec<Range<Point>>,
 7082        window: &mut Window,
 7083        cx: &mut Context<Editor>,
 7084    ) {
 7085        let mut revert_changes = HashMap::default();
 7086        let snapshot = self.buffer.read(cx).snapshot(cx);
 7087        let Some(project) = &self.project else {
 7088            return;
 7089        };
 7090
 7091        let chunk_by = self
 7092            .snapshot(window, cx)
 7093            .hunks_for_ranges(ranges.into_iter())
 7094            .into_iter()
 7095            .chunk_by(|hunk| hunk.buffer_id);
 7096        for (buffer_id, hunks) in &chunk_by {
 7097            let hunks = hunks.collect::<Vec<_>>();
 7098            for hunk in &hunks {
 7099                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 7100            }
 7101            Self::do_stage_or_unstage(project, false, buffer_id, hunks.into_iter(), &snapshot, cx);
 7102        }
 7103        drop(chunk_by);
 7104        if !revert_changes.is_empty() {
 7105            self.transact(window, cx, |editor, window, cx| {
 7106                editor.revert(revert_changes, window, cx);
 7107            });
 7108        }
 7109    }
 7110
 7111    pub fn open_active_item_in_terminal(
 7112        &mut self,
 7113        _: &OpenInTerminal,
 7114        window: &mut Window,
 7115        cx: &mut Context<Self>,
 7116    ) {
 7117        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7118            let project_path = buffer.read(cx).project_path(cx)?;
 7119            let project = self.project.as_ref()?.read(cx);
 7120            let entry = project.entry_for_path(&project_path, cx)?;
 7121            let parent = match &entry.canonical_path {
 7122                Some(canonical_path) => canonical_path.to_path_buf(),
 7123                None => project.absolute_path(&project_path, cx)?,
 7124            }
 7125            .parent()?
 7126            .to_path_buf();
 7127            Some(parent)
 7128        }) {
 7129            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7130        }
 7131    }
 7132
 7133    pub fn prepare_restore_change(
 7134        &self,
 7135        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7136        hunk: &MultiBufferDiffHunk,
 7137        cx: &mut App,
 7138    ) -> Option<()> {
 7139        let buffer = self.buffer.read(cx);
 7140        let diff = buffer.diff_for(hunk.buffer_id)?;
 7141        let buffer = buffer.buffer(hunk.buffer_id)?;
 7142        let buffer = buffer.read(cx);
 7143        let original_text = diff
 7144            .read(cx)
 7145            .base_text()
 7146            .as_ref()?
 7147            .as_rope()
 7148            .slice(hunk.diff_base_byte_range.clone());
 7149        let buffer_snapshot = buffer.snapshot();
 7150        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7151        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7152            probe
 7153                .0
 7154                .start
 7155                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7156                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7157        }) {
 7158            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7159            Some(())
 7160        } else {
 7161            None
 7162        }
 7163    }
 7164
 7165    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7166        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7167    }
 7168
 7169    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7170        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7171    }
 7172
 7173    fn manipulate_lines<Fn>(
 7174        &mut self,
 7175        window: &mut Window,
 7176        cx: &mut Context<Self>,
 7177        mut callback: Fn,
 7178    ) where
 7179        Fn: FnMut(&mut Vec<&str>),
 7180    {
 7181        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7182        let buffer = self.buffer.read(cx).snapshot(cx);
 7183
 7184        let mut edits = Vec::new();
 7185
 7186        let selections = self.selections.all::<Point>(cx);
 7187        let mut selections = selections.iter().peekable();
 7188        let mut contiguous_row_selections = Vec::new();
 7189        let mut new_selections = Vec::new();
 7190        let mut added_lines = 0;
 7191        let mut removed_lines = 0;
 7192
 7193        while let Some(selection) = selections.next() {
 7194            let (start_row, end_row) = consume_contiguous_rows(
 7195                &mut contiguous_row_selections,
 7196                selection,
 7197                &display_map,
 7198                &mut selections,
 7199            );
 7200
 7201            let start_point = Point::new(start_row.0, 0);
 7202            let end_point = Point::new(
 7203                end_row.previous_row().0,
 7204                buffer.line_len(end_row.previous_row()),
 7205            );
 7206            let text = buffer
 7207                .text_for_range(start_point..end_point)
 7208                .collect::<String>();
 7209
 7210            let mut lines = text.split('\n').collect_vec();
 7211
 7212            let lines_before = lines.len();
 7213            callback(&mut lines);
 7214            let lines_after = lines.len();
 7215
 7216            edits.push((start_point..end_point, lines.join("\n")));
 7217
 7218            // Selections must change based on added and removed line count
 7219            let start_row =
 7220                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7221            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7222            new_selections.push(Selection {
 7223                id: selection.id,
 7224                start: start_row,
 7225                end: end_row,
 7226                goal: SelectionGoal::None,
 7227                reversed: selection.reversed,
 7228            });
 7229
 7230            if lines_after > lines_before {
 7231                added_lines += lines_after - lines_before;
 7232            } else if lines_before > lines_after {
 7233                removed_lines += lines_before - lines_after;
 7234            }
 7235        }
 7236
 7237        self.transact(window, cx, |this, window, cx| {
 7238            let buffer = this.buffer.update(cx, |buffer, cx| {
 7239                buffer.edit(edits, None, cx);
 7240                buffer.snapshot(cx)
 7241            });
 7242
 7243            // Recalculate offsets on newly edited buffer
 7244            let new_selections = new_selections
 7245                .iter()
 7246                .map(|s| {
 7247                    let start_point = Point::new(s.start.0, 0);
 7248                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7249                    Selection {
 7250                        id: s.id,
 7251                        start: buffer.point_to_offset(start_point),
 7252                        end: buffer.point_to_offset(end_point),
 7253                        goal: s.goal,
 7254                        reversed: s.reversed,
 7255                    }
 7256                })
 7257                .collect();
 7258
 7259            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7260                s.select(new_selections);
 7261            });
 7262
 7263            this.request_autoscroll(Autoscroll::fit(), cx);
 7264        });
 7265    }
 7266
 7267    pub fn convert_to_upper_case(
 7268        &mut self,
 7269        _: &ConvertToUpperCase,
 7270        window: &mut Window,
 7271        cx: &mut Context<Self>,
 7272    ) {
 7273        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7274    }
 7275
 7276    pub fn convert_to_lower_case(
 7277        &mut self,
 7278        _: &ConvertToLowerCase,
 7279        window: &mut Window,
 7280        cx: &mut Context<Self>,
 7281    ) {
 7282        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7283    }
 7284
 7285    pub fn convert_to_title_case(
 7286        &mut self,
 7287        _: &ConvertToTitleCase,
 7288        window: &mut Window,
 7289        cx: &mut Context<Self>,
 7290    ) {
 7291        self.manipulate_text(window, cx, |text| {
 7292            text.split('\n')
 7293                .map(|line| line.to_case(Case::Title))
 7294                .join("\n")
 7295        })
 7296    }
 7297
 7298    pub fn convert_to_snake_case(
 7299        &mut self,
 7300        _: &ConvertToSnakeCase,
 7301        window: &mut Window,
 7302        cx: &mut Context<Self>,
 7303    ) {
 7304        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7305    }
 7306
 7307    pub fn convert_to_kebab_case(
 7308        &mut self,
 7309        _: &ConvertToKebabCase,
 7310        window: &mut Window,
 7311        cx: &mut Context<Self>,
 7312    ) {
 7313        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7314    }
 7315
 7316    pub fn convert_to_upper_camel_case(
 7317        &mut self,
 7318        _: &ConvertToUpperCamelCase,
 7319        window: &mut Window,
 7320        cx: &mut Context<Self>,
 7321    ) {
 7322        self.manipulate_text(window, cx, |text| {
 7323            text.split('\n')
 7324                .map(|line| line.to_case(Case::UpperCamel))
 7325                .join("\n")
 7326        })
 7327    }
 7328
 7329    pub fn convert_to_lower_camel_case(
 7330        &mut self,
 7331        _: &ConvertToLowerCamelCase,
 7332        window: &mut Window,
 7333        cx: &mut Context<Self>,
 7334    ) {
 7335        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7336    }
 7337
 7338    pub fn convert_to_opposite_case(
 7339        &mut self,
 7340        _: &ConvertToOppositeCase,
 7341        window: &mut Window,
 7342        cx: &mut Context<Self>,
 7343    ) {
 7344        self.manipulate_text(window, cx, |text| {
 7345            text.chars()
 7346                .fold(String::with_capacity(text.len()), |mut t, c| {
 7347                    if c.is_uppercase() {
 7348                        t.extend(c.to_lowercase());
 7349                    } else {
 7350                        t.extend(c.to_uppercase());
 7351                    }
 7352                    t
 7353                })
 7354        })
 7355    }
 7356
 7357    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7358    where
 7359        Fn: FnMut(&str) -> String,
 7360    {
 7361        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7362        let buffer = self.buffer.read(cx).snapshot(cx);
 7363
 7364        let mut new_selections = Vec::new();
 7365        let mut edits = Vec::new();
 7366        let mut selection_adjustment = 0i32;
 7367
 7368        for selection in self.selections.all::<usize>(cx) {
 7369            let selection_is_empty = selection.is_empty();
 7370
 7371            let (start, end) = if selection_is_empty {
 7372                let word_range = movement::surrounding_word(
 7373                    &display_map,
 7374                    selection.start.to_display_point(&display_map),
 7375                );
 7376                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7377                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7378                (start, end)
 7379            } else {
 7380                (selection.start, selection.end)
 7381            };
 7382
 7383            let text = buffer.text_for_range(start..end).collect::<String>();
 7384            let old_length = text.len() as i32;
 7385            let text = callback(&text);
 7386
 7387            new_selections.push(Selection {
 7388                start: (start as i32 - selection_adjustment) as usize,
 7389                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7390                goal: SelectionGoal::None,
 7391                ..selection
 7392            });
 7393
 7394            selection_adjustment += old_length - text.len() as i32;
 7395
 7396            edits.push((start..end, text));
 7397        }
 7398
 7399        self.transact(window, cx, |this, window, cx| {
 7400            this.buffer.update(cx, |buffer, cx| {
 7401                buffer.edit(edits, None, cx);
 7402            });
 7403
 7404            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7405                s.select(new_selections);
 7406            });
 7407
 7408            this.request_autoscroll(Autoscroll::fit(), cx);
 7409        });
 7410    }
 7411
 7412    pub fn duplicate(
 7413        &mut self,
 7414        upwards: bool,
 7415        whole_lines: bool,
 7416        window: &mut Window,
 7417        cx: &mut Context<Self>,
 7418    ) {
 7419        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7420        let buffer = &display_map.buffer_snapshot;
 7421        let selections = self.selections.all::<Point>(cx);
 7422
 7423        let mut edits = Vec::new();
 7424        let mut selections_iter = selections.iter().peekable();
 7425        while let Some(selection) = selections_iter.next() {
 7426            let mut rows = selection.spanned_rows(false, &display_map);
 7427            // duplicate line-wise
 7428            if whole_lines || selection.start == selection.end {
 7429                // Avoid duplicating the same lines twice.
 7430                while let Some(next_selection) = selections_iter.peek() {
 7431                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7432                    if next_rows.start < rows.end {
 7433                        rows.end = next_rows.end;
 7434                        selections_iter.next().unwrap();
 7435                    } else {
 7436                        break;
 7437                    }
 7438                }
 7439
 7440                // Copy the text from the selected row region and splice it either at the start
 7441                // or end of the region.
 7442                let start = Point::new(rows.start.0, 0);
 7443                let end = Point::new(
 7444                    rows.end.previous_row().0,
 7445                    buffer.line_len(rows.end.previous_row()),
 7446                );
 7447                let text = buffer
 7448                    .text_for_range(start..end)
 7449                    .chain(Some("\n"))
 7450                    .collect::<String>();
 7451                let insert_location = if upwards {
 7452                    Point::new(rows.end.0, 0)
 7453                } else {
 7454                    start
 7455                };
 7456                edits.push((insert_location..insert_location, text));
 7457            } else {
 7458                // duplicate character-wise
 7459                let start = selection.start;
 7460                let end = selection.end;
 7461                let text = buffer.text_for_range(start..end).collect::<String>();
 7462                edits.push((selection.end..selection.end, text));
 7463            }
 7464        }
 7465
 7466        self.transact(window, cx, |this, _, cx| {
 7467            this.buffer.update(cx, |buffer, cx| {
 7468                buffer.edit(edits, None, cx);
 7469            });
 7470
 7471            this.request_autoscroll(Autoscroll::fit(), cx);
 7472        });
 7473    }
 7474
 7475    pub fn duplicate_line_up(
 7476        &mut self,
 7477        _: &DuplicateLineUp,
 7478        window: &mut Window,
 7479        cx: &mut Context<Self>,
 7480    ) {
 7481        self.duplicate(true, true, window, cx);
 7482    }
 7483
 7484    pub fn duplicate_line_down(
 7485        &mut self,
 7486        _: &DuplicateLineDown,
 7487        window: &mut Window,
 7488        cx: &mut Context<Self>,
 7489    ) {
 7490        self.duplicate(false, true, window, cx);
 7491    }
 7492
 7493    pub fn duplicate_selection(
 7494        &mut self,
 7495        _: &DuplicateSelection,
 7496        window: &mut Window,
 7497        cx: &mut Context<Self>,
 7498    ) {
 7499        self.duplicate(false, false, window, cx);
 7500    }
 7501
 7502    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7503        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7504        let buffer = self.buffer.read(cx).snapshot(cx);
 7505
 7506        let mut edits = Vec::new();
 7507        let mut unfold_ranges = Vec::new();
 7508        let mut refold_creases = Vec::new();
 7509
 7510        let selections = self.selections.all::<Point>(cx);
 7511        let mut selections = selections.iter().peekable();
 7512        let mut contiguous_row_selections = Vec::new();
 7513        let mut new_selections = Vec::new();
 7514
 7515        while let Some(selection) = selections.next() {
 7516            // Find all the selections that span a contiguous row range
 7517            let (start_row, end_row) = consume_contiguous_rows(
 7518                &mut contiguous_row_selections,
 7519                selection,
 7520                &display_map,
 7521                &mut selections,
 7522            );
 7523
 7524            // Move the text spanned by the row range to be before the line preceding the row range
 7525            if start_row.0 > 0 {
 7526                let range_to_move = Point::new(
 7527                    start_row.previous_row().0,
 7528                    buffer.line_len(start_row.previous_row()),
 7529                )
 7530                    ..Point::new(
 7531                        end_row.previous_row().0,
 7532                        buffer.line_len(end_row.previous_row()),
 7533                    );
 7534                let insertion_point = display_map
 7535                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7536                    .0;
 7537
 7538                // Don't move lines across excerpts
 7539                if buffer
 7540                    .excerpt_containing(insertion_point..range_to_move.end)
 7541                    .is_some()
 7542                {
 7543                    let text = buffer
 7544                        .text_for_range(range_to_move.clone())
 7545                        .flat_map(|s| s.chars())
 7546                        .skip(1)
 7547                        .chain(['\n'])
 7548                        .collect::<String>();
 7549
 7550                    edits.push((
 7551                        buffer.anchor_after(range_to_move.start)
 7552                            ..buffer.anchor_before(range_to_move.end),
 7553                        String::new(),
 7554                    ));
 7555                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7556                    edits.push((insertion_anchor..insertion_anchor, text));
 7557
 7558                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7559
 7560                    // Move selections up
 7561                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7562                        |mut selection| {
 7563                            selection.start.row -= row_delta;
 7564                            selection.end.row -= row_delta;
 7565                            selection
 7566                        },
 7567                    ));
 7568
 7569                    // Move folds up
 7570                    unfold_ranges.push(range_to_move.clone());
 7571                    for fold in display_map.folds_in_range(
 7572                        buffer.anchor_before(range_to_move.start)
 7573                            ..buffer.anchor_after(range_to_move.end),
 7574                    ) {
 7575                        let mut start = fold.range.start.to_point(&buffer);
 7576                        let mut end = fold.range.end.to_point(&buffer);
 7577                        start.row -= row_delta;
 7578                        end.row -= row_delta;
 7579                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7580                    }
 7581                }
 7582            }
 7583
 7584            // If we didn't move line(s), preserve the existing selections
 7585            new_selections.append(&mut contiguous_row_selections);
 7586        }
 7587
 7588        self.transact(window, cx, |this, window, cx| {
 7589            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7590            this.buffer.update(cx, |buffer, cx| {
 7591                for (range, text) in edits {
 7592                    buffer.edit([(range, text)], None, cx);
 7593                }
 7594            });
 7595            this.fold_creases(refold_creases, true, window, cx);
 7596            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7597                s.select(new_selections);
 7598            })
 7599        });
 7600    }
 7601
 7602    pub fn move_line_down(
 7603        &mut self,
 7604        _: &MoveLineDown,
 7605        window: &mut Window,
 7606        cx: &mut Context<Self>,
 7607    ) {
 7608        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7609        let buffer = self.buffer.read(cx).snapshot(cx);
 7610
 7611        let mut edits = Vec::new();
 7612        let mut unfold_ranges = Vec::new();
 7613        let mut refold_creases = Vec::new();
 7614
 7615        let selections = self.selections.all::<Point>(cx);
 7616        let mut selections = selections.iter().peekable();
 7617        let mut contiguous_row_selections = Vec::new();
 7618        let mut new_selections = Vec::new();
 7619
 7620        while let Some(selection) = selections.next() {
 7621            // Find all the selections that span a contiguous row range
 7622            let (start_row, end_row) = consume_contiguous_rows(
 7623                &mut contiguous_row_selections,
 7624                selection,
 7625                &display_map,
 7626                &mut selections,
 7627            );
 7628
 7629            // Move the text spanned by the row range to be after the last line of the row range
 7630            if end_row.0 <= buffer.max_point().row {
 7631                let range_to_move =
 7632                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7633                let insertion_point = display_map
 7634                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7635                    .0;
 7636
 7637                // Don't move lines across excerpt boundaries
 7638                if buffer
 7639                    .excerpt_containing(range_to_move.start..insertion_point)
 7640                    .is_some()
 7641                {
 7642                    let mut text = String::from("\n");
 7643                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7644                    text.pop(); // Drop trailing newline
 7645                    edits.push((
 7646                        buffer.anchor_after(range_to_move.start)
 7647                            ..buffer.anchor_before(range_to_move.end),
 7648                        String::new(),
 7649                    ));
 7650                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7651                    edits.push((insertion_anchor..insertion_anchor, text));
 7652
 7653                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7654
 7655                    // Move selections down
 7656                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7657                        |mut selection| {
 7658                            selection.start.row += row_delta;
 7659                            selection.end.row += row_delta;
 7660                            selection
 7661                        },
 7662                    ));
 7663
 7664                    // Move folds down
 7665                    unfold_ranges.push(range_to_move.clone());
 7666                    for fold in display_map.folds_in_range(
 7667                        buffer.anchor_before(range_to_move.start)
 7668                            ..buffer.anchor_after(range_to_move.end),
 7669                    ) {
 7670                        let mut start = fold.range.start.to_point(&buffer);
 7671                        let mut end = fold.range.end.to_point(&buffer);
 7672                        start.row += row_delta;
 7673                        end.row += row_delta;
 7674                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7675                    }
 7676                }
 7677            }
 7678
 7679            // If we didn't move line(s), preserve the existing selections
 7680            new_selections.append(&mut contiguous_row_selections);
 7681        }
 7682
 7683        self.transact(window, cx, |this, window, cx| {
 7684            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7685            this.buffer.update(cx, |buffer, cx| {
 7686                for (range, text) in edits {
 7687                    buffer.edit([(range, text)], None, cx);
 7688                }
 7689            });
 7690            this.fold_creases(refold_creases, true, window, cx);
 7691            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7692                s.select(new_selections)
 7693            });
 7694        });
 7695    }
 7696
 7697    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7698        let text_layout_details = &self.text_layout_details(window);
 7699        self.transact(window, cx, |this, window, cx| {
 7700            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7701                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7702                let line_mode = s.line_mode;
 7703                s.move_with(|display_map, selection| {
 7704                    if !selection.is_empty() || line_mode {
 7705                        return;
 7706                    }
 7707
 7708                    let mut head = selection.head();
 7709                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7710                    if head.column() == display_map.line_len(head.row()) {
 7711                        transpose_offset = display_map
 7712                            .buffer_snapshot
 7713                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7714                    }
 7715
 7716                    if transpose_offset == 0 {
 7717                        return;
 7718                    }
 7719
 7720                    *head.column_mut() += 1;
 7721                    head = display_map.clip_point(head, Bias::Right);
 7722                    let goal = SelectionGoal::HorizontalPosition(
 7723                        display_map
 7724                            .x_for_display_point(head, text_layout_details)
 7725                            .into(),
 7726                    );
 7727                    selection.collapse_to(head, goal);
 7728
 7729                    let transpose_start = display_map
 7730                        .buffer_snapshot
 7731                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7732                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7733                        let transpose_end = display_map
 7734                            .buffer_snapshot
 7735                            .clip_offset(transpose_offset + 1, Bias::Right);
 7736                        if let Some(ch) =
 7737                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7738                        {
 7739                            edits.push((transpose_start..transpose_offset, String::new()));
 7740                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7741                        }
 7742                    }
 7743                });
 7744                edits
 7745            });
 7746            this.buffer
 7747                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7748            let selections = this.selections.all::<usize>(cx);
 7749            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7750                s.select(selections);
 7751            });
 7752        });
 7753    }
 7754
 7755    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7756        self.rewrap_impl(IsVimMode::No, cx)
 7757    }
 7758
 7759    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7760        let buffer = self.buffer.read(cx).snapshot(cx);
 7761        let selections = self.selections.all::<Point>(cx);
 7762        let mut selections = selections.iter().peekable();
 7763
 7764        let mut edits = Vec::new();
 7765        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7766
 7767        while let Some(selection) = selections.next() {
 7768            let mut start_row = selection.start.row;
 7769            let mut end_row = selection.end.row;
 7770
 7771            // Skip selections that overlap with a range that has already been rewrapped.
 7772            let selection_range = start_row..end_row;
 7773            if rewrapped_row_ranges
 7774                .iter()
 7775                .any(|range| range.overlaps(&selection_range))
 7776            {
 7777                continue;
 7778            }
 7779
 7780            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7781
 7782            // Since not all lines in the selection may be at the same indent
 7783            // level, choose the indent size that is the most common between all
 7784            // of the lines.
 7785            //
 7786            // If there is a tie, we use the deepest indent.
 7787            let (indent_size, indent_end) = {
 7788                let mut indent_size_occurrences = HashMap::default();
 7789                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7790
 7791                for row in start_row..=end_row {
 7792                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7793                    rows_by_indent_size.entry(indent).or_default().push(row);
 7794                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7795                }
 7796
 7797                let indent_size = indent_size_occurrences
 7798                    .into_iter()
 7799                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7800                    .map(|(indent, _)| indent)
 7801                    .unwrap_or_default();
 7802                let row = rows_by_indent_size[&indent_size][0];
 7803                let indent_end = Point::new(row, indent_size.len);
 7804
 7805                (indent_size, indent_end)
 7806            };
 7807
 7808            let mut line_prefix = indent_size.chars().collect::<String>();
 7809
 7810            let mut inside_comment = false;
 7811            if let Some(comment_prefix) =
 7812                buffer
 7813                    .language_scope_at(selection.head())
 7814                    .and_then(|language| {
 7815                        language
 7816                            .line_comment_prefixes()
 7817                            .iter()
 7818                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7819                            .cloned()
 7820                    })
 7821            {
 7822                line_prefix.push_str(&comment_prefix);
 7823                inside_comment = true;
 7824            }
 7825
 7826            let language_settings = buffer.settings_at(selection.head(), cx);
 7827            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 7828                RewrapBehavior::InComments => inside_comment,
 7829                RewrapBehavior::InSelections => !selection.is_empty(),
 7830                RewrapBehavior::Anywhere => true,
 7831            };
 7832
 7833            let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
 7834            if !should_rewrap {
 7835                continue;
 7836            }
 7837
 7838            if selection.is_empty() {
 7839                'expand_upwards: while start_row > 0 {
 7840                    let prev_row = start_row - 1;
 7841                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7842                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7843                    {
 7844                        start_row = prev_row;
 7845                    } else {
 7846                        break 'expand_upwards;
 7847                    }
 7848                }
 7849
 7850                'expand_downwards: while end_row < buffer.max_point().row {
 7851                    let next_row = end_row + 1;
 7852                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7853                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7854                    {
 7855                        end_row = next_row;
 7856                    } else {
 7857                        break 'expand_downwards;
 7858                    }
 7859                }
 7860            }
 7861
 7862            let start = Point::new(start_row, 0);
 7863            let start_offset = start.to_offset(&buffer);
 7864            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7865            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7866            let Some(lines_without_prefixes) = selection_text
 7867                .lines()
 7868                .map(|line| {
 7869                    line.strip_prefix(&line_prefix)
 7870                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7871                        .ok_or_else(|| {
 7872                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7873                        })
 7874                })
 7875                .collect::<Result<Vec<_>, _>>()
 7876                .log_err()
 7877            else {
 7878                continue;
 7879            };
 7880
 7881            let wrap_column = buffer
 7882                .settings_at(Point::new(start_row, 0), cx)
 7883                .preferred_line_length as usize;
 7884            let wrapped_text = wrap_with_prefix(
 7885                line_prefix,
 7886                lines_without_prefixes.join(" "),
 7887                wrap_column,
 7888                tab_size,
 7889            );
 7890
 7891            // TODO: should always use char-based diff while still supporting cursor behavior that
 7892            // matches vim.
 7893            let mut diff_options = DiffOptions::default();
 7894            if is_vim_mode == IsVimMode::Yes {
 7895                diff_options.max_word_diff_len = 0;
 7896                diff_options.max_word_diff_line_count = 0;
 7897            } else {
 7898                diff_options.max_word_diff_len = usize::MAX;
 7899                diff_options.max_word_diff_line_count = usize::MAX;
 7900            }
 7901
 7902            for (old_range, new_text) in
 7903                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 7904            {
 7905                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 7906                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 7907                edits.push((edit_start..edit_end, new_text));
 7908            }
 7909
 7910            rewrapped_row_ranges.push(start_row..=end_row);
 7911        }
 7912
 7913        self.buffer
 7914            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7915    }
 7916
 7917    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7918        let mut text = String::new();
 7919        let buffer = self.buffer.read(cx).snapshot(cx);
 7920        let mut selections = self.selections.all::<Point>(cx);
 7921        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7922        {
 7923            let max_point = buffer.max_point();
 7924            let mut is_first = true;
 7925            for selection in &mut selections {
 7926                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7927                if is_entire_line {
 7928                    selection.start = Point::new(selection.start.row, 0);
 7929                    if !selection.is_empty() && selection.end.column == 0 {
 7930                        selection.end = cmp::min(max_point, selection.end);
 7931                    } else {
 7932                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7933                    }
 7934                    selection.goal = SelectionGoal::None;
 7935                }
 7936                if is_first {
 7937                    is_first = false;
 7938                } else {
 7939                    text += "\n";
 7940                }
 7941                let mut len = 0;
 7942                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7943                    text.push_str(chunk);
 7944                    len += chunk.len();
 7945                }
 7946                clipboard_selections.push(ClipboardSelection {
 7947                    len,
 7948                    is_entire_line,
 7949                    start_column: selection.start.column,
 7950                });
 7951            }
 7952        }
 7953
 7954        self.transact(window, cx, |this, window, cx| {
 7955            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7956                s.select(selections);
 7957            });
 7958            this.insert("", window, cx);
 7959        });
 7960        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7961    }
 7962
 7963    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7964        let item = self.cut_common(window, cx);
 7965        cx.write_to_clipboard(item);
 7966    }
 7967
 7968    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7969        self.change_selections(None, window, cx, |s| {
 7970            s.move_with(|snapshot, sel| {
 7971                if sel.is_empty() {
 7972                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7973                }
 7974            });
 7975        });
 7976        let item = self.cut_common(window, cx);
 7977        cx.set_global(KillRing(item))
 7978    }
 7979
 7980    pub fn kill_ring_yank(
 7981        &mut self,
 7982        _: &KillRingYank,
 7983        window: &mut Window,
 7984        cx: &mut Context<Self>,
 7985    ) {
 7986        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7987            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7988                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7989            } else {
 7990                return;
 7991            }
 7992        } else {
 7993            return;
 7994        };
 7995        self.do_paste(&text, metadata, false, window, cx);
 7996    }
 7997
 7998    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7999        let selections = self.selections.all::<Point>(cx);
 8000        let buffer = self.buffer.read(cx).read(cx);
 8001        let mut text = String::new();
 8002
 8003        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8004        {
 8005            let max_point = buffer.max_point();
 8006            let mut is_first = true;
 8007            for selection in selections.iter() {
 8008                let mut start = selection.start;
 8009                let mut end = selection.end;
 8010                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8011                if is_entire_line {
 8012                    start = Point::new(start.row, 0);
 8013                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8014                }
 8015                if is_first {
 8016                    is_first = false;
 8017                } else {
 8018                    text += "\n";
 8019                }
 8020                let mut len = 0;
 8021                for chunk in buffer.text_for_range(start..end) {
 8022                    text.push_str(chunk);
 8023                    len += chunk.len();
 8024                }
 8025                clipboard_selections.push(ClipboardSelection {
 8026                    len,
 8027                    is_entire_line,
 8028                    start_column: start.column,
 8029                });
 8030            }
 8031        }
 8032
 8033        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8034            text,
 8035            clipboard_selections,
 8036        ));
 8037    }
 8038
 8039    pub fn do_paste(
 8040        &mut self,
 8041        text: &String,
 8042        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8043        handle_entire_lines: bool,
 8044        window: &mut Window,
 8045        cx: &mut Context<Self>,
 8046    ) {
 8047        if self.read_only(cx) {
 8048            return;
 8049        }
 8050
 8051        let clipboard_text = Cow::Borrowed(text);
 8052
 8053        self.transact(window, cx, |this, window, cx| {
 8054            if let Some(mut clipboard_selections) = clipboard_selections {
 8055                let old_selections = this.selections.all::<usize>(cx);
 8056                let all_selections_were_entire_line =
 8057                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8058                let first_selection_start_column =
 8059                    clipboard_selections.first().map(|s| s.start_column);
 8060                if clipboard_selections.len() != old_selections.len() {
 8061                    clipboard_selections.drain(..);
 8062                }
 8063                let cursor_offset = this.selections.last::<usize>(cx).head();
 8064                let mut auto_indent_on_paste = true;
 8065
 8066                this.buffer.update(cx, |buffer, cx| {
 8067                    let snapshot = buffer.read(cx);
 8068                    auto_indent_on_paste =
 8069                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 8070
 8071                    let mut start_offset = 0;
 8072                    let mut edits = Vec::new();
 8073                    let mut original_start_columns = Vec::new();
 8074                    for (ix, selection) in old_selections.iter().enumerate() {
 8075                        let to_insert;
 8076                        let entire_line;
 8077                        let original_start_column;
 8078                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8079                            let end_offset = start_offset + clipboard_selection.len;
 8080                            to_insert = &clipboard_text[start_offset..end_offset];
 8081                            entire_line = clipboard_selection.is_entire_line;
 8082                            start_offset = end_offset + 1;
 8083                            original_start_column = Some(clipboard_selection.start_column);
 8084                        } else {
 8085                            to_insert = clipboard_text.as_str();
 8086                            entire_line = all_selections_were_entire_line;
 8087                            original_start_column = first_selection_start_column
 8088                        }
 8089
 8090                        // If the corresponding selection was empty when this slice of the
 8091                        // clipboard text was written, then the entire line containing the
 8092                        // selection was copied. If this selection is also currently empty,
 8093                        // then paste the line before the current line of the buffer.
 8094                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8095                            let column = selection.start.to_point(&snapshot).column as usize;
 8096                            let line_start = selection.start - column;
 8097                            line_start..line_start
 8098                        } else {
 8099                            selection.range()
 8100                        };
 8101
 8102                        edits.push((range, to_insert));
 8103                        original_start_columns.extend(original_start_column);
 8104                    }
 8105                    drop(snapshot);
 8106
 8107                    buffer.edit(
 8108                        edits,
 8109                        if auto_indent_on_paste {
 8110                            Some(AutoindentMode::Block {
 8111                                original_start_columns,
 8112                            })
 8113                        } else {
 8114                            None
 8115                        },
 8116                        cx,
 8117                    );
 8118                });
 8119
 8120                let selections = this.selections.all::<usize>(cx);
 8121                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8122                    s.select(selections)
 8123                });
 8124            } else {
 8125                this.insert(&clipboard_text, window, cx);
 8126            }
 8127        });
 8128    }
 8129
 8130    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8131        if let Some(item) = cx.read_from_clipboard() {
 8132            let entries = item.entries();
 8133
 8134            match entries.first() {
 8135                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8136                // of all the pasted entries.
 8137                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8138                    .do_paste(
 8139                        clipboard_string.text(),
 8140                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8141                        true,
 8142                        window,
 8143                        cx,
 8144                    ),
 8145                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8146            }
 8147        }
 8148    }
 8149
 8150    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8151        if self.read_only(cx) {
 8152            return;
 8153        }
 8154
 8155        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8156            if let Some((selections, _)) =
 8157                self.selection_history.transaction(transaction_id).cloned()
 8158            {
 8159                self.change_selections(None, window, cx, |s| {
 8160                    s.select_anchors(selections.to_vec());
 8161                });
 8162            }
 8163            self.request_autoscroll(Autoscroll::fit(), cx);
 8164            self.unmark_text(window, cx);
 8165            self.refresh_inline_completion(true, false, window, cx);
 8166            cx.emit(EditorEvent::Edited { transaction_id });
 8167            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8168        }
 8169    }
 8170
 8171    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8172        if self.read_only(cx) {
 8173            return;
 8174        }
 8175
 8176        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8177            if let Some((_, Some(selections))) =
 8178                self.selection_history.transaction(transaction_id).cloned()
 8179            {
 8180                self.change_selections(None, window, cx, |s| {
 8181                    s.select_anchors(selections.to_vec());
 8182                });
 8183            }
 8184            self.request_autoscroll(Autoscroll::fit(), cx);
 8185            self.unmark_text(window, cx);
 8186            self.refresh_inline_completion(true, false, window, cx);
 8187            cx.emit(EditorEvent::Edited { transaction_id });
 8188        }
 8189    }
 8190
 8191    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8192        self.buffer
 8193            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8194    }
 8195
 8196    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8197        self.buffer
 8198            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8199    }
 8200
 8201    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8202        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8203            let line_mode = s.line_mode;
 8204            s.move_with(|map, selection| {
 8205                let cursor = if selection.is_empty() && !line_mode {
 8206                    movement::left(map, selection.start)
 8207                } else {
 8208                    selection.start
 8209                };
 8210                selection.collapse_to(cursor, SelectionGoal::None);
 8211            });
 8212        })
 8213    }
 8214
 8215    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8216        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8217            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8218        })
 8219    }
 8220
 8221    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8222        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8223            let line_mode = s.line_mode;
 8224            s.move_with(|map, selection| {
 8225                let cursor = if selection.is_empty() && !line_mode {
 8226                    movement::right(map, selection.end)
 8227                } else {
 8228                    selection.end
 8229                };
 8230                selection.collapse_to(cursor, SelectionGoal::None)
 8231            });
 8232        })
 8233    }
 8234
 8235    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8236        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8237            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8238        })
 8239    }
 8240
 8241    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8242        if self.take_rename(true, window, cx).is_some() {
 8243            return;
 8244        }
 8245
 8246        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8247            cx.propagate();
 8248            return;
 8249        }
 8250
 8251        let text_layout_details = &self.text_layout_details(window);
 8252        let selection_count = self.selections.count();
 8253        let first_selection = self.selections.first_anchor();
 8254
 8255        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8256            let line_mode = s.line_mode;
 8257            s.move_with(|map, selection| {
 8258                if !selection.is_empty() && !line_mode {
 8259                    selection.goal = SelectionGoal::None;
 8260                }
 8261                let (cursor, goal) = movement::up(
 8262                    map,
 8263                    selection.start,
 8264                    selection.goal,
 8265                    false,
 8266                    text_layout_details,
 8267                );
 8268                selection.collapse_to(cursor, goal);
 8269            });
 8270        });
 8271
 8272        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8273        {
 8274            cx.propagate();
 8275        }
 8276    }
 8277
 8278    pub fn move_up_by_lines(
 8279        &mut self,
 8280        action: &MoveUpByLines,
 8281        window: &mut Window,
 8282        cx: &mut Context<Self>,
 8283    ) {
 8284        if self.take_rename(true, window, cx).is_some() {
 8285            return;
 8286        }
 8287
 8288        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8289            cx.propagate();
 8290            return;
 8291        }
 8292
 8293        let text_layout_details = &self.text_layout_details(window);
 8294
 8295        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8296            let line_mode = s.line_mode;
 8297            s.move_with(|map, selection| {
 8298                if !selection.is_empty() && !line_mode {
 8299                    selection.goal = SelectionGoal::None;
 8300                }
 8301                let (cursor, goal) = movement::up_by_rows(
 8302                    map,
 8303                    selection.start,
 8304                    action.lines,
 8305                    selection.goal,
 8306                    false,
 8307                    text_layout_details,
 8308                );
 8309                selection.collapse_to(cursor, goal);
 8310            });
 8311        })
 8312    }
 8313
 8314    pub fn move_down_by_lines(
 8315        &mut self,
 8316        action: &MoveDownByLines,
 8317        window: &mut Window,
 8318        cx: &mut Context<Self>,
 8319    ) {
 8320        if self.take_rename(true, window, cx).is_some() {
 8321            return;
 8322        }
 8323
 8324        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8325            cx.propagate();
 8326            return;
 8327        }
 8328
 8329        let text_layout_details = &self.text_layout_details(window);
 8330
 8331        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8332            let line_mode = s.line_mode;
 8333            s.move_with(|map, selection| {
 8334                if !selection.is_empty() && !line_mode {
 8335                    selection.goal = SelectionGoal::None;
 8336                }
 8337                let (cursor, goal) = movement::down_by_rows(
 8338                    map,
 8339                    selection.start,
 8340                    action.lines,
 8341                    selection.goal,
 8342                    false,
 8343                    text_layout_details,
 8344                );
 8345                selection.collapse_to(cursor, goal);
 8346            });
 8347        })
 8348    }
 8349
 8350    pub fn select_down_by_lines(
 8351        &mut self,
 8352        action: &SelectDownByLines,
 8353        window: &mut Window,
 8354        cx: &mut Context<Self>,
 8355    ) {
 8356        let text_layout_details = &self.text_layout_details(window);
 8357        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8358            s.move_heads_with(|map, head, goal| {
 8359                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8360            })
 8361        })
 8362    }
 8363
 8364    pub fn select_up_by_lines(
 8365        &mut self,
 8366        action: &SelectUpByLines,
 8367        window: &mut Window,
 8368        cx: &mut Context<Self>,
 8369    ) {
 8370        let text_layout_details = &self.text_layout_details(window);
 8371        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8372            s.move_heads_with(|map, head, goal| {
 8373                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8374            })
 8375        })
 8376    }
 8377
 8378    pub fn select_page_up(
 8379        &mut self,
 8380        _: &SelectPageUp,
 8381        window: &mut Window,
 8382        cx: &mut Context<Self>,
 8383    ) {
 8384        let Some(row_count) = self.visible_row_count() else {
 8385            return;
 8386        };
 8387
 8388        let text_layout_details = &self.text_layout_details(window);
 8389
 8390        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8391            s.move_heads_with(|map, head, goal| {
 8392                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8393            })
 8394        })
 8395    }
 8396
 8397    pub fn move_page_up(
 8398        &mut self,
 8399        action: &MovePageUp,
 8400        window: &mut Window,
 8401        cx: &mut Context<Self>,
 8402    ) {
 8403        if self.take_rename(true, window, cx).is_some() {
 8404            return;
 8405        }
 8406
 8407        if self
 8408            .context_menu
 8409            .borrow_mut()
 8410            .as_mut()
 8411            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8412            .unwrap_or(false)
 8413        {
 8414            return;
 8415        }
 8416
 8417        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8418            cx.propagate();
 8419            return;
 8420        }
 8421
 8422        let Some(row_count) = self.visible_row_count() else {
 8423            return;
 8424        };
 8425
 8426        let autoscroll = if action.center_cursor {
 8427            Autoscroll::center()
 8428        } else {
 8429            Autoscroll::fit()
 8430        };
 8431
 8432        let text_layout_details = &self.text_layout_details(window);
 8433
 8434        self.change_selections(Some(autoscroll), window, cx, |s| {
 8435            let line_mode = s.line_mode;
 8436            s.move_with(|map, selection| {
 8437                if !selection.is_empty() && !line_mode {
 8438                    selection.goal = SelectionGoal::None;
 8439                }
 8440                let (cursor, goal) = movement::up_by_rows(
 8441                    map,
 8442                    selection.end,
 8443                    row_count,
 8444                    selection.goal,
 8445                    false,
 8446                    text_layout_details,
 8447                );
 8448                selection.collapse_to(cursor, goal);
 8449            });
 8450        });
 8451    }
 8452
 8453    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8454        let text_layout_details = &self.text_layout_details(window);
 8455        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8456            s.move_heads_with(|map, head, goal| {
 8457                movement::up(map, head, goal, false, text_layout_details)
 8458            })
 8459        })
 8460    }
 8461
 8462    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8463        self.take_rename(true, window, cx);
 8464
 8465        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8466            cx.propagate();
 8467            return;
 8468        }
 8469
 8470        let text_layout_details = &self.text_layout_details(window);
 8471        let selection_count = self.selections.count();
 8472        let first_selection = self.selections.first_anchor();
 8473
 8474        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8475            let line_mode = s.line_mode;
 8476            s.move_with(|map, selection| {
 8477                if !selection.is_empty() && !line_mode {
 8478                    selection.goal = SelectionGoal::None;
 8479                }
 8480                let (cursor, goal) = movement::down(
 8481                    map,
 8482                    selection.end,
 8483                    selection.goal,
 8484                    false,
 8485                    text_layout_details,
 8486                );
 8487                selection.collapse_to(cursor, goal);
 8488            });
 8489        });
 8490
 8491        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8492        {
 8493            cx.propagate();
 8494        }
 8495    }
 8496
 8497    pub fn select_page_down(
 8498        &mut self,
 8499        _: &SelectPageDown,
 8500        window: &mut Window,
 8501        cx: &mut Context<Self>,
 8502    ) {
 8503        let Some(row_count) = self.visible_row_count() else {
 8504            return;
 8505        };
 8506
 8507        let text_layout_details = &self.text_layout_details(window);
 8508
 8509        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8510            s.move_heads_with(|map, head, goal| {
 8511                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8512            })
 8513        })
 8514    }
 8515
 8516    pub fn move_page_down(
 8517        &mut self,
 8518        action: &MovePageDown,
 8519        window: &mut Window,
 8520        cx: &mut Context<Self>,
 8521    ) {
 8522        if self.take_rename(true, window, cx).is_some() {
 8523            return;
 8524        }
 8525
 8526        if self
 8527            .context_menu
 8528            .borrow_mut()
 8529            .as_mut()
 8530            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8531            .unwrap_or(false)
 8532        {
 8533            return;
 8534        }
 8535
 8536        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8537            cx.propagate();
 8538            return;
 8539        }
 8540
 8541        let Some(row_count) = self.visible_row_count() else {
 8542            return;
 8543        };
 8544
 8545        let autoscroll = if action.center_cursor {
 8546            Autoscroll::center()
 8547        } else {
 8548            Autoscroll::fit()
 8549        };
 8550
 8551        let text_layout_details = &self.text_layout_details(window);
 8552        self.change_selections(Some(autoscroll), window, cx, |s| {
 8553            let line_mode = s.line_mode;
 8554            s.move_with(|map, selection| {
 8555                if !selection.is_empty() && !line_mode {
 8556                    selection.goal = SelectionGoal::None;
 8557                }
 8558                let (cursor, goal) = movement::down_by_rows(
 8559                    map,
 8560                    selection.end,
 8561                    row_count,
 8562                    selection.goal,
 8563                    false,
 8564                    text_layout_details,
 8565                );
 8566                selection.collapse_to(cursor, goal);
 8567            });
 8568        });
 8569    }
 8570
 8571    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8572        let text_layout_details = &self.text_layout_details(window);
 8573        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8574            s.move_heads_with(|map, head, goal| {
 8575                movement::down(map, head, goal, false, text_layout_details)
 8576            })
 8577        });
 8578    }
 8579
 8580    pub fn context_menu_first(
 8581        &mut self,
 8582        _: &ContextMenuFirst,
 8583        _window: &mut Window,
 8584        cx: &mut Context<Self>,
 8585    ) {
 8586        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8587            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8588        }
 8589    }
 8590
 8591    pub fn context_menu_prev(
 8592        &mut self,
 8593        _: &ContextMenuPrev,
 8594        _window: &mut Window,
 8595        cx: &mut Context<Self>,
 8596    ) {
 8597        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8598            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8599        }
 8600    }
 8601
 8602    pub fn context_menu_next(
 8603        &mut self,
 8604        _: &ContextMenuNext,
 8605        _window: &mut Window,
 8606        cx: &mut Context<Self>,
 8607    ) {
 8608        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8609            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8610        }
 8611    }
 8612
 8613    pub fn context_menu_last(
 8614        &mut self,
 8615        _: &ContextMenuLast,
 8616        _window: &mut Window,
 8617        cx: &mut Context<Self>,
 8618    ) {
 8619        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8620            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8621        }
 8622    }
 8623
 8624    pub fn move_to_previous_word_start(
 8625        &mut self,
 8626        _: &MoveToPreviousWordStart,
 8627        window: &mut Window,
 8628        cx: &mut Context<Self>,
 8629    ) {
 8630        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8631            s.move_cursors_with(|map, head, _| {
 8632                (
 8633                    movement::previous_word_start(map, head),
 8634                    SelectionGoal::None,
 8635                )
 8636            });
 8637        })
 8638    }
 8639
 8640    pub fn move_to_previous_subword_start(
 8641        &mut self,
 8642        _: &MoveToPreviousSubwordStart,
 8643        window: &mut Window,
 8644        cx: &mut Context<Self>,
 8645    ) {
 8646        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8647            s.move_cursors_with(|map, head, _| {
 8648                (
 8649                    movement::previous_subword_start(map, head),
 8650                    SelectionGoal::None,
 8651                )
 8652            });
 8653        })
 8654    }
 8655
 8656    pub fn select_to_previous_word_start(
 8657        &mut self,
 8658        _: &SelectToPreviousWordStart,
 8659        window: &mut Window,
 8660        cx: &mut Context<Self>,
 8661    ) {
 8662        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8663            s.move_heads_with(|map, head, _| {
 8664                (
 8665                    movement::previous_word_start(map, head),
 8666                    SelectionGoal::None,
 8667                )
 8668            });
 8669        })
 8670    }
 8671
 8672    pub fn select_to_previous_subword_start(
 8673        &mut self,
 8674        _: &SelectToPreviousSubwordStart,
 8675        window: &mut Window,
 8676        cx: &mut Context<Self>,
 8677    ) {
 8678        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8679            s.move_heads_with(|map, head, _| {
 8680                (
 8681                    movement::previous_subword_start(map, head),
 8682                    SelectionGoal::None,
 8683                )
 8684            });
 8685        })
 8686    }
 8687
 8688    pub fn delete_to_previous_word_start(
 8689        &mut self,
 8690        action: &DeleteToPreviousWordStart,
 8691        window: &mut Window,
 8692        cx: &mut Context<Self>,
 8693    ) {
 8694        self.transact(window, cx, |this, window, cx| {
 8695            this.select_autoclose_pair(window, cx);
 8696            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8697                let line_mode = s.line_mode;
 8698                s.move_with(|map, selection| {
 8699                    if selection.is_empty() && !line_mode {
 8700                        let cursor = if action.ignore_newlines {
 8701                            movement::previous_word_start(map, selection.head())
 8702                        } else {
 8703                            movement::previous_word_start_or_newline(map, selection.head())
 8704                        };
 8705                        selection.set_head(cursor, SelectionGoal::None);
 8706                    }
 8707                });
 8708            });
 8709            this.insert("", window, cx);
 8710        });
 8711    }
 8712
 8713    pub fn delete_to_previous_subword_start(
 8714        &mut self,
 8715        _: &DeleteToPreviousSubwordStart,
 8716        window: &mut Window,
 8717        cx: &mut Context<Self>,
 8718    ) {
 8719        self.transact(window, cx, |this, window, cx| {
 8720            this.select_autoclose_pair(window, cx);
 8721            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8722                let line_mode = s.line_mode;
 8723                s.move_with(|map, selection| {
 8724                    if selection.is_empty() && !line_mode {
 8725                        let cursor = movement::previous_subword_start(map, selection.head());
 8726                        selection.set_head(cursor, SelectionGoal::None);
 8727                    }
 8728                });
 8729            });
 8730            this.insert("", window, cx);
 8731        });
 8732    }
 8733
 8734    pub fn move_to_next_word_end(
 8735        &mut self,
 8736        _: &MoveToNextWordEnd,
 8737        window: &mut Window,
 8738        cx: &mut Context<Self>,
 8739    ) {
 8740        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8741            s.move_cursors_with(|map, head, _| {
 8742                (movement::next_word_end(map, head), SelectionGoal::None)
 8743            });
 8744        })
 8745    }
 8746
 8747    pub fn move_to_next_subword_end(
 8748        &mut self,
 8749        _: &MoveToNextSubwordEnd,
 8750        window: &mut Window,
 8751        cx: &mut Context<Self>,
 8752    ) {
 8753        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8754            s.move_cursors_with(|map, head, _| {
 8755                (movement::next_subword_end(map, head), SelectionGoal::None)
 8756            });
 8757        })
 8758    }
 8759
 8760    pub fn select_to_next_word_end(
 8761        &mut self,
 8762        _: &SelectToNextWordEnd,
 8763        window: &mut Window,
 8764        cx: &mut Context<Self>,
 8765    ) {
 8766        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8767            s.move_heads_with(|map, head, _| {
 8768                (movement::next_word_end(map, head), SelectionGoal::None)
 8769            });
 8770        })
 8771    }
 8772
 8773    pub fn select_to_next_subword_end(
 8774        &mut self,
 8775        _: &SelectToNextSubwordEnd,
 8776        window: &mut Window,
 8777        cx: &mut Context<Self>,
 8778    ) {
 8779        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8780            s.move_heads_with(|map, head, _| {
 8781                (movement::next_subword_end(map, head), SelectionGoal::None)
 8782            });
 8783        })
 8784    }
 8785
 8786    pub fn delete_to_next_word_end(
 8787        &mut self,
 8788        action: &DeleteToNextWordEnd,
 8789        window: &mut Window,
 8790        cx: &mut Context<Self>,
 8791    ) {
 8792        self.transact(window, cx, |this, window, cx| {
 8793            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8794                let line_mode = s.line_mode;
 8795                s.move_with(|map, selection| {
 8796                    if selection.is_empty() && !line_mode {
 8797                        let cursor = if action.ignore_newlines {
 8798                            movement::next_word_end(map, selection.head())
 8799                        } else {
 8800                            movement::next_word_end_or_newline(map, selection.head())
 8801                        };
 8802                        selection.set_head(cursor, SelectionGoal::None);
 8803                    }
 8804                });
 8805            });
 8806            this.insert("", window, cx);
 8807        });
 8808    }
 8809
 8810    pub fn delete_to_next_subword_end(
 8811        &mut self,
 8812        _: &DeleteToNextSubwordEnd,
 8813        window: &mut Window,
 8814        cx: &mut Context<Self>,
 8815    ) {
 8816        self.transact(window, cx, |this, window, cx| {
 8817            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8818                s.move_with(|map, selection| {
 8819                    if selection.is_empty() {
 8820                        let cursor = movement::next_subword_end(map, selection.head());
 8821                        selection.set_head(cursor, SelectionGoal::None);
 8822                    }
 8823                });
 8824            });
 8825            this.insert("", window, cx);
 8826        });
 8827    }
 8828
 8829    pub fn move_to_beginning_of_line(
 8830        &mut self,
 8831        action: &MoveToBeginningOfLine,
 8832        window: &mut Window,
 8833        cx: &mut Context<Self>,
 8834    ) {
 8835        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8836            s.move_cursors_with(|map, head, _| {
 8837                (
 8838                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8839                    SelectionGoal::None,
 8840                )
 8841            });
 8842        })
 8843    }
 8844
 8845    pub fn select_to_beginning_of_line(
 8846        &mut self,
 8847        action: &SelectToBeginningOfLine,
 8848        window: &mut Window,
 8849        cx: &mut Context<Self>,
 8850    ) {
 8851        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8852            s.move_heads_with(|map, head, _| {
 8853                (
 8854                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8855                    SelectionGoal::None,
 8856                )
 8857            });
 8858        });
 8859    }
 8860
 8861    pub fn delete_to_beginning_of_line(
 8862        &mut self,
 8863        _: &DeleteToBeginningOfLine,
 8864        window: &mut Window,
 8865        cx: &mut Context<Self>,
 8866    ) {
 8867        self.transact(window, cx, |this, window, cx| {
 8868            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8869                s.move_with(|_, selection| {
 8870                    selection.reversed = true;
 8871                });
 8872            });
 8873
 8874            this.select_to_beginning_of_line(
 8875                &SelectToBeginningOfLine {
 8876                    stop_at_soft_wraps: false,
 8877                },
 8878                window,
 8879                cx,
 8880            );
 8881            this.backspace(&Backspace, window, cx);
 8882        });
 8883    }
 8884
 8885    pub fn move_to_end_of_line(
 8886        &mut self,
 8887        action: &MoveToEndOfLine,
 8888        window: &mut Window,
 8889        cx: &mut Context<Self>,
 8890    ) {
 8891        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8892            s.move_cursors_with(|map, head, _| {
 8893                (
 8894                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8895                    SelectionGoal::None,
 8896                )
 8897            });
 8898        })
 8899    }
 8900
 8901    pub fn select_to_end_of_line(
 8902        &mut self,
 8903        action: &SelectToEndOfLine,
 8904        window: &mut Window,
 8905        cx: &mut Context<Self>,
 8906    ) {
 8907        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8908            s.move_heads_with(|map, head, _| {
 8909                (
 8910                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8911                    SelectionGoal::None,
 8912                )
 8913            });
 8914        })
 8915    }
 8916
 8917    pub fn delete_to_end_of_line(
 8918        &mut self,
 8919        _: &DeleteToEndOfLine,
 8920        window: &mut Window,
 8921        cx: &mut Context<Self>,
 8922    ) {
 8923        self.transact(window, cx, |this, window, cx| {
 8924            this.select_to_end_of_line(
 8925                &SelectToEndOfLine {
 8926                    stop_at_soft_wraps: false,
 8927                },
 8928                window,
 8929                cx,
 8930            );
 8931            this.delete(&Delete, window, cx);
 8932        });
 8933    }
 8934
 8935    pub fn cut_to_end_of_line(
 8936        &mut self,
 8937        _: &CutToEndOfLine,
 8938        window: &mut Window,
 8939        cx: &mut Context<Self>,
 8940    ) {
 8941        self.transact(window, cx, |this, window, cx| {
 8942            this.select_to_end_of_line(
 8943                &SelectToEndOfLine {
 8944                    stop_at_soft_wraps: false,
 8945                },
 8946                window,
 8947                cx,
 8948            );
 8949            this.cut(&Cut, window, cx);
 8950        });
 8951    }
 8952
 8953    pub fn move_to_start_of_paragraph(
 8954        &mut self,
 8955        _: &MoveToStartOfParagraph,
 8956        window: &mut Window,
 8957        cx: &mut Context<Self>,
 8958    ) {
 8959        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8960            cx.propagate();
 8961            return;
 8962        }
 8963
 8964        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8965            s.move_with(|map, selection| {
 8966                selection.collapse_to(
 8967                    movement::start_of_paragraph(map, selection.head(), 1),
 8968                    SelectionGoal::None,
 8969                )
 8970            });
 8971        })
 8972    }
 8973
 8974    pub fn move_to_end_of_paragraph(
 8975        &mut self,
 8976        _: &MoveToEndOfParagraph,
 8977        window: &mut Window,
 8978        cx: &mut Context<Self>,
 8979    ) {
 8980        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8981            cx.propagate();
 8982            return;
 8983        }
 8984
 8985        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8986            s.move_with(|map, selection| {
 8987                selection.collapse_to(
 8988                    movement::end_of_paragraph(map, selection.head(), 1),
 8989                    SelectionGoal::None,
 8990                )
 8991            });
 8992        })
 8993    }
 8994
 8995    pub fn select_to_start_of_paragraph(
 8996        &mut self,
 8997        _: &SelectToStartOfParagraph,
 8998        window: &mut Window,
 8999        cx: &mut Context<Self>,
 9000    ) {
 9001        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9002            cx.propagate();
 9003            return;
 9004        }
 9005
 9006        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9007            s.move_heads_with(|map, head, _| {
 9008                (
 9009                    movement::start_of_paragraph(map, head, 1),
 9010                    SelectionGoal::None,
 9011                )
 9012            });
 9013        })
 9014    }
 9015
 9016    pub fn select_to_end_of_paragraph(
 9017        &mut self,
 9018        _: &SelectToEndOfParagraph,
 9019        window: &mut Window,
 9020        cx: &mut Context<Self>,
 9021    ) {
 9022        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9023            cx.propagate();
 9024            return;
 9025        }
 9026
 9027        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9028            s.move_heads_with(|map, head, _| {
 9029                (
 9030                    movement::end_of_paragraph(map, head, 1),
 9031                    SelectionGoal::None,
 9032                )
 9033            });
 9034        })
 9035    }
 9036
 9037    pub fn move_to_start_of_excerpt(
 9038        &mut self,
 9039        _: &MoveToStartOfExcerpt,
 9040        window: &mut Window,
 9041        cx: &mut Context<Self>,
 9042    ) {
 9043        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9044            cx.propagate();
 9045            return;
 9046        }
 9047
 9048        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9049            s.move_with(|map, selection| {
 9050                selection.collapse_to(
 9051                    movement::start_of_excerpt(
 9052                        map,
 9053                        selection.head(),
 9054                        workspace::searchable::Direction::Prev,
 9055                    ),
 9056                    SelectionGoal::None,
 9057                )
 9058            });
 9059        })
 9060    }
 9061
 9062    pub fn move_to_end_of_excerpt(
 9063        &mut self,
 9064        _: &MoveToEndOfExcerpt,
 9065        window: &mut Window,
 9066        cx: &mut Context<Self>,
 9067    ) {
 9068        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9069            cx.propagate();
 9070            return;
 9071        }
 9072
 9073        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9074            s.move_with(|map, selection| {
 9075                selection.collapse_to(
 9076                    movement::end_of_excerpt(
 9077                        map,
 9078                        selection.head(),
 9079                        workspace::searchable::Direction::Next,
 9080                    ),
 9081                    SelectionGoal::None,
 9082                )
 9083            });
 9084        })
 9085    }
 9086
 9087    pub fn select_to_start_of_excerpt(
 9088        &mut self,
 9089        _: &SelectToStartOfExcerpt,
 9090        window: &mut Window,
 9091        cx: &mut Context<Self>,
 9092    ) {
 9093        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9094            cx.propagate();
 9095            return;
 9096        }
 9097
 9098        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9099            s.move_heads_with(|map, head, _| {
 9100                (
 9101                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
 9102                    SelectionGoal::None,
 9103                )
 9104            });
 9105        })
 9106    }
 9107
 9108    pub fn select_to_end_of_excerpt(
 9109        &mut self,
 9110        _: &SelectToEndOfExcerpt,
 9111        window: &mut Window,
 9112        cx: &mut Context<Self>,
 9113    ) {
 9114        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9115            cx.propagate();
 9116            return;
 9117        }
 9118
 9119        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9120            s.move_heads_with(|map, head, _| {
 9121                (
 9122                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
 9123                    SelectionGoal::None,
 9124                )
 9125            });
 9126        })
 9127    }
 9128
 9129    pub fn move_to_beginning(
 9130        &mut self,
 9131        _: &MoveToBeginning,
 9132        window: &mut Window,
 9133        cx: &mut Context<Self>,
 9134    ) {
 9135        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9136            cx.propagate();
 9137            return;
 9138        }
 9139
 9140        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9141            s.select_ranges(vec![0..0]);
 9142        });
 9143    }
 9144
 9145    pub fn select_to_beginning(
 9146        &mut self,
 9147        _: &SelectToBeginning,
 9148        window: &mut Window,
 9149        cx: &mut Context<Self>,
 9150    ) {
 9151        let mut selection = self.selections.last::<Point>(cx);
 9152        selection.set_head(Point::zero(), SelectionGoal::None);
 9153
 9154        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9155            s.select(vec![selection]);
 9156        });
 9157    }
 9158
 9159    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9160        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9161            cx.propagate();
 9162            return;
 9163        }
 9164
 9165        let cursor = self.buffer.read(cx).read(cx).len();
 9166        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9167            s.select_ranges(vec![cursor..cursor])
 9168        });
 9169    }
 9170
 9171    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9172        self.nav_history = nav_history;
 9173    }
 9174
 9175    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9176        self.nav_history.as_ref()
 9177    }
 9178
 9179    fn push_to_nav_history(
 9180        &mut self,
 9181        cursor_anchor: Anchor,
 9182        new_position: Option<Point>,
 9183        cx: &mut Context<Self>,
 9184    ) {
 9185        if let Some(nav_history) = self.nav_history.as_mut() {
 9186            let buffer = self.buffer.read(cx).read(cx);
 9187            let cursor_position = cursor_anchor.to_point(&buffer);
 9188            let scroll_state = self.scroll_manager.anchor();
 9189            let scroll_top_row = scroll_state.top_row(&buffer);
 9190            drop(buffer);
 9191
 9192            if let Some(new_position) = new_position {
 9193                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9194                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9195                    return;
 9196                }
 9197            }
 9198
 9199            nav_history.push(
 9200                Some(NavigationData {
 9201                    cursor_anchor,
 9202                    cursor_position,
 9203                    scroll_anchor: scroll_state,
 9204                    scroll_top_row,
 9205                }),
 9206                cx,
 9207            );
 9208        }
 9209    }
 9210
 9211    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9212        let buffer = self.buffer.read(cx).snapshot(cx);
 9213        let mut selection = self.selections.first::<usize>(cx);
 9214        selection.set_head(buffer.len(), SelectionGoal::None);
 9215        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9216            s.select(vec![selection]);
 9217        });
 9218    }
 9219
 9220    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9221        let end = self.buffer.read(cx).read(cx).len();
 9222        self.change_selections(None, window, cx, |s| {
 9223            s.select_ranges(vec![0..end]);
 9224        });
 9225    }
 9226
 9227    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9228        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9229        let mut selections = self.selections.all::<Point>(cx);
 9230        let max_point = display_map.buffer_snapshot.max_point();
 9231        for selection in &mut selections {
 9232            let rows = selection.spanned_rows(true, &display_map);
 9233            selection.start = Point::new(rows.start.0, 0);
 9234            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9235            selection.reversed = false;
 9236        }
 9237        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9238            s.select(selections);
 9239        });
 9240    }
 9241
 9242    pub fn split_selection_into_lines(
 9243        &mut self,
 9244        _: &SplitSelectionIntoLines,
 9245        window: &mut Window,
 9246        cx: &mut Context<Self>,
 9247    ) {
 9248        let selections = self
 9249            .selections
 9250            .all::<Point>(cx)
 9251            .into_iter()
 9252            .map(|selection| selection.start..selection.end)
 9253            .collect::<Vec<_>>();
 9254        self.unfold_ranges(&selections, true, true, cx);
 9255
 9256        let mut new_selection_ranges = Vec::new();
 9257        {
 9258            let buffer = self.buffer.read(cx).read(cx);
 9259            for selection in selections {
 9260                for row in selection.start.row..selection.end.row {
 9261                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9262                    new_selection_ranges.push(cursor..cursor);
 9263                }
 9264
 9265                let is_multiline_selection = selection.start.row != selection.end.row;
 9266                // Don't insert last one if it's a multi-line selection ending at the start of a line,
 9267                // so this action feels more ergonomic when paired with other selection operations
 9268                let should_skip_last = is_multiline_selection && selection.end.column == 0;
 9269                if !should_skip_last {
 9270                    new_selection_ranges.push(selection.end..selection.end);
 9271                }
 9272            }
 9273        }
 9274        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9275            s.select_ranges(new_selection_ranges);
 9276        });
 9277    }
 9278
 9279    pub fn add_selection_above(
 9280        &mut self,
 9281        _: &AddSelectionAbove,
 9282        window: &mut Window,
 9283        cx: &mut Context<Self>,
 9284    ) {
 9285        self.add_selection(true, window, cx);
 9286    }
 9287
 9288    pub fn add_selection_below(
 9289        &mut self,
 9290        _: &AddSelectionBelow,
 9291        window: &mut Window,
 9292        cx: &mut Context<Self>,
 9293    ) {
 9294        self.add_selection(false, window, cx);
 9295    }
 9296
 9297    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9298        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9299        let mut selections = self.selections.all::<Point>(cx);
 9300        let text_layout_details = self.text_layout_details(window);
 9301        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9302            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9303            let range = oldest_selection.display_range(&display_map).sorted();
 9304
 9305            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9306            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9307            let positions = start_x.min(end_x)..start_x.max(end_x);
 9308
 9309            selections.clear();
 9310            let mut stack = Vec::new();
 9311            for row in range.start.row().0..=range.end.row().0 {
 9312                if let Some(selection) = self.selections.build_columnar_selection(
 9313                    &display_map,
 9314                    DisplayRow(row),
 9315                    &positions,
 9316                    oldest_selection.reversed,
 9317                    &text_layout_details,
 9318                ) {
 9319                    stack.push(selection.id);
 9320                    selections.push(selection);
 9321                }
 9322            }
 9323
 9324            if above {
 9325                stack.reverse();
 9326            }
 9327
 9328            AddSelectionsState { above, stack }
 9329        });
 9330
 9331        let last_added_selection = *state.stack.last().unwrap();
 9332        let mut new_selections = Vec::new();
 9333        if above == state.above {
 9334            let end_row = if above {
 9335                DisplayRow(0)
 9336            } else {
 9337                display_map.max_point().row()
 9338            };
 9339
 9340            'outer: for selection in selections {
 9341                if selection.id == last_added_selection {
 9342                    let range = selection.display_range(&display_map).sorted();
 9343                    debug_assert_eq!(range.start.row(), range.end.row());
 9344                    let mut row = range.start.row();
 9345                    let positions =
 9346                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9347                            px(start)..px(end)
 9348                        } else {
 9349                            let start_x =
 9350                                display_map.x_for_display_point(range.start, &text_layout_details);
 9351                            let end_x =
 9352                                display_map.x_for_display_point(range.end, &text_layout_details);
 9353                            start_x.min(end_x)..start_x.max(end_x)
 9354                        };
 9355
 9356                    while row != end_row {
 9357                        if above {
 9358                            row.0 -= 1;
 9359                        } else {
 9360                            row.0 += 1;
 9361                        }
 9362
 9363                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9364                            &display_map,
 9365                            row,
 9366                            &positions,
 9367                            selection.reversed,
 9368                            &text_layout_details,
 9369                        ) {
 9370                            state.stack.push(new_selection.id);
 9371                            if above {
 9372                                new_selections.push(new_selection);
 9373                                new_selections.push(selection);
 9374                            } else {
 9375                                new_selections.push(selection);
 9376                                new_selections.push(new_selection);
 9377                            }
 9378
 9379                            continue 'outer;
 9380                        }
 9381                    }
 9382                }
 9383
 9384                new_selections.push(selection);
 9385            }
 9386        } else {
 9387            new_selections = selections;
 9388            new_selections.retain(|s| s.id != last_added_selection);
 9389            state.stack.pop();
 9390        }
 9391
 9392        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9393            s.select(new_selections);
 9394        });
 9395        if state.stack.len() > 1 {
 9396            self.add_selections_state = Some(state);
 9397        }
 9398    }
 9399
 9400    pub fn select_next_match_internal(
 9401        &mut self,
 9402        display_map: &DisplaySnapshot,
 9403        replace_newest: bool,
 9404        autoscroll: Option<Autoscroll>,
 9405        window: &mut Window,
 9406        cx: &mut Context<Self>,
 9407    ) -> Result<()> {
 9408        fn select_next_match_ranges(
 9409            this: &mut Editor,
 9410            range: Range<usize>,
 9411            replace_newest: bool,
 9412            auto_scroll: Option<Autoscroll>,
 9413            window: &mut Window,
 9414            cx: &mut Context<Editor>,
 9415        ) {
 9416            this.unfold_ranges(&[range.clone()], false, true, cx);
 9417            this.change_selections(auto_scroll, window, cx, |s| {
 9418                if replace_newest {
 9419                    s.delete(s.newest_anchor().id);
 9420                }
 9421                s.insert_range(range.clone());
 9422            });
 9423        }
 9424
 9425        let buffer = &display_map.buffer_snapshot;
 9426        let mut selections = self.selections.all::<usize>(cx);
 9427        if let Some(mut select_next_state) = self.select_next_state.take() {
 9428            let query = &select_next_state.query;
 9429            if !select_next_state.done {
 9430                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9431                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9432                let mut next_selected_range = None;
 9433
 9434                let bytes_after_last_selection =
 9435                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9436                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9437                let query_matches = query
 9438                    .stream_find_iter(bytes_after_last_selection)
 9439                    .map(|result| (last_selection.end, result))
 9440                    .chain(
 9441                        query
 9442                            .stream_find_iter(bytes_before_first_selection)
 9443                            .map(|result| (0, result)),
 9444                    );
 9445
 9446                for (start_offset, query_match) in query_matches {
 9447                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9448                    let offset_range =
 9449                        start_offset + query_match.start()..start_offset + query_match.end();
 9450                    let display_range = offset_range.start.to_display_point(display_map)
 9451                        ..offset_range.end.to_display_point(display_map);
 9452
 9453                    if !select_next_state.wordwise
 9454                        || (!movement::is_inside_word(display_map, display_range.start)
 9455                            && !movement::is_inside_word(display_map, display_range.end))
 9456                    {
 9457                        // TODO: This is n^2, because we might check all the selections
 9458                        if !selections
 9459                            .iter()
 9460                            .any(|selection| selection.range().overlaps(&offset_range))
 9461                        {
 9462                            next_selected_range = Some(offset_range);
 9463                            break;
 9464                        }
 9465                    }
 9466                }
 9467
 9468                if let Some(next_selected_range) = next_selected_range {
 9469                    select_next_match_ranges(
 9470                        self,
 9471                        next_selected_range,
 9472                        replace_newest,
 9473                        autoscroll,
 9474                        window,
 9475                        cx,
 9476                    );
 9477                } else {
 9478                    select_next_state.done = true;
 9479                }
 9480            }
 9481
 9482            self.select_next_state = Some(select_next_state);
 9483        } else {
 9484            let mut only_carets = true;
 9485            let mut same_text_selected = true;
 9486            let mut selected_text = None;
 9487
 9488            let mut selections_iter = selections.iter().peekable();
 9489            while let Some(selection) = selections_iter.next() {
 9490                if selection.start != selection.end {
 9491                    only_carets = false;
 9492                }
 9493
 9494                if same_text_selected {
 9495                    if selected_text.is_none() {
 9496                        selected_text =
 9497                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9498                    }
 9499
 9500                    if let Some(next_selection) = selections_iter.peek() {
 9501                        if next_selection.range().len() == selection.range().len() {
 9502                            let next_selected_text = buffer
 9503                                .text_for_range(next_selection.range())
 9504                                .collect::<String>();
 9505                            if Some(next_selected_text) != selected_text {
 9506                                same_text_selected = false;
 9507                                selected_text = None;
 9508                            }
 9509                        } else {
 9510                            same_text_selected = false;
 9511                            selected_text = None;
 9512                        }
 9513                    }
 9514                }
 9515            }
 9516
 9517            if only_carets {
 9518                for selection in &mut selections {
 9519                    let word_range = movement::surrounding_word(
 9520                        display_map,
 9521                        selection.start.to_display_point(display_map),
 9522                    );
 9523                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9524                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9525                    selection.goal = SelectionGoal::None;
 9526                    selection.reversed = false;
 9527                    select_next_match_ranges(
 9528                        self,
 9529                        selection.start..selection.end,
 9530                        replace_newest,
 9531                        autoscroll,
 9532                        window,
 9533                        cx,
 9534                    );
 9535                }
 9536
 9537                if selections.len() == 1 {
 9538                    let selection = selections
 9539                        .last()
 9540                        .expect("ensured that there's only one selection");
 9541                    let query = buffer
 9542                        .text_for_range(selection.start..selection.end)
 9543                        .collect::<String>();
 9544                    let is_empty = query.is_empty();
 9545                    let select_state = SelectNextState {
 9546                        query: AhoCorasick::new(&[query])?,
 9547                        wordwise: true,
 9548                        done: is_empty,
 9549                    };
 9550                    self.select_next_state = Some(select_state);
 9551                } else {
 9552                    self.select_next_state = None;
 9553                }
 9554            } else if let Some(selected_text) = selected_text {
 9555                self.select_next_state = Some(SelectNextState {
 9556                    query: AhoCorasick::new(&[selected_text])?,
 9557                    wordwise: false,
 9558                    done: false,
 9559                });
 9560                self.select_next_match_internal(
 9561                    display_map,
 9562                    replace_newest,
 9563                    autoscroll,
 9564                    window,
 9565                    cx,
 9566                )?;
 9567            }
 9568        }
 9569        Ok(())
 9570    }
 9571
 9572    pub fn select_all_matches(
 9573        &mut self,
 9574        _action: &SelectAllMatches,
 9575        window: &mut Window,
 9576        cx: &mut Context<Self>,
 9577    ) -> Result<()> {
 9578        self.push_to_selection_history();
 9579        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9580
 9581        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9582        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9583            return Ok(());
 9584        };
 9585        if select_next_state.done {
 9586            return Ok(());
 9587        }
 9588
 9589        let mut new_selections = self.selections.all::<usize>(cx);
 9590
 9591        let buffer = &display_map.buffer_snapshot;
 9592        let query_matches = select_next_state
 9593            .query
 9594            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9595
 9596        for query_match in query_matches {
 9597            let query_match = query_match.unwrap(); // can only fail due to I/O
 9598            let offset_range = query_match.start()..query_match.end();
 9599            let display_range = offset_range.start.to_display_point(&display_map)
 9600                ..offset_range.end.to_display_point(&display_map);
 9601
 9602            if !select_next_state.wordwise
 9603                || (!movement::is_inside_word(&display_map, display_range.start)
 9604                    && !movement::is_inside_word(&display_map, display_range.end))
 9605            {
 9606                self.selections.change_with(cx, |selections| {
 9607                    new_selections.push(Selection {
 9608                        id: selections.new_selection_id(),
 9609                        start: offset_range.start,
 9610                        end: offset_range.end,
 9611                        reversed: false,
 9612                        goal: SelectionGoal::None,
 9613                    });
 9614                });
 9615            }
 9616        }
 9617
 9618        new_selections.sort_by_key(|selection| selection.start);
 9619        let mut ix = 0;
 9620        while ix + 1 < new_selections.len() {
 9621            let current_selection = &new_selections[ix];
 9622            let next_selection = &new_selections[ix + 1];
 9623            if current_selection.range().overlaps(&next_selection.range()) {
 9624                if current_selection.id < next_selection.id {
 9625                    new_selections.remove(ix + 1);
 9626                } else {
 9627                    new_selections.remove(ix);
 9628                }
 9629            } else {
 9630                ix += 1;
 9631            }
 9632        }
 9633
 9634        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9635
 9636        for selection in new_selections.iter_mut() {
 9637            selection.reversed = reversed;
 9638        }
 9639
 9640        select_next_state.done = true;
 9641        self.unfold_ranges(
 9642            &new_selections
 9643                .iter()
 9644                .map(|selection| selection.range())
 9645                .collect::<Vec<_>>(),
 9646            false,
 9647            false,
 9648            cx,
 9649        );
 9650        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9651            selections.select(new_selections)
 9652        });
 9653
 9654        Ok(())
 9655    }
 9656
 9657    pub fn select_next(
 9658        &mut self,
 9659        action: &SelectNext,
 9660        window: &mut Window,
 9661        cx: &mut Context<Self>,
 9662    ) -> Result<()> {
 9663        self.push_to_selection_history();
 9664        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9665        self.select_next_match_internal(
 9666            &display_map,
 9667            action.replace_newest,
 9668            Some(Autoscroll::newest()),
 9669            window,
 9670            cx,
 9671        )?;
 9672        Ok(())
 9673    }
 9674
 9675    pub fn select_previous(
 9676        &mut self,
 9677        action: &SelectPrevious,
 9678        window: &mut Window,
 9679        cx: &mut Context<Self>,
 9680    ) -> Result<()> {
 9681        self.push_to_selection_history();
 9682        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9683        let buffer = &display_map.buffer_snapshot;
 9684        let mut selections = self.selections.all::<usize>(cx);
 9685        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9686            let query = &select_prev_state.query;
 9687            if !select_prev_state.done {
 9688                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9689                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9690                let mut next_selected_range = None;
 9691                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9692                let bytes_before_last_selection =
 9693                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9694                let bytes_after_first_selection =
 9695                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9696                let query_matches = query
 9697                    .stream_find_iter(bytes_before_last_selection)
 9698                    .map(|result| (last_selection.start, result))
 9699                    .chain(
 9700                        query
 9701                            .stream_find_iter(bytes_after_first_selection)
 9702                            .map(|result| (buffer.len(), result)),
 9703                    );
 9704                for (end_offset, query_match) in query_matches {
 9705                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9706                    let offset_range =
 9707                        end_offset - query_match.end()..end_offset - query_match.start();
 9708                    let display_range = offset_range.start.to_display_point(&display_map)
 9709                        ..offset_range.end.to_display_point(&display_map);
 9710
 9711                    if !select_prev_state.wordwise
 9712                        || (!movement::is_inside_word(&display_map, display_range.start)
 9713                            && !movement::is_inside_word(&display_map, display_range.end))
 9714                    {
 9715                        next_selected_range = Some(offset_range);
 9716                        break;
 9717                    }
 9718                }
 9719
 9720                if let Some(next_selected_range) = next_selected_range {
 9721                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9722                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9723                        if action.replace_newest {
 9724                            s.delete(s.newest_anchor().id);
 9725                        }
 9726                        s.insert_range(next_selected_range);
 9727                    });
 9728                } else {
 9729                    select_prev_state.done = true;
 9730                }
 9731            }
 9732
 9733            self.select_prev_state = Some(select_prev_state);
 9734        } else {
 9735            let mut only_carets = true;
 9736            let mut same_text_selected = true;
 9737            let mut selected_text = None;
 9738
 9739            let mut selections_iter = selections.iter().peekable();
 9740            while let Some(selection) = selections_iter.next() {
 9741                if selection.start != selection.end {
 9742                    only_carets = false;
 9743                }
 9744
 9745                if same_text_selected {
 9746                    if selected_text.is_none() {
 9747                        selected_text =
 9748                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9749                    }
 9750
 9751                    if let Some(next_selection) = selections_iter.peek() {
 9752                        if next_selection.range().len() == selection.range().len() {
 9753                            let next_selected_text = buffer
 9754                                .text_for_range(next_selection.range())
 9755                                .collect::<String>();
 9756                            if Some(next_selected_text) != selected_text {
 9757                                same_text_selected = false;
 9758                                selected_text = None;
 9759                            }
 9760                        } else {
 9761                            same_text_selected = false;
 9762                            selected_text = None;
 9763                        }
 9764                    }
 9765                }
 9766            }
 9767
 9768            if only_carets {
 9769                for selection in &mut selections {
 9770                    let word_range = movement::surrounding_word(
 9771                        &display_map,
 9772                        selection.start.to_display_point(&display_map),
 9773                    );
 9774                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9775                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9776                    selection.goal = SelectionGoal::None;
 9777                    selection.reversed = false;
 9778                }
 9779                if selections.len() == 1 {
 9780                    let selection = selections
 9781                        .last()
 9782                        .expect("ensured that there's only one selection");
 9783                    let query = buffer
 9784                        .text_for_range(selection.start..selection.end)
 9785                        .collect::<String>();
 9786                    let is_empty = query.is_empty();
 9787                    let select_state = SelectNextState {
 9788                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9789                        wordwise: true,
 9790                        done: is_empty,
 9791                    };
 9792                    self.select_prev_state = Some(select_state);
 9793                } else {
 9794                    self.select_prev_state = None;
 9795                }
 9796
 9797                self.unfold_ranges(
 9798                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9799                    false,
 9800                    true,
 9801                    cx,
 9802                );
 9803                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9804                    s.select(selections);
 9805                });
 9806            } else if let Some(selected_text) = selected_text {
 9807                self.select_prev_state = Some(SelectNextState {
 9808                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9809                    wordwise: false,
 9810                    done: false,
 9811                });
 9812                self.select_previous(action, window, cx)?;
 9813            }
 9814        }
 9815        Ok(())
 9816    }
 9817
 9818    pub fn toggle_comments(
 9819        &mut self,
 9820        action: &ToggleComments,
 9821        window: &mut Window,
 9822        cx: &mut Context<Self>,
 9823    ) {
 9824        if self.read_only(cx) {
 9825            return;
 9826        }
 9827        let text_layout_details = &self.text_layout_details(window);
 9828        self.transact(window, cx, |this, window, cx| {
 9829            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9830            let mut edits = Vec::new();
 9831            let mut selection_edit_ranges = Vec::new();
 9832            let mut last_toggled_row = None;
 9833            let snapshot = this.buffer.read(cx).read(cx);
 9834            let empty_str: Arc<str> = Arc::default();
 9835            let mut suffixes_inserted = Vec::new();
 9836            let ignore_indent = action.ignore_indent;
 9837
 9838            fn comment_prefix_range(
 9839                snapshot: &MultiBufferSnapshot,
 9840                row: MultiBufferRow,
 9841                comment_prefix: &str,
 9842                comment_prefix_whitespace: &str,
 9843                ignore_indent: bool,
 9844            ) -> Range<Point> {
 9845                let indent_size = if ignore_indent {
 9846                    0
 9847                } else {
 9848                    snapshot.indent_size_for_line(row).len
 9849                };
 9850
 9851                let start = Point::new(row.0, indent_size);
 9852
 9853                let mut line_bytes = snapshot
 9854                    .bytes_in_range(start..snapshot.max_point())
 9855                    .flatten()
 9856                    .copied();
 9857
 9858                // If this line currently begins with the line comment prefix, then record
 9859                // the range containing the prefix.
 9860                if line_bytes
 9861                    .by_ref()
 9862                    .take(comment_prefix.len())
 9863                    .eq(comment_prefix.bytes())
 9864                {
 9865                    // Include any whitespace that matches the comment prefix.
 9866                    let matching_whitespace_len = line_bytes
 9867                        .zip(comment_prefix_whitespace.bytes())
 9868                        .take_while(|(a, b)| a == b)
 9869                        .count() as u32;
 9870                    let end = Point::new(
 9871                        start.row,
 9872                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9873                    );
 9874                    start..end
 9875                } else {
 9876                    start..start
 9877                }
 9878            }
 9879
 9880            fn comment_suffix_range(
 9881                snapshot: &MultiBufferSnapshot,
 9882                row: MultiBufferRow,
 9883                comment_suffix: &str,
 9884                comment_suffix_has_leading_space: bool,
 9885            ) -> Range<Point> {
 9886                let end = Point::new(row.0, snapshot.line_len(row));
 9887                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9888
 9889                let mut line_end_bytes = snapshot
 9890                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9891                    .flatten()
 9892                    .copied();
 9893
 9894                let leading_space_len = if suffix_start_column > 0
 9895                    && line_end_bytes.next() == Some(b' ')
 9896                    && comment_suffix_has_leading_space
 9897                {
 9898                    1
 9899                } else {
 9900                    0
 9901                };
 9902
 9903                // If this line currently begins with the line comment prefix, then record
 9904                // the range containing the prefix.
 9905                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9906                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9907                    start..end
 9908                } else {
 9909                    end..end
 9910                }
 9911            }
 9912
 9913            // TODO: Handle selections that cross excerpts
 9914            for selection in &mut selections {
 9915                let start_column = snapshot
 9916                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9917                    .len;
 9918                let language = if let Some(language) =
 9919                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9920                {
 9921                    language
 9922                } else {
 9923                    continue;
 9924                };
 9925
 9926                selection_edit_ranges.clear();
 9927
 9928                // If multiple selections contain a given row, avoid processing that
 9929                // row more than once.
 9930                let mut start_row = MultiBufferRow(selection.start.row);
 9931                if last_toggled_row == Some(start_row) {
 9932                    start_row = start_row.next_row();
 9933                }
 9934                let end_row =
 9935                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9936                        MultiBufferRow(selection.end.row - 1)
 9937                    } else {
 9938                        MultiBufferRow(selection.end.row)
 9939                    };
 9940                last_toggled_row = Some(end_row);
 9941
 9942                if start_row > end_row {
 9943                    continue;
 9944                }
 9945
 9946                // If the language has line comments, toggle those.
 9947                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9948
 9949                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9950                if ignore_indent {
 9951                    full_comment_prefixes = full_comment_prefixes
 9952                        .into_iter()
 9953                        .map(|s| Arc::from(s.trim_end()))
 9954                        .collect();
 9955                }
 9956
 9957                if !full_comment_prefixes.is_empty() {
 9958                    let first_prefix = full_comment_prefixes
 9959                        .first()
 9960                        .expect("prefixes is non-empty");
 9961                    let prefix_trimmed_lengths = full_comment_prefixes
 9962                        .iter()
 9963                        .map(|p| p.trim_end_matches(' ').len())
 9964                        .collect::<SmallVec<[usize; 4]>>();
 9965
 9966                    let mut all_selection_lines_are_comments = true;
 9967
 9968                    for row in start_row.0..=end_row.0 {
 9969                        let row = MultiBufferRow(row);
 9970                        if start_row < end_row && snapshot.is_line_blank(row) {
 9971                            continue;
 9972                        }
 9973
 9974                        let prefix_range = full_comment_prefixes
 9975                            .iter()
 9976                            .zip(prefix_trimmed_lengths.iter().copied())
 9977                            .map(|(prefix, trimmed_prefix_len)| {
 9978                                comment_prefix_range(
 9979                                    snapshot.deref(),
 9980                                    row,
 9981                                    &prefix[..trimmed_prefix_len],
 9982                                    &prefix[trimmed_prefix_len..],
 9983                                    ignore_indent,
 9984                                )
 9985                            })
 9986                            .max_by_key(|range| range.end.column - range.start.column)
 9987                            .expect("prefixes is non-empty");
 9988
 9989                        if prefix_range.is_empty() {
 9990                            all_selection_lines_are_comments = false;
 9991                        }
 9992
 9993                        selection_edit_ranges.push(prefix_range);
 9994                    }
 9995
 9996                    if all_selection_lines_are_comments {
 9997                        edits.extend(
 9998                            selection_edit_ranges
 9999                                .iter()
10000                                .cloned()
10001                                .map(|range| (range, empty_str.clone())),
10002                        );
10003                    } else {
10004                        let min_column = selection_edit_ranges
10005                            .iter()
10006                            .map(|range| range.start.column)
10007                            .min()
10008                            .unwrap_or(0);
10009                        edits.extend(selection_edit_ranges.iter().map(|range| {
10010                            let position = Point::new(range.start.row, min_column);
10011                            (position..position, first_prefix.clone())
10012                        }));
10013                    }
10014                } else if let Some((full_comment_prefix, comment_suffix)) =
10015                    language.block_comment_delimiters()
10016                {
10017                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10018                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10019                    let prefix_range = comment_prefix_range(
10020                        snapshot.deref(),
10021                        start_row,
10022                        comment_prefix,
10023                        comment_prefix_whitespace,
10024                        ignore_indent,
10025                    );
10026                    let suffix_range = comment_suffix_range(
10027                        snapshot.deref(),
10028                        end_row,
10029                        comment_suffix.trim_start_matches(' '),
10030                        comment_suffix.starts_with(' '),
10031                    );
10032
10033                    if prefix_range.is_empty() || suffix_range.is_empty() {
10034                        edits.push((
10035                            prefix_range.start..prefix_range.start,
10036                            full_comment_prefix.clone(),
10037                        ));
10038                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10039                        suffixes_inserted.push((end_row, comment_suffix.len()));
10040                    } else {
10041                        edits.push((prefix_range, empty_str.clone()));
10042                        edits.push((suffix_range, empty_str.clone()));
10043                    }
10044                } else {
10045                    continue;
10046                }
10047            }
10048
10049            drop(snapshot);
10050            this.buffer.update(cx, |buffer, cx| {
10051                buffer.edit(edits, None, cx);
10052            });
10053
10054            // Adjust selections so that they end before any comment suffixes that
10055            // were inserted.
10056            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10057            let mut selections = this.selections.all::<Point>(cx);
10058            let snapshot = this.buffer.read(cx).read(cx);
10059            for selection in &mut selections {
10060                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10061                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10062                        Ordering::Less => {
10063                            suffixes_inserted.next();
10064                            continue;
10065                        }
10066                        Ordering::Greater => break,
10067                        Ordering::Equal => {
10068                            if selection.end.column == snapshot.line_len(row) {
10069                                if selection.is_empty() {
10070                                    selection.start.column -= suffix_len as u32;
10071                                }
10072                                selection.end.column -= suffix_len as u32;
10073                            }
10074                            break;
10075                        }
10076                    }
10077                }
10078            }
10079
10080            drop(snapshot);
10081            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10082                s.select(selections)
10083            });
10084
10085            let selections = this.selections.all::<Point>(cx);
10086            let selections_on_single_row = selections.windows(2).all(|selections| {
10087                selections[0].start.row == selections[1].start.row
10088                    && selections[0].end.row == selections[1].end.row
10089                    && selections[0].start.row == selections[0].end.row
10090            });
10091            let selections_selecting = selections
10092                .iter()
10093                .any(|selection| selection.start != selection.end);
10094            let advance_downwards = action.advance_downwards
10095                && selections_on_single_row
10096                && !selections_selecting
10097                && !matches!(this.mode, EditorMode::SingleLine { .. });
10098
10099            if advance_downwards {
10100                let snapshot = this.buffer.read(cx).snapshot(cx);
10101
10102                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10103                    s.move_cursors_with(|display_snapshot, display_point, _| {
10104                        let mut point = display_point.to_point(display_snapshot);
10105                        point.row += 1;
10106                        point = snapshot.clip_point(point, Bias::Left);
10107                        let display_point = point.to_display_point(display_snapshot);
10108                        let goal = SelectionGoal::HorizontalPosition(
10109                            display_snapshot
10110                                .x_for_display_point(display_point, text_layout_details)
10111                                .into(),
10112                        );
10113                        (display_point, goal)
10114                    })
10115                });
10116            }
10117        });
10118    }
10119
10120    pub fn select_enclosing_symbol(
10121        &mut self,
10122        _: &SelectEnclosingSymbol,
10123        window: &mut Window,
10124        cx: &mut Context<Self>,
10125    ) {
10126        let buffer = self.buffer.read(cx).snapshot(cx);
10127        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10128
10129        fn update_selection(
10130            selection: &Selection<usize>,
10131            buffer_snap: &MultiBufferSnapshot,
10132        ) -> Option<Selection<usize>> {
10133            let cursor = selection.head();
10134            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10135            for symbol in symbols.iter().rev() {
10136                let start = symbol.range.start.to_offset(buffer_snap);
10137                let end = symbol.range.end.to_offset(buffer_snap);
10138                let new_range = start..end;
10139                if start < selection.start || end > selection.end {
10140                    return Some(Selection {
10141                        id: selection.id,
10142                        start: new_range.start,
10143                        end: new_range.end,
10144                        goal: SelectionGoal::None,
10145                        reversed: selection.reversed,
10146                    });
10147                }
10148            }
10149            None
10150        }
10151
10152        let mut selected_larger_symbol = false;
10153        let new_selections = old_selections
10154            .iter()
10155            .map(|selection| match update_selection(selection, &buffer) {
10156                Some(new_selection) => {
10157                    if new_selection.range() != selection.range() {
10158                        selected_larger_symbol = true;
10159                    }
10160                    new_selection
10161                }
10162                None => selection.clone(),
10163            })
10164            .collect::<Vec<_>>();
10165
10166        if selected_larger_symbol {
10167            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10168                s.select(new_selections);
10169            });
10170        }
10171    }
10172
10173    pub fn select_larger_syntax_node(
10174        &mut self,
10175        _: &SelectLargerSyntaxNode,
10176        window: &mut Window,
10177        cx: &mut Context<Self>,
10178    ) {
10179        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10180        let buffer = self.buffer.read(cx).snapshot(cx);
10181        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10182
10183        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10184        let mut selected_larger_node = false;
10185        let new_selections = old_selections
10186            .iter()
10187            .map(|selection| {
10188                let old_range = selection.start..selection.end;
10189                let mut new_range = old_range.clone();
10190                let mut new_node = None;
10191                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10192                {
10193                    new_node = Some(node);
10194                    new_range = containing_range;
10195                    if !display_map.intersects_fold(new_range.start)
10196                        && !display_map.intersects_fold(new_range.end)
10197                    {
10198                        break;
10199                    }
10200                }
10201
10202                if let Some(node) = new_node {
10203                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10204                    // nodes. Parent and grandparent are also logged because this operation will not
10205                    // visit nodes that have the same range as their parent.
10206                    log::info!("Node: {node:?}");
10207                    let parent = node.parent();
10208                    log::info!("Parent: {parent:?}");
10209                    let grandparent = parent.and_then(|x| x.parent());
10210                    log::info!("Grandparent: {grandparent:?}");
10211                }
10212
10213                selected_larger_node |= new_range != old_range;
10214                Selection {
10215                    id: selection.id,
10216                    start: new_range.start,
10217                    end: new_range.end,
10218                    goal: SelectionGoal::None,
10219                    reversed: selection.reversed,
10220                }
10221            })
10222            .collect::<Vec<_>>();
10223
10224        if selected_larger_node {
10225            stack.push(old_selections);
10226            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10227                s.select(new_selections);
10228            });
10229        }
10230        self.select_larger_syntax_node_stack = stack;
10231    }
10232
10233    pub fn select_smaller_syntax_node(
10234        &mut self,
10235        _: &SelectSmallerSyntaxNode,
10236        window: &mut Window,
10237        cx: &mut Context<Self>,
10238    ) {
10239        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10240        if let Some(selections) = stack.pop() {
10241            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10242                s.select(selections.to_vec());
10243            });
10244        }
10245        self.select_larger_syntax_node_stack = stack;
10246    }
10247
10248    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10249        if !EditorSettings::get_global(cx).gutter.runnables {
10250            self.clear_tasks();
10251            return Task::ready(());
10252        }
10253        let project = self.project.as_ref().map(Entity::downgrade);
10254        cx.spawn_in(window, |this, mut cx| async move {
10255            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10256            let Some(project) = project.and_then(|p| p.upgrade()) else {
10257                return;
10258            };
10259            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10260                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10261            }) else {
10262                return;
10263            };
10264
10265            let hide_runnables = project
10266                .update(&mut cx, |project, cx| {
10267                    // Do not display any test indicators in non-dev server remote projects.
10268                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10269                })
10270                .unwrap_or(true);
10271            if hide_runnables {
10272                return;
10273            }
10274            let new_rows =
10275                cx.background_spawn({
10276                    let snapshot = display_snapshot.clone();
10277                    async move {
10278                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10279                    }
10280                })
10281                    .await;
10282
10283            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10284            this.update(&mut cx, |this, _| {
10285                this.clear_tasks();
10286                for (key, value) in rows {
10287                    this.insert_tasks(key, value);
10288                }
10289            })
10290            .ok();
10291        })
10292    }
10293    fn fetch_runnable_ranges(
10294        snapshot: &DisplaySnapshot,
10295        range: Range<Anchor>,
10296    ) -> Vec<language::RunnableRange> {
10297        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10298    }
10299
10300    fn runnable_rows(
10301        project: Entity<Project>,
10302        snapshot: DisplaySnapshot,
10303        runnable_ranges: Vec<RunnableRange>,
10304        mut cx: AsyncWindowContext,
10305    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10306        runnable_ranges
10307            .into_iter()
10308            .filter_map(|mut runnable| {
10309                let tasks = cx
10310                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10311                    .ok()?;
10312                if tasks.is_empty() {
10313                    return None;
10314                }
10315
10316                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10317
10318                let row = snapshot
10319                    .buffer_snapshot
10320                    .buffer_line_for_row(MultiBufferRow(point.row))?
10321                    .1
10322                    .start
10323                    .row;
10324
10325                let context_range =
10326                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10327                Some((
10328                    (runnable.buffer_id, row),
10329                    RunnableTasks {
10330                        templates: tasks,
10331                        offset: MultiBufferOffset(runnable.run_range.start),
10332                        context_range,
10333                        column: point.column,
10334                        extra_variables: runnable.extra_captures,
10335                    },
10336                ))
10337            })
10338            .collect()
10339    }
10340
10341    fn templates_with_tags(
10342        project: &Entity<Project>,
10343        runnable: &mut Runnable,
10344        cx: &mut App,
10345    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10346        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10347            let (worktree_id, file) = project
10348                .buffer_for_id(runnable.buffer, cx)
10349                .and_then(|buffer| buffer.read(cx).file())
10350                .map(|file| (file.worktree_id(cx), file.clone()))
10351                .unzip();
10352
10353            (
10354                project.task_store().read(cx).task_inventory().cloned(),
10355                worktree_id,
10356                file,
10357            )
10358        });
10359
10360        let tags = mem::take(&mut runnable.tags);
10361        let mut tags: Vec<_> = tags
10362            .into_iter()
10363            .flat_map(|tag| {
10364                let tag = tag.0.clone();
10365                inventory
10366                    .as_ref()
10367                    .into_iter()
10368                    .flat_map(|inventory| {
10369                        inventory.read(cx).list_tasks(
10370                            file.clone(),
10371                            Some(runnable.language.clone()),
10372                            worktree_id,
10373                            cx,
10374                        )
10375                    })
10376                    .filter(move |(_, template)| {
10377                        template.tags.iter().any(|source_tag| source_tag == &tag)
10378                    })
10379            })
10380            .sorted_by_key(|(kind, _)| kind.to_owned())
10381            .collect();
10382        if let Some((leading_tag_source, _)) = tags.first() {
10383            // Strongest source wins; if we have worktree tag binding, prefer that to
10384            // global and language bindings;
10385            // if we have a global binding, prefer that to language binding.
10386            let first_mismatch = tags
10387                .iter()
10388                .position(|(tag_source, _)| tag_source != leading_tag_source);
10389            if let Some(index) = first_mismatch {
10390                tags.truncate(index);
10391            }
10392        }
10393
10394        tags
10395    }
10396
10397    pub fn move_to_enclosing_bracket(
10398        &mut self,
10399        _: &MoveToEnclosingBracket,
10400        window: &mut Window,
10401        cx: &mut Context<Self>,
10402    ) {
10403        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10404            s.move_offsets_with(|snapshot, selection| {
10405                let Some(enclosing_bracket_ranges) =
10406                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10407                else {
10408                    return;
10409                };
10410
10411                let mut best_length = usize::MAX;
10412                let mut best_inside = false;
10413                let mut best_in_bracket_range = false;
10414                let mut best_destination = None;
10415                for (open, close) in enclosing_bracket_ranges {
10416                    let close = close.to_inclusive();
10417                    let length = close.end() - open.start;
10418                    let inside = selection.start >= open.end && selection.end <= *close.start();
10419                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10420                        || close.contains(&selection.head());
10421
10422                    // If best is next to a bracket and current isn't, skip
10423                    if !in_bracket_range && best_in_bracket_range {
10424                        continue;
10425                    }
10426
10427                    // Prefer smaller lengths unless best is inside and current isn't
10428                    if length > best_length && (best_inside || !inside) {
10429                        continue;
10430                    }
10431
10432                    best_length = length;
10433                    best_inside = inside;
10434                    best_in_bracket_range = in_bracket_range;
10435                    best_destination = Some(
10436                        if close.contains(&selection.start) && close.contains(&selection.end) {
10437                            if inside {
10438                                open.end
10439                            } else {
10440                                open.start
10441                            }
10442                        } else if inside {
10443                            *close.start()
10444                        } else {
10445                            *close.end()
10446                        },
10447                    );
10448                }
10449
10450                if let Some(destination) = best_destination {
10451                    selection.collapse_to(destination, SelectionGoal::None);
10452                }
10453            })
10454        });
10455    }
10456
10457    pub fn undo_selection(
10458        &mut self,
10459        _: &UndoSelection,
10460        window: &mut Window,
10461        cx: &mut Context<Self>,
10462    ) {
10463        self.end_selection(window, cx);
10464        self.selection_history.mode = SelectionHistoryMode::Undoing;
10465        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10466            self.change_selections(None, window, cx, |s| {
10467                s.select_anchors(entry.selections.to_vec())
10468            });
10469            self.select_next_state = entry.select_next_state;
10470            self.select_prev_state = entry.select_prev_state;
10471            self.add_selections_state = entry.add_selections_state;
10472            self.request_autoscroll(Autoscroll::newest(), cx);
10473        }
10474        self.selection_history.mode = SelectionHistoryMode::Normal;
10475    }
10476
10477    pub fn redo_selection(
10478        &mut self,
10479        _: &RedoSelection,
10480        window: &mut Window,
10481        cx: &mut Context<Self>,
10482    ) {
10483        self.end_selection(window, cx);
10484        self.selection_history.mode = SelectionHistoryMode::Redoing;
10485        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10486            self.change_selections(None, window, cx, |s| {
10487                s.select_anchors(entry.selections.to_vec())
10488            });
10489            self.select_next_state = entry.select_next_state;
10490            self.select_prev_state = entry.select_prev_state;
10491            self.add_selections_state = entry.add_selections_state;
10492            self.request_autoscroll(Autoscroll::newest(), cx);
10493        }
10494        self.selection_history.mode = SelectionHistoryMode::Normal;
10495    }
10496
10497    pub fn expand_excerpts(
10498        &mut self,
10499        action: &ExpandExcerpts,
10500        _: &mut Window,
10501        cx: &mut Context<Self>,
10502    ) {
10503        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10504    }
10505
10506    pub fn expand_excerpts_down(
10507        &mut self,
10508        action: &ExpandExcerptsDown,
10509        _: &mut Window,
10510        cx: &mut Context<Self>,
10511    ) {
10512        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10513    }
10514
10515    pub fn expand_excerpts_up(
10516        &mut self,
10517        action: &ExpandExcerptsUp,
10518        _: &mut Window,
10519        cx: &mut Context<Self>,
10520    ) {
10521        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10522    }
10523
10524    pub fn expand_excerpts_for_direction(
10525        &mut self,
10526        lines: u32,
10527        direction: ExpandExcerptDirection,
10528
10529        cx: &mut Context<Self>,
10530    ) {
10531        let selections = self.selections.disjoint_anchors();
10532
10533        let lines = if lines == 0 {
10534            EditorSettings::get_global(cx).expand_excerpt_lines
10535        } else {
10536            lines
10537        };
10538
10539        self.buffer.update(cx, |buffer, cx| {
10540            let snapshot = buffer.snapshot(cx);
10541            let mut excerpt_ids = selections
10542                .iter()
10543                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10544                .collect::<Vec<_>>();
10545            excerpt_ids.sort();
10546            excerpt_ids.dedup();
10547            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10548        })
10549    }
10550
10551    pub fn expand_excerpt(
10552        &mut self,
10553        excerpt: ExcerptId,
10554        direction: ExpandExcerptDirection,
10555        cx: &mut Context<Self>,
10556    ) {
10557        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10558        self.buffer.update(cx, |buffer, cx| {
10559            buffer.expand_excerpts([excerpt], lines, direction, cx)
10560        })
10561    }
10562
10563    pub fn go_to_singleton_buffer_point(
10564        &mut self,
10565        point: Point,
10566        window: &mut Window,
10567        cx: &mut Context<Self>,
10568    ) {
10569        self.go_to_singleton_buffer_range(point..point, window, cx);
10570    }
10571
10572    pub fn go_to_singleton_buffer_range(
10573        &mut self,
10574        range: Range<Point>,
10575        window: &mut Window,
10576        cx: &mut Context<Self>,
10577    ) {
10578        let multibuffer = self.buffer().read(cx);
10579        let Some(buffer) = multibuffer.as_singleton() else {
10580            return;
10581        };
10582        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10583            return;
10584        };
10585        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10586            return;
10587        };
10588        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10589            s.select_anchor_ranges([start..end])
10590        });
10591    }
10592
10593    fn go_to_diagnostic(
10594        &mut self,
10595        _: &GoToDiagnostic,
10596        window: &mut Window,
10597        cx: &mut Context<Self>,
10598    ) {
10599        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10600    }
10601
10602    fn go_to_prev_diagnostic(
10603        &mut self,
10604        _: &GoToPrevDiagnostic,
10605        window: &mut Window,
10606        cx: &mut Context<Self>,
10607    ) {
10608        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10609    }
10610
10611    pub fn go_to_diagnostic_impl(
10612        &mut self,
10613        direction: Direction,
10614        window: &mut Window,
10615        cx: &mut Context<Self>,
10616    ) {
10617        let buffer = self.buffer.read(cx).snapshot(cx);
10618        let selection = self.selections.newest::<usize>(cx);
10619
10620        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10621        if direction == Direction::Next {
10622            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10623                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10624                    return;
10625                };
10626                self.activate_diagnostics(
10627                    buffer_id,
10628                    popover.local_diagnostic.diagnostic.group_id,
10629                    window,
10630                    cx,
10631                );
10632                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10633                    let primary_range_start = active_diagnostics.primary_range.start;
10634                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10635                        let mut new_selection = s.newest_anchor().clone();
10636                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10637                        s.select_anchors(vec![new_selection.clone()]);
10638                    });
10639                    self.refresh_inline_completion(false, true, window, cx);
10640                }
10641                return;
10642            }
10643        }
10644
10645        let active_group_id = self
10646            .active_diagnostics
10647            .as_ref()
10648            .map(|active_group| active_group.group_id);
10649        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10650            active_diagnostics
10651                .primary_range
10652                .to_offset(&buffer)
10653                .to_inclusive()
10654        });
10655        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10656            if active_primary_range.contains(&selection.head()) {
10657                *active_primary_range.start()
10658            } else {
10659                selection.head()
10660            }
10661        } else {
10662            selection.head()
10663        };
10664
10665        let snapshot = self.snapshot(window, cx);
10666        let primary_diagnostics_before = buffer
10667            .diagnostics_in_range::<usize>(0..search_start)
10668            .filter(|entry| entry.diagnostic.is_primary)
10669            .filter(|entry| entry.range.start != entry.range.end)
10670            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10671            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10672            .collect::<Vec<_>>();
10673        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10674            primary_diagnostics_before
10675                .iter()
10676                .position(|entry| entry.diagnostic.group_id == active_group_id)
10677        });
10678
10679        let primary_diagnostics_after = buffer
10680            .diagnostics_in_range::<usize>(search_start..buffer.len())
10681            .filter(|entry| entry.diagnostic.is_primary)
10682            .filter(|entry| entry.range.start != entry.range.end)
10683            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10684            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10685            .collect::<Vec<_>>();
10686        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10687            primary_diagnostics_after
10688                .iter()
10689                .enumerate()
10690                .rev()
10691                .find_map(|(i, entry)| {
10692                    if entry.diagnostic.group_id == active_group_id {
10693                        Some(i)
10694                    } else {
10695                        None
10696                    }
10697                })
10698        });
10699
10700        let next_primary_diagnostic = match direction {
10701            Direction::Prev => primary_diagnostics_before
10702                .iter()
10703                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10704                .rev()
10705                .next(),
10706            Direction::Next => primary_diagnostics_after
10707                .iter()
10708                .skip(
10709                    last_same_group_diagnostic_after
10710                        .map(|index| index + 1)
10711                        .unwrap_or(0),
10712                )
10713                .next(),
10714        };
10715
10716        // Cycle around to the start of the buffer, potentially moving back to the start of
10717        // the currently active diagnostic.
10718        let cycle_around = || match direction {
10719            Direction::Prev => primary_diagnostics_after
10720                .iter()
10721                .rev()
10722                .chain(primary_diagnostics_before.iter().rev())
10723                .next(),
10724            Direction::Next => primary_diagnostics_before
10725                .iter()
10726                .chain(primary_diagnostics_after.iter())
10727                .next(),
10728        };
10729
10730        if let Some((primary_range, group_id)) = next_primary_diagnostic
10731            .or_else(cycle_around)
10732            .map(|entry| (&entry.range, entry.diagnostic.group_id))
10733        {
10734            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10735                return;
10736            };
10737            self.activate_diagnostics(buffer_id, group_id, window, cx);
10738            if self.active_diagnostics.is_some() {
10739                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10740                    s.select(vec![Selection {
10741                        id: selection.id,
10742                        start: primary_range.start,
10743                        end: primary_range.start,
10744                        reversed: false,
10745                        goal: SelectionGoal::None,
10746                    }]);
10747                });
10748                self.refresh_inline_completion(false, true, window, cx);
10749            }
10750        }
10751    }
10752
10753    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10754        let snapshot = self.snapshot(window, cx);
10755        let selection = self.selections.newest::<Point>(cx);
10756        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10757    }
10758
10759    fn go_to_hunk_after_position(
10760        &mut self,
10761        snapshot: &EditorSnapshot,
10762        position: Point,
10763        window: &mut Window,
10764        cx: &mut Context<Editor>,
10765    ) -> Option<MultiBufferDiffHunk> {
10766        let mut hunk = snapshot
10767            .buffer_snapshot
10768            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10769            .find(|hunk| hunk.row_range.start.0 > position.row);
10770        if hunk.is_none() {
10771            hunk = snapshot
10772                .buffer_snapshot
10773                .diff_hunks_in_range(Point::zero()..position)
10774                .find(|hunk| hunk.row_range.end.0 < position.row)
10775        }
10776        if let Some(hunk) = &hunk {
10777            let destination = Point::new(hunk.row_range.start.0, 0);
10778            self.unfold_ranges(&[destination..destination], false, false, cx);
10779            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10780                s.select_ranges(vec![destination..destination]);
10781            });
10782        }
10783
10784        hunk
10785    }
10786
10787    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10788        let snapshot = self.snapshot(window, cx);
10789        let selection = self.selections.newest::<Point>(cx);
10790        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10791    }
10792
10793    fn go_to_hunk_before_position(
10794        &mut self,
10795        snapshot: &EditorSnapshot,
10796        position: Point,
10797        window: &mut Window,
10798        cx: &mut Context<Editor>,
10799    ) -> Option<MultiBufferDiffHunk> {
10800        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10801        if hunk.is_none() {
10802            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10803        }
10804        if let Some(hunk) = &hunk {
10805            let destination = Point::new(hunk.row_range.start.0, 0);
10806            self.unfold_ranges(&[destination..destination], false, false, cx);
10807            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10808                s.select_ranges(vec![destination..destination]);
10809            });
10810        }
10811
10812        hunk
10813    }
10814
10815    pub fn go_to_definition(
10816        &mut self,
10817        _: &GoToDefinition,
10818        window: &mut Window,
10819        cx: &mut Context<Self>,
10820    ) -> Task<Result<Navigated>> {
10821        let definition =
10822            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10823        cx.spawn_in(window, |editor, mut cx| async move {
10824            if definition.await? == Navigated::Yes {
10825                return Ok(Navigated::Yes);
10826            }
10827            match editor.update_in(&mut cx, |editor, window, cx| {
10828                editor.find_all_references(&FindAllReferences, window, cx)
10829            })? {
10830                Some(references) => references.await,
10831                None => Ok(Navigated::No),
10832            }
10833        })
10834    }
10835
10836    pub fn go_to_declaration(
10837        &mut self,
10838        _: &GoToDeclaration,
10839        window: &mut Window,
10840        cx: &mut Context<Self>,
10841    ) -> Task<Result<Navigated>> {
10842        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10843    }
10844
10845    pub fn go_to_declaration_split(
10846        &mut self,
10847        _: &GoToDeclaration,
10848        window: &mut Window,
10849        cx: &mut Context<Self>,
10850    ) -> Task<Result<Navigated>> {
10851        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10852    }
10853
10854    pub fn go_to_implementation(
10855        &mut self,
10856        _: &GoToImplementation,
10857        window: &mut Window,
10858        cx: &mut Context<Self>,
10859    ) -> Task<Result<Navigated>> {
10860        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10861    }
10862
10863    pub fn go_to_implementation_split(
10864        &mut self,
10865        _: &GoToImplementationSplit,
10866        window: &mut Window,
10867        cx: &mut Context<Self>,
10868    ) -> Task<Result<Navigated>> {
10869        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10870    }
10871
10872    pub fn go_to_type_definition(
10873        &mut self,
10874        _: &GoToTypeDefinition,
10875        window: &mut Window,
10876        cx: &mut Context<Self>,
10877    ) -> Task<Result<Navigated>> {
10878        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10879    }
10880
10881    pub fn go_to_definition_split(
10882        &mut self,
10883        _: &GoToDefinitionSplit,
10884        window: &mut Window,
10885        cx: &mut Context<Self>,
10886    ) -> Task<Result<Navigated>> {
10887        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10888    }
10889
10890    pub fn go_to_type_definition_split(
10891        &mut self,
10892        _: &GoToTypeDefinitionSplit,
10893        window: &mut Window,
10894        cx: &mut Context<Self>,
10895    ) -> Task<Result<Navigated>> {
10896        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10897    }
10898
10899    fn go_to_definition_of_kind(
10900        &mut self,
10901        kind: GotoDefinitionKind,
10902        split: bool,
10903        window: &mut Window,
10904        cx: &mut Context<Self>,
10905    ) -> Task<Result<Navigated>> {
10906        let Some(provider) = self.semantics_provider.clone() else {
10907            return Task::ready(Ok(Navigated::No));
10908        };
10909        let head = self.selections.newest::<usize>(cx).head();
10910        let buffer = self.buffer.read(cx);
10911        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10912            text_anchor
10913        } else {
10914            return Task::ready(Ok(Navigated::No));
10915        };
10916
10917        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10918            return Task::ready(Ok(Navigated::No));
10919        };
10920
10921        cx.spawn_in(window, |editor, mut cx| async move {
10922            let definitions = definitions.await?;
10923            let navigated = editor
10924                .update_in(&mut cx, |editor, window, cx| {
10925                    editor.navigate_to_hover_links(
10926                        Some(kind),
10927                        definitions
10928                            .into_iter()
10929                            .filter(|location| {
10930                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10931                            })
10932                            .map(HoverLink::Text)
10933                            .collect::<Vec<_>>(),
10934                        split,
10935                        window,
10936                        cx,
10937                    )
10938                })?
10939                .await?;
10940            anyhow::Ok(navigated)
10941        })
10942    }
10943
10944    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10945        let selection = self.selections.newest_anchor();
10946        let head = selection.head();
10947        let tail = selection.tail();
10948
10949        let Some((buffer, start_position)) =
10950            self.buffer.read(cx).text_anchor_for_position(head, cx)
10951        else {
10952            return;
10953        };
10954
10955        let end_position = if head != tail {
10956            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10957                return;
10958            };
10959            Some(pos)
10960        } else {
10961            None
10962        };
10963
10964        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10965            let url = if let Some(end_pos) = end_position {
10966                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10967            } else {
10968                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10969            };
10970
10971            if let Some(url) = url {
10972                editor.update(&mut cx, |_, cx| {
10973                    cx.open_url(&url);
10974                })
10975            } else {
10976                Ok(())
10977            }
10978        });
10979
10980        url_finder.detach();
10981    }
10982
10983    pub fn open_selected_filename(
10984        &mut self,
10985        _: &OpenSelectedFilename,
10986        window: &mut Window,
10987        cx: &mut Context<Self>,
10988    ) {
10989        let Some(workspace) = self.workspace() else {
10990            return;
10991        };
10992
10993        let position = self.selections.newest_anchor().head();
10994
10995        let Some((buffer, buffer_position)) =
10996            self.buffer.read(cx).text_anchor_for_position(position, cx)
10997        else {
10998            return;
10999        };
11000
11001        let project = self.project.clone();
11002
11003        cx.spawn_in(window, |_, mut cx| async move {
11004            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11005
11006            if let Some((_, path)) = result {
11007                workspace
11008                    .update_in(&mut cx, |workspace, window, cx| {
11009                        workspace.open_resolved_path(path, window, cx)
11010                    })?
11011                    .await?;
11012            }
11013            anyhow::Ok(())
11014        })
11015        .detach();
11016    }
11017
11018    pub(crate) fn navigate_to_hover_links(
11019        &mut self,
11020        kind: Option<GotoDefinitionKind>,
11021        mut definitions: Vec<HoverLink>,
11022        split: bool,
11023        window: &mut Window,
11024        cx: &mut Context<Editor>,
11025    ) -> Task<Result<Navigated>> {
11026        // If there is one definition, just open it directly
11027        if definitions.len() == 1 {
11028            let definition = definitions.pop().unwrap();
11029
11030            enum TargetTaskResult {
11031                Location(Option<Location>),
11032                AlreadyNavigated,
11033            }
11034
11035            let target_task = match definition {
11036                HoverLink::Text(link) => {
11037                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11038                }
11039                HoverLink::InlayHint(lsp_location, server_id) => {
11040                    let computation =
11041                        self.compute_target_location(lsp_location, server_id, window, cx);
11042                    cx.background_spawn(async move {
11043                        let location = computation.await?;
11044                        Ok(TargetTaskResult::Location(location))
11045                    })
11046                }
11047                HoverLink::Url(url) => {
11048                    cx.open_url(&url);
11049                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11050                }
11051                HoverLink::File(path) => {
11052                    if let Some(workspace) = self.workspace() {
11053                        cx.spawn_in(window, |_, mut cx| async move {
11054                            workspace
11055                                .update_in(&mut cx, |workspace, window, cx| {
11056                                    workspace.open_resolved_path(path, window, cx)
11057                                })?
11058                                .await
11059                                .map(|_| TargetTaskResult::AlreadyNavigated)
11060                        })
11061                    } else {
11062                        Task::ready(Ok(TargetTaskResult::Location(None)))
11063                    }
11064                }
11065            };
11066            cx.spawn_in(window, |editor, mut cx| async move {
11067                let target = match target_task.await.context("target resolution task")? {
11068                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11069                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11070                    TargetTaskResult::Location(Some(target)) => target,
11071                };
11072
11073                editor.update_in(&mut cx, |editor, window, cx| {
11074                    let Some(workspace) = editor.workspace() else {
11075                        return Navigated::No;
11076                    };
11077                    let pane = workspace.read(cx).active_pane().clone();
11078
11079                    let range = target.range.to_point(target.buffer.read(cx));
11080                    let range = editor.range_for_match(&range);
11081                    let range = collapse_multiline_range(range);
11082
11083                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
11084                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11085                    } else {
11086                        window.defer(cx, move |window, cx| {
11087                            let target_editor: Entity<Self> =
11088                                workspace.update(cx, |workspace, cx| {
11089                                    let pane = if split {
11090                                        workspace.adjacent_pane(window, cx)
11091                                    } else {
11092                                        workspace.active_pane().clone()
11093                                    };
11094
11095                                    workspace.open_project_item(
11096                                        pane,
11097                                        target.buffer.clone(),
11098                                        true,
11099                                        true,
11100                                        window,
11101                                        cx,
11102                                    )
11103                                });
11104                            target_editor.update(cx, |target_editor, cx| {
11105                                // When selecting a definition in a different buffer, disable the nav history
11106                                // to avoid creating a history entry at the previous cursor location.
11107                                pane.update(cx, |pane, _| pane.disable_history());
11108                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11109                                pane.update(cx, |pane, _| pane.enable_history());
11110                            });
11111                        });
11112                    }
11113                    Navigated::Yes
11114                })
11115            })
11116        } else if !definitions.is_empty() {
11117            cx.spawn_in(window, |editor, mut cx| async move {
11118                let (title, location_tasks, workspace) = editor
11119                    .update_in(&mut cx, |editor, window, cx| {
11120                        let tab_kind = match kind {
11121                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11122                            _ => "Definitions",
11123                        };
11124                        let title = definitions
11125                            .iter()
11126                            .find_map(|definition| match definition {
11127                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11128                                    let buffer = origin.buffer.read(cx);
11129                                    format!(
11130                                        "{} for {}",
11131                                        tab_kind,
11132                                        buffer
11133                                            .text_for_range(origin.range.clone())
11134                                            .collect::<String>()
11135                                    )
11136                                }),
11137                                HoverLink::InlayHint(_, _) => None,
11138                                HoverLink::Url(_) => None,
11139                                HoverLink::File(_) => None,
11140                            })
11141                            .unwrap_or(tab_kind.to_string());
11142                        let location_tasks = definitions
11143                            .into_iter()
11144                            .map(|definition| match definition {
11145                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11146                                HoverLink::InlayHint(lsp_location, server_id) => editor
11147                                    .compute_target_location(lsp_location, server_id, window, cx),
11148                                HoverLink::Url(_) => Task::ready(Ok(None)),
11149                                HoverLink::File(_) => Task::ready(Ok(None)),
11150                            })
11151                            .collect::<Vec<_>>();
11152                        (title, location_tasks, editor.workspace().clone())
11153                    })
11154                    .context("location tasks preparation")?;
11155
11156                let locations = future::join_all(location_tasks)
11157                    .await
11158                    .into_iter()
11159                    .filter_map(|location| location.transpose())
11160                    .collect::<Result<_>>()
11161                    .context("location tasks")?;
11162
11163                let Some(workspace) = workspace else {
11164                    return Ok(Navigated::No);
11165                };
11166                let opened = workspace
11167                    .update_in(&mut cx, |workspace, window, cx| {
11168                        Self::open_locations_in_multibuffer(
11169                            workspace,
11170                            locations,
11171                            title,
11172                            split,
11173                            MultibufferSelectionMode::First,
11174                            window,
11175                            cx,
11176                        )
11177                    })
11178                    .ok();
11179
11180                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11181            })
11182        } else {
11183            Task::ready(Ok(Navigated::No))
11184        }
11185    }
11186
11187    fn compute_target_location(
11188        &self,
11189        lsp_location: lsp::Location,
11190        server_id: LanguageServerId,
11191        window: &mut Window,
11192        cx: &mut Context<Self>,
11193    ) -> Task<anyhow::Result<Option<Location>>> {
11194        let Some(project) = self.project.clone() else {
11195            return Task::ready(Ok(None));
11196        };
11197
11198        cx.spawn_in(window, move |editor, mut cx| async move {
11199            let location_task = editor.update(&mut cx, |_, cx| {
11200                project.update(cx, |project, cx| {
11201                    let language_server_name = project
11202                        .language_server_statuses(cx)
11203                        .find(|(id, _)| server_id == *id)
11204                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11205                    language_server_name.map(|language_server_name| {
11206                        project.open_local_buffer_via_lsp(
11207                            lsp_location.uri.clone(),
11208                            server_id,
11209                            language_server_name,
11210                            cx,
11211                        )
11212                    })
11213                })
11214            })?;
11215            let location = match location_task {
11216                Some(task) => Some({
11217                    let target_buffer_handle = task.await.context("open local buffer")?;
11218                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11219                        let target_start = target_buffer
11220                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11221                        let target_end = target_buffer
11222                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11223                        target_buffer.anchor_after(target_start)
11224                            ..target_buffer.anchor_before(target_end)
11225                    })?;
11226                    Location {
11227                        buffer: target_buffer_handle,
11228                        range,
11229                    }
11230                }),
11231                None => None,
11232            };
11233            Ok(location)
11234        })
11235    }
11236
11237    pub fn find_all_references(
11238        &mut self,
11239        _: &FindAllReferences,
11240        window: &mut Window,
11241        cx: &mut Context<Self>,
11242    ) -> Option<Task<Result<Navigated>>> {
11243        let selection = self.selections.newest::<usize>(cx);
11244        let multi_buffer = self.buffer.read(cx);
11245        let head = selection.head();
11246
11247        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11248        let head_anchor = multi_buffer_snapshot.anchor_at(
11249            head,
11250            if head < selection.tail() {
11251                Bias::Right
11252            } else {
11253                Bias::Left
11254            },
11255        );
11256
11257        match self
11258            .find_all_references_task_sources
11259            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11260        {
11261            Ok(_) => {
11262                log::info!(
11263                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11264                );
11265                return None;
11266            }
11267            Err(i) => {
11268                self.find_all_references_task_sources.insert(i, head_anchor);
11269            }
11270        }
11271
11272        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11273        let workspace = self.workspace()?;
11274        let project = workspace.read(cx).project().clone();
11275        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11276        Some(cx.spawn_in(window, |editor, mut cx| async move {
11277            let _cleanup = defer({
11278                let mut cx = cx.clone();
11279                move || {
11280                    let _ = editor.update(&mut cx, |editor, _| {
11281                        if let Ok(i) =
11282                            editor
11283                                .find_all_references_task_sources
11284                                .binary_search_by(|anchor| {
11285                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11286                                })
11287                        {
11288                            editor.find_all_references_task_sources.remove(i);
11289                        }
11290                    });
11291                }
11292            });
11293
11294            let locations = references.await?;
11295            if locations.is_empty() {
11296                return anyhow::Ok(Navigated::No);
11297            }
11298
11299            workspace.update_in(&mut cx, |workspace, window, cx| {
11300                let title = locations
11301                    .first()
11302                    .as_ref()
11303                    .map(|location| {
11304                        let buffer = location.buffer.read(cx);
11305                        format!(
11306                            "References to `{}`",
11307                            buffer
11308                                .text_for_range(location.range.clone())
11309                                .collect::<String>()
11310                        )
11311                    })
11312                    .unwrap();
11313                Self::open_locations_in_multibuffer(
11314                    workspace,
11315                    locations,
11316                    title,
11317                    false,
11318                    MultibufferSelectionMode::First,
11319                    window,
11320                    cx,
11321                );
11322                Navigated::Yes
11323            })
11324        }))
11325    }
11326
11327    /// Opens a multibuffer with the given project locations in it
11328    pub fn open_locations_in_multibuffer(
11329        workspace: &mut Workspace,
11330        mut locations: Vec<Location>,
11331        title: String,
11332        split: bool,
11333        multibuffer_selection_mode: MultibufferSelectionMode,
11334        window: &mut Window,
11335        cx: &mut Context<Workspace>,
11336    ) {
11337        // If there are multiple definitions, open them in a multibuffer
11338        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11339        let mut locations = locations.into_iter().peekable();
11340        let mut ranges = Vec::new();
11341        let capability = workspace.project().read(cx).capability();
11342
11343        let excerpt_buffer = cx.new(|cx| {
11344            let mut multibuffer = MultiBuffer::new(capability);
11345            while let Some(location) = locations.next() {
11346                let buffer = location.buffer.read(cx);
11347                let mut ranges_for_buffer = Vec::new();
11348                let range = location.range.to_offset(buffer);
11349                ranges_for_buffer.push(range.clone());
11350
11351                while let Some(next_location) = locations.peek() {
11352                    if next_location.buffer == location.buffer {
11353                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11354                        locations.next();
11355                    } else {
11356                        break;
11357                    }
11358                }
11359
11360                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11361                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11362                    location.buffer.clone(),
11363                    ranges_for_buffer,
11364                    DEFAULT_MULTIBUFFER_CONTEXT,
11365                    cx,
11366                ))
11367            }
11368
11369            multibuffer.with_title(title)
11370        });
11371
11372        let editor = cx.new(|cx| {
11373            Editor::for_multibuffer(
11374                excerpt_buffer,
11375                Some(workspace.project().clone()),
11376                true,
11377                window,
11378                cx,
11379            )
11380        });
11381        editor.update(cx, |editor, cx| {
11382            match multibuffer_selection_mode {
11383                MultibufferSelectionMode::First => {
11384                    if let Some(first_range) = ranges.first() {
11385                        editor.change_selections(None, window, cx, |selections| {
11386                            selections.clear_disjoint();
11387                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11388                        });
11389                    }
11390                    editor.highlight_background::<Self>(
11391                        &ranges,
11392                        |theme| theme.editor_highlighted_line_background,
11393                        cx,
11394                    );
11395                }
11396                MultibufferSelectionMode::All => {
11397                    editor.change_selections(None, window, cx, |selections| {
11398                        selections.clear_disjoint();
11399                        selections.select_anchor_ranges(ranges);
11400                    });
11401                }
11402            }
11403            editor.register_buffers_with_language_servers(cx);
11404        });
11405
11406        let item = Box::new(editor);
11407        let item_id = item.item_id();
11408
11409        if split {
11410            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11411        } else {
11412            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11413                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11414                    pane.close_current_preview_item(window, cx)
11415                } else {
11416                    None
11417                }
11418            });
11419            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11420        }
11421        workspace.active_pane().update(cx, |pane, cx| {
11422            pane.set_preview_item_id(Some(item_id), cx);
11423        });
11424    }
11425
11426    pub fn rename(
11427        &mut self,
11428        _: &Rename,
11429        window: &mut Window,
11430        cx: &mut Context<Self>,
11431    ) -> Option<Task<Result<()>>> {
11432        use language::ToOffset as _;
11433
11434        let provider = self.semantics_provider.clone()?;
11435        let selection = self.selections.newest_anchor().clone();
11436        let (cursor_buffer, cursor_buffer_position) = self
11437            .buffer
11438            .read(cx)
11439            .text_anchor_for_position(selection.head(), cx)?;
11440        let (tail_buffer, cursor_buffer_position_end) = self
11441            .buffer
11442            .read(cx)
11443            .text_anchor_for_position(selection.tail(), cx)?;
11444        if tail_buffer != cursor_buffer {
11445            return None;
11446        }
11447
11448        let snapshot = cursor_buffer.read(cx).snapshot();
11449        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11450        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11451        let prepare_rename = provider
11452            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11453            .unwrap_or_else(|| Task::ready(Ok(None)));
11454        drop(snapshot);
11455
11456        Some(cx.spawn_in(window, |this, mut cx| async move {
11457            let rename_range = if let Some(range) = prepare_rename.await? {
11458                Some(range)
11459            } else {
11460                this.update(&mut cx, |this, cx| {
11461                    let buffer = this.buffer.read(cx).snapshot(cx);
11462                    let mut buffer_highlights = this
11463                        .document_highlights_for_position(selection.head(), &buffer)
11464                        .filter(|highlight| {
11465                            highlight.start.excerpt_id == selection.head().excerpt_id
11466                                && highlight.end.excerpt_id == selection.head().excerpt_id
11467                        });
11468                    buffer_highlights
11469                        .next()
11470                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11471                })?
11472            };
11473            if let Some(rename_range) = rename_range {
11474                this.update_in(&mut cx, |this, window, cx| {
11475                    let snapshot = cursor_buffer.read(cx).snapshot();
11476                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11477                    let cursor_offset_in_rename_range =
11478                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11479                    let cursor_offset_in_rename_range_end =
11480                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11481
11482                    this.take_rename(false, window, cx);
11483                    let buffer = this.buffer.read(cx).read(cx);
11484                    let cursor_offset = selection.head().to_offset(&buffer);
11485                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11486                    let rename_end = rename_start + rename_buffer_range.len();
11487                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11488                    let mut old_highlight_id = None;
11489                    let old_name: Arc<str> = buffer
11490                        .chunks(rename_start..rename_end, true)
11491                        .map(|chunk| {
11492                            if old_highlight_id.is_none() {
11493                                old_highlight_id = chunk.syntax_highlight_id;
11494                            }
11495                            chunk.text
11496                        })
11497                        .collect::<String>()
11498                        .into();
11499
11500                    drop(buffer);
11501
11502                    // Position the selection in the rename editor so that it matches the current selection.
11503                    this.show_local_selections = false;
11504                    let rename_editor = cx.new(|cx| {
11505                        let mut editor = Editor::single_line(window, cx);
11506                        editor.buffer.update(cx, |buffer, cx| {
11507                            buffer.edit([(0..0, old_name.clone())], None, cx)
11508                        });
11509                        let rename_selection_range = match cursor_offset_in_rename_range
11510                            .cmp(&cursor_offset_in_rename_range_end)
11511                        {
11512                            Ordering::Equal => {
11513                                editor.select_all(&SelectAll, window, cx);
11514                                return editor;
11515                            }
11516                            Ordering::Less => {
11517                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11518                            }
11519                            Ordering::Greater => {
11520                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11521                            }
11522                        };
11523                        if rename_selection_range.end > old_name.len() {
11524                            editor.select_all(&SelectAll, window, cx);
11525                        } else {
11526                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11527                                s.select_ranges([rename_selection_range]);
11528                            });
11529                        }
11530                        editor
11531                    });
11532                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11533                        if e == &EditorEvent::Focused {
11534                            cx.emit(EditorEvent::FocusedIn)
11535                        }
11536                    })
11537                    .detach();
11538
11539                    let write_highlights =
11540                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11541                    let read_highlights =
11542                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11543                    let ranges = write_highlights
11544                        .iter()
11545                        .flat_map(|(_, ranges)| ranges.iter())
11546                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11547                        .cloned()
11548                        .collect();
11549
11550                    this.highlight_text::<Rename>(
11551                        ranges,
11552                        HighlightStyle {
11553                            fade_out: Some(0.6),
11554                            ..Default::default()
11555                        },
11556                        cx,
11557                    );
11558                    let rename_focus_handle = rename_editor.focus_handle(cx);
11559                    window.focus(&rename_focus_handle);
11560                    let block_id = this.insert_blocks(
11561                        [BlockProperties {
11562                            style: BlockStyle::Flex,
11563                            placement: BlockPlacement::Below(range.start),
11564                            height: 1,
11565                            render: Arc::new({
11566                                let rename_editor = rename_editor.clone();
11567                                move |cx: &mut BlockContext| {
11568                                    let mut text_style = cx.editor_style.text.clone();
11569                                    if let Some(highlight_style) = old_highlight_id
11570                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11571                                    {
11572                                        text_style = text_style.highlight(highlight_style);
11573                                    }
11574                                    div()
11575                                        .block_mouse_down()
11576                                        .pl(cx.anchor_x)
11577                                        .child(EditorElement::new(
11578                                            &rename_editor,
11579                                            EditorStyle {
11580                                                background: cx.theme().system().transparent,
11581                                                local_player: cx.editor_style.local_player,
11582                                                text: text_style,
11583                                                scrollbar_width: cx.editor_style.scrollbar_width,
11584                                                syntax: cx.editor_style.syntax.clone(),
11585                                                status: cx.editor_style.status.clone(),
11586                                                inlay_hints_style: HighlightStyle {
11587                                                    font_weight: Some(FontWeight::BOLD),
11588                                                    ..make_inlay_hints_style(cx.app)
11589                                                },
11590                                                inline_completion_styles: make_suggestion_styles(
11591                                                    cx.app,
11592                                                ),
11593                                                ..EditorStyle::default()
11594                                            },
11595                                        ))
11596                                        .into_any_element()
11597                                }
11598                            }),
11599                            priority: 0,
11600                        }],
11601                        Some(Autoscroll::fit()),
11602                        cx,
11603                    )[0];
11604                    this.pending_rename = Some(RenameState {
11605                        range,
11606                        old_name,
11607                        editor: rename_editor,
11608                        block_id,
11609                    });
11610                })?;
11611            }
11612
11613            Ok(())
11614        }))
11615    }
11616
11617    pub fn confirm_rename(
11618        &mut self,
11619        _: &ConfirmRename,
11620        window: &mut Window,
11621        cx: &mut Context<Self>,
11622    ) -> Option<Task<Result<()>>> {
11623        let rename = self.take_rename(false, window, cx)?;
11624        let workspace = self.workspace()?.downgrade();
11625        let (buffer, start) = self
11626            .buffer
11627            .read(cx)
11628            .text_anchor_for_position(rename.range.start, cx)?;
11629        let (end_buffer, _) = self
11630            .buffer
11631            .read(cx)
11632            .text_anchor_for_position(rename.range.end, cx)?;
11633        if buffer != end_buffer {
11634            return None;
11635        }
11636
11637        let old_name = rename.old_name;
11638        let new_name = rename.editor.read(cx).text(cx);
11639
11640        let rename = self.semantics_provider.as_ref()?.perform_rename(
11641            &buffer,
11642            start,
11643            new_name.clone(),
11644            cx,
11645        )?;
11646
11647        Some(cx.spawn_in(window, |editor, mut cx| async move {
11648            let project_transaction = rename.await?;
11649            Self::open_project_transaction(
11650                &editor,
11651                workspace,
11652                project_transaction,
11653                format!("Rename: {}{}", old_name, new_name),
11654                cx.clone(),
11655            )
11656            .await?;
11657
11658            editor.update(&mut cx, |editor, cx| {
11659                editor.refresh_document_highlights(cx);
11660            })?;
11661            Ok(())
11662        }))
11663    }
11664
11665    fn take_rename(
11666        &mut self,
11667        moving_cursor: bool,
11668        window: &mut Window,
11669        cx: &mut Context<Self>,
11670    ) -> Option<RenameState> {
11671        let rename = self.pending_rename.take()?;
11672        if rename.editor.focus_handle(cx).is_focused(window) {
11673            window.focus(&self.focus_handle);
11674        }
11675
11676        self.remove_blocks(
11677            [rename.block_id].into_iter().collect(),
11678            Some(Autoscroll::fit()),
11679            cx,
11680        );
11681        self.clear_highlights::<Rename>(cx);
11682        self.show_local_selections = true;
11683
11684        if moving_cursor {
11685            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11686                editor.selections.newest::<usize>(cx).head()
11687            });
11688
11689            // Update the selection to match the position of the selection inside
11690            // the rename editor.
11691            let snapshot = self.buffer.read(cx).read(cx);
11692            let rename_range = rename.range.to_offset(&snapshot);
11693            let cursor_in_editor = snapshot
11694                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11695                .min(rename_range.end);
11696            drop(snapshot);
11697
11698            self.change_selections(None, window, cx, |s| {
11699                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11700            });
11701        } else {
11702            self.refresh_document_highlights(cx);
11703        }
11704
11705        Some(rename)
11706    }
11707
11708    pub fn pending_rename(&self) -> Option<&RenameState> {
11709        self.pending_rename.as_ref()
11710    }
11711
11712    fn format(
11713        &mut self,
11714        _: &Format,
11715        window: &mut Window,
11716        cx: &mut Context<Self>,
11717    ) -> Option<Task<Result<()>>> {
11718        let project = match &self.project {
11719            Some(project) => project.clone(),
11720            None => return None,
11721        };
11722
11723        Some(self.perform_format(
11724            project,
11725            FormatTrigger::Manual,
11726            FormatTarget::Buffers,
11727            window,
11728            cx,
11729        ))
11730    }
11731
11732    fn format_selections(
11733        &mut self,
11734        _: &FormatSelections,
11735        window: &mut Window,
11736        cx: &mut Context<Self>,
11737    ) -> Option<Task<Result<()>>> {
11738        let project = match &self.project {
11739            Some(project) => project.clone(),
11740            None => return None,
11741        };
11742
11743        let ranges = self
11744            .selections
11745            .all_adjusted(cx)
11746            .into_iter()
11747            .map(|selection| selection.range())
11748            .collect_vec();
11749
11750        Some(self.perform_format(
11751            project,
11752            FormatTrigger::Manual,
11753            FormatTarget::Ranges(ranges),
11754            window,
11755            cx,
11756        ))
11757    }
11758
11759    fn perform_format(
11760        &mut self,
11761        project: Entity<Project>,
11762        trigger: FormatTrigger,
11763        target: FormatTarget,
11764        window: &mut Window,
11765        cx: &mut Context<Self>,
11766    ) -> Task<Result<()>> {
11767        let buffer = self.buffer.clone();
11768        let (buffers, target) = match target {
11769            FormatTarget::Buffers => {
11770                let mut buffers = buffer.read(cx).all_buffers();
11771                if trigger == FormatTrigger::Save {
11772                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11773                }
11774                (buffers, LspFormatTarget::Buffers)
11775            }
11776            FormatTarget::Ranges(selection_ranges) => {
11777                let multi_buffer = buffer.read(cx);
11778                let snapshot = multi_buffer.read(cx);
11779                let mut buffers = HashSet::default();
11780                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11781                    BTreeMap::new();
11782                for selection_range in selection_ranges {
11783                    for (buffer, buffer_range, _) in
11784                        snapshot.range_to_buffer_ranges(selection_range)
11785                    {
11786                        let buffer_id = buffer.remote_id();
11787                        let start = buffer.anchor_before(buffer_range.start);
11788                        let end = buffer.anchor_after(buffer_range.end);
11789                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11790                        buffer_id_to_ranges
11791                            .entry(buffer_id)
11792                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11793                            .or_insert_with(|| vec![start..end]);
11794                    }
11795                }
11796                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11797            }
11798        };
11799
11800        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11801        let format = project.update(cx, |project, cx| {
11802            project.format(buffers, target, true, trigger, cx)
11803        });
11804
11805        cx.spawn_in(window, |_, mut cx| async move {
11806            let transaction = futures::select_biased! {
11807                () = timeout => {
11808                    log::warn!("timed out waiting for formatting");
11809                    None
11810                }
11811                transaction = format.log_err().fuse() => transaction,
11812            };
11813
11814            buffer
11815                .update(&mut cx, |buffer, cx| {
11816                    if let Some(transaction) = transaction {
11817                        if !buffer.is_singleton() {
11818                            buffer.push_transaction(&transaction.0, cx);
11819                        }
11820                    }
11821
11822                    cx.notify();
11823                })
11824                .ok();
11825
11826            Ok(())
11827        })
11828    }
11829
11830    fn restart_language_server(
11831        &mut self,
11832        _: &RestartLanguageServer,
11833        _: &mut Window,
11834        cx: &mut Context<Self>,
11835    ) {
11836        if let Some(project) = self.project.clone() {
11837            self.buffer.update(cx, |multi_buffer, cx| {
11838                project.update(cx, |project, cx| {
11839                    project.restart_language_servers_for_buffers(
11840                        multi_buffer.all_buffers().into_iter().collect(),
11841                        cx,
11842                    );
11843                });
11844            })
11845        }
11846    }
11847
11848    fn cancel_language_server_work(
11849        workspace: &mut Workspace,
11850        _: &actions::CancelLanguageServerWork,
11851        _: &mut Window,
11852        cx: &mut Context<Workspace>,
11853    ) {
11854        let project = workspace.project();
11855        let buffers = workspace
11856            .active_item(cx)
11857            .and_then(|item| item.act_as::<Editor>(cx))
11858            .map_or(HashSet::default(), |editor| {
11859                editor.read(cx).buffer.read(cx).all_buffers()
11860            });
11861        project.update(cx, |project, cx| {
11862            project.cancel_language_server_work_for_buffers(buffers, cx);
11863        });
11864    }
11865
11866    fn show_character_palette(
11867        &mut self,
11868        _: &ShowCharacterPalette,
11869        window: &mut Window,
11870        _: &mut Context<Self>,
11871    ) {
11872        window.show_character_palette();
11873    }
11874
11875    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11876        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11877            let buffer = self.buffer.read(cx).snapshot(cx);
11878            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11879            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11880            let is_valid = buffer
11881                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11882                .any(|entry| {
11883                    entry.diagnostic.is_primary
11884                        && !entry.range.is_empty()
11885                        && entry.range.start == primary_range_start
11886                        && entry.diagnostic.message == active_diagnostics.primary_message
11887                });
11888
11889            if is_valid != active_diagnostics.is_valid {
11890                active_diagnostics.is_valid = is_valid;
11891                let mut new_styles = HashMap::default();
11892                for (block_id, diagnostic) in &active_diagnostics.blocks {
11893                    new_styles.insert(
11894                        *block_id,
11895                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11896                    );
11897                }
11898                self.display_map.update(cx, |display_map, _cx| {
11899                    display_map.replace_blocks(new_styles)
11900                });
11901            }
11902        }
11903    }
11904
11905    fn activate_diagnostics(
11906        &mut self,
11907        buffer_id: BufferId,
11908        group_id: usize,
11909        window: &mut Window,
11910        cx: &mut Context<Self>,
11911    ) {
11912        self.dismiss_diagnostics(cx);
11913        let snapshot = self.snapshot(window, cx);
11914        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11915            let buffer = self.buffer.read(cx).snapshot(cx);
11916
11917            let mut primary_range = None;
11918            let mut primary_message = None;
11919            let diagnostic_group = buffer
11920                .diagnostic_group(buffer_id, group_id)
11921                .filter_map(|entry| {
11922                    let start = entry.range.start;
11923                    let end = entry.range.end;
11924                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11925                        && (start.row == end.row
11926                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11927                    {
11928                        return None;
11929                    }
11930                    if entry.diagnostic.is_primary {
11931                        primary_range = Some(entry.range.clone());
11932                        primary_message = Some(entry.diagnostic.message.clone());
11933                    }
11934                    Some(entry)
11935                })
11936                .collect::<Vec<_>>();
11937            let primary_range = primary_range?;
11938            let primary_message = primary_message?;
11939
11940            let blocks = display_map
11941                .insert_blocks(
11942                    diagnostic_group.iter().map(|entry| {
11943                        let diagnostic = entry.diagnostic.clone();
11944                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11945                        BlockProperties {
11946                            style: BlockStyle::Fixed,
11947                            placement: BlockPlacement::Below(
11948                                buffer.anchor_after(entry.range.start),
11949                            ),
11950                            height: message_height,
11951                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11952                            priority: 0,
11953                        }
11954                    }),
11955                    cx,
11956                )
11957                .into_iter()
11958                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11959                .collect();
11960
11961            Some(ActiveDiagnosticGroup {
11962                primary_range: buffer.anchor_before(primary_range.start)
11963                    ..buffer.anchor_after(primary_range.end),
11964                primary_message,
11965                group_id,
11966                blocks,
11967                is_valid: true,
11968            })
11969        });
11970    }
11971
11972    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11973        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11974            self.display_map.update(cx, |display_map, cx| {
11975                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11976            });
11977            cx.notify();
11978        }
11979    }
11980
11981    /// Disable inline diagnostics rendering for this editor.
11982    pub fn disable_inline_diagnostics(&mut self) {
11983        self.inline_diagnostics_enabled = false;
11984        self.inline_diagnostics_update = Task::ready(());
11985        self.inline_diagnostics.clear();
11986    }
11987
11988    pub fn inline_diagnostics_enabled(&self) -> bool {
11989        self.inline_diagnostics_enabled
11990    }
11991
11992    pub fn show_inline_diagnostics(&self) -> bool {
11993        self.show_inline_diagnostics
11994    }
11995
11996    pub fn toggle_inline_diagnostics(
11997        &mut self,
11998        _: &ToggleInlineDiagnostics,
11999        window: &mut Window,
12000        cx: &mut Context<'_, Editor>,
12001    ) {
12002        self.show_inline_diagnostics = !self.show_inline_diagnostics;
12003        self.refresh_inline_diagnostics(false, window, cx);
12004    }
12005
12006    fn refresh_inline_diagnostics(
12007        &mut self,
12008        debounce: bool,
12009        window: &mut Window,
12010        cx: &mut Context<Self>,
12011    ) {
12012        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12013            self.inline_diagnostics_update = Task::ready(());
12014            self.inline_diagnostics.clear();
12015            return;
12016        }
12017
12018        let debounce_ms = ProjectSettings::get_global(cx)
12019            .diagnostics
12020            .inline
12021            .update_debounce_ms;
12022        let debounce = if debounce && debounce_ms > 0 {
12023            Some(Duration::from_millis(debounce_ms))
12024        } else {
12025            None
12026        };
12027        self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12028            if let Some(debounce) = debounce {
12029                cx.background_executor().timer(debounce).await;
12030            }
12031            let Some(snapshot) = editor
12032                .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12033                .ok()
12034            else {
12035                return;
12036            };
12037
12038            let new_inline_diagnostics = cx
12039                .background_spawn(async move {
12040                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12041                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12042                        let message = diagnostic_entry
12043                            .diagnostic
12044                            .message
12045                            .split_once('\n')
12046                            .map(|(line, _)| line)
12047                            .map(SharedString::new)
12048                            .unwrap_or_else(|| {
12049                                SharedString::from(diagnostic_entry.diagnostic.message)
12050                            });
12051                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12052                        let (Ok(i) | Err(i)) = inline_diagnostics
12053                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12054                        inline_diagnostics.insert(
12055                            i,
12056                            (
12057                                start_anchor,
12058                                InlineDiagnostic {
12059                                    message,
12060                                    group_id: diagnostic_entry.diagnostic.group_id,
12061                                    start: diagnostic_entry.range.start.to_point(&snapshot),
12062                                    is_primary: diagnostic_entry.diagnostic.is_primary,
12063                                    severity: diagnostic_entry.diagnostic.severity,
12064                                },
12065                            ),
12066                        );
12067                    }
12068                    inline_diagnostics
12069                })
12070                .await;
12071
12072            editor
12073                .update(&mut cx, |editor, cx| {
12074                    editor.inline_diagnostics = new_inline_diagnostics;
12075                    cx.notify();
12076                })
12077                .ok();
12078        });
12079    }
12080
12081    pub fn set_selections_from_remote(
12082        &mut self,
12083        selections: Vec<Selection<Anchor>>,
12084        pending_selection: Option<Selection<Anchor>>,
12085        window: &mut Window,
12086        cx: &mut Context<Self>,
12087    ) {
12088        let old_cursor_position = self.selections.newest_anchor().head();
12089        self.selections.change_with(cx, |s| {
12090            s.select_anchors(selections);
12091            if let Some(pending_selection) = pending_selection {
12092                s.set_pending(pending_selection, SelectMode::Character);
12093            } else {
12094                s.clear_pending();
12095            }
12096        });
12097        self.selections_did_change(false, &old_cursor_position, true, window, cx);
12098    }
12099
12100    fn push_to_selection_history(&mut self) {
12101        self.selection_history.push(SelectionHistoryEntry {
12102            selections: self.selections.disjoint_anchors(),
12103            select_next_state: self.select_next_state.clone(),
12104            select_prev_state: self.select_prev_state.clone(),
12105            add_selections_state: self.add_selections_state.clone(),
12106        });
12107    }
12108
12109    pub fn transact(
12110        &mut self,
12111        window: &mut Window,
12112        cx: &mut Context<Self>,
12113        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12114    ) -> Option<TransactionId> {
12115        self.start_transaction_at(Instant::now(), window, cx);
12116        update(self, window, cx);
12117        self.end_transaction_at(Instant::now(), cx)
12118    }
12119
12120    pub fn start_transaction_at(
12121        &mut self,
12122        now: Instant,
12123        window: &mut Window,
12124        cx: &mut Context<Self>,
12125    ) {
12126        self.end_selection(window, cx);
12127        if let Some(tx_id) = self
12128            .buffer
12129            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12130        {
12131            self.selection_history
12132                .insert_transaction(tx_id, self.selections.disjoint_anchors());
12133            cx.emit(EditorEvent::TransactionBegun {
12134                transaction_id: tx_id,
12135            })
12136        }
12137    }
12138
12139    pub fn end_transaction_at(
12140        &mut self,
12141        now: Instant,
12142        cx: &mut Context<Self>,
12143    ) -> Option<TransactionId> {
12144        if let Some(transaction_id) = self
12145            .buffer
12146            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12147        {
12148            if let Some((_, end_selections)) =
12149                self.selection_history.transaction_mut(transaction_id)
12150            {
12151                *end_selections = Some(self.selections.disjoint_anchors());
12152            } else {
12153                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12154            }
12155
12156            cx.emit(EditorEvent::Edited { transaction_id });
12157            Some(transaction_id)
12158        } else {
12159            None
12160        }
12161    }
12162
12163    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12164        if self.selection_mark_mode {
12165            self.change_selections(None, window, cx, |s| {
12166                s.move_with(|_, sel| {
12167                    sel.collapse_to(sel.head(), SelectionGoal::None);
12168                });
12169            })
12170        }
12171        self.selection_mark_mode = true;
12172        cx.notify();
12173    }
12174
12175    pub fn swap_selection_ends(
12176        &mut self,
12177        _: &actions::SwapSelectionEnds,
12178        window: &mut Window,
12179        cx: &mut Context<Self>,
12180    ) {
12181        self.change_selections(None, window, cx, |s| {
12182            s.move_with(|_, sel| {
12183                if sel.start != sel.end {
12184                    sel.reversed = !sel.reversed
12185                }
12186            });
12187        });
12188        self.request_autoscroll(Autoscroll::newest(), cx);
12189        cx.notify();
12190    }
12191
12192    pub fn toggle_fold(
12193        &mut self,
12194        _: &actions::ToggleFold,
12195        window: &mut Window,
12196        cx: &mut Context<Self>,
12197    ) {
12198        if self.is_singleton(cx) {
12199            let selection = self.selections.newest::<Point>(cx);
12200
12201            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12202            let range = if selection.is_empty() {
12203                let point = selection.head().to_display_point(&display_map);
12204                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12205                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12206                    .to_point(&display_map);
12207                start..end
12208            } else {
12209                selection.range()
12210            };
12211            if display_map.folds_in_range(range).next().is_some() {
12212                self.unfold_lines(&Default::default(), window, cx)
12213            } else {
12214                self.fold(&Default::default(), window, cx)
12215            }
12216        } else {
12217            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12218            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12219                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12220                .map(|(snapshot, _, _)| snapshot.remote_id())
12221                .collect();
12222
12223            for buffer_id in buffer_ids {
12224                if self.is_buffer_folded(buffer_id, cx) {
12225                    self.unfold_buffer(buffer_id, cx);
12226                } else {
12227                    self.fold_buffer(buffer_id, cx);
12228                }
12229            }
12230        }
12231    }
12232
12233    pub fn toggle_fold_recursive(
12234        &mut self,
12235        _: &actions::ToggleFoldRecursive,
12236        window: &mut Window,
12237        cx: &mut Context<Self>,
12238    ) {
12239        let selection = self.selections.newest::<Point>(cx);
12240
12241        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12242        let range = if selection.is_empty() {
12243            let point = selection.head().to_display_point(&display_map);
12244            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12245            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12246                .to_point(&display_map);
12247            start..end
12248        } else {
12249            selection.range()
12250        };
12251        if display_map.folds_in_range(range).next().is_some() {
12252            self.unfold_recursive(&Default::default(), window, cx)
12253        } else {
12254            self.fold_recursive(&Default::default(), window, cx)
12255        }
12256    }
12257
12258    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12259        if self.is_singleton(cx) {
12260            let mut to_fold = Vec::new();
12261            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12262            let selections = self.selections.all_adjusted(cx);
12263
12264            for selection in selections {
12265                let range = selection.range().sorted();
12266                let buffer_start_row = range.start.row;
12267
12268                if range.start.row != range.end.row {
12269                    let mut found = false;
12270                    let mut row = range.start.row;
12271                    while row <= range.end.row {
12272                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12273                        {
12274                            found = true;
12275                            row = crease.range().end.row + 1;
12276                            to_fold.push(crease);
12277                        } else {
12278                            row += 1
12279                        }
12280                    }
12281                    if found {
12282                        continue;
12283                    }
12284                }
12285
12286                for row in (0..=range.start.row).rev() {
12287                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12288                        if crease.range().end.row >= buffer_start_row {
12289                            to_fold.push(crease);
12290                            if row <= range.start.row {
12291                                break;
12292                            }
12293                        }
12294                    }
12295                }
12296            }
12297
12298            self.fold_creases(to_fold, true, window, cx);
12299        } else {
12300            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12301
12302            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12303                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12304                .map(|(snapshot, _, _)| snapshot.remote_id())
12305                .collect();
12306            for buffer_id in buffer_ids {
12307                self.fold_buffer(buffer_id, cx);
12308            }
12309        }
12310    }
12311
12312    fn fold_at_level(
12313        &mut self,
12314        fold_at: &FoldAtLevel,
12315        window: &mut Window,
12316        cx: &mut Context<Self>,
12317    ) {
12318        if !self.buffer.read(cx).is_singleton() {
12319            return;
12320        }
12321
12322        let fold_at_level = fold_at.0;
12323        let snapshot = self.buffer.read(cx).snapshot(cx);
12324        let mut to_fold = Vec::new();
12325        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12326
12327        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12328            while start_row < end_row {
12329                match self
12330                    .snapshot(window, cx)
12331                    .crease_for_buffer_row(MultiBufferRow(start_row))
12332                {
12333                    Some(crease) => {
12334                        let nested_start_row = crease.range().start.row + 1;
12335                        let nested_end_row = crease.range().end.row;
12336
12337                        if current_level < fold_at_level {
12338                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12339                        } else if current_level == fold_at_level {
12340                            to_fold.push(crease);
12341                        }
12342
12343                        start_row = nested_end_row + 1;
12344                    }
12345                    None => start_row += 1,
12346                }
12347            }
12348        }
12349
12350        self.fold_creases(to_fold, true, window, cx);
12351    }
12352
12353    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12354        if self.buffer.read(cx).is_singleton() {
12355            let mut fold_ranges = Vec::new();
12356            let snapshot = self.buffer.read(cx).snapshot(cx);
12357
12358            for row in 0..snapshot.max_row().0 {
12359                if let Some(foldable_range) = self
12360                    .snapshot(window, cx)
12361                    .crease_for_buffer_row(MultiBufferRow(row))
12362                {
12363                    fold_ranges.push(foldable_range);
12364                }
12365            }
12366
12367            self.fold_creases(fold_ranges, true, window, cx);
12368        } else {
12369            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12370                editor
12371                    .update_in(&mut cx, |editor, _, cx| {
12372                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12373                            editor.fold_buffer(buffer_id, cx);
12374                        }
12375                    })
12376                    .ok();
12377            });
12378        }
12379    }
12380
12381    pub fn fold_function_bodies(
12382        &mut self,
12383        _: &actions::FoldFunctionBodies,
12384        window: &mut Window,
12385        cx: &mut Context<Self>,
12386    ) {
12387        let snapshot = self.buffer.read(cx).snapshot(cx);
12388
12389        let ranges = snapshot
12390            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12391            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12392            .collect::<Vec<_>>();
12393
12394        let creases = ranges
12395            .into_iter()
12396            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12397            .collect();
12398
12399        self.fold_creases(creases, true, window, cx);
12400    }
12401
12402    pub fn fold_recursive(
12403        &mut self,
12404        _: &actions::FoldRecursive,
12405        window: &mut Window,
12406        cx: &mut Context<Self>,
12407    ) {
12408        let mut to_fold = Vec::new();
12409        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12410        let selections = self.selections.all_adjusted(cx);
12411
12412        for selection in selections {
12413            let range = selection.range().sorted();
12414            let buffer_start_row = range.start.row;
12415
12416            if range.start.row != range.end.row {
12417                let mut found = false;
12418                for row in range.start.row..=range.end.row {
12419                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12420                        found = true;
12421                        to_fold.push(crease);
12422                    }
12423                }
12424                if found {
12425                    continue;
12426                }
12427            }
12428
12429            for row in (0..=range.start.row).rev() {
12430                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12431                    if crease.range().end.row >= buffer_start_row {
12432                        to_fold.push(crease);
12433                    } else {
12434                        break;
12435                    }
12436                }
12437            }
12438        }
12439
12440        self.fold_creases(to_fold, true, window, cx);
12441    }
12442
12443    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12444        let buffer_row = fold_at.buffer_row;
12445        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12446
12447        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12448            let autoscroll = self
12449                .selections
12450                .all::<Point>(cx)
12451                .iter()
12452                .any(|selection| crease.range().overlaps(&selection.range()));
12453
12454            self.fold_creases(vec![crease], autoscroll, window, cx);
12455        }
12456    }
12457
12458    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12459        if self.is_singleton(cx) {
12460            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12461            let buffer = &display_map.buffer_snapshot;
12462            let selections = self.selections.all::<Point>(cx);
12463            let ranges = selections
12464                .iter()
12465                .map(|s| {
12466                    let range = s.display_range(&display_map).sorted();
12467                    let mut start = range.start.to_point(&display_map);
12468                    let mut end = range.end.to_point(&display_map);
12469                    start.column = 0;
12470                    end.column = buffer.line_len(MultiBufferRow(end.row));
12471                    start..end
12472                })
12473                .collect::<Vec<_>>();
12474
12475            self.unfold_ranges(&ranges, true, true, cx);
12476        } else {
12477            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12478            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12479                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12480                .map(|(snapshot, _, _)| snapshot.remote_id())
12481                .collect();
12482            for buffer_id in buffer_ids {
12483                self.unfold_buffer(buffer_id, cx);
12484            }
12485        }
12486    }
12487
12488    pub fn unfold_recursive(
12489        &mut self,
12490        _: &UnfoldRecursive,
12491        _window: &mut Window,
12492        cx: &mut Context<Self>,
12493    ) {
12494        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12495        let selections = self.selections.all::<Point>(cx);
12496        let ranges = selections
12497            .iter()
12498            .map(|s| {
12499                let mut range = s.display_range(&display_map).sorted();
12500                *range.start.column_mut() = 0;
12501                *range.end.column_mut() = display_map.line_len(range.end.row());
12502                let start = range.start.to_point(&display_map);
12503                let end = range.end.to_point(&display_map);
12504                start..end
12505            })
12506            .collect::<Vec<_>>();
12507
12508        self.unfold_ranges(&ranges, true, true, cx);
12509    }
12510
12511    pub fn unfold_at(
12512        &mut self,
12513        unfold_at: &UnfoldAt,
12514        _window: &mut Window,
12515        cx: &mut Context<Self>,
12516    ) {
12517        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12518
12519        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12520            ..Point::new(
12521                unfold_at.buffer_row.0,
12522                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12523            );
12524
12525        let autoscroll = self
12526            .selections
12527            .all::<Point>(cx)
12528            .iter()
12529            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12530
12531        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12532    }
12533
12534    pub fn unfold_all(
12535        &mut self,
12536        _: &actions::UnfoldAll,
12537        _window: &mut Window,
12538        cx: &mut Context<Self>,
12539    ) {
12540        if self.buffer.read(cx).is_singleton() {
12541            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12542            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12543        } else {
12544            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12545                editor
12546                    .update(&mut cx, |editor, cx| {
12547                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12548                            editor.unfold_buffer(buffer_id, cx);
12549                        }
12550                    })
12551                    .ok();
12552            });
12553        }
12554    }
12555
12556    pub fn fold_selected_ranges(
12557        &mut self,
12558        _: &FoldSelectedRanges,
12559        window: &mut Window,
12560        cx: &mut Context<Self>,
12561    ) {
12562        let selections = self.selections.all::<Point>(cx);
12563        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12564        let line_mode = self.selections.line_mode;
12565        let ranges = selections
12566            .into_iter()
12567            .map(|s| {
12568                if line_mode {
12569                    let start = Point::new(s.start.row, 0);
12570                    let end = Point::new(
12571                        s.end.row,
12572                        display_map
12573                            .buffer_snapshot
12574                            .line_len(MultiBufferRow(s.end.row)),
12575                    );
12576                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12577                } else {
12578                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12579                }
12580            })
12581            .collect::<Vec<_>>();
12582        self.fold_creases(ranges, true, window, cx);
12583    }
12584
12585    pub fn fold_ranges<T: ToOffset + Clone>(
12586        &mut self,
12587        ranges: Vec<Range<T>>,
12588        auto_scroll: bool,
12589        window: &mut Window,
12590        cx: &mut Context<Self>,
12591    ) {
12592        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12593        let ranges = ranges
12594            .into_iter()
12595            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12596            .collect::<Vec<_>>();
12597        self.fold_creases(ranges, auto_scroll, window, cx);
12598    }
12599
12600    pub fn fold_creases<T: ToOffset + Clone>(
12601        &mut self,
12602        creases: Vec<Crease<T>>,
12603        auto_scroll: bool,
12604        window: &mut Window,
12605        cx: &mut Context<Self>,
12606    ) {
12607        if creases.is_empty() {
12608            return;
12609        }
12610
12611        let mut buffers_affected = HashSet::default();
12612        let multi_buffer = self.buffer().read(cx);
12613        for crease in &creases {
12614            if let Some((_, buffer, _)) =
12615                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12616            {
12617                buffers_affected.insert(buffer.read(cx).remote_id());
12618            };
12619        }
12620
12621        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12622
12623        if auto_scroll {
12624            self.request_autoscroll(Autoscroll::fit(), cx);
12625        }
12626
12627        cx.notify();
12628
12629        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12630            // Clear diagnostics block when folding a range that contains it.
12631            let snapshot = self.snapshot(window, cx);
12632            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12633                drop(snapshot);
12634                self.active_diagnostics = Some(active_diagnostics);
12635                self.dismiss_diagnostics(cx);
12636            } else {
12637                self.active_diagnostics = Some(active_diagnostics);
12638            }
12639        }
12640
12641        self.scrollbar_marker_state.dirty = true;
12642    }
12643
12644    /// Removes any folds whose ranges intersect any of the given ranges.
12645    pub fn unfold_ranges<T: ToOffset + Clone>(
12646        &mut self,
12647        ranges: &[Range<T>],
12648        inclusive: bool,
12649        auto_scroll: bool,
12650        cx: &mut Context<Self>,
12651    ) {
12652        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12653            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12654        });
12655    }
12656
12657    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12658        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12659            return;
12660        }
12661        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12662        self.display_map
12663            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12664        cx.emit(EditorEvent::BufferFoldToggled {
12665            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12666            folded: true,
12667        });
12668        cx.notify();
12669    }
12670
12671    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12672        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12673            return;
12674        }
12675        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12676        self.display_map.update(cx, |display_map, cx| {
12677            display_map.unfold_buffer(buffer_id, cx);
12678        });
12679        cx.emit(EditorEvent::BufferFoldToggled {
12680            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12681            folded: false,
12682        });
12683        cx.notify();
12684    }
12685
12686    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12687        self.display_map.read(cx).is_buffer_folded(buffer)
12688    }
12689
12690    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12691        self.display_map.read(cx).folded_buffers()
12692    }
12693
12694    /// Removes any folds with the given ranges.
12695    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12696        &mut self,
12697        ranges: &[Range<T>],
12698        type_id: TypeId,
12699        auto_scroll: bool,
12700        cx: &mut Context<Self>,
12701    ) {
12702        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12703            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12704        });
12705    }
12706
12707    fn remove_folds_with<T: ToOffset + Clone>(
12708        &mut self,
12709        ranges: &[Range<T>],
12710        auto_scroll: bool,
12711        cx: &mut Context<Self>,
12712        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12713    ) {
12714        if ranges.is_empty() {
12715            return;
12716        }
12717
12718        let mut buffers_affected = HashSet::default();
12719        let multi_buffer = self.buffer().read(cx);
12720        for range in ranges {
12721            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12722                buffers_affected.insert(buffer.read(cx).remote_id());
12723            };
12724        }
12725
12726        self.display_map.update(cx, update);
12727
12728        if auto_scroll {
12729            self.request_autoscroll(Autoscroll::fit(), cx);
12730        }
12731
12732        cx.notify();
12733        self.scrollbar_marker_state.dirty = true;
12734        self.active_indent_guides_state.dirty = true;
12735    }
12736
12737    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12738        self.display_map.read(cx).fold_placeholder.clone()
12739    }
12740
12741    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12742        self.buffer.update(cx, |buffer, cx| {
12743            buffer.set_all_diff_hunks_expanded(cx);
12744        });
12745    }
12746
12747    pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12748        self.distinguish_unstaged_diff_hunks = true;
12749    }
12750
12751    pub fn expand_all_diff_hunks(
12752        &mut self,
12753        _: &ExpandAllHunkDiffs,
12754        _window: &mut Window,
12755        cx: &mut Context<Self>,
12756    ) {
12757        self.buffer.update(cx, |buffer, cx| {
12758            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12759        });
12760    }
12761
12762    pub fn toggle_selected_diff_hunks(
12763        &mut self,
12764        _: &ToggleSelectedDiffHunks,
12765        _window: &mut Window,
12766        cx: &mut Context<Self>,
12767    ) {
12768        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12769        self.toggle_diff_hunks_in_ranges(ranges, cx);
12770    }
12771
12772    fn diff_hunks_in_ranges<'a>(
12773        &'a self,
12774        ranges: &'a [Range<Anchor>],
12775        buffer: &'a MultiBufferSnapshot,
12776    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12777        ranges.iter().flat_map(move |range| {
12778            let end_excerpt_id = range.end.excerpt_id;
12779            let range = range.to_point(buffer);
12780            let mut peek_end = range.end;
12781            if range.end.row < buffer.max_row().0 {
12782                peek_end = Point::new(range.end.row + 1, 0);
12783            }
12784            buffer
12785                .diff_hunks_in_range(range.start..peek_end)
12786                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12787        })
12788    }
12789
12790    pub fn has_stageable_diff_hunks_in_ranges(
12791        &self,
12792        ranges: &[Range<Anchor>],
12793        snapshot: &MultiBufferSnapshot,
12794    ) -> bool {
12795        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12796        hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12797    }
12798
12799    pub fn toggle_staged_selected_diff_hunks(
12800        &mut self,
12801        _: &::git::ToggleStaged,
12802        _window: &mut Window,
12803        cx: &mut Context<Self>,
12804    ) {
12805        let snapshot = self.buffer.read(cx).snapshot(cx);
12806        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12807        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
12808        self.stage_or_unstage_diff_hunks(stage, &ranges, cx);
12809    }
12810
12811    pub fn stage_and_next(
12812        &mut self,
12813        _: &::git::StageAndNext,
12814        window: &mut Window,
12815        cx: &mut Context<Self>,
12816    ) {
12817        let head = self.selections.newest_anchor().head();
12818        self.stage_or_unstage_diff_hunks(true, &[head..head], cx);
12819        self.go_to_next_hunk(&Default::default(), window, cx);
12820    }
12821
12822    pub fn unstage_and_next(
12823        &mut self,
12824        _: &::git::UnstageAndNext,
12825        window: &mut Window,
12826        cx: &mut Context<Self>,
12827    ) {
12828        let head = self.selections.newest_anchor().head();
12829        self.stage_or_unstage_diff_hunks(false, &[head..head], cx);
12830        self.go_to_next_hunk(&Default::default(), window, cx);
12831    }
12832
12833    pub fn stage_or_unstage_diff_hunks(
12834        &mut self,
12835        stage: bool,
12836        ranges: &[Range<Anchor>],
12837        cx: &mut Context<Self>,
12838    ) {
12839        let snapshot = self.buffer.read(cx).snapshot(cx);
12840        let Some(project) = &self.project else {
12841            return;
12842        };
12843
12844        let chunk_by = self
12845            .diff_hunks_in_ranges(&ranges, &snapshot)
12846            .chunk_by(|hunk| hunk.buffer_id);
12847        for (buffer_id, hunks) in &chunk_by {
12848            Self::do_stage_or_unstage(project, stage, buffer_id, hunks, &snapshot, cx);
12849        }
12850    }
12851
12852    fn do_stage_or_unstage(
12853        project: &Entity<Project>,
12854        stage: bool,
12855        buffer_id: BufferId,
12856        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
12857        snapshot: &MultiBufferSnapshot,
12858        cx: &mut Context<Self>,
12859    ) {
12860        let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12861            log::debug!("no buffer for id");
12862            return;
12863        };
12864        let buffer = buffer.read(cx).snapshot();
12865        let Some((repo, path)) = project
12866            .read(cx)
12867            .repository_and_path_for_buffer_id(buffer_id, cx)
12868        else {
12869            log::debug!("no git repo for buffer id");
12870            return;
12871        };
12872        let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12873            log::debug!("no diff for buffer id");
12874            return;
12875        };
12876        let Some(secondary_diff) = diff.secondary_diff() else {
12877            log::debug!("no secondary diff for buffer id");
12878            return;
12879        };
12880
12881        let edits = diff.secondary_edits_for_stage_or_unstage(
12882            stage,
12883            hunks.filter_map(|hunk| {
12884                if stage && hunk.secondary_status == DiffHunkSecondaryStatus::None {
12885                    return None;
12886                } else if !stage
12887                    && hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
12888                {
12889                    return None;
12890                }
12891                Some((
12892                    hunk.diff_base_byte_range.clone(),
12893                    hunk.secondary_diff_base_byte_range.clone(),
12894                    hunk.buffer_range.clone(),
12895                ))
12896            }),
12897            &buffer,
12898        );
12899
12900        let Some(index_base) = secondary_diff
12901            .base_text()
12902            .map(|snapshot| snapshot.text.as_rope().clone())
12903        else {
12904            log::debug!("no index base");
12905            return;
12906        };
12907        let index_buffer = cx.new(|cx| {
12908            Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12909        });
12910        let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12911            index_buffer.edit(edits, None, cx);
12912            index_buffer.snapshot().as_rope().to_string()
12913        });
12914        let new_index_text = if new_index_text.is_empty()
12915            && (diff.is_single_insertion
12916                || buffer
12917                    .file()
12918                    .map_or(false, |file| file.disk_state() == DiskState::New))
12919        {
12920            log::debug!("removing from index");
12921            None
12922        } else {
12923            Some(new_index_text)
12924        };
12925
12926        let _ = repo.read(cx).set_index_text(&path, new_index_text);
12927    }
12928
12929    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12930        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12931        self.buffer
12932            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12933    }
12934
12935    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12936        self.buffer.update(cx, |buffer, cx| {
12937            let ranges = vec![Anchor::min()..Anchor::max()];
12938            if !buffer.all_diff_hunks_expanded()
12939                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12940            {
12941                buffer.collapse_diff_hunks(ranges, cx);
12942                true
12943            } else {
12944                false
12945            }
12946        })
12947    }
12948
12949    fn toggle_diff_hunks_in_ranges(
12950        &mut self,
12951        ranges: Vec<Range<Anchor>>,
12952        cx: &mut Context<'_, Editor>,
12953    ) {
12954        self.buffer.update(cx, |buffer, cx| {
12955            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12956            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12957        })
12958    }
12959
12960    fn toggle_diff_hunks_in_ranges_narrow(
12961        &mut self,
12962        ranges: Vec<Range<Anchor>>,
12963        cx: &mut Context<'_, Editor>,
12964    ) {
12965        self.buffer.update(cx, |buffer, cx| {
12966            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12967            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12968        })
12969    }
12970
12971    pub(crate) fn apply_all_diff_hunks(
12972        &mut self,
12973        _: &ApplyAllDiffHunks,
12974        window: &mut Window,
12975        cx: &mut Context<Self>,
12976    ) {
12977        let buffers = self.buffer.read(cx).all_buffers();
12978        for branch_buffer in buffers {
12979            branch_buffer.update(cx, |branch_buffer, cx| {
12980                branch_buffer.merge_into_base(Vec::new(), cx);
12981            });
12982        }
12983
12984        if let Some(project) = self.project.clone() {
12985            self.save(true, project, window, cx).detach_and_log_err(cx);
12986        }
12987    }
12988
12989    pub(crate) fn apply_selected_diff_hunks(
12990        &mut self,
12991        _: &ApplyDiffHunk,
12992        window: &mut Window,
12993        cx: &mut Context<Self>,
12994    ) {
12995        let snapshot = self.snapshot(window, cx);
12996        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12997        let mut ranges_by_buffer = HashMap::default();
12998        self.transact(window, cx, |editor, _window, cx| {
12999            for hunk in hunks {
13000                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13001                    ranges_by_buffer
13002                        .entry(buffer.clone())
13003                        .or_insert_with(Vec::new)
13004                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13005                }
13006            }
13007
13008            for (buffer, ranges) in ranges_by_buffer {
13009                buffer.update(cx, |buffer, cx| {
13010                    buffer.merge_into_base(ranges, cx);
13011                });
13012            }
13013        });
13014
13015        if let Some(project) = self.project.clone() {
13016            self.save(true, project, window, cx).detach_and_log_err(cx);
13017        }
13018    }
13019
13020    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13021        if hovered != self.gutter_hovered {
13022            self.gutter_hovered = hovered;
13023            cx.notify();
13024        }
13025    }
13026
13027    pub fn insert_blocks(
13028        &mut self,
13029        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13030        autoscroll: Option<Autoscroll>,
13031        cx: &mut Context<Self>,
13032    ) -> Vec<CustomBlockId> {
13033        let blocks = self
13034            .display_map
13035            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13036        if let Some(autoscroll) = autoscroll {
13037            self.request_autoscroll(autoscroll, cx);
13038        }
13039        cx.notify();
13040        blocks
13041    }
13042
13043    pub fn resize_blocks(
13044        &mut self,
13045        heights: HashMap<CustomBlockId, u32>,
13046        autoscroll: Option<Autoscroll>,
13047        cx: &mut Context<Self>,
13048    ) {
13049        self.display_map
13050            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13051        if let Some(autoscroll) = autoscroll {
13052            self.request_autoscroll(autoscroll, cx);
13053        }
13054        cx.notify();
13055    }
13056
13057    pub fn replace_blocks(
13058        &mut self,
13059        renderers: HashMap<CustomBlockId, RenderBlock>,
13060        autoscroll: Option<Autoscroll>,
13061        cx: &mut Context<Self>,
13062    ) {
13063        self.display_map
13064            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13065        if let Some(autoscroll) = autoscroll {
13066            self.request_autoscroll(autoscroll, cx);
13067        }
13068        cx.notify();
13069    }
13070
13071    pub fn remove_blocks(
13072        &mut self,
13073        block_ids: HashSet<CustomBlockId>,
13074        autoscroll: Option<Autoscroll>,
13075        cx: &mut Context<Self>,
13076    ) {
13077        self.display_map.update(cx, |display_map, cx| {
13078            display_map.remove_blocks(block_ids, cx)
13079        });
13080        if let Some(autoscroll) = autoscroll {
13081            self.request_autoscroll(autoscroll, cx);
13082        }
13083        cx.notify();
13084    }
13085
13086    pub fn row_for_block(
13087        &self,
13088        block_id: CustomBlockId,
13089        cx: &mut Context<Self>,
13090    ) -> Option<DisplayRow> {
13091        self.display_map
13092            .update(cx, |map, cx| map.row_for_block(block_id, cx))
13093    }
13094
13095    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13096        self.focused_block = Some(focused_block);
13097    }
13098
13099    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13100        self.focused_block.take()
13101    }
13102
13103    pub fn insert_creases(
13104        &mut self,
13105        creases: impl IntoIterator<Item = Crease<Anchor>>,
13106        cx: &mut Context<Self>,
13107    ) -> Vec<CreaseId> {
13108        self.display_map
13109            .update(cx, |map, cx| map.insert_creases(creases, cx))
13110    }
13111
13112    pub fn remove_creases(
13113        &mut self,
13114        ids: impl IntoIterator<Item = CreaseId>,
13115        cx: &mut Context<Self>,
13116    ) {
13117        self.display_map
13118            .update(cx, |map, cx| map.remove_creases(ids, cx));
13119    }
13120
13121    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13122        self.display_map
13123            .update(cx, |map, cx| map.snapshot(cx))
13124            .longest_row()
13125    }
13126
13127    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13128        self.display_map
13129            .update(cx, |map, cx| map.snapshot(cx))
13130            .max_point()
13131    }
13132
13133    pub fn text(&self, cx: &App) -> String {
13134        self.buffer.read(cx).read(cx).text()
13135    }
13136
13137    pub fn is_empty(&self, cx: &App) -> bool {
13138        self.buffer.read(cx).read(cx).is_empty()
13139    }
13140
13141    pub fn text_option(&self, cx: &App) -> Option<String> {
13142        let text = self.text(cx);
13143        let text = text.trim();
13144
13145        if text.is_empty() {
13146            return None;
13147        }
13148
13149        Some(text.to_string())
13150    }
13151
13152    pub fn set_text(
13153        &mut self,
13154        text: impl Into<Arc<str>>,
13155        window: &mut Window,
13156        cx: &mut Context<Self>,
13157    ) {
13158        self.transact(window, cx, |this, _, cx| {
13159            this.buffer
13160                .read(cx)
13161                .as_singleton()
13162                .expect("you can only call set_text on editors for singleton buffers")
13163                .update(cx, |buffer, cx| buffer.set_text(text, cx));
13164        });
13165    }
13166
13167    pub fn display_text(&self, cx: &mut App) -> String {
13168        self.display_map
13169            .update(cx, |map, cx| map.snapshot(cx))
13170            .text()
13171    }
13172
13173    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
13174        let mut wrap_guides = smallvec::smallvec![];
13175
13176        if self.show_wrap_guides == Some(false) {
13177            return wrap_guides;
13178        }
13179
13180        let settings = self.buffer.read(cx).settings_at(0, cx);
13181        if settings.show_wrap_guides {
13182            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
13183                wrap_guides.push((soft_wrap as usize, true));
13184            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
13185                wrap_guides.push((soft_wrap as usize, true));
13186            }
13187            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
13188        }
13189
13190        wrap_guides
13191    }
13192
13193    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
13194        let settings = self.buffer.read(cx).settings_at(0, cx);
13195        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
13196        match mode {
13197            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
13198                SoftWrap::None
13199            }
13200            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13201            language_settings::SoftWrap::PreferredLineLength => {
13202                SoftWrap::Column(settings.preferred_line_length)
13203            }
13204            language_settings::SoftWrap::Bounded => {
13205                SoftWrap::Bounded(settings.preferred_line_length)
13206            }
13207        }
13208    }
13209
13210    pub fn set_soft_wrap_mode(
13211        &mut self,
13212        mode: language_settings::SoftWrap,
13213
13214        cx: &mut Context<Self>,
13215    ) {
13216        self.soft_wrap_mode_override = Some(mode);
13217        cx.notify();
13218    }
13219
13220    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13221        self.text_style_refinement = Some(style);
13222    }
13223
13224    /// called by the Element so we know what style we were most recently rendered with.
13225    pub(crate) fn set_style(
13226        &mut self,
13227        style: EditorStyle,
13228        window: &mut Window,
13229        cx: &mut Context<Self>,
13230    ) {
13231        let rem_size = window.rem_size();
13232        self.display_map.update(cx, |map, cx| {
13233            map.set_font(
13234                style.text.font(),
13235                style.text.font_size.to_pixels(rem_size),
13236                cx,
13237            )
13238        });
13239        self.style = Some(style);
13240    }
13241
13242    pub fn style(&self) -> Option<&EditorStyle> {
13243        self.style.as_ref()
13244    }
13245
13246    // Called by the element. This method is not designed to be called outside of the editor
13247    // element's layout code because it does not notify when rewrapping is computed synchronously.
13248    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13249        self.display_map
13250            .update(cx, |map, cx| map.set_wrap_width(width, cx))
13251    }
13252
13253    pub fn set_soft_wrap(&mut self) {
13254        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13255    }
13256
13257    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13258        if self.soft_wrap_mode_override.is_some() {
13259            self.soft_wrap_mode_override.take();
13260        } else {
13261            let soft_wrap = match self.soft_wrap_mode(cx) {
13262                SoftWrap::GitDiff => return,
13263                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13264                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13265                    language_settings::SoftWrap::None
13266                }
13267            };
13268            self.soft_wrap_mode_override = Some(soft_wrap);
13269        }
13270        cx.notify();
13271    }
13272
13273    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13274        let Some(workspace) = self.workspace() else {
13275            return;
13276        };
13277        let fs = workspace.read(cx).app_state().fs.clone();
13278        let current_show = TabBarSettings::get_global(cx).show;
13279        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13280            setting.show = Some(!current_show);
13281        });
13282    }
13283
13284    pub fn toggle_indent_guides(
13285        &mut self,
13286        _: &ToggleIndentGuides,
13287        _: &mut Window,
13288        cx: &mut Context<Self>,
13289    ) {
13290        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13291            self.buffer
13292                .read(cx)
13293                .settings_at(0, cx)
13294                .indent_guides
13295                .enabled
13296        });
13297        self.show_indent_guides = Some(!currently_enabled);
13298        cx.notify();
13299    }
13300
13301    fn should_show_indent_guides(&self) -> Option<bool> {
13302        self.show_indent_guides
13303    }
13304
13305    pub fn toggle_line_numbers(
13306        &mut self,
13307        _: &ToggleLineNumbers,
13308        _: &mut Window,
13309        cx: &mut Context<Self>,
13310    ) {
13311        let mut editor_settings = EditorSettings::get_global(cx).clone();
13312        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13313        EditorSettings::override_global(editor_settings, cx);
13314    }
13315
13316    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13317        self.use_relative_line_numbers
13318            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13319    }
13320
13321    pub fn toggle_relative_line_numbers(
13322        &mut self,
13323        _: &ToggleRelativeLineNumbers,
13324        _: &mut Window,
13325        cx: &mut Context<Self>,
13326    ) {
13327        let is_relative = self.should_use_relative_line_numbers(cx);
13328        self.set_relative_line_number(Some(!is_relative), cx)
13329    }
13330
13331    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13332        self.use_relative_line_numbers = is_relative;
13333        cx.notify();
13334    }
13335
13336    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13337        self.show_gutter = show_gutter;
13338        cx.notify();
13339    }
13340
13341    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13342        self.show_scrollbars = show_scrollbars;
13343        cx.notify();
13344    }
13345
13346    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13347        self.show_line_numbers = Some(show_line_numbers);
13348        cx.notify();
13349    }
13350
13351    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13352        self.show_git_diff_gutter = Some(show_git_diff_gutter);
13353        cx.notify();
13354    }
13355
13356    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13357        self.show_code_actions = Some(show_code_actions);
13358        cx.notify();
13359    }
13360
13361    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13362        self.show_runnables = Some(show_runnables);
13363        cx.notify();
13364    }
13365
13366    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13367        if self.display_map.read(cx).masked != masked {
13368            self.display_map.update(cx, |map, _| map.masked = masked);
13369        }
13370        cx.notify()
13371    }
13372
13373    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13374        self.show_wrap_guides = Some(show_wrap_guides);
13375        cx.notify();
13376    }
13377
13378    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13379        self.show_indent_guides = Some(show_indent_guides);
13380        cx.notify();
13381    }
13382
13383    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13384        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13385            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13386                if let Some(dir) = file.abs_path(cx).parent() {
13387                    return Some(dir.to_owned());
13388                }
13389            }
13390
13391            if let Some(project_path) = buffer.read(cx).project_path(cx) {
13392                return Some(project_path.path.to_path_buf());
13393            }
13394        }
13395
13396        None
13397    }
13398
13399    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13400        self.active_excerpt(cx)?
13401            .1
13402            .read(cx)
13403            .file()
13404            .and_then(|f| f.as_local())
13405    }
13406
13407    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13408        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13409            let buffer = buffer.read(cx);
13410            if let Some(project_path) = buffer.project_path(cx) {
13411                let project = self.project.as_ref()?.read(cx);
13412                project.absolute_path(&project_path, cx)
13413            } else {
13414                buffer
13415                    .file()
13416                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13417            }
13418        })
13419    }
13420
13421    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13422        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13423            let project_path = buffer.read(cx).project_path(cx)?;
13424            let project = self.project.as_ref()?.read(cx);
13425            let entry = project.entry_for_path(&project_path, cx)?;
13426            let path = entry.path.to_path_buf();
13427            Some(path)
13428        })
13429    }
13430
13431    pub fn reveal_in_finder(
13432        &mut self,
13433        _: &RevealInFileManager,
13434        _window: &mut Window,
13435        cx: &mut Context<Self>,
13436    ) {
13437        if let Some(target) = self.target_file(cx) {
13438            cx.reveal_path(&target.abs_path(cx));
13439        }
13440    }
13441
13442    pub fn copy_path(
13443        &mut self,
13444        _: &zed_actions::workspace::CopyPath,
13445        _window: &mut Window,
13446        cx: &mut Context<Self>,
13447    ) {
13448        if let Some(path) = self.target_file_abs_path(cx) {
13449            if let Some(path) = path.to_str() {
13450                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13451            }
13452        }
13453    }
13454
13455    pub fn copy_relative_path(
13456        &mut self,
13457        _: &zed_actions::workspace::CopyRelativePath,
13458        _window: &mut Window,
13459        cx: &mut Context<Self>,
13460    ) {
13461        if let Some(path) = self.target_file_path(cx) {
13462            if let Some(path) = path.to_str() {
13463                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13464            }
13465        }
13466    }
13467
13468    pub fn copy_file_name_without_extension(
13469        &mut self,
13470        _: &CopyFileNameWithoutExtension,
13471        _: &mut Window,
13472        cx: &mut Context<Self>,
13473    ) {
13474        if let Some(file) = self.target_file(cx) {
13475            if let Some(file_stem) = file.path().file_stem() {
13476                if let Some(name) = file_stem.to_str() {
13477                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13478                }
13479            }
13480        }
13481    }
13482
13483    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13484        if let Some(file) = self.target_file(cx) {
13485            if let Some(file_name) = file.path().file_name() {
13486                if let Some(name) = file_name.to_str() {
13487                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13488                }
13489            }
13490        }
13491    }
13492
13493    pub fn toggle_git_blame(
13494        &mut self,
13495        _: &ToggleGitBlame,
13496        window: &mut Window,
13497        cx: &mut Context<Self>,
13498    ) {
13499        self.show_git_blame_gutter = !self.show_git_blame_gutter;
13500
13501        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13502            self.start_git_blame(true, window, cx);
13503        }
13504
13505        cx.notify();
13506    }
13507
13508    pub fn toggle_git_blame_inline(
13509        &mut self,
13510        _: &ToggleGitBlameInline,
13511        window: &mut Window,
13512        cx: &mut Context<Self>,
13513    ) {
13514        self.toggle_git_blame_inline_internal(true, window, cx);
13515        cx.notify();
13516    }
13517
13518    pub fn git_blame_inline_enabled(&self) -> bool {
13519        self.git_blame_inline_enabled
13520    }
13521
13522    pub fn toggle_selection_menu(
13523        &mut self,
13524        _: &ToggleSelectionMenu,
13525        _: &mut Window,
13526        cx: &mut Context<Self>,
13527    ) {
13528        self.show_selection_menu = self
13529            .show_selection_menu
13530            .map(|show_selections_menu| !show_selections_menu)
13531            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13532
13533        cx.notify();
13534    }
13535
13536    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13537        self.show_selection_menu
13538            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13539    }
13540
13541    fn start_git_blame(
13542        &mut self,
13543        user_triggered: bool,
13544        window: &mut Window,
13545        cx: &mut Context<Self>,
13546    ) {
13547        if let Some(project) = self.project.as_ref() {
13548            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13549                return;
13550            };
13551
13552            if buffer.read(cx).file().is_none() {
13553                return;
13554            }
13555
13556            let focused = self.focus_handle(cx).contains_focused(window, cx);
13557
13558            let project = project.clone();
13559            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13560            self.blame_subscription =
13561                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13562            self.blame = Some(blame);
13563        }
13564    }
13565
13566    fn toggle_git_blame_inline_internal(
13567        &mut self,
13568        user_triggered: bool,
13569        window: &mut Window,
13570        cx: &mut Context<Self>,
13571    ) {
13572        if self.git_blame_inline_enabled {
13573            self.git_blame_inline_enabled = false;
13574            self.show_git_blame_inline = false;
13575            self.show_git_blame_inline_delay_task.take();
13576        } else {
13577            self.git_blame_inline_enabled = true;
13578            self.start_git_blame_inline(user_triggered, window, cx);
13579        }
13580
13581        cx.notify();
13582    }
13583
13584    fn start_git_blame_inline(
13585        &mut self,
13586        user_triggered: bool,
13587        window: &mut Window,
13588        cx: &mut Context<Self>,
13589    ) {
13590        self.start_git_blame(user_triggered, window, cx);
13591
13592        if ProjectSettings::get_global(cx)
13593            .git
13594            .inline_blame_delay()
13595            .is_some()
13596        {
13597            self.start_inline_blame_timer(window, cx);
13598        } else {
13599            self.show_git_blame_inline = true
13600        }
13601    }
13602
13603    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13604        self.blame.as_ref()
13605    }
13606
13607    pub fn show_git_blame_gutter(&self) -> bool {
13608        self.show_git_blame_gutter
13609    }
13610
13611    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13612        self.show_git_blame_gutter && self.has_blame_entries(cx)
13613    }
13614
13615    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13616        self.show_git_blame_inline
13617            && (self.focus_handle.is_focused(window)
13618                || self
13619                    .git_blame_inline_tooltip
13620                    .as_ref()
13621                    .and_then(|t| t.upgrade())
13622                    .is_some())
13623            && !self.newest_selection_head_on_empty_line(cx)
13624            && self.has_blame_entries(cx)
13625    }
13626
13627    fn has_blame_entries(&self, cx: &App) -> bool {
13628        self.blame()
13629            .map_or(false, |blame| blame.read(cx).has_generated_entries())
13630    }
13631
13632    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13633        let cursor_anchor = self.selections.newest_anchor().head();
13634
13635        let snapshot = self.buffer.read(cx).snapshot(cx);
13636        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13637
13638        snapshot.line_len(buffer_row) == 0
13639    }
13640
13641    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13642        let buffer_and_selection = maybe!({
13643            let selection = self.selections.newest::<Point>(cx);
13644            let selection_range = selection.range();
13645
13646            let multi_buffer = self.buffer().read(cx);
13647            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13648            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13649
13650            let (buffer, range, _) = if selection.reversed {
13651                buffer_ranges.first()
13652            } else {
13653                buffer_ranges.last()
13654            }?;
13655
13656            let selection = text::ToPoint::to_point(&range.start, &buffer).row
13657                ..text::ToPoint::to_point(&range.end, &buffer).row;
13658            Some((
13659                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13660                selection,
13661            ))
13662        });
13663
13664        let Some((buffer, selection)) = buffer_and_selection else {
13665            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13666        };
13667
13668        let Some(project) = self.project.as_ref() else {
13669            return Task::ready(Err(anyhow!("editor does not have project")));
13670        };
13671
13672        project.update(cx, |project, cx| {
13673            project.get_permalink_to_line(&buffer, selection, cx)
13674        })
13675    }
13676
13677    pub fn copy_permalink_to_line(
13678        &mut self,
13679        _: &CopyPermalinkToLine,
13680        window: &mut Window,
13681        cx: &mut Context<Self>,
13682    ) {
13683        let permalink_task = self.get_permalink_to_line(cx);
13684        let workspace = self.workspace();
13685
13686        cx.spawn_in(window, |_, mut cx| async move {
13687            match permalink_task.await {
13688                Ok(permalink) => {
13689                    cx.update(|_, cx| {
13690                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13691                    })
13692                    .ok();
13693                }
13694                Err(err) => {
13695                    let message = format!("Failed to copy permalink: {err}");
13696
13697                    Err::<(), anyhow::Error>(err).log_err();
13698
13699                    if let Some(workspace) = workspace {
13700                        workspace
13701                            .update_in(&mut cx, |workspace, _, cx| {
13702                                struct CopyPermalinkToLine;
13703
13704                                workspace.show_toast(
13705                                    Toast::new(
13706                                        NotificationId::unique::<CopyPermalinkToLine>(),
13707                                        message,
13708                                    ),
13709                                    cx,
13710                                )
13711                            })
13712                            .ok();
13713                    }
13714                }
13715            }
13716        })
13717        .detach();
13718    }
13719
13720    pub fn copy_file_location(
13721        &mut self,
13722        _: &CopyFileLocation,
13723        _: &mut Window,
13724        cx: &mut Context<Self>,
13725    ) {
13726        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13727        if let Some(file) = self.target_file(cx) {
13728            if let Some(path) = file.path().to_str() {
13729                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13730            }
13731        }
13732    }
13733
13734    pub fn open_permalink_to_line(
13735        &mut self,
13736        _: &OpenPermalinkToLine,
13737        window: &mut Window,
13738        cx: &mut Context<Self>,
13739    ) {
13740        let permalink_task = self.get_permalink_to_line(cx);
13741        let workspace = self.workspace();
13742
13743        cx.spawn_in(window, |_, mut cx| async move {
13744            match permalink_task.await {
13745                Ok(permalink) => {
13746                    cx.update(|_, cx| {
13747                        cx.open_url(permalink.as_ref());
13748                    })
13749                    .ok();
13750                }
13751                Err(err) => {
13752                    let message = format!("Failed to open permalink: {err}");
13753
13754                    Err::<(), anyhow::Error>(err).log_err();
13755
13756                    if let Some(workspace) = workspace {
13757                        workspace
13758                            .update(&mut cx, |workspace, cx| {
13759                                struct OpenPermalinkToLine;
13760
13761                                workspace.show_toast(
13762                                    Toast::new(
13763                                        NotificationId::unique::<OpenPermalinkToLine>(),
13764                                        message,
13765                                    ),
13766                                    cx,
13767                                )
13768                            })
13769                            .ok();
13770                    }
13771                }
13772            }
13773        })
13774        .detach();
13775    }
13776
13777    pub fn insert_uuid_v4(
13778        &mut self,
13779        _: &InsertUuidV4,
13780        window: &mut Window,
13781        cx: &mut Context<Self>,
13782    ) {
13783        self.insert_uuid(UuidVersion::V4, window, cx);
13784    }
13785
13786    pub fn insert_uuid_v7(
13787        &mut self,
13788        _: &InsertUuidV7,
13789        window: &mut Window,
13790        cx: &mut Context<Self>,
13791    ) {
13792        self.insert_uuid(UuidVersion::V7, window, cx);
13793    }
13794
13795    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13796        self.transact(window, cx, |this, window, cx| {
13797            let edits = this
13798                .selections
13799                .all::<Point>(cx)
13800                .into_iter()
13801                .map(|selection| {
13802                    let uuid = match version {
13803                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13804                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13805                    };
13806
13807                    (selection.range(), uuid.to_string())
13808                });
13809            this.edit(edits, cx);
13810            this.refresh_inline_completion(true, false, window, cx);
13811        });
13812    }
13813
13814    pub fn open_selections_in_multibuffer(
13815        &mut self,
13816        _: &OpenSelectionsInMultibuffer,
13817        window: &mut Window,
13818        cx: &mut Context<Self>,
13819    ) {
13820        let multibuffer = self.buffer.read(cx);
13821
13822        let Some(buffer) = multibuffer.as_singleton() else {
13823            return;
13824        };
13825
13826        let Some(workspace) = self.workspace() else {
13827            return;
13828        };
13829
13830        let locations = self
13831            .selections
13832            .disjoint_anchors()
13833            .iter()
13834            .map(|range| Location {
13835                buffer: buffer.clone(),
13836                range: range.start.text_anchor..range.end.text_anchor,
13837            })
13838            .collect::<Vec<_>>();
13839
13840        let title = multibuffer.title(cx).to_string();
13841
13842        cx.spawn_in(window, |_, mut cx| async move {
13843            workspace.update_in(&mut cx, |workspace, window, cx| {
13844                Self::open_locations_in_multibuffer(
13845                    workspace,
13846                    locations,
13847                    format!("Selections for '{title}'"),
13848                    false,
13849                    MultibufferSelectionMode::All,
13850                    window,
13851                    cx,
13852                );
13853            })
13854        })
13855        .detach();
13856    }
13857
13858    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13859    /// last highlight added will be used.
13860    ///
13861    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13862    pub fn highlight_rows<T: 'static>(
13863        &mut self,
13864        range: Range<Anchor>,
13865        color: Hsla,
13866        should_autoscroll: bool,
13867        cx: &mut Context<Self>,
13868    ) {
13869        let snapshot = self.buffer().read(cx).snapshot(cx);
13870        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13871        let ix = row_highlights.binary_search_by(|highlight| {
13872            Ordering::Equal
13873                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13874                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13875        });
13876
13877        if let Err(mut ix) = ix {
13878            let index = post_inc(&mut self.highlight_order);
13879
13880            // If this range intersects with the preceding highlight, then merge it with
13881            // the preceding highlight. Otherwise insert a new highlight.
13882            let mut merged = false;
13883            if ix > 0 {
13884                let prev_highlight = &mut row_highlights[ix - 1];
13885                if prev_highlight
13886                    .range
13887                    .end
13888                    .cmp(&range.start, &snapshot)
13889                    .is_ge()
13890                {
13891                    ix -= 1;
13892                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13893                        prev_highlight.range.end = range.end;
13894                    }
13895                    merged = true;
13896                    prev_highlight.index = index;
13897                    prev_highlight.color = color;
13898                    prev_highlight.should_autoscroll = should_autoscroll;
13899                }
13900            }
13901
13902            if !merged {
13903                row_highlights.insert(
13904                    ix,
13905                    RowHighlight {
13906                        range: range.clone(),
13907                        index,
13908                        color,
13909                        should_autoscroll,
13910                    },
13911                );
13912            }
13913
13914            // If any of the following highlights intersect with this one, merge them.
13915            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13916                let highlight = &row_highlights[ix];
13917                if next_highlight
13918                    .range
13919                    .start
13920                    .cmp(&highlight.range.end, &snapshot)
13921                    .is_le()
13922                {
13923                    if next_highlight
13924                        .range
13925                        .end
13926                        .cmp(&highlight.range.end, &snapshot)
13927                        .is_gt()
13928                    {
13929                        row_highlights[ix].range.end = next_highlight.range.end;
13930                    }
13931                    row_highlights.remove(ix + 1);
13932                } else {
13933                    break;
13934                }
13935            }
13936        }
13937    }
13938
13939    /// Remove any highlighted row ranges of the given type that intersect the
13940    /// given ranges.
13941    pub fn remove_highlighted_rows<T: 'static>(
13942        &mut self,
13943        ranges_to_remove: Vec<Range<Anchor>>,
13944        cx: &mut Context<Self>,
13945    ) {
13946        let snapshot = self.buffer().read(cx).snapshot(cx);
13947        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13948        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13949        row_highlights.retain(|highlight| {
13950            while let Some(range_to_remove) = ranges_to_remove.peek() {
13951                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13952                    Ordering::Less | Ordering::Equal => {
13953                        ranges_to_remove.next();
13954                    }
13955                    Ordering::Greater => {
13956                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13957                            Ordering::Less | Ordering::Equal => {
13958                                return false;
13959                            }
13960                            Ordering::Greater => break,
13961                        }
13962                    }
13963                }
13964            }
13965
13966            true
13967        })
13968    }
13969
13970    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13971    pub fn clear_row_highlights<T: 'static>(&mut self) {
13972        self.highlighted_rows.remove(&TypeId::of::<T>());
13973    }
13974
13975    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13976    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13977        self.highlighted_rows
13978            .get(&TypeId::of::<T>())
13979            .map_or(&[] as &[_], |vec| vec.as_slice())
13980            .iter()
13981            .map(|highlight| (highlight.range.clone(), highlight.color))
13982    }
13983
13984    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13985    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13986    /// Allows to ignore certain kinds of highlights.
13987    pub fn highlighted_display_rows(
13988        &self,
13989        window: &mut Window,
13990        cx: &mut App,
13991    ) -> BTreeMap<DisplayRow, Background> {
13992        let snapshot = self.snapshot(window, cx);
13993        let mut used_highlight_orders = HashMap::default();
13994        self.highlighted_rows
13995            .iter()
13996            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13997            .fold(
13998                BTreeMap::<DisplayRow, Background>::new(),
13999                |mut unique_rows, highlight| {
14000                    let start = highlight.range.start.to_display_point(&snapshot);
14001                    let end = highlight.range.end.to_display_point(&snapshot);
14002                    let start_row = start.row().0;
14003                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14004                        && end.column() == 0
14005                    {
14006                        end.row().0.saturating_sub(1)
14007                    } else {
14008                        end.row().0
14009                    };
14010                    for row in start_row..=end_row {
14011                        let used_index =
14012                            used_highlight_orders.entry(row).or_insert(highlight.index);
14013                        if highlight.index >= *used_index {
14014                            *used_index = highlight.index;
14015                            unique_rows.insert(DisplayRow(row), highlight.color.into());
14016                        }
14017                    }
14018                    unique_rows
14019                },
14020            )
14021    }
14022
14023    pub fn highlighted_display_row_for_autoscroll(
14024        &self,
14025        snapshot: &DisplaySnapshot,
14026    ) -> Option<DisplayRow> {
14027        self.highlighted_rows
14028            .values()
14029            .flat_map(|highlighted_rows| highlighted_rows.iter())
14030            .filter_map(|highlight| {
14031                if highlight.should_autoscroll {
14032                    Some(highlight.range.start.to_display_point(snapshot).row())
14033                } else {
14034                    None
14035                }
14036            })
14037            .min()
14038    }
14039
14040    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14041        self.highlight_background::<SearchWithinRange>(
14042            ranges,
14043            |colors| colors.editor_document_highlight_read_background,
14044            cx,
14045        )
14046    }
14047
14048    pub fn set_breadcrumb_header(&mut self, new_header: String) {
14049        self.breadcrumb_header = Some(new_header);
14050    }
14051
14052    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14053        self.clear_background_highlights::<SearchWithinRange>(cx);
14054    }
14055
14056    pub fn highlight_background<T: 'static>(
14057        &mut self,
14058        ranges: &[Range<Anchor>],
14059        color_fetcher: fn(&ThemeColors) -> Hsla,
14060        cx: &mut Context<Self>,
14061    ) {
14062        self.background_highlights
14063            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14064        self.scrollbar_marker_state.dirty = true;
14065        cx.notify();
14066    }
14067
14068    pub fn clear_background_highlights<T: 'static>(
14069        &mut self,
14070        cx: &mut Context<Self>,
14071    ) -> Option<BackgroundHighlight> {
14072        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14073        if !text_highlights.1.is_empty() {
14074            self.scrollbar_marker_state.dirty = true;
14075            cx.notify();
14076        }
14077        Some(text_highlights)
14078    }
14079
14080    pub fn highlight_gutter<T: 'static>(
14081        &mut self,
14082        ranges: &[Range<Anchor>],
14083        color_fetcher: fn(&App) -> Hsla,
14084        cx: &mut Context<Self>,
14085    ) {
14086        self.gutter_highlights
14087            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14088        cx.notify();
14089    }
14090
14091    pub fn clear_gutter_highlights<T: 'static>(
14092        &mut self,
14093        cx: &mut Context<Self>,
14094    ) -> Option<GutterHighlight> {
14095        cx.notify();
14096        self.gutter_highlights.remove(&TypeId::of::<T>())
14097    }
14098
14099    #[cfg(feature = "test-support")]
14100    pub fn all_text_background_highlights(
14101        &self,
14102        window: &mut Window,
14103        cx: &mut Context<Self>,
14104    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14105        let snapshot = self.snapshot(window, cx);
14106        let buffer = &snapshot.buffer_snapshot;
14107        let start = buffer.anchor_before(0);
14108        let end = buffer.anchor_after(buffer.len());
14109        let theme = cx.theme().colors();
14110        self.background_highlights_in_range(start..end, &snapshot, theme)
14111    }
14112
14113    #[cfg(feature = "test-support")]
14114    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14115        let snapshot = self.buffer().read(cx).snapshot(cx);
14116
14117        let highlights = self
14118            .background_highlights
14119            .get(&TypeId::of::<items::BufferSearchHighlights>());
14120
14121        if let Some((_color, ranges)) = highlights {
14122            ranges
14123                .iter()
14124                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14125                .collect_vec()
14126        } else {
14127            vec![]
14128        }
14129    }
14130
14131    fn document_highlights_for_position<'a>(
14132        &'a self,
14133        position: Anchor,
14134        buffer: &'a MultiBufferSnapshot,
14135    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
14136        let read_highlights = self
14137            .background_highlights
14138            .get(&TypeId::of::<DocumentHighlightRead>())
14139            .map(|h| &h.1);
14140        let write_highlights = self
14141            .background_highlights
14142            .get(&TypeId::of::<DocumentHighlightWrite>())
14143            .map(|h| &h.1);
14144        let left_position = position.bias_left(buffer);
14145        let right_position = position.bias_right(buffer);
14146        read_highlights
14147            .into_iter()
14148            .chain(write_highlights)
14149            .flat_map(move |ranges| {
14150                let start_ix = match ranges.binary_search_by(|probe| {
14151                    let cmp = probe.end.cmp(&left_position, buffer);
14152                    if cmp.is_ge() {
14153                        Ordering::Greater
14154                    } else {
14155                        Ordering::Less
14156                    }
14157                }) {
14158                    Ok(i) | Err(i) => i,
14159                };
14160
14161                ranges[start_ix..]
14162                    .iter()
14163                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
14164            })
14165    }
14166
14167    pub fn has_background_highlights<T: 'static>(&self) -> bool {
14168        self.background_highlights
14169            .get(&TypeId::of::<T>())
14170            .map_or(false, |(_, highlights)| !highlights.is_empty())
14171    }
14172
14173    pub fn background_highlights_in_range(
14174        &self,
14175        search_range: Range<Anchor>,
14176        display_snapshot: &DisplaySnapshot,
14177        theme: &ThemeColors,
14178    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14179        let mut results = Vec::new();
14180        for (color_fetcher, ranges) in self.background_highlights.values() {
14181            let color = color_fetcher(theme);
14182            let start_ix = match ranges.binary_search_by(|probe| {
14183                let cmp = probe
14184                    .end
14185                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14186                if cmp.is_gt() {
14187                    Ordering::Greater
14188                } else {
14189                    Ordering::Less
14190                }
14191            }) {
14192                Ok(i) | Err(i) => i,
14193            };
14194            for range in &ranges[start_ix..] {
14195                if range
14196                    .start
14197                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14198                    .is_ge()
14199                {
14200                    break;
14201                }
14202
14203                let start = range.start.to_display_point(display_snapshot);
14204                let end = range.end.to_display_point(display_snapshot);
14205                results.push((start..end, color))
14206            }
14207        }
14208        results
14209    }
14210
14211    pub fn background_highlight_row_ranges<T: 'static>(
14212        &self,
14213        search_range: Range<Anchor>,
14214        display_snapshot: &DisplaySnapshot,
14215        count: usize,
14216    ) -> Vec<RangeInclusive<DisplayPoint>> {
14217        let mut results = Vec::new();
14218        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14219            return vec![];
14220        };
14221
14222        let start_ix = match ranges.binary_search_by(|probe| {
14223            let cmp = probe
14224                .end
14225                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14226            if cmp.is_gt() {
14227                Ordering::Greater
14228            } else {
14229                Ordering::Less
14230            }
14231        }) {
14232            Ok(i) | Err(i) => i,
14233        };
14234        let mut push_region = |start: Option<Point>, end: Option<Point>| {
14235            if let (Some(start_display), Some(end_display)) = (start, end) {
14236                results.push(
14237                    start_display.to_display_point(display_snapshot)
14238                        ..=end_display.to_display_point(display_snapshot),
14239                );
14240            }
14241        };
14242        let mut start_row: Option<Point> = None;
14243        let mut end_row: Option<Point> = None;
14244        if ranges.len() > count {
14245            return Vec::new();
14246        }
14247        for range in &ranges[start_ix..] {
14248            if range
14249                .start
14250                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14251                .is_ge()
14252            {
14253                break;
14254            }
14255            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14256            if let Some(current_row) = &end_row {
14257                if end.row == current_row.row {
14258                    continue;
14259                }
14260            }
14261            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14262            if start_row.is_none() {
14263                assert_eq!(end_row, None);
14264                start_row = Some(start);
14265                end_row = Some(end);
14266                continue;
14267            }
14268            if let Some(current_end) = end_row.as_mut() {
14269                if start.row > current_end.row + 1 {
14270                    push_region(start_row, end_row);
14271                    start_row = Some(start);
14272                    end_row = Some(end);
14273                } else {
14274                    // Merge two hunks.
14275                    *current_end = end;
14276                }
14277            } else {
14278                unreachable!();
14279            }
14280        }
14281        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14282        push_region(start_row, end_row);
14283        results
14284    }
14285
14286    pub fn gutter_highlights_in_range(
14287        &self,
14288        search_range: Range<Anchor>,
14289        display_snapshot: &DisplaySnapshot,
14290        cx: &App,
14291    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14292        let mut results = Vec::new();
14293        for (color_fetcher, ranges) in self.gutter_highlights.values() {
14294            let color = color_fetcher(cx);
14295            let start_ix = match ranges.binary_search_by(|probe| {
14296                let cmp = probe
14297                    .end
14298                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14299                if cmp.is_gt() {
14300                    Ordering::Greater
14301                } else {
14302                    Ordering::Less
14303                }
14304            }) {
14305                Ok(i) | Err(i) => i,
14306            };
14307            for range in &ranges[start_ix..] {
14308                if range
14309                    .start
14310                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14311                    .is_ge()
14312                {
14313                    break;
14314                }
14315
14316                let start = range.start.to_display_point(display_snapshot);
14317                let end = range.end.to_display_point(display_snapshot);
14318                results.push((start..end, color))
14319            }
14320        }
14321        results
14322    }
14323
14324    /// Get the text ranges corresponding to the redaction query
14325    pub fn redacted_ranges(
14326        &self,
14327        search_range: Range<Anchor>,
14328        display_snapshot: &DisplaySnapshot,
14329        cx: &App,
14330    ) -> Vec<Range<DisplayPoint>> {
14331        display_snapshot
14332            .buffer_snapshot
14333            .redacted_ranges(search_range, |file| {
14334                if let Some(file) = file {
14335                    file.is_private()
14336                        && EditorSettings::get(
14337                            Some(SettingsLocation {
14338                                worktree_id: file.worktree_id(cx),
14339                                path: file.path().as_ref(),
14340                            }),
14341                            cx,
14342                        )
14343                        .redact_private_values
14344                } else {
14345                    false
14346                }
14347            })
14348            .map(|range| {
14349                range.start.to_display_point(display_snapshot)
14350                    ..range.end.to_display_point(display_snapshot)
14351            })
14352            .collect()
14353    }
14354
14355    pub fn highlight_text<T: 'static>(
14356        &mut self,
14357        ranges: Vec<Range<Anchor>>,
14358        style: HighlightStyle,
14359        cx: &mut Context<Self>,
14360    ) {
14361        self.display_map.update(cx, |map, _| {
14362            map.highlight_text(TypeId::of::<T>(), ranges, style)
14363        });
14364        cx.notify();
14365    }
14366
14367    pub(crate) fn highlight_inlays<T: 'static>(
14368        &mut self,
14369        highlights: Vec<InlayHighlight>,
14370        style: HighlightStyle,
14371        cx: &mut Context<Self>,
14372    ) {
14373        self.display_map.update(cx, |map, _| {
14374            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14375        });
14376        cx.notify();
14377    }
14378
14379    pub fn text_highlights<'a, T: 'static>(
14380        &'a self,
14381        cx: &'a App,
14382    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14383        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14384    }
14385
14386    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14387        let cleared = self
14388            .display_map
14389            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14390        if cleared {
14391            cx.notify();
14392        }
14393    }
14394
14395    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14396        (self.read_only(cx) || self.blink_manager.read(cx).visible())
14397            && self.focus_handle.is_focused(window)
14398    }
14399
14400    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14401        self.show_cursor_when_unfocused = is_enabled;
14402        cx.notify();
14403    }
14404
14405    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14406        cx.notify();
14407    }
14408
14409    fn on_buffer_event(
14410        &mut self,
14411        multibuffer: &Entity<MultiBuffer>,
14412        event: &multi_buffer::Event,
14413        window: &mut Window,
14414        cx: &mut Context<Self>,
14415    ) {
14416        match event {
14417            multi_buffer::Event::Edited {
14418                singleton_buffer_edited,
14419                edited_buffer: buffer_edited,
14420            } => {
14421                self.scrollbar_marker_state.dirty = true;
14422                self.active_indent_guides_state.dirty = true;
14423                self.refresh_active_diagnostics(cx);
14424                self.refresh_code_actions(window, cx);
14425                if self.has_active_inline_completion() {
14426                    self.update_visible_inline_completion(window, cx);
14427                }
14428                if let Some(buffer) = buffer_edited {
14429                    let buffer_id = buffer.read(cx).remote_id();
14430                    if !self.registered_buffers.contains_key(&buffer_id) {
14431                        if let Some(project) = self.project.as_ref() {
14432                            project.update(cx, |project, cx| {
14433                                self.registered_buffers.insert(
14434                                    buffer_id,
14435                                    project.register_buffer_with_language_servers(&buffer, cx),
14436                                );
14437                            })
14438                        }
14439                    }
14440                }
14441                cx.emit(EditorEvent::BufferEdited);
14442                cx.emit(SearchEvent::MatchesInvalidated);
14443                if *singleton_buffer_edited {
14444                    if let Some(project) = &self.project {
14445                        #[allow(clippy::mutable_key_type)]
14446                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14447                            multibuffer
14448                                .all_buffers()
14449                                .into_iter()
14450                                .filter_map(|buffer| {
14451                                    buffer.update(cx, |buffer, cx| {
14452                                        let language = buffer.language()?;
14453                                        let should_discard = project.update(cx, |project, cx| {
14454                                            project.is_local()
14455                                                && !project.has_language_servers_for(buffer, cx)
14456                                        });
14457                                        should_discard.not().then_some(language.clone())
14458                                    })
14459                                })
14460                                .collect::<HashSet<_>>()
14461                        });
14462                        if !languages_affected.is_empty() {
14463                            self.refresh_inlay_hints(
14464                                InlayHintRefreshReason::BufferEdited(languages_affected),
14465                                cx,
14466                            );
14467                        }
14468                    }
14469                }
14470
14471                let Some(project) = &self.project else { return };
14472                let (telemetry, is_via_ssh) = {
14473                    let project = project.read(cx);
14474                    let telemetry = project.client().telemetry().clone();
14475                    let is_via_ssh = project.is_via_ssh();
14476                    (telemetry, is_via_ssh)
14477                };
14478                refresh_linked_ranges(self, window, cx);
14479                telemetry.log_edit_event("editor", is_via_ssh);
14480            }
14481            multi_buffer::Event::ExcerptsAdded {
14482                buffer,
14483                predecessor,
14484                excerpts,
14485            } => {
14486                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14487                let buffer_id = buffer.read(cx).remote_id();
14488                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14489                    if let Some(project) = &self.project {
14490                        get_uncommitted_diff_for_buffer(
14491                            project,
14492                            [buffer.clone()],
14493                            self.buffer.clone(),
14494                            cx,
14495                        )
14496                        .detach();
14497                    }
14498                }
14499                cx.emit(EditorEvent::ExcerptsAdded {
14500                    buffer: buffer.clone(),
14501                    predecessor: *predecessor,
14502                    excerpts: excerpts.clone(),
14503                });
14504                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14505            }
14506            multi_buffer::Event::ExcerptsRemoved { ids } => {
14507                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14508                let buffer = self.buffer.read(cx);
14509                self.registered_buffers
14510                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14511                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14512            }
14513            multi_buffer::Event::ExcerptsEdited { ids } => {
14514                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14515            }
14516            multi_buffer::Event::ExcerptsExpanded { ids } => {
14517                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14518                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14519            }
14520            multi_buffer::Event::Reparsed(buffer_id) => {
14521                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14522
14523                cx.emit(EditorEvent::Reparsed(*buffer_id));
14524            }
14525            multi_buffer::Event::DiffHunksToggled => {
14526                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14527            }
14528            multi_buffer::Event::LanguageChanged(buffer_id) => {
14529                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14530                cx.emit(EditorEvent::Reparsed(*buffer_id));
14531                cx.notify();
14532            }
14533            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14534            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14535            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14536                cx.emit(EditorEvent::TitleChanged)
14537            }
14538            // multi_buffer::Event::DiffBaseChanged => {
14539            //     self.scrollbar_marker_state.dirty = true;
14540            //     cx.emit(EditorEvent::DiffBaseChanged);
14541            //     cx.notify();
14542            // }
14543            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14544            multi_buffer::Event::DiagnosticsUpdated => {
14545                self.refresh_active_diagnostics(cx);
14546                self.refresh_inline_diagnostics(true, window, cx);
14547                self.scrollbar_marker_state.dirty = true;
14548                cx.notify();
14549            }
14550            _ => {}
14551        };
14552    }
14553
14554    fn on_display_map_changed(
14555        &mut self,
14556        _: Entity<DisplayMap>,
14557        _: &mut Window,
14558        cx: &mut Context<Self>,
14559    ) {
14560        cx.notify();
14561    }
14562
14563    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14564        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14565        self.refresh_inline_completion(true, false, window, cx);
14566        self.refresh_inlay_hints(
14567            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14568                self.selections.newest_anchor().head(),
14569                &self.buffer.read(cx).snapshot(cx),
14570                cx,
14571            )),
14572            cx,
14573        );
14574
14575        let old_cursor_shape = self.cursor_shape;
14576
14577        {
14578            let editor_settings = EditorSettings::get_global(cx);
14579            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14580            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14581            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14582            self.hide_mouse_while_typing = editor_settings.hide_mouse_while_typing.unwrap_or(true);
14583
14584            if !self.hide_mouse_while_typing {
14585                self.mouse_cursor_hidden = false;
14586            }
14587        }
14588
14589        if old_cursor_shape != self.cursor_shape {
14590            cx.emit(EditorEvent::CursorShapeChanged);
14591        }
14592
14593        let project_settings = ProjectSettings::get_global(cx);
14594        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14595
14596        if self.mode == EditorMode::Full {
14597            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
14598            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14599            if self.show_inline_diagnostics != show_inline_diagnostics {
14600                self.show_inline_diagnostics = show_inline_diagnostics;
14601                self.refresh_inline_diagnostics(false, window, cx);
14602            }
14603
14604            if self.git_blame_inline_enabled != inline_blame_enabled {
14605                self.toggle_git_blame_inline_internal(false, window, cx);
14606            }
14607        }
14608
14609        cx.notify();
14610    }
14611
14612    pub fn set_searchable(&mut self, searchable: bool) {
14613        self.searchable = searchable;
14614    }
14615
14616    pub fn searchable(&self) -> bool {
14617        self.searchable
14618    }
14619
14620    fn open_proposed_changes_editor(
14621        &mut self,
14622        _: &OpenProposedChangesEditor,
14623        window: &mut Window,
14624        cx: &mut Context<Self>,
14625    ) {
14626        let Some(workspace) = self.workspace() else {
14627            cx.propagate();
14628            return;
14629        };
14630
14631        let selections = self.selections.all::<usize>(cx);
14632        let multi_buffer = self.buffer.read(cx);
14633        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14634        let mut new_selections_by_buffer = HashMap::default();
14635        for selection in selections {
14636            for (buffer, range, _) in
14637                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14638            {
14639                let mut range = range.to_point(buffer);
14640                range.start.column = 0;
14641                range.end.column = buffer.line_len(range.end.row);
14642                new_selections_by_buffer
14643                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14644                    .or_insert(Vec::new())
14645                    .push(range)
14646            }
14647        }
14648
14649        let proposed_changes_buffers = new_selections_by_buffer
14650            .into_iter()
14651            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14652            .collect::<Vec<_>>();
14653        let proposed_changes_editor = cx.new(|cx| {
14654            ProposedChangesEditor::new(
14655                "Proposed changes",
14656                proposed_changes_buffers,
14657                self.project.clone(),
14658                window,
14659                cx,
14660            )
14661        });
14662
14663        window.defer(cx, move |window, cx| {
14664            workspace.update(cx, |workspace, cx| {
14665                workspace.active_pane().update(cx, |pane, cx| {
14666                    pane.add_item(
14667                        Box::new(proposed_changes_editor),
14668                        true,
14669                        true,
14670                        None,
14671                        window,
14672                        cx,
14673                    );
14674                });
14675            });
14676        });
14677    }
14678
14679    pub fn open_excerpts_in_split(
14680        &mut self,
14681        _: &OpenExcerptsSplit,
14682        window: &mut Window,
14683        cx: &mut Context<Self>,
14684    ) {
14685        self.open_excerpts_common(None, true, window, cx)
14686    }
14687
14688    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14689        self.open_excerpts_common(None, false, window, cx)
14690    }
14691
14692    fn open_excerpts_common(
14693        &mut self,
14694        jump_data: Option<JumpData>,
14695        split: bool,
14696        window: &mut Window,
14697        cx: &mut Context<Self>,
14698    ) {
14699        let Some(workspace) = self.workspace() else {
14700            cx.propagate();
14701            return;
14702        };
14703
14704        if self.buffer.read(cx).is_singleton() {
14705            cx.propagate();
14706            return;
14707        }
14708
14709        let mut new_selections_by_buffer = HashMap::default();
14710        match &jump_data {
14711            Some(JumpData::MultiBufferPoint {
14712                excerpt_id,
14713                position,
14714                anchor,
14715                line_offset_from_top,
14716            }) => {
14717                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14718                if let Some(buffer) = multi_buffer_snapshot
14719                    .buffer_id_for_excerpt(*excerpt_id)
14720                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14721                {
14722                    let buffer_snapshot = buffer.read(cx).snapshot();
14723                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14724                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14725                    } else {
14726                        buffer_snapshot.clip_point(*position, Bias::Left)
14727                    };
14728                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14729                    new_selections_by_buffer.insert(
14730                        buffer,
14731                        (
14732                            vec![jump_to_offset..jump_to_offset],
14733                            Some(*line_offset_from_top),
14734                        ),
14735                    );
14736                }
14737            }
14738            Some(JumpData::MultiBufferRow {
14739                row,
14740                line_offset_from_top,
14741            }) => {
14742                let point = MultiBufferPoint::new(row.0, 0);
14743                if let Some((buffer, buffer_point, _)) =
14744                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14745                {
14746                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14747                    new_selections_by_buffer
14748                        .entry(buffer)
14749                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14750                        .0
14751                        .push(buffer_offset..buffer_offset)
14752                }
14753            }
14754            None => {
14755                let selections = self.selections.all::<usize>(cx);
14756                let multi_buffer = self.buffer.read(cx);
14757                for selection in selections {
14758                    for (buffer, mut range, _) in multi_buffer
14759                        .snapshot(cx)
14760                        .range_to_buffer_ranges(selection.range())
14761                    {
14762                        // When editing branch buffers, jump to the corresponding location
14763                        // in their base buffer.
14764                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14765                        let buffer = buffer_handle.read(cx);
14766                        if let Some(base_buffer) = buffer.base_buffer() {
14767                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14768                            buffer_handle = base_buffer;
14769                        }
14770
14771                        if selection.reversed {
14772                            mem::swap(&mut range.start, &mut range.end);
14773                        }
14774                        new_selections_by_buffer
14775                            .entry(buffer_handle)
14776                            .or_insert((Vec::new(), None))
14777                            .0
14778                            .push(range)
14779                    }
14780                }
14781            }
14782        }
14783
14784        if new_selections_by_buffer.is_empty() {
14785            return;
14786        }
14787
14788        // We defer the pane interaction because we ourselves are a workspace item
14789        // and activating a new item causes the pane to call a method on us reentrantly,
14790        // which panics if we're on the stack.
14791        window.defer(cx, move |window, cx| {
14792            workspace.update(cx, |workspace, cx| {
14793                let pane = if split {
14794                    workspace.adjacent_pane(window, cx)
14795                } else {
14796                    workspace.active_pane().clone()
14797                };
14798
14799                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14800                    let editor = buffer
14801                        .read(cx)
14802                        .file()
14803                        .is_none()
14804                        .then(|| {
14805                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14806                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14807                            // Instead, we try to activate the existing editor in the pane first.
14808                            let (editor, pane_item_index) =
14809                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14810                                    let editor = item.downcast::<Editor>()?;
14811                                    let singleton_buffer =
14812                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14813                                    if singleton_buffer == buffer {
14814                                        Some((editor, i))
14815                                    } else {
14816                                        None
14817                                    }
14818                                })?;
14819                            pane.update(cx, |pane, cx| {
14820                                pane.activate_item(pane_item_index, true, true, window, cx)
14821                            });
14822                            Some(editor)
14823                        })
14824                        .flatten()
14825                        .unwrap_or_else(|| {
14826                            workspace.open_project_item::<Self>(
14827                                pane.clone(),
14828                                buffer,
14829                                true,
14830                                true,
14831                                window,
14832                                cx,
14833                            )
14834                        });
14835
14836                    editor.update(cx, |editor, cx| {
14837                        let autoscroll = match scroll_offset {
14838                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14839                            None => Autoscroll::newest(),
14840                        };
14841                        let nav_history = editor.nav_history.take();
14842                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14843                            s.select_ranges(ranges);
14844                        });
14845                        editor.nav_history = nav_history;
14846                    });
14847                }
14848            })
14849        });
14850    }
14851
14852    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14853        let snapshot = self.buffer.read(cx).read(cx);
14854        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14855        Some(
14856            ranges
14857                .iter()
14858                .map(move |range| {
14859                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14860                })
14861                .collect(),
14862        )
14863    }
14864
14865    fn selection_replacement_ranges(
14866        &self,
14867        range: Range<OffsetUtf16>,
14868        cx: &mut App,
14869    ) -> Vec<Range<OffsetUtf16>> {
14870        let selections = self.selections.all::<OffsetUtf16>(cx);
14871        let newest_selection = selections
14872            .iter()
14873            .max_by_key(|selection| selection.id)
14874            .unwrap();
14875        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14876        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14877        let snapshot = self.buffer.read(cx).read(cx);
14878        selections
14879            .into_iter()
14880            .map(|mut selection| {
14881                selection.start.0 =
14882                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14883                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14884                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14885                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14886            })
14887            .collect()
14888    }
14889
14890    fn report_editor_event(
14891        &self,
14892        event_type: &'static str,
14893        file_extension: Option<String>,
14894        cx: &App,
14895    ) {
14896        if cfg!(any(test, feature = "test-support")) {
14897            return;
14898        }
14899
14900        let Some(project) = &self.project else { return };
14901
14902        // If None, we are in a file without an extension
14903        let file = self
14904            .buffer
14905            .read(cx)
14906            .as_singleton()
14907            .and_then(|b| b.read(cx).file());
14908        let file_extension = file_extension.or(file
14909            .as_ref()
14910            .and_then(|file| Path::new(file.file_name(cx)).extension())
14911            .and_then(|e| e.to_str())
14912            .map(|a| a.to_string()));
14913
14914        let vim_mode = cx
14915            .global::<SettingsStore>()
14916            .raw_user_settings()
14917            .get("vim_mode")
14918            == Some(&serde_json::Value::Bool(true));
14919
14920        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14921        let copilot_enabled = edit_predictions_provider
14922            == language::language_settings::EditPredictionProvider::Copilot;
14923        let copilot_enabled_for_language = self
14924            .buffer
14925            .read(cx)
14926            .settings_at(0, cx)
14927            .show_edit_predictions;
14928
14929        let project = project.read(cx);
14930        telemetry::event!(
14931            event_type,
14932            file_extension,
14933            vim_mode,
14934            copilot_enabled,
14935            copilot_enabled_for_language,
14936            edit_predictions_provider,
14937            is_via_ssh = project.is_via_ssh(),
14938        );
14939    }
14940
14941    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14942    /// with each line being an array of {text, highlight} objects.
14943    fn copy_highlight_json(
14944        &mut self,
14945        _: &CopyHighlightJson,
14946        window: &mut Window,
14947        cx: &mut Context<Self>,
14948    ) {
14949        #[derive(Serialize)]
14950        struct Chunk<'a> {
14951            text: String,
14952            highlight: Option<&'a str>,
14953        }
14954
14955        let snapshot = self.buffer.read(cx).snapshot(cx);
14956        let range = self
14957            .selected_text_range(false, window, cx)
14958            .and_then(|selection| {
14959                if selection.range.is_empty() {
14960                    None
14961                } else {
14962                    Some(selection.range)
14963                }
14964            })
14965            .unwrap_or_else(|| 0..snapshot.len());
14966
14967        let chunks = snapshot.chunks(range, true);
14968        let mut lines = Vec::new();
14969        let mut line: VecDeque<Chunk> = VecDeque::new();
14970
14971        let Some(style) = self.style.as_ref() else {
14972            return;
14973        };
14974
14975        for chunk in chunks {
14976            let highlight = chunk
14977                .syntax_highlight_id
14978                .and_then(|id| id.name(&style.syntax));
14979            let mut chunk_lines = chunk.text.split('\n').peekable();
14980            while let Some(text) = chunk_lines.next() {
14981                let mut merged_with_last_token = false;
14982                if let Some(last_token) = line.back_mut() {
14983                    if last_token.highlight == highlight {
14984                        last_token.text.push_str(text);
14985                        merged_with_last_token = true;
14986                    }
14987                }
14988
14989                if !merged_with_last_token {
14990                    line.push_back(Chunk {
14991                        text: text.into(),
14992                        highlight,
14993                    });
14994                }
14995
14996                if chunk_lines.peek().is_some() {
14997                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14998                        line.pop_front();
14999                    }
15000                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
15001                        line.pop_back();
15002                    }
15003
15004                    lines.push(mem::take(&mut line));
15005                }
15006            }
15007        }
15008
15009        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15010            return;
15011        };
15012        cx.write_to_clipboard(ClipboardItem::new_string(lines));
15013    }
15014
15015    pub fn open_context_menu(
15016        &mut self,
15017        _: &OpenContextMenu,
15018        window: &mut Window,
15019        cx: &mut Context<Self>,
15020    ) {
15021        self.request_autoscroll(Autoscroll::newest(), cx);
15022        let position = self.selections.newest_display(cx).start;
15023        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15024    }
15025
15026    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15027        &self.inlay_hint_cache
15028    }
15029
15030    pub fn replay_insert_event(
15031        &mut self,
15032        text: &str,
15033        relative_utf16_range: Option<Range<isize>>,
15034        window: &mut Window,
15035        cx: &mut Context<Self>,
15036    ) {
15037        if !self.input_enabled {
15038            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15039            return;
15040        }
15041        if let Some(relative_utf16_range) = relative_utf16_range {
15042            let selections = self.selections.all::<OffsetUtf16>(cx);
15043            self.change_selections(None, window, cx, |s| {
15044                let new_ranges = selections.into_iter().map(|range| {
15045                    let start = OffsetUtf16(
15046                        range
15047                            .head()
15048                            .0
15049                            .saturating_add_signed(relative_utf16_range.start),
15050                    );
15051                    let end = OffsetUtf16(
15052                        range
15053                            .head()
15054                            .0
15055                            .saturating_add_signed(relative_utf16_range.end),
15056                    );
15057                    start..end
15058                });
15059                s.select_ranges(new_ranges);
15060            });
15061        }
15062
15063        self.handle_input(text, window, cx);
15064    }
15065
15066    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15067        let Some(provider) = self.semantics_provider.as_ref() else {
15068            return false;
15069        };
15070
15071        let mut supports = false;
15072        self.buffer().update(cx, |this, cx| {
15073            this.for_each_buffer(|buffer| {
15074                supports |= provider.supports_inlay_hints(buffer, cx);
15075            });
15076        });
15077
15078        supports
15079    }
15080
15081    pub fn is_focused(&self, window: &Window) -> bool {
15082        self.focus_handle.is_focused(window)
15083    }
15084
15085    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15086        cx.emit(EditorEvent::Focused);
15087
15088        if let Some(descendant) = self
15089            .last_focused_descendant
15090            .take()
15091            .and_then(|descendant| descendant.upgrade())
15092        {
15093            window.focus(&descendant);
15094        } else {
15095            if let Some(blame) = self.blame.as_ref() {
15096                blame.update(cx, GitBlame::focus)
15097            }
15098
15099            self.blink_manager.update(cx, BlinkManager::enable);
15100            self.show_cursor_names(window, cx);
15101            self.buffer.update(cx, |buffer, cx| {
15102                buffer.finalize_last_transaction(cx);
15103                if self.leader_peer_id.is_none() {
15104                    buffer.set_active_selections(
15105                        &self.selections.disjoint_anchors(),
15106                        self.selections.line_mode,
15107                        self.cursor_shape,
15108                        cx,
15109                    );
15110                }
15111            });
15112        }
15113    }
15114
15115    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15116        cx.emit(EditorEvent::FocusedIn)
15117    }
15118
15119    fn handle_focus_out(
15120        &mut self,
15121        event: FocusOutEvent,
15122        _window: &mut Window,
15123        _cx: &mut Context<Self>,
15124    ) {
15125        if event.blurred != self.focus_handle {
15126            self.last_focused_descendant = Some(event.blurred);
15127        }
15128    }
15129
15130    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15131        self.blink_manager.update(cx, BlinkManager::disable);
15132        self.buffer
15133            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
15134
15135        if let Some(blame) = self.blame.as_ref() {
15136            blame.update(cx, GitBlame::blur)
15137        }
15138        if !self.hover_state.focused(window, cx) {
15139            hide_hover(self, cx);
15140        }
15141        if !self
15142            .context_menu
15143            .borrow()
15144            .as_ref()
15145            .is_some_and(|context_menu| context_menu.focused(window, cx))
15146        {
15147            self.hide_context_menu(window, cx);
15148        }
15149        self.discard_inline_completion(false, cx);
15150        cx.emit(EditorEvent::Blurred);
15151        cx.notify();
15152    }
15153
15154    pub fn register_action<A: Action>(
15155        &mut self,
15156        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
15157    ) -> Subscription {
15158        let id = self.next_editor_action_id.post_inc();
15159        let listener = Arc::new(listener);
15160        self.editor_actions.borrow_mut().insert(
15161            id,
15162            Box::new(move |window, _| {
15163                let listener = listener.clone();
15164                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
15165                    let action = action.downcast_ref().unwrap();
15166                    if phase == DispatchPhase::Bubble {
15167                        listener(action, window, cx)
15168                    }
15169                })
15170            }),
15171        );
15172
15173        let editor_actions = self.editor_actions.clone();
15174        Subscription::new(move || {
15175            editor_actions.borrow_mut().remove(&id);
15176        })
15177    }
15178
15179    pub fn file_header_size(&self) -> u32 {
15180        FILE_HEADER_HEIGHT
15181    }
15182
15183    pub fn revert(
15184        &mut self,
15185        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
15186        window: &mut Window,
15187        cx: &mut Context<Self>,
15188    ) {
15189        self.buffer().update(cx, |multi_buffer, cx| {
15190            for (buffer_id, changes) in revert_changes {
15191                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
15192                    buffer.update(cx, |buffer, cx| {
15193                        buffer.edit(
15194                            changes.into_iter().map(|(range, text)| {
15195                                (range, text.to_string().map(Arc::<str>::from))
15196                            }),
15197                            None,
15198                            cx,
15199                        );
15200                    });
15201                }
15202            }
15203        });
15204        self.change_selections(None, window, cx, |selections| selections.refresh());
15205    }
15206
15207    pub fn to_pixel_point(
15208        &self,
15209        source: multi_buffer::Anchor,
15210        editor_snapshot: &EditorSnapshot,
15211        window: &mut Window,
15212    ) -> Option<gpui::Point<Pixels>> {
15213        let source_point = source.to_display_point(editor_snapshot);
15214        self.display_to_pixel_point(source_point, editor_snapshot, window)
15215    }
15216
15217    pub fn display_to_pixel_point(
15218        &self,
15219        source: DisplayPoint,
15220        editor_snapshot: &EditorSnapshot,
15221        window: &mut Window,
15222    ) -> Option<gpui::Point<Pixels>> {
15223        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15224        let text_layout_details = self.text_layout_details(window);
15225        let scroll_top = text_layout_details
15226            .scroll_anchor
15227            .scroll_position(editor_snapshot)
15228            .y;
15229
15230        if source.row().as_f32() < scroll_top.floor() {
15231            return None;
15232        }
15233        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15234        let source_y = line_height * (source.row().as_f32() - scroll_top);
15235        Some(gpui::Point::new(source_x, source_y))
15236    }
15237
15238    pub fn has_visible_completions_menu(&self) -> bool {
15239        !self.edit_prediction_preview_is_active()
15240            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15241                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15242            })
15243    }
15244
15245    pub fn register_addon<T: Addon>(&mut self, instance: T) {
15246        self.addons
15247            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15248    }
15249
15250    pub fn unregister_addon<T: Addon>(&mut self) {
15251        self.addons.remove(&std::any::TypeId::of::<T>());
15252    }
15253
15254    pub fn addon<T: Addon>(&self) -> Option<&T> {
15255        let type_id = std::any::TypeId::of::<T>();
15256        self.addons
15257            .get(&type_id)
15258            .and_then(|item| item.to_any().downcast_ref::<T>())
15259    }
15260
15261    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15262        let text_layout_details = self.text_layout_details(window);
15263        let style = &text_layout_details.editor_style;
15264        let font_id = window.text_system().resolve_font(&style.text.font());
15265        let font_size = style.text.font_size.to_pixels(window.rem_size());
15266        let line_height = style.text.line_height_in_pixels(window.rem_size());
15267        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15268
15269        gpui::Size::new(em_width, line_height)
15270    }
15271
15272    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15273        self.load_diff_task.clone()
15274    }
15275
15276    fn read_selections_from_db(
15277        &mut self,
15278        item_id: u64,
15279        workspace_id: WorkspaceId,
15280        window: &mut Window,
15281        cx: &mut Context<Editor>,
15282    ) {
15283        if !self.is_singleton(cx)
15284            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15285        {
15286            return;
15287        }
15288        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15289            return;
15290        };
15291        if selections.is_empty() {
15292            return;
15293        }
15294
15295        let snapshot = self.buffer.read(cx).snapshot(cx);
15296        self.change_selections(None, window, cx, |s| {
15297            s.select_ranges(selections.into_iter().map(|(start, end)| {
15298                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15299            }));
15300        });
15301    }
15302}
15303
15304fn insert_extra_newline_brackets(
15305    buffer: &MultiBufferSnapshot,
15306    range: Range<usize>,
15307    language: &language::LanguageScope,
15308) -> bool {
15309    let leading_whitespace_len = buffer
15310        .reversed_chars_at(range.start)
15311        .take_while(|c| c.is_whitespace() && *c != '\n')
15312        .map(|c| c.len_utf8())
15313        .sum::<usize>();
15314    let trailing_whitespace_len = buffer
15315        .chars_at(range.end)
15316        .take_while(|c| c.is_whitespace() && *c != '\n')
15317        .map(|c| c.len_utf8())
15318        .sum::<usize>();
15319    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
15320
15321    language.brackets().any(|(pair, enabled)| {
15322        let pair_start = pair.start.trim_end();
15323        let pair_end = pair.end.trim_start();
15324
15325        enabled
15326            && pair.newline
15327            && buffer.contains_str_at(range.end, pair_end)
15328            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
15329    })
15330}
15331
15332fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
15333    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
15334        [(buffer, range, _)] => (*buffer, range.clone()),
15335        _ => return false,
15336    };
15337    let pair = {
15338        let mut result: Option<BracketMatch> = None;
15339
15340        for pair in buffer
15341            .all_bracket_ranges(range.clone())
15342            .filter(move |pair| {
15343                pair.open_range.start <= range.start && pair.close_range.end >= range.end
15344            })
15345        {
15346            let len = pair.close_range.end - pair.open_range.start;
15347
15348            if let Some(existing) = &result {
15349                let existing_len = existing.close_range.end - existing.open_range.start;
15350                if len > existing_len {
15351                    continue;
15352                }
15353            }
15354
15355            result = Some(pair);
15356        }
15357
15358        result
15359    };
15360    let Some(pair) = pair else {
15361        return false;
15362    };
15363    pair.newline_only
15364        && buffer
15365            .chars_for_range(pair.open_range.end..range.start)
15366            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
15367            .all(|c| c.is_whitespace() && c != '\n')
15368}
15369
15370fn get_uncommitted_diff_for_buffer(
15371    project: &Entity<Project>,
15372    buffers: impl IntoIterator<Item = Entity<Buffer>>,
15373    buffer: Entity<MultiBuffer>,
15374    cx: &mut App,
15375) -> Task<()> {
15376    let mut tasks = Vec::new();
15377    project.update(cx, |project, cx| {
15378        for buffer in buffers {
15379            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15380        }
15381    });
15382    cx.spawn(|mut cx| async move {
15383        let diffs = futures::future::join_all(tasks).await;
15384        buffer
15385            .update(&mut cx, |buffer, cx| {
15386                for diff in diffs.into_iter().flatten() {
15387                    buffer.add_diff(diff, cx);
15388                }
15389            })
15390            .ok();
15391    })
15392}
15393
15394fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15395    let tab_size = tab_size.get() as usize;
15396    let mut width = offset;
15397
15398    for ch in text.chars() {
15399        width += if ch == '\t' {
15400            tab_size - (width % tab_size)
15401        } else {
15402            1
15403        };
15404    }
15405
15406    width - offset
15407}
15408
15409#[cfg(test)]
15410mod tests {
15411    use super::*;
15412
15413    #[test]
15414    fn test_string_size_with_expanded_tabs() {
15415        let nz = |val| NonZeroU32::new(val).unwrap();
15416        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
15417        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
15418        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
15419        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
15420        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
15421        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
15422        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
15423        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
15424    }
15425}
15426
15427/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
15428struct WordBreakingTokenizer<'a> {
15429    input: &'a str,
15430}
15431
15432impl<'a> WordBreakingTokenizer<'a> {
15433    fn new(input: &'a str) -> Self {
15434        Self { input }
15435    }
15436}
15437
15438fn is_char_ideographic(ch: char) -> bool {
15439    use unicode_script::Script::*;
15440    use unicode_script::UnicodeScript;
15441    matches!(ch.script(), Han | Tangut | Yi)
15442}
15443
15444fn is_grapheme_ideographic(text: &str) -> bool {
15445    text.chars().any(is_char_ideographic)
15446}
15447
15448fn is_grapheme_whitespace(text: &str) -> bool {
15449    text.chars().any(|x| x.is_whitespace())
15450}
15451
15452fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15453    text.chars().next().map_or(false, |ch| {
15454        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15455    })
15456}
15457
15458#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15459struct WordBreakToken<'a> {
15460    token: &'a str,
15461    grapheme_len: usize,
15462    is_whitespace: bool,
15463}
15464
15465impl<'a> Iterator for WordBreakingTokenizer<'a> {
15466    /// Yields a span, the count of graphemes in the token, and whether it was
15467    /// whitespace. Note that it also breaks at word boundaries.
15468    type Item = WordBreakToken<'a>;
15469
15470    fn next(&mut self) -> Option<Self::Item> {
15471        use unicode_segmentation::UnicodeSegmentation;
15472        if self.input.is_empty() {
15473            return None;
15474        }
15475
15476        let mut iter = self.input.graphemes(true).peekable();
15477        let mut offset = 0;
15478        let mut graphemes = 0;
15479        if let Some(first_grapheme) = iter.next() {
15480            let is_whitespace = is_grapheme_whitespace(first_grapheme);
15481            offset += first_grapheme.len();
15482            graphemes += 1;
15483            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15484                if let Some(grapheme) = iter.peek().copied() {
15485                    if should_stay_with_preceding_ideograph(grapheme) {
15486                        offset += grapheme.len();
15487                        graphemes += 1;
15488                    }
15489                }
15490            } else {
15491                let mut words = self.input[offset..].split_word_bound_indices().peekable();
15492                let mut next_word_bound = words.peek().copied();
15493                if next_word_bound.map_or(false, |(i, _)| i == 0) {
15494                    next_word_bound = words.next();
15495                }
15496                while let Some(grapheme) = iter.peek().copied() {
15497                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
15498                        break;
15499                    };
15500                    if is_grapheme_whitespace(grapheme) != is_whitespace {
15501                        break;
15502                    };
15503                    offset += grapheme.len();
15504                    graphemes += 1;
15505                    iter.next();
15506                }
15507            }
15508            let token = &self.input[..offset];
15509            self.input = &self.input[offset..];
15510            if is_whitespace {
15511                Some(WordBreakToken {
15512                    token: " ",
15513                    grapheme_len: 1,
15514                    is_whitespace: true,
15515                })
15516            } else {
15517                Some(WordBreakToken {
15518                    token,
15519                    grapheme_len: graphemes,
15520                    is_whitespace: false,
15521                })
15522            }
15523        } else {
15524            None
15525        }
15526    }
15527}
15528
15529#[test]
15530fn test_word_breaking_tokenizer() {
15531    let tests: &[(&str, &[(&str, usize, bool)])] = &[
15532        ("", &[]),
15533        ("  ", &[(" ", 1, true)]),
15534        ("Ʒ", &[("Ʒ", 1, false)]),
15535        ("Ǽ", &[("Ǽ", 1, false)]),
15536        ("", &[("", 1, false)]),
15537        ("⋑⋑", &[("⋑⋑", 2, false)]),
15538        (
15539            "原理,进而",
15540            &[
15541                ("", 1, false),
15542                ("理,", 2, false),
15543                ("", 1, false),
15544                ("", 1, false),
15545            ],
15546        ),
15547        (
15548            "hello world",
15549            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15550        ),
15551        (
15552            "hello, world",
15553            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15554        ),
15555        (
15556            "  hello world",
15557            &[
15558                (" ", 1, true),
15559                ("hello", 5, false),
15560                (" ", 1, true),
15561                ("world", 5, false),
15562            ],
15563        ),
15564        (
15565            "这是什么 \n 钢笔",
15566            &[
15567                ("", 1, false),
15568                ("", 1, false),
15569                ("", 1, false),
15570                ("", 1, false),
15571                (" ", 1, true),
15572                ("", 1, false),
15573                ("", 1, false),
15574            ],
15575        ),
15576        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15577    ];
15578
15579    for (input, result) in tests {
15580        assert_eq!(
15581            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15582            result
15583                .iter()
15584                .copied()
15585                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15586                    token,
15587                    grapheme_len,
15588                    is_whitespace,
15589                })
15590                .collect::<Vec<_>>()
15591        );
15592    }
15593}
15594
15595fn wrap_with_prefix(
15596    line_prefix: String,
15597    unwrapped_text: String,
15598    wrap_column: usize,
15599    tab_size: NonZeroU32,
15600) -> String {
15601    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15602    let mut wrapped_text = String::new();
15603    let mut current_line = line_prefix.clone();
15604
15605    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15606    let mut current_line_len = line_prefix_len;
15607    for WordBreakToken {
15608        token,
15609        grapheme_len,
15610        is_whitespace,
15611    } in tokenizer
15612    {
15613        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15614            wrapped_text.push_str(current_line.trim_end());
15615            wrapped_text.push('\n');
15616            current_line.truncate(line_prefix.len());
15617            current_line_len = line_prefix_len;
15618            if !is_whitespace {
15619                current_line.push_str(token);
15620                current_line_len += grapheme_len;
15621            }
15622        } else if !is_whitespace {
15623            current_line.push_str(token);
15624            current_line_len += grapheme_len;
15625        } else if current_line_len != line_prefix_len {
15626            current_line.push(' ');
15627            current_line_len += 1;
15628        }
15629    }
15630
15631    if !current_line.is_empty() {
15632        wrapped_text.push_str(&current_line);
15633    }
15634    wrapped_text
15635}
15636
15637#[test]
15638fn test_wrap_with_prefix() {
15639    assert_eq!(
15640        wrap_with_prefix(
15641            "# ".to_string(),
15642            "abcdefg".to_string(),
15643            4,
15644            NonZeroU32::new(4).unwrap()
15645        ),
15646        "# abcdefg"
15647    );
15648    assert_eq!(
15649        wrap_with_prefix(
15650            "".to_string(),
15651            "\thello world".to_string(),
15652            8,
15653            NonZeroU32::new(4).unwrap()
15654        ),
15655        "hello\nworld"
15656    );
15657    assert_eq!(
15658        wrap_with_prefix(
15659            "// ".to_string(),
15660            "xx \nyy zz aa bb cc".to_string(),
15661            12,
15662            NonZeroU32::new(4).unwrap()
15663        ),
15664        "// xx yy zz\n// aa bb cc"
15665    );
15666    assert_eq!(
15667        wrap_with_prefix(
15668            String::new(),
15669            "这是什么 \n 钢笔".to_string(),
15670            3,
15671            NonZeroU32::new(4).unwrap()
15672        ),
15673        "这是什\n么 钢\n"
15674    );
15675}
15676
15677pub trait CollaborationHub {
15678    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15679    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15680    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15681}
15682
15683impl CollaborationHub for Entity<Project> {
15684    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15685        self.read(cx).collaborators()
15686    }
15687
15688    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15689        self.read(cx).user_store().read(cx).participant_indices()
15690    }
15691
15692    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15693        let this = self.read(cx);
15694        let user_ids = this.collaborators().values().map(|c| c.user_id);
15695        this.user_store().read_with(cx, |user_store, cx| {
15696            user_store.participant_names(user_ids, cx)
15697        })
15698    }
15699}
15700
15701pub trait SemanticsProvider {
15702    fn hover(
15703        &self,
15704        buffer: &Entity<Buffer>,
15705        position: text::Anchor,
15706        cx: &mut App,
15707    ) -> Option<Task<Vec<project::Hover>>>;
15708
15709    fn inlay_hints(
15710        &self,
15711        buffer_handle: Entity<Buffer>,
15712        range: Range<text::Anchor>,
15713        cx: &mut App,
15714    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15715
15716    fn resolve_inlay_hint(
15717        &self,
15718        hint: InlayHint,
15719        buffer_handle: Entity<Buffer>,
15720        server_id: LanguageServerId,
15721        cx: &mut App,
15722    ) -> Option<Task<anyhow::Result<InlayHint>>>;
15723
15724    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15725
15726    fn document_highlights(
15727        &self,
15728        buffer: &Entity<Buffer>,
15729        position: text::Anchor,
15730        cx: &mut App,
15731    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15732
15733    fn definitions(
15734        &self,
15735        buffer: &Entity<Buffer>,
15736        position: text::Anchor,
15737        kind: GotoDefinitionKind,
15738        cx: &mut App,
15739    ) -> Option<Task<Result<Vec<LocationLink>>>>;
15740
15741    fn range_for_rename(
15742        &self,
15743        buffer: &Entity<Buffer>,
15744        position: text::Anchor,
15745        cx: &mut App,
15746    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15747
15748    fn perform_rename(
15749        &self,
15750        buffer: &Entity<Buffer>,
15751        position: text::Anchor,
15752        new_name: String,
15753        cx: &mut App,
15754    ) -> Option<Task<Result<ProjectTransaction>>>;
15755}
15756
15757pub trait CompletionProvider {
15758    fn completions(
15759        &self,
15760        buffer: &Entity<Buffer>,
15761        buffer_position: text::Anchor,
15762        trigger: CompletionContext,
15763        window: &mut Window,
15764        cx: &mut Context<Editor>,
15765    ) -> Task<Result<Vec<Completion>>>;
15766
15767    fn resolve_completions(
15768        &self,
15769        buffer: Entity<Buffer>,
15770        completion_indices: Vec<usize>,
15771        completions: Rc<RefCell<Box<[Completion]>>>,
15772        cx: &mut Context<Editor>,
15773    ) -> Task<Result<bool>>;
15774
15775    fn apply_additional_edits_for_completion(
15776        &self,
15777        _buffer: Entity<Buffer>,
15778        _completions: Rc<RefCell<Box<[Completion]>>>,
15779        _completion_index: usize,
15780        _push_to_history: bool,
15781        _cx: &mut Context<Editor>,
15782    ) -> Task<Result<Option<language::Transaction>>> {
15783        Task::ready(Ok(None))
15784    }
15785
15786    fn is_completion_trigger(
15787        &self,
15788        buffer: &Entity<Buffer>,
15789        position: language::Anchor,
15790        text: &str,
15791        trigger_in_words: bool,
15792        cx: &mut Context<Editor>,
15793    ) -> bool;
15794
15795    fn sort_completions(&self) -> bool {
15796        true
15797    }
15798}
15799
15800pub trait CodeActionProvider {
15801    fn id(&self) -> Arc<str>;
15802
15803    fn code_actions(
15804        &self,
15805        buffer: &Entity<Buffer>,
15806        range: Range<text::Anchor>,
15807        window: &mut Window,
15808        cx: &mut App,
15809    ) -> Task<Result<Vec<CodeAction>>>;
15810
15811    fn apply_code_action(
15812        &self,
15813        buffer_handle: Entity<Buffer>,
15814        action: CodeAction,
15815        excerpt_id: ExcerptId,
15816        push_to_history: bool,
15817        window: &mut Window,
15818        cx: &mut App,
15819    ) -> Task<Result<ProjectTransaction>>;
15820}
15821
15822impl CodeActionProvider for Entity<Project> {
15823    fn id(&self) -> Arc<str> {
15824        "project".into()
15825    }
15826
15827    fn code_actions(
15828        &self,
15829        buffer: &Entity<Buffer>,
15830        range: Range<text::Anchor>,
15831        _window: &mut Window,
15832        cx: &mut App,
15833    ) -> Task<Result<Vec<CodeAction>>> {
15834        self.update(cx, |project, cx| {
15835            project.code_actions(buffer, range, None, cx)
15836        })
15837    }
15838
15839    fn apply_code_action(
15840        &self,
15841        buffer_handle: Entity<Buffer>,
15842        action: CodeAction,
15843        _excerpt_id: ExcerptId,
15844        push_to_history: bool,
15845        _window: &mut Window,
15846        cx: &mut App,
15847    ) -> Task<Result<ProjectTransaction>> {
15848        self.update(cx, |project, cx| {
15849            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15850        })
15851    }
15852}
15853
15854fn snippet_completions(
15855    project: &Project,
15856    buffer: &Entity<Buffer>,
15857    buffer_position: text::Anchor,
15858    cx: &mut App,
15859) -> Task<Result<Vec<Completion>>> {
15860    let language = buffer.read(cx).language_at(buffer_position);
15861    let language_name = language.as_ref().map(|language| language.lsp_id());
15862    let snippet_store = project.snippets().read(cx);
15863    let snippets = snippet_store.snippets_for(language_name, cx);
15864
15865    if snippets.is_empty() {
15866        return Task::ready(Ok(vec![]));
15867    }
15868    let snapshot = buffer.read(cx).text_snapshot();
15869    let chars: String = snapshot
15870        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15871        .collect();
15872
15873    let scope = language.map(|language| language.default_scope());
15874    let executor = cx.background_executor().clone();
15875
15876    cx.background_spawn(async move {
15877        let classifier = CharClassifier::new(scope).for_completion(true);
15878        let mut last_word = chars
15879            .chars()
15880            .take_while(|c| classifier.is_word(*c))
15881            .collect::<String>();
15882        last_word = last_word.chars().rev().collect();
15883
15884        if last_word.is_empty() {
15885            return Ok(vec![]);
15886        }
15887
15888        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15889        let to_lsp = |point: &text::Anchor| {
15890            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15891            point_to_lsp(end)
15892        };
15893        let lsp_end = to_lsp(&buffer_position);
15894
15895        let candidates = snippets
15896            .iter()
15897            .enumerate()
15898            .flat_map(|(ix, snippet)| {
15899                snippet
15900                    .prefix
15901                    .iter()
15902                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15903            })
15904            .collect::<Vec<StringMatchCandidate>>();
15905
15906        let mut matches = fuzzy::match_strings(
15907            &candidates,
15908            &last_word,
15909            last_word.chars().any(|c| c.is_uppercase()),
15910            100,
15911            &Default::default(),
15912            executor,
15913        )
15914        .await;
15915
15916        // Remove all candidates where the query's start does not match the start of any word in the candidate
15917        if let Some(query_start) = last_word.chars().next() {
15918            matches.retain(|string_match| {
15919                split_words(&string_match.string).any(|word| {
15920                    // Check that the first codepoint of the word as lowercase matches the first
15921                    // codepoint of the query as lowercase
15922                    word.chars()
15923                        .flat_map(|codepoint| codepoint.to_lowercase())
15924                        .zip(query_start.to_lowercase())
15925                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15926                })
15927            });
15928        }
15929
15930        let matched_strings = matches
15931            .into_iter()
15932            .map(|m| m.string)
15933            .collect::<HashSet<_>>();
15934
15935        let result: Vec<Completion> = snippets
15936            .into_iter()
15937            .filter_map(|snippet| {
15938                let matching_prefix = snippet
15939                    .prefix
15940                    .iter()
15941                    .find(|prefix| matched_strings.contains(*prefix))?;
15942                let start = as_offset - last_word.len();
15943                let start = snapshot.anchor_before(start);
15944                let range = start..buffer_position;
15945                let lsp_start = to_lsp(&start);
15946                let lsp_range = lsp::Range {
15947                    start: lsp_start,
15948                    end: lsp_end,
15949                };
15950                Some(Completion {
15951                    old_range: range,
15952                    new_text: snippet.body.clone(),
15953                    resolved: false,
15954                    label: CodeLabel {
15955                        text: matching_prefix.clone(),
15956                        runs: vec![],
15957                        filter_range: 0..matching_prefix.len(),
15958                    },
15959                    server_id: LanguageServerId(usize::MAX),
15960                    documentation: snippet
15961                        .description
15962                        .clone()
15963                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
15964                    lsp_completion: lsp::CompletionItem {
15965                        label: snippet.prefix.first().unwrap().clone(),
15966                        kind: Some(CompletionItemKind::SNIPPET),
15967                        label_details: snippet.description.as_ref().map(|description| {
15968                            lsp::CompletionItemLabelDetails {
15969                                detail: Some(description.clone()),
15970                                description: None,
15971                            }
15972                        }),
15973                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15974                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15975                            lsp::InsertReplaceEdit {
15976                                new_text: snippet.body.clone(),
15977                                insert: lsp_range,
15978                                replace: lsp_range,
15979                            },
15980                        )),
15981                        filter_text: Some(snippet.body.clone()),
15982                        sort_text: Some(char::MAX.to_string()),
15983                        ..Default::default()
15984                    },
15985                    confirm: None,
15986                })
15987            })
15988            .collect();
15989
15990        Ok(result)
15991    })
15992}
15993
15994impl CompletionProvider for Entity<Project> {
15995    fn completions(
15996        &self,
15997        buffer: &Entity<Buffer>,
15998        buffer_position: text::Anchor,
15999        options: CompletionContext,
16000        _window: &mut Window,
16001        cx: &mut Context<Editor>,
16002    ) -> Task<Result<Vec<Completion>>> {
16003        self.update(cx, |project, cx| {
16004            let snippets = snippet_completions(project, buffer, buffer_position, cx);
16005            let project_completions = project.completions(buffer, buffer_position, options, cx);
16006            cx.background_spawn(async move {
16007                let mut completions = project_completions.await?;
16008                let snippets_completions = snippets.await?;
16009                completions.extend(snippets_completions);
16010                Ok(completions)
16011            })
16012        })
16013    }
16014
16015    fn resolve_completions(
16016        &self,
16017        buffer: Entity<Buffer>,
16018        completion_indices: Vec<usize>,
16019        completions: Rc<RefCell<Box<[Completion]>>>,
16020        cx: &mut Context<Editor>,
16021    ) -> Task<Result<bool>> {
16022        self.update(cx, |project, cx| {
16023            project.lsp_store().update(cx, |lsp_store, cx| {
16024                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16025            })
16026        })
16027    }
16028
16029    fn apply_additional_edits_for_completion(
16030        &self,
16031        buffer: Entity<Buffer>,
16032        completions: Rc<RefCell<Box<[Completion]>>>,
16033        completion_index: usize,
16034        push_to_history: bool,
16035        cx: &mut Context<Editor>,
16036    ) -> Task<Result<Option<language::Transaction>>> {
16037        self.update(cx, |project, cx| {
16038            project.lsp_store().update(cx, |lsp_store, cx| {
16039                lsp_store.apply_additional_edits_for_completion(
16040                    buffer,
16041                    completions,
16042                    completion_index,
16043                    push_to_history,
16044                    cx,
16045                )
16046            })
16047        })
16048    }
16049
16050    fn is_completion_trigger(
16051        &self,
16052        buffer: &Entity<Buffer>,
16053        position: language::Anchor,
16054        text: &str,
16055        trigger_in_words: bool,
16056        cx: &mut Context<Editor>,
16057    ) -> bool {
16058        let mut chars = text.chars();
16059        let char = if let Some(char) = chars.next() {
16060            char
16061        } else {
16062            return false;
16063        };
16064        if chars.next().is_some() {
16065            return false;
16066        }
16067
16068        let buffer = buffer.read(cx);
16069        let snapshot = buffer.snapshot();
16070        if !snapshot.settings_at(position, cx).show_completions_on_input {
16071            return false;
16072        }
16073        let classifier = snapshot.char_classifier_at(position).for_completion(true);
16074        if trigger_in_words && classifier.is_word(char) {
16075            return true;
16076        }
16077
16078        buffer.completion_triggers().contains(text)
16079    }
16080}
16081
16082impl SemanticsProvider for Entity<Project> {
16083    fn hover(
16084        &self,
16085        buffer: &Entity<Buffer>,
16086        position: text::Anchor,
16087        cx: &mut App,
16088    ) -> Option<Task<Vec<project::Hover>>> {
16089        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
16090    }
16091
16092    fn document_highlights(
16093        &self,
16094        buffer: &Entity<Buffer>,
16095        position: text::Anchor,
16096        cx: &mut App,
16097    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
16098        Some(self.update(cx, |project, cx| {
16099            project.document_highlights(buffer, position, cx)
16100        }))
16101    }
16102
16103    fn definitions(
16104        &self,
16105        buffer: &Entity<Buffer>,
16106        position: text::Anchor,
16107        kind: GotoDefinitionKind,
16108        cx: &mut App,
16109    ) -> Option<Task<Result<Vec<LocationLink>>>> {
16110        Some(self.update(cx, |project, cx| match kind {
16111            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
16112            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
16113            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
16114            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
16115        }))
16116    }
16117
16118    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
16119        // TODO: make this work for remote projects
16120        self.update(cx, |this, cx| {
16121            buffer.update(cx, |buffer, cx| {
16122                this.any_language_server_supports_inlay_hints(buffer, cx)
16123            })
16124        })
16125    }
16126
16127    fn inlay_hints(
16128        &self,
16129        buffer_handle: Entity<Buffer>,
16130        range: Range<text::Anchor>,
16131        cx: &mut App,
16132    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
16133        Some(self.update(cx, |project, cx| {
16134            project.inlay_hints(buffer_handle, range, cx)
16135        }))
16136    }
16137
16138    fn resolve_inlay_hint(
16139        &self,
16140        hint: InlayHint,
16141        buffer_handle: Entity<Buffer>,
16142        server_id: LanguageServerId,
16143        cx: &mut App,
16144    ) -> Option<Task<anyhow::Result<InlayHint>>> {
16145        Some(self.update(cx, |project, cx| {
16146            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
16147        }))
16148    }
16149
16150    fn range_for_rename(
16151        &self,
16152        buffer: &Entity<Buffer>,
16153        position: text::Anchor,
16154        cx: &mut App,
16155    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
16156        Some(self.update(cx, |project, cx| {
16157            let buffer = buffer.clone();
16158            let task = project.prepare_rename(buffer.clone(), position, cx);
16159            cx.spawn(|_, mut cx| async move {
16160                Ok(match task.await? {
16161                    PrepareRenameResponse::Success(range) => Some(range),
16162                    PrepareRenameResponse::InvalidPosition => None,
16163                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
16164                        // Fallback on using TreeSitter info to determine identifier range
16165                        buffer.update(&mut cx, |buffer, _| {
16166                            let snapshot = buffer.snapshot();
16167                            let (range, kind) = snapshot.surrounding_word(position);
16168                            if kind != Some(CharKind::Word) {
16169                                return None;
16170                            }
16171                            Some(
16172                                snapshot.anchor_before(range.start)
16173                                    ..snapshot.anchor_after(range.end),
16174                            )
16175                        })?
16176                    }
16177                })
16178            })
16179        }))
16180    }
16181
16182    fn perform_rename(
16183        &self,
16184        buffer: &Entity<Buffer>,
16185        position: text::Anchor,
16186        new_name: String,
16187        cx: &mut App,
16188    ) -> Option<Task<Result<ProjectTransaction>>> {
16189        Some(self.update(cx, |project, cx| {
16190            project.perform_rename(buffer.clone(), position, new_name, cx)
16191        }))
16192    }
16193}
16194
16195fn inlay_hint_settings(
16196    location: Anchor,
16197    snapshot: &MultiBufferSnapshot,
16198    cx: &mut Context<Editor>,
16199) -> InlayHintSettings {
16200    let file = snapshot.file_at(location);
16201    let language = snapshot.language_at(location).map(|l| l.name());
16202    language_settings(language, file, cx).inlay_hints
16203}
16204
16205fn consume_contiguous_rows(
16206    contiguous_row_selections: &mut Vec<Selection<Point>>,
16207    selection: &Selection<Point>,
16208    display_map: &DisplaySnapshot,
16209    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
16210) -> (MultiBufferRow, MultiBufferRow) {
16211    contiguous_row_selections.push(selection.clone());
16212    let start_row = MultiBufferRow(selection.start.row);
16213    let mut end_row = ending_row(selection, display_map);
16214
16215    while let Some(next_selection) = selections.peek() {
16216        if next_selection.start.row <= end_row.0 {
16217            end_row = ending_row(next_selection, display_map);
16218            contiguous_row_selections.push(selections.next().unwrap().clone());
16219        } else {
16220            break;
16221        }
16222    }
16223    (start_row, end_row)
16224}
16225
16226fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
16227    if next_selection.end.column > 0 || next_selection.is_empty() {
16228        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
16229    } else {
16230        MultiBufferRow(next_selection.end.row)
16231    }
16232}
16233
16234impl EditorSnapshot {
16235    pub fn remote_selections_in_range<'a>(
16236        &'a self,
16237        range: &'a Range<Anchor>,
16238        collaboration_hub: &dyn CollaborationHub,
16239        cx: &'a App,
16240    ) -> impl 'a + Iterator<Item = RemoteSelection> {
16241        let participant_names = collaboration_hub.user_names(cx);
16242        let participant_indices = collaboration_hub.user_participant_indices(cx);
16243        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
16244        let collaborators_by_replica_id = collaborators_by_peer_id
16245            .iter()
16246            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
16247            .collect::<HashMap<_, _>>();
16248        self.buffer_snapshot
16249            .selections_in_range(range, false)
16250            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
16251                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
16252                let participant_index = participant_indices.get(&collaborator.user_id).copied();
16253                let user_name = participant_names.get(&collaborator.user_id).cloned();
16254                Some(RemoteSelection {
16255                    replica_id,
16256                    selection,
16257                    cursor_shape,
16258                    line_mode,
16259                    participant_index,
16260                    peer_id: collaborator.peer_id,
16261                    user_name,
16262                })
16263            })
16264    }
16265
16266    pub fn hunks_for_ranges(
16267        &self,
16268        ranges: impl Iterator<Item = Range<Point>>,
16269    ) -> Vec<MultiBufferDiffHunk> {
16270        let mut hunks = Vec::new();
16271        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
16272            HashMap::default();
16273        for query_range in ranges {
16274            let query_rows =
16275                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
16276            for hunk in self.buffer_snapshot.diff_hunks_in_range(
16277                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
16278            ) {
16279                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
16280                // when the caret is just above or just below the deleted hunk.
16281                let allow_adjacent = hunk.status().is_deleted();
16282                let related_to_selection = if allow_adjacent {
16283                    hunk.row_range.overlaps(&query_rows)
16284                        || hunk.row_range.start == query_rows.end
16285                        || hunk.row_range.end == query_rows.start
16286                } else {
16287                    hunk.row_range.overlaps(&query_rows)
16288                };
16289                if related_to_selection {
16290                    if !processed_buffer_rows
16291                        .entry(hunk.buffer_id)
16292                        .or_default()
16293                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16294                    {
16295                        continue;
16296                    }
16297                    hunks.push(hunk);
16298                }
16299            }
16300        }
16301
16302        hunks
16303    }
16304
16305    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16306        self.display_snapshot.buffer_snapshot.language_at(position)
16307    }
16308
16309    pub fn is_focused(&self) -> bool {
16310        self.is_focused
16311    }
16312
16313    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16314        self.placeholder_text.as_ref()
16315    }
16316
16317    pub fn scroll_position(&self) -> gpui::Point<f32> {
16318        self.scroll_anchor.scroll_position(&self.display_snapshot)
16319    }
16320
16321    fn gutter_dimensions(
16322        &self,
16323        font_id: FontId,
16324        font_size: Pixels,
16325        max_line_number_width: Pixels,
16326        cx: &App,
16327    ) -> Option<GutterDimensions> {
16328        if !self.show_gutter {
16329            return None;
16330        }
16331
16332        let descent = cx.text_system().descent(font_id, font_size);
16333        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16334        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16335
16336        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16337            matches!(
16338                ProjectSettings::get_global(cx).git.git_gutter,
16339                Some(GitGutterSetting::TrackedFiles)
16340            )
16341        });
16342        let gutter_settings = EditorSettings::get_global(cx).gutter;
16343        let show_line_numbers = self
16344            .show_line_numbers
16345            .unwrap_or(gutter_settings.line_numbers);
16346        let line_gutter_width = if show_line_numbers {
16347            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16348            let min_width_for_number_on_gutter = em_advance * 4.0;
16349            max_line_number_width.max(min_width_for_number_on_gutter)
16350        } else {
16351            0.0.into()
16352        };
16353
16354        let show_code_actions = self
16355            .show_code_actions
16356            .unwrap_or(gutter_settings.code_actions);
16357
16358        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16359
16360        let git_blame_entries_width =
16361            self.git_blame_gutter_max_author_length
16362                .map(|max_author_length| {
16363                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16364
16365                    /// The number of characters to dedicate to gaps and margins.
16366                    const SPACING_WIDTH: usize = 4;
16367
16368                    let max_char_count = max_author_length
16369                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16370                        + ::git::SHORT_SHA_LENGTH
16371                        + MAX_RELATIVE_TIMESTAMP.len()
16372                        + SPACING_WIDTH;
16373
16374                    em_advance * max_char_count
16375                });
16376
16377        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16378        left_padding += if show_code_actions || show_runnables {
16379            em_width * 3.0
16380        } else if show_git_gutter && show_line_numbers {
16381            em_width * 2.0
16382        } else if show_git_gutter || show_line_numbers {
16383            em_width
16384        } else {
16385            px(0.)
16386        };
16387
16388        let right_padding = if gutter_settings.folds && show_line_numbers {
16389            em_width * 4.0
16390        } else if gutter_settings.folds {
16391            em_width * 3.0
16392        } else if show_line_numbers {
16393            em_width
16394        } else {
16395            px(0.)
16396        };
16397
16398        Some(GutterDimensions {
16399            left_padding,
16400            right_padding,
16401            width: line_gutter_width + left_padding + right_padding,
16402            margin: -descent,
16403            git_blame_entries_width,
16404        })
16405    }
16406
16407    pub fn render_crease_toggle(
16408        &self,
16409        buffer_row: MultiBufferRow,
16410        row_contains_cursor: bool,
16411        editor: Entity<Editor>,
16412        window: &mut Window,
16413        cx: &mut App,
16414    ) -> Option<AnyElement> {
16415        let folded = self.is_line_folded(buffer_row);
16416        let mut is_foldable = false;
16417
16418        if let Some(crease) = self
16419            .crease_snapshot
16420            .query_row(buffer_row, &self.buffer_snapshot)
16421        {
16422            is_foldable = true;
16423            match crease {
16424                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
16425                    if let Some(render_toggle) = render_toggle {
16426                        let toggle_callback =
16427                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
16428                                if folded {
16429                                    editor.update(cx, |editor, cx| {
16430                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
16431                                    });
16432                                } else {
16433                                    editor.update(cx, |editor, cx| {
16434                                        editor.unfold_at(
16435                                            &crate::UnfoldAt { buffer_row },
16436                                            window,
16437                                            cx,
16438                                        )
16439                                    });
16440                                }
16441                            });
16442                        return Some((render_toggle)(
16443                            buffer_row,
16444                            folded,
16445                            toggle_callback,
16446                            window,
16447                            cx,
16448                        ));
16449                    }
16450                }
16451            }
16452        }
16453
16454        is_foldable |= self.starts_indent(buffer_row);
16455
16456        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16457            Some(
16458                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16459                    .toggle_state(folded)
16460                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16461                        if folded {
16462                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16463                        } else {
16464                            this.fold_at(&FoldAt { buffer_row }, window, cx);
16465                        }
16466                    }))
16467                    .into_any_element(),
16468            )
16469        } else {
16470            None
16471        }
16472    }
16473
16474    pub fn render_crease_trailer(
16475        &self,
16476        buffer_row: MultiBufferRow,
16477        window: &mut Window,
16478        cx: &mut App,
16479    ) -> Option<AnyElement> {
16480        let folded = self.is_line_folded(buffer_row);
16481        if let Crease::Inline { render_trailer, .. } = self
16482            .crease_snapshot
16483            .query_row(buffer_row, &self.buffer_snapshot)?
16484        {
16485            let render_trailer = render_trailer.as_ref()?;
16486            Some(render_trailer(buffer_row, folded, window, cx))
16487        } else {
16488            None
16489        }
16490    }
16491}
16492
16493impl Deref for EditorSnapshot {
16494    type Target = DisplaySnapshot;
16495
16496    fn deref(&self) -> &Self::Target {
16497        &self.display_snapshot
16498    }
16499}
16500
16501#[derive(Clone, Debug, PartialEq, Eq)]
16502pub enum EditorEvent {
16503    InputIgnored {
16504        text: Arc<str>,
16505    },
16506    InputHandled {
16507        utf16_range_to_replace: Option<Range<isize>>,
16508        text: Arc<str>,
16509    },
16510    ExcerptsAdded {
16511        buffer: Entity<Buffer>,
16512        predecessor: ExcerptId,
16513        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16514    },
16515    ExcerptsRemoved {
16516        ids: Vec<ExcerptId>,
16517    },
16518    BufferFoldToggled {
16519        ids: Vec<ExcerptId>,
16520        folded: bool,
16521    },
16522    ExcerptsEdited {
16523        ids: Vec<ExcerptId>,
16524    },
16525    ExcerptsExpanded {
16526        ids: Vec<ExcerptId>,
16527    },
16528    BufferEdited,
16529    Edited {
16530        transaction_id: clock::Lamport,
16531    },
16532    Reparsed(BufferId),
16533    Focused,
16534    FocusedIn,
16535    Blurred,
16536    DirtyChanged,
16537    Saved,
16538    TitleChanged,
16539    DiffBaseChanged,
16540    SelectionsChanged {
16541        local: bool,
16542    },
16543    ScrollPositionChanged {
16544        local: bool,
16545        autoscroll: bool,
16546    },
16547    Closed,
16548    TransactionUndone {
16549        transaction_id: clock::Lamport,
16550    },
16551    TransactionBegun {
16552        transaction_id: clock::Lamport,
16553    },
16554    Reloaded,
16555    CursorShapeChanged,
16556}
16557
16558impl EventEmitter<EditorEvent> for Editor {}
16559
16560impl Focusable for Editor {
16561    fn focus_handle(&self, _cx: &App) -> FocusHandle {
16562        self.focus_handle.clone()
16563    }
16564}
16565
16566impl Render for Editor {
16567    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16568        let settings = ThemeSettings::get_global(cx);
16569
16570        let mut text_style = match self.mode {
16571            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16572                color: cx.theme().colors().editor_foreground,
16573                font_family: settings.ui_font.family.clone(),
16574                font_features: settings.ui_font.features.clone(),
16575                font_fallbacks: settings.ui_font.fallbacks.clone(),
16576                font_size: rems(0.875).into(),
16577                font_weight: settings.ui_font.weight,
16578                line_height: relative(settings.buffer_line_height.value()),
16579                ..Default::default()
16580            },
16581            EditorMode::Full => TextStyle {
16582                color: cx.theme().colors().editor_foreground,
16583                font_family: settings.buffer_font.family.clone(),
16584                font_features: settings.buffer_font.features.clone(),
16585                font_fallbacks: settings.buffer_font.fallbacks.clone(),
16586                font_size: settings.buffer_font_size(cx).into(),
16587                font_weight: settings.buffer_font.weight,
16588                line_height: relative(settings.buffer_line_height.value()),
16589                ..Default::default()
16590            },
16591        };
16592        if let Some(text_style_refinement) = &self.text_style_refinement {
16593            text_style.refine(text_style_refinement)
16594        }
16595
16596        let background = match self.mode {
16597            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16598            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16599            EditorMode::Full => cx.theme().colors().editor_background,
16600        };
16601
16602        EditorElement::new(
16603            &cx.entity(),
16604            EditorStyle {
16605                background,
16606                local_player: cx.theme().players().local(),
16607                text: text_style,
16608                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16609                syntax: cx.theme().syntax().clone(),
16610                status: cx.theme().status().clone(),
16611                inlay_hints_style: make_inlay_hints_style(cx),
16612                inline_completion_styles: make_suggestion_styles(cx),
16613                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16614            },
16615        )
16616    }
16617}
16618
16619impl EntityInputHandler for Editor {
16620    fn text_for_range(
16621        &mut self,
16622        range_utf16: Range<usize>,
16623        adjusted_range: &mut Option<Range<usize>>,
16624        _: &mut Window,
16625        cx: &mut Context<Self>,
16626    ) -> Option<String> {
16627        let snapshot = self.buffer.read(cx).read(cx);
16628        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16629        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16630        if (start.0..end.0) != range_utf16 {
16631            adjusted_range.replace(start.0..end.0);
16632        }
16633        Some(snapshot.text_for_range(start..end).collect())
16634    }
16635
16636    fn selected_text_range(
16637        &mut self,
16638        ignore_disabled_input: bool,
16639        _: &mut Window,
16640        cx: &mut Context<Self>,
16641    ) -> Option<UTF16Selection> {
16642        // Prevent the IME menu from appearing when holding down an alphabetic key
16643        // while input is disabled.
16644        if !ignore_disabled_input && !self.input_enabled {
16645            return None;
16646        }
16647
16648        let selection = self.selections.newest::<OffsetUtf16>(cx);
16649        let range = selection.range();
16650
16651        Some(UTF16Selection {
16652            range: range.start.0..range.end.0,
16653            reversed: selection.reversed,
16654        })
16655    }
16656
16657    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16658        let snapshot = self.buffer.read(cx).read(cx);
16659        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16660        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16661    }
16662
16663    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16664        self.clear_highlights::<InputComposition>(cx);
16665        self.ime_transaction.take();
16666    }
16667
16668    fn replace_text_in_range(
16669        &mut self,
16670        range_utf16: Option<Range<usize>>,
16671        text: &str,
16672        window: &mut Window,
16673        cx: &mut Context<Self>,
16674    ) {
16675        if !self.input_enabled {
16676            cx.emit(EditorEvent::InputIgnored { text: text.into() });
16677            return;
16678        }
16679
16680        self.transact(window, cx, |this, window, cx| {
16681            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16682                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16683                Some(this.selection_replacement_ranges(range_utf16, cx))
16684            } else {
16685                this.marked_text_ranges(cx)
16686            };
16687
16688            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16689                let newest_selection_id = this.selections.newest_anchor().id;
16690                this.selections
16691                    .all::<OffsetUtf16>(cx)
16692                    .iter()
16693                    .zip(ranges_to_replace.iter())
16694                    .find_map(|(selection, range)| {
16695                        if selection.id == newest_selection_id {
16696                            Some(
16697                                (range.start.0 as isize - selection.head().0 as isize)
16698                                    ..(range.end.0 as isize - selection.head().0 as isize),
16699                            )
16700                        } else {
16701                            None
16702                        }
16703                    })
16704            });
16705
16706            cx.emit(EditorEvent::InputHandled {
16707                utf16_range_to_replace: range_to_replace,
16708                text: text.into(),
16709            });
16710
16711            if let Some(new_selected_ranges) = new_selected_ranges {
16712                this.change_selections(None, window, cx, |selections| {
16713                    selections.select_ranges(new_selected_ranges)
16714                });
16715                this.backspace(&Default::default(), window, cx);
16716            }
16717
16718            this.handle_input(text, window, cx);
16719        });
16720
16721        if let Some(transaction) = self.ime_transaction {
16722            self.buffer.update(cx, |buffer, cx| {
16723                buffer.group_until_transaction(transaction, cx);
16724            });
16725        }
16726
16727        self.unmark_text(window, cx);
16728    }
16729
16730    fn replace_and_mark_text_in_range(
16731        &mut self,
16732        range_utf16: Option<Range<usize>>,
16733        text: &str,
16734        new_selected_range_utf16: Option<Range<usize>>,
16735        window: &mut Window,
16736        cx: &mut Context<Self>,
16737    ) {
16738        if !self.input_enabled {
16739            return;
16740        }
16741
16742        let transaction = self.transact(window, cx, |this, window, cx| {
16743            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16744                let snapshot = this.buffer.read(cx).read(cx);
16745                if let Some(relative_range_utf16) = range_utf16.as_ref() {
16746                    for marked_range in &mut marked_ranges {
16747                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16748                        marked_range.start.0 += relative_range_utf16.start;
16749                        marked_range.start =
16750                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16751                        marked_range.end =
16752                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16753                    }
16754                }
16755                Some(marked_ranges)
16756            } else if let Some(range_utf16) = range_utf16 {
16757                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16758                Some(this.selection_replacement_ranges(range_utf16, cx))
16759            } else {
16760                None
16761            };
16762
16763            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16764                let newest_selection_id = this.selections.newest_anchor().id;
16765                this.selections
16766                    .all::<OffsetUtf16>(cx)
16767                    .iter()
16768                    .zip(ranges_to_replace.iter())
16769                    .find_map(|(selection, range)| {
16770                        if selection.id == newest_selection_id {
16771                            Some(
16772                                (range.start.0 as isize - selection.head().0 as isize)
16773                                    ..(range.end.0 as isize - selection.head().0 as isize),
16774                            )
16775                        } else {
16776                            None
16777                        }
16778                    })
16779            });
16780
16781            cx.emit(EditorEvent::InputHandled {
16782                utf16_range_to_replace: range_to_replace,
16783                text: text.into(),
16784            });
16785
16786            if let Some(ranges) = ranges_to_replace {
16787                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16788            }
16789
16790            let marked_ranges = {
16791                let snapshot = this.buffer.read(cx).read(cx);
16792                this.selections
16793                    .disjoint_anchors()
16794                    .iter()
16795                    .map(|selection| {
16796                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16797                    })
16798                    .collect::<Vec<_>>()
16799            };
16800
16801            if text.is_empty() {
16802                this.unmark_text(window, cx);
16803            } else {
16804                this.highlight_text::<InputComposition>(
16805                    marked_ranges.clone(),
16806                    HighlightStyle {
16807                        underline: Some(UnderlineStyle {
16808                            thickness: px(1.),
16809                            color: None,
16810                            wavy: false,
16811                        }),
16812                        ..Default::default()
16813                    },
16814                    cx,
16815                );
16816            }
16817
16818            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16819            let use_autoclose = this.use_autoclose;
16820            let use_auto_surround = this.use_auto_surround;
16821            this.set_use_autoclose(false);
16822            this.set_use_auto_surround(false);
16823            this.handle_input(text, window, cx);
16824            this.set_use_autoclose(use_autoclose);
16825            this.set_use_auto_surround(use_auto_surround);
16826
16827            if let Some(new_selected_range) = new_selected_range_utf16 {
16828                let snapshot = this.buffer.read(cx).read(cx);
16829                let new_selected_ranges = marked_ranges
16830                    .into_iter()
16831                    .map(|marked_range| {
16832                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16833                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16834                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16835                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16836                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16837                    })
16838                    .collect::<Vec<_>>();
16839
16840                drop(snapshot);
16841                this.change_selections(None, window, cx, |selections| {
16842                    selections.select_ranges(new_selected_ranges)
16843                });
16844            }
16845        });
16846
16847        self.ime_transaction = self.ime_transaction.or(transaction);
16848        if let Some(transaction) = self.ime_transaction {
16849            self.buffer.update(cx, |buffer, cx| {
16850                buffer.group_until_transaction(transaction, cx);
16851            });
16852        }
16853
16854        if self.text_highlights::<InputComposition>(cx).is_none() {
16855            self.ime_transaction.take();
16856        }
16857    }
16858
16859    fn bounds_for_range(
16860        &mut self,
16861        range_utf16: Range<usize>,
16862        element_bounds: gpui::Bounds<Pixels>,
16863        window: &mut Window,
16864        cx: &mut Context<Self>,
16865    ) -> Option<gpui::Bounds<Pixels>> {
16866        let text_layout_details = self.text_layout_details(window);
16867        let gpui::Size {
16868            width: em_width,
16869            height: line_height,
16870        } = self.character_size(window);
16871
16872        let snapshot = self.snapshot(window, cx);
16873        let scroll_position = snapshot.scroll_position();
16874        let scroll_left = scroll_position.x * em_width;
16875
16876        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16877        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16878            + self.gutter_dimensions.width
16879            + self.gutter_dimensions.margin;
16880        let y = line_height * (start.row().as_f32() - scroll_position.y);
16881
16882        Some(Bounds {
16883            origin: element_bounds.origin + point(x, y),
16884            size: size(em_width, line_height),
16885        })
16886    }
16887
16888    fn character_index_for_point(
16889        &mut self,
16890        point: gpui::Point<Pixels>,
16891        _window: &mut Window,
16892        _cx: &mut Context<Self>,
16893    ) -> Option<usize> {
16894        let position_map = self.last_position_map.as_ref()?;
16895        if !position_map.text_hitbox.contains(&point) {
16896            return None;
16897        }
16898        let display_point = position_map.point_for_position(point).previous_valid;
16899        let anchor = position_map
16900            .snapshot
16901            .display_point_to_anchor(display_point, Bias::Left);
16902        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16903        Some(utf16_offset.0)
16904    }
16905}
16906
16907trait SelectionExt {
16908    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16909    fn spanned_rows(
16910        &self,
16911        include_end_if_at_line_start: bool,
16912        map: &DisplaySnapshot,
16913    ) -> Range<MultiBufferRow>;
16914}
16915
16916impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16917    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16918        let start = self
16919            .start
16920            .to_point(&map.buffer_snapshot)
16921            .to_display_point(map);
16922        let end = self
16923            .end
16924            .to_point(&map.buffer_snapshot)
16925            .to_display_point(map);
16926        if self.reversed {
16927            end..start
16928        } else {
16929            start..end
16930        }
16931    }
16932
16933    fn spanned_rows(
16934        &self,
16935        include_end_if_at_line_start: bool,
16936        map: &DisplaySnapshot,
16937    ) -> Range<MultiBufferRow> {
16938        let start = self.start.to_point(&map.buffer_snapshot);
16939        let mut end = self.end.to_point(&map.buffer_snapshot);
16940        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16941            end.row -= 1;
16942        }
16943
16944        let buffer_start = map.prev_line_boundary(start).0;
16945        let buffer_end = map.next_line_boundary(end).0;
16946        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16947    }
16948}
16949
16950impl<T: InvalidationRegion> InvalidationStack<T> {
16951    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16952    where
16953        S: Clone + ToOffset,
16954    {
16955        while let Some(region) = self.last() {
16956            let all_selections_inside_invalidation_ranges =
16957                if selections.len() == region.ranges().len() {
16958                    selections
16959                        .iter()
16960                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16961                        .all(|(selection, invalidation_range)| {
16962                            let head = selection.head().to_offset(buffer);
16963                            invalidation_range.start <= head && invalidation_range.end >= head
16964                        })
16965                } else {
16966                    false
16967                };
16968
16969            if all_selections_inside_invalidation_ranges {
16970                break;
16971            } else {
16972                self.pop();
16973            }
16974        }
16975    }
16976}
16977
16978impl<T> Default for InvalidationStack<T> {
16979    fn default() -> Self {
16980        Self(Default::default())
16981    }
16982}
16983
16984impl<T> Deref for InvalidationStack<T> {
16985    type Target = Vec<T>;
16986
16987    fn deref(&self) -> &Self::Target {
16988        &self.0
16989    }
16990}
16991
16992impl<T> DerefMut for InvalidationStack<T> {
16993    fn deref_mut(&mut self) -> &mut Self::Target {
16994        &mut self.0
16995    }
16996}
16997
16998impl InvalidationRegion for SnippetState {
16999    fn ranges(&self) -> &[Range<Anchor>] {
17000        &self.ranges[self.active_index]
17001    }
17002}
17003
17004pub fn diagnostic_block_renderer(
17005    diagnostic: Diagnostic,
17006    max_message_rows: Option<u8>,
17007    allow_closing: bool,
17008    _is_valid: bool,
17009) -> RenderBlock {
17010    let (text_without_backticks, code_ranges) =
17011        highlight_diagnostic_message(&diagnostic, max_message_rows);
17012
17013    Arc::new(move |cx: &mut BlockContext| {
17014        let group_id: SharedString = cx.block_id.to_string().into();
17015
17016        let mut text_style = cx.window.text_style().clone();
17017        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17018        let theme_settings = ThemeSettings::get_global(cx);
17019        text_style.font_family = theme_settings.buffer_font.family.clone();
17020        text_style.font_style = theme_settings.buffer_font.style;
17021        text_style.font_features = theme_settings.buffer_font.features.clone();
17022        text_style.font_weight = theme_settings.buffer_font.weight;
17023
17024        let multi_line_diagnostic = diagnostic.message.contains('\n');
17025
17026        let buttons = |diagnostic: &Diagnostic| {
17027            if multi_line_diagnostic {
17028                v_flex()
17029            } else {
17030                h_flex()
17031            }
17032            .when(allow_closing, |div| {
17033                div.children(diagnostic.is_primary.then(|| {
17034                    IconButton::new("close-block", IconName::XCircle)
17035                        .icon_color(Color::Muted)
17036                        .size(ButtonSize::Compact)
17037                        .style(ButtonStyle::Transparent)
17038                        .visible_on_hover(group_id.clone())
17039                        .on_click(move |_click, window, cx| {
17040                            window.dispatch_action(Box::new(Cancel), cx)
17041                        })
17042                        .tooltip(|window, cx| {
17043                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
17044                        })
17045                }))
17046            })
17047            .child(
17048                IconButton::new("copy-block", IconName::Copy)
17049                    .icon_color(Color::Muted)
17050                    .size(ButtonSize::Compact)
17051                    .style(ButtonStyle::Transparent)
17052                    .visible_on_hover(group_id.clone())
17053                    .on_click({
17054                        let message = diagnostic.message.clone();
17055                        move |_click, _, cx| {
17056                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
17057                        }
17058                    })
17059                    .tooltip(Tooltip::text("Copy diagnostic message")),
17060            )
17061        };
17062
17063        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
17064            AvailableSpace::min_size(),
17065            cx.window,
17066            cx.app,
17067        );
17068
17069        h_flex()
17070            .id(cx.block_id)
17071            .group(group_id.clone())
17072            .relative()
17073            .size_full()
17074            .block_mouse_down()
17075            .pl(cx.gutter_dimensions.width)
17076            .w(cx.max_width - cx.gutter_dimensions.full_width())
17077            .child(
17078                div()
17079                    .flex()
17080                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
17081                    .flex_shrink(),
17082            )
17083            .child(buttons(&diagnostic))
17084            .child(div().flex().flex_shrink_0().child(
17085                StyledText::new(text_without_backticks.clone()).with_highlights(
17086                    &text_style,
17087                    code_ranges.iter().map(|range| {
17088                        (
17089                            range.clone(),
17090                            HighlightStyle {
17091                                font_weight: Some(FontWeight::BOLD),
17092                                ..Default::default()
17093                            },
17094                        )
17095                    }),
17096                ),
17097            ))
17098            .into_any_element()
17099    })
17100}
17101
17102fn inline_completion_edit_text(
17103    current_snapshot: &BufferSnapshot,
17104    edits: &[(Range<Anchor>, String)],
17105    edit_preview: &EditPreview,
17106    include_deletions: bool,
17107    cx: &App,
17108) -> HighlightedText {
17109    let edits = edits
17110        .iter()
17111        .map(|(anchor, text)| {
17112            (
17113                anchor.start.text_anchor..anchor.end.text_anchor,
17114                text.clone(),
17115            )
17116        })
17117        .collect::<Vec<_>>();
17118
17119    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
17120}
17121
17122pub fn highlight_diagnostic_message(
17123    diagnostic: &Diagnostic,
17124    mut max_message_rows: Option<u8>,
17125) -> (SharedString, Vec<Range<usize>>) {
17126    let mut text_without_backticks = String::new();
17127    let mut code_ranges = Vec::new();
17128
17129    if let Some(source) = &diagnostic.source {
17130        text_without_backticks.push_str(source);
17131        code_ranges.push(0..source.len());
17132        text_without_backticks.push_str(": ");
17133    }
17134
17135    let mut prev_offset = 0;
17136    let mut in_code_block = false;
17137    let has_row_limit = max_message_rows.is_some();
17138    let mut newline_indices = diagnostic
17139        .message
17140        .match_indices('\n')
17141        .filter(|_| has_row_limit)
17142        .map(|(ix, _)| ix)
17143        .fuse()
17144        .peekable();
17145
17146    for (quote_ix, _) in diagnostic
17147        .message
17148        .match_indices('`')
17149        .chain([(diagnostic.message.len(), "")])
17150    {
17151        let mut first_newline_ix = None;
17152        let mut last_newline_ix = None;
17153        while let Some(newline_ix) = newline_indices.peek() {
17154            if *newline_ix < quote_ix {
17155                if first_newline_ix.is_none() {
17156                    first_newline_ix = Some(*newline_ix);
17157                }
17158                last_newline_ix = Some(*newline_ix);
17159
17160                if let Some(rows_left) = &mut max_message_rows {
17161                    if *rows_left == 0 {
17162                        break;
17163                    } else {
17164                        *rows_left -= 1;
17165                    }
17166                }
17167                let _ = newline_indices.next();
17168            } else {
17169                break;
17170            }
17171        }
17172        let prev_len = text_without_backticks.len();
17173        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
17174        text_without_backticks.push_str(new_text);
17175        if in_code_block {
17176            code_ranges.push(prev_len..text_without_backticks.len());
17177        }
17178        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
17179        in_code_block = !in_code_block;
17180        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
17181            text_without_backticks.push_str("...");
17182            break;
17183        }
17184    }
17185
17186    (text_without_backticks.into(), code_ranges)
17187}
17188
17189fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
17190    match severity {
17191        DiagnosticSeverity::ERROR => colors.error,
17192        DiagnosticSeverity::WARNING => colors.warning,
17193        DiagnosticSeverity::INFORMATION => colors.info,
17194        DiagnosticSeverity::HINT => colors.info,
17195        _ => colors.ignored,
17196    }
17197}
17198
17199pub fn styled_runs_for_code_label<'a>(
17200    label: &'a CodeLabel,
17201    syntax_theme: &'a theme::SyntaxTheme,
17202) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
17203    let fade_out = HighlightStyle {
17204        fade_out: Some(0.35),
17205        ..Default::default()
17206    };
17207
17208    let mut prev_end = label.filter_range.end;
17209    label
17210        .runs
17211        .iter()
17212        .enumerate()
17213        .flat_map(move |(ix, (range, highlight_id))| {
17214            let style = if let Some(style) = highlight_id.style(syntax_theme) {
17215                style
17216            } else {
17217                return Default::default();
17218            };
17219            let mut muted_style = style;
17220            muted_style.highlight(fade_out);
17221
17222            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
17223            if range.start >= label.filter_range.end {
17224                if range.start > prev_end {
17225                    runs.push((prev_end..range.start, fade_out));
17226                }
17227                runs.push((range.clone(), muted_style));
17228            } else if range.end <= label.filter_range.end {
17229                runs.push((range.clone(), style));
17230            } else {
17231                runs.push((range.start..label.filter_range.end, style));
17232                runs.push((label.filter_range.end..range.end, muted_style));
17233            }
17234            prev_end = cmp::max(prev_end, range.end);
17235
17236            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
17237                runs.push((prev_end..label.text.len(), fade_out));
17238            }
17239
17240            runs
17241        })
17242}
17243
17244pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
17245    let mut prev_index = 0;
17246    let mut prev_codepoint: Option<char> = None;
17247    text.char_indices()
17248        .chain([(text.len(), '\0')])
17249        .filter_map(move |(index, codepoint)| {
17250            let prev_codepoint = prev_codepoint.replace(codepoint)?;
17251            let is_boundary = index == text.len()
17252                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
17253                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
17254            if is_boundary {
17255                let chunk = &text[prev_index..index];
17256                prev_index = index;
17257                Some(chunk)
17258            } else {
17259                None
17260            }
17261        })
17262}
17263
17264pub trait RangeToAnchorExt: Sized {
17265    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
17266
17267    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
17268        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
17269        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
17270    }
17271}
17272
17273impl<T: ToOffset> RangeToAnchorExt for Range<T> {
17274    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
17275        let start_offset = self.start.to_offset(snapshot);
17276        let end_offset = self.end.to_offset(snapshot);
17277        if start_offset == end_offset {
17278            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
17279        } else {
17280            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
17281        }
17282    }
17283}
17284
17285pub trait RowExt {
17286    fn as_f32(&self) -> f32;
17287
17288    fn next_row(&self) -> Self;
17289
17290    fn previous_row(&self) -> Self;
17291
17292    fn minus(&self, other: Self) -> u32;
17293}
17294
17295impl RowExt for DisplayRow {
17296    fn as_f32(&self) -> f32 {
17297        self.0 as f32
17298    }
17299
17300    fn next_row(&self) -> Self {
17301        Self(self.0 + 1)
17302    }
17303
17304    fn previous_row(&self) -> Self {
17305        Self(self.0.saturating_sub(1))
17306    }
17307
17308    fn minus(&self, other: Self) -> u32 {
17309        self.0 - other.0
17310    }
17311}
17312
17313impl RowExt for MultiBufferRow {
17314    fn as_f32(&self) -> f32 {
17315        self.0 as f32
17316    }
17317
17318    fn next_row(&self) -> Self {
17319        Self(self.0 + 1)
17320    }
17321
17322    fn previous_row(&self) -> Self {
17323        Self(self.0.saturating_sub(1))
17324    }
17325
17326    fn minus(&self, other: Self) -> u32 {
17327        self.0 - other.0
17328    }
17329}
17330
17331trait RowRangeExt {
17332    type Row;
17333
17334    fn len(&self) -> usize;
17335
17336    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17337}
17338
17339impl RowRangeExt for Range<MultiBufferRow> {
17340    type Row = MultiBufferRow;
17341
17342    fn len(&self) -> usize {
17343        (self.end.0 - self.start.0) as usize
17344    }
17345
17346    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17347        (self.start.0..self.end.0).map(MultiBufferRow)
17348    }
17349}
17350
17351impl RowRangeExt for Range<DisplayRow> {
17352    type Row = DisplayRow;
17353
17354    fn len(&self) -> usize {
17355        (self.end.0 - self.start.0) as usize
17356    }
17357
17358    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17359        (self.start.0..self.end.0).map(DisplayRow)
17360    }
17361}
17362
17363/// If select range has more than one line, we
17364/// just point the cursor to range.start.
17365fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17366    if range.start.row == range.end.row {
17367        range
17368    } else {
17369        range.start..range.start
17370    }
17371}
17372pub struct KillRing(ClipboardItem);
17373impl Global for KillRing {}
17374
17375const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17376
17377fn all_edits_insertions_or_deletions(
17378    edits: &Vec<(Range<Anchor>, String)>,
17379    snapshot: &MultiBufferSnapshot,
17380) -> bool {
17381    let mut all_insertions = true;
17382    let mut all_deletions = true;
17383
17384    for (range, new_text) in edits.iter() {
17385        let range_is_empty = range.to_offset(&snapshot).is_empty();
17386        let text_is_empty = new_text.is_empty();
17387
17388        if range_is_empty != text_is_empty {
17389            if range_is_empty {
17390                all_deletions = false;
17391            } else {
17392                all_insertions = false;
17393            }
17394        } else {
17395            return false;
17396        }
17397
17398        if !all_insertions && !all_deletions {
17399            return false;
17400        }
17401    }
17402    all_insertions || all_deletions
17403}