editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod commit_tooltip;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use buffer_diff::DiffHunkStatus;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{
   71    future::{self, Shared},
   72    FutureExt,
   73};
   74use fuzzy::StringMatchCandidate;
   75
   76use ::git::Restore;
   77use code_context_menus::{
   78    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   79    CompletionsMenu, ContextMenuOrigin,
   80};
   81use git::blame::GitBlame;
   82use gpui::{
   83    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   84    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   85    ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler,
   86    EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
   87    HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
   88    ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription, Task,
   89    TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   90    WeakEntity, WeakFocusHandle, Window,
   91};
   92use highlight_matching_bracket::refresh_matching_bracket_highlights;
   93use hover_popover::{hide_hover, HoverState};
   94use indent_guides::ActiveIndentGuidesState;
   95use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   96pub use inline_completion::Direction;
   97use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   98pub use items::MAX_TAB_TITLE_LEN;
   99use itertools::Itertools;
  100use language::{
  101    language_settings::{
  102        self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
  103    },
  104    point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
  105    Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, EditPredictionsMode,
  106    EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
  107    Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
  108};
  109use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  110use linked_editing_ranges::refresh_linked_ranges;
  111use mouse_context_menu::MouseContextMenu;
  112use persistence::DB;
  113pub use proposed_changes_editor::{
  114    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  115};
  116use smallvec::smallvec;
  117use std::iter::Peekable;
  118use task::{ResolvedTask, TaskTemplate, TaskVariables};
  119
  120use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  121pub use lsp::CompletionContext;
  122use lsp::{
  123    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  124    InsertTextFormat, LanguageServerId, LanguageServerName,
  125};
  126
  127use language::BufferSnapshot;
  128use movement::TextLayoutDetails;
  129pub use multi_buffer::{
  130    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  131    ToOffset, ToPoint,
  132};
  133use multi_buffer::{
  134    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  135    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  136};
  137use project::{
  138    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  139    project_settings::{GitGutterSetting, ProjectSettings},
  140    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  141    PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  142};
  143use rand::prelude::*;
  144use rpc::{proto::*, ErrorExt};
  145use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  146use selections_collection::{
  147    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  148};
  149use serde::{Deserialize, Serialize};
  150use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  151use smallvec::SmallVec;
  152use snippet::Snippet;
  153use std::{
  154    any::TypeId,
  155    borrow::Cow,
  156    cell::RefCell,
  157    cmp::{self, Ordering, Reverse},
  158    mem,
  159    num::NonZeroU32,
  160    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  161    path::{Path, PathBuf},
  162    rc::Rc,
  163    sync::Arc,
  164    time::{Duration, Instant},
  165};
  166pub use sum_tree::Bias;
  167use sum_tree::TreeMap;
  168use text::{BufferId, OffsetUtf16, Rope};
  169use theme::{
  170    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  171    ThemeColors, ThemeSettings,
  172};
  173use ui::{
  174    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  175    Tooltip,
  176};
  177use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  178use workspace::{
  179    item::{ItemHandle, PreviewTabsSettings},
  180    ItemId, RestoreOnStartupBehavior,
  181};
  182use workspace::{
  183    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  184    WorkspaceSettings,
  185};
  186use workspace::{
  187    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  188};
  189use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  190
  191use crate::hover_links::{find_url, find_url_from_range};
  192use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  193
  194pub const FILE_HEADER_HEIGHT: u32 = 2;
  195pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  196pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  197pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  198const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  199const MAX_LINE_LEN: usize = 1024;
  200const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  201const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  202pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  203#[doc(hidden)]
  204pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  205
  206pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  207pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  208pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  209
  210pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  211pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  212
  213const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  214    alt: true,
  215    shift: true,
  216    control: false,
  217    platform: false,
  218    function: false,
  219};
  220
  221#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  222pub enum InlayId {
  223    InlineCompletion(usize),
  224    Hint(usize),
  225}
  226
  227impl InlayId {
  228    fn id(&self) -> usize {
  229        match self {
  230            Self::InlineCompletion(id) => *id,
  231            Self::Hint(id) => *id,
  232        }
  233    }
  234}
  235
  236enum DocumentHighlightRead {}
  237enum DocumentHighlightWrite {}
  238enum InputComposition {}
  239enum SelectedTextHighlight {}
  240
  241#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  242pub enum Navigated {
  243    Yes,
  244    No,
  245}
  246
  247impl Navigated {
  248    pub fn from_bool(yes: bool) -> Navigated {
  249        if yes {
  250            Navigated::Yes
  251        } else {
  252            Navigated::No
  253        }
  254    }
  255}
  256
  257#[derive(Debug, Clone, PartialEq, Eq)]
  258enum DisplayDiffHunk {
  259    Folded {
  260        display_row: DisplayRow,
  261    },
  262    Unfolded {
  263        is_created_file: bool,
  264        diff_base_byte_range: Range<usize>,
  265        display_row_range: Range<DisplayRow>,
  266        multi_buffer_range: Range<Anchor>,
  267        status: DiffHunkStatus,
  268    },
  269}
  270
  271pub fn init_settings(cx: &mut App) {
  272    EditorSettings::register(cx);
  273}
  274
  275pub fn init(cx: &mut App) {
  276    init_settings(cx);
  277
  278    workspace::register_project_item::<Editor>(cx);
  279    workspace::FollowableViewRegistry::register::<Editor>(cx);
  280    workspace::register_serializable_item::<Editor>(cx);
  281
  282    cx.observe_new(
  283        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  284            workspace.register_action(Editor::new_file);
  285            workspace.register_action(Editor::new_file_vertical);
  286            workspace.register_action(Editor::new_file_horizontal);
  287            workspace.register_action(Editor::cancel_language_server_work);
  288        },
  289    )
  290    .detach();
  291
  292    cx.on_action(move |_: &workspace::NewFile, cx| {
  293        let app_state = workspace::AppState::global(cx);
  294        if let Some(app_state) = app_state.upgrade() {
  295            workspace::open_new(
  296                Default::default(),
  297                app_state,
  298                cx,
  299                |workspace, window, cx| {
  300                    Editor::new_file(workspace, &Default::default(), window, cx)
  301                },
  302            )
  303            .detach();
  304        }
  305    });
  306    cx.on_action(move |_: &workspace::NewWindow, cx| {
  307        let app_state = workspace::AppState::global(cx);
  308        if let Some(app_state) = app_state.upgrade() {
  309            workspace::open_new(
  310                Default::default(),
  311                app_state,
  312                cx,
  313                |workspace, window, cx| {
  314                    cx.activate(true);
  315                    Editor::new_file(workspace, &Default::default(), window, cx)
  316                },
  317            )
  318            .detach();
  319        }
  320    });
  321}
  322
  323pub struct SearchWithinRange;
  324
  325trait InvalidationRegion {
  326    fn ranges(&self) -> &[Range<Anchor>];
  327}
  328
  329#[derive(Clone, Debug, PartialEq)]
  330pub enum SelectPhase {
  331    Begin {
  332        position: DisplayPoint,
  333        add: bool,
  334        click_count: usize,
  335    },
  336    BeginColumnar {
  337        position: DisplayPoint,
  338        reset: bool,
  339        goal_column: u32,
  340    },
  341    Extend {
  342        position: DisplayPoint,
  343        click_count: usize,
  344    },
  345    Update {
  346        position: DisplayPoint,
  347        goal_column: u32,
  348        scroll_delta: gpui::Point<f32>,
  349    },
  350    End,
  351}
  352
  353#[derive(Clone, Debug)]
  354pub enum SelectMode {
  355    Character,
  356    Word(Range<Anchor>),
  357    Line(Range<Anchor>),
  358    All,
  359}
  360
  361#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  362pub enum EditorMode {
  363    SingleLine { auto_width: bool },
  364    AutoHeight { max_lines: usize },
  365    Full,
  366}
  367
  368#[derive(Copy, Clone, Debug)]
  369pub enum SoftWrap {
  370    /// Prefer not to wrap at all.
  371    ///
  372    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  373    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  374    GitDiff,
  375    /// Prefer a single line generally, unless an overly long line is encountered.
  376    None,
  377    /// Soft wrap lines that exceed the editor width.
  378    EditorWidth,
  379    /// Soft wrap lines at the preferred line length.
  380    Column(u32),
  381    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  382    Bounded(u32),
  383}
  384
  385#[derive(Clone)]
  386pub struct EditorStyle {
  387    pub background: Hsla,
  388    pub local_player: PlayerColor,
  389    pub text: TextStyle,
  390    pub scrollbar_width: Pixels,
  391    pub syntax: Arc<SyntaxTheme>,
  392    pub status: StatusColors,
  393    pub inlay_hints_style: HighlightStyle,
  394    pub inline_completion_styles: InlineCompletionStyles,
  395    pub unnecessary_code_fade: f32,
  396}
  397
  398impl Default for EditorStyle {
  399    fn default() -> Self {
  400        Self {
  401            background: Hsla::default(),
  402            local_player: PlayerColor::default(),
  403            text: TextStyle::default(),
  404            scrollbar_width: Pixels::default(),
  405            syntax: Default::default(),
  406            // HACK: Status colors don't have a real default.
  407            // We should look into removing the status colors from the editor
  408            // style and retrieve them directly from the theme.
  409            status: StatusColors::dark(),
  410            inlay_hints_style: HighlightStyle::default(),
  411            inline_completion_styles: InlineCompletionStyles {
  412                insertion: HighlightStyle::default(),
  413                whitespace: HighlightStyle::default(),
  414            },
  415            unnecessary_code_fade: Default::default(),
  416        }
  417    }
  418}
  419
  420pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  421    let show_background = language_settings::language_settings(None, None, cx)
  422        .inlay_hints
  423        .show_background;
  424
  425    HighlightStyle {
  426        color: Some(cx.theme().status().hint),
  427        background_color: show_background.then(|| cx.theme().status().hint_background),
  428        ..HighlightStyle::default()
  429    }
  430}
  431
  432pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  433    InlineCompletionStyles {
  434        insertion: HighlightStyle {
  435            color: Some(cx.theme().status().predictive),
  436            ..HighlightStyle::default()
  437        },
  438        whitespace: HighlightStyle {
  439            background_color: Some(cx.theme().status().created_background),
  440            ..HighlightStyle::default()
  441        },
  442    }
  443}
  444
  445type CompletionId = usize;
  446
  447pub(crate) enum EditDisplayMode {
  448    TabAccept,
  449    DiffPopover,
  450    Inline,
  451}
  452
  453enum InlineCompletion {
  454    Edit {
  455        edits: Vec<(Range<Anchor>, String)>,
  456        edit_preview: Option<EditPreview>,
  457        display_mode: EditDisplayMode,
  458        snapshot: BufferSnapshot,
  459    },
  460    Move {
  461        target: Anchor,
  462        snapshot: BufferSnapshot,
  463    },
  464}
  465
  466struct InlineCompletionState {
  467    inlay_ids: Vec<InlayId>,
  468    completion: InlineCompletion,
  469    completion_id: Option<SharedString>,
  470    invalidation_range: Range<Anchor>,
  471}
  472
  473enum EditPredictionSettings {
  474    Disabled,
  475    Enabled {
  476        show_in_menu: bool,
  477        preview_requires_modifier: bool,
  478    },
  479}
  480
  481enum InlineCompletionHighlight {}
  482
  483#[derive(Debug, Clone)]
  484struct InlineDiagnostic {
  485    message: SharedString,
  486    group_id: usize,
  487    is_primary: bool,
  488    start: Point,
  489    severity: DiagnosticSeverity,
  490}
  491
  492pub enum MenuInlineCompletionsPolicy {
  493    Never,
  494    ByProvider,
  495}
  496
  497pub enum EditPredictionPreview {
  498    /// Modifier is not pressed
  499    Inactive { released_too_fast: bool },
  500    /// Modifier pressed
  501    Active {
  502        since: Instant,
  503        previous_scroll_position: Option<ScrollAnchor>,
  504    },
  505}
  506
  507impl EditPredictionPreview {
  508    pub fn released_too_fast(&self) -> bool {
  509        match self {
  510            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  511            EditPredictionPreview::Active { .. } => false,
  512        }
  513    }
  514
  515    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  516        if let EditPredictionPreview::Active {
  517            previous_scroll_position,
  518            ..
  519        } = self
  520        {
  521            *previous_scroll_position = scroll_position;
  522        }
  523    }
  524}
  525
  526#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  527struct EditorActionId(usize);
  528
  529impl EditorActionId {
  530    pub fn post_inc(&mut self) -> Self {
  531        let answer = self.0;
  532
  533        *self = Self(answer + 1);
  534
  535        Self(answer)
  536    }
  537}
  538
  539// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  540// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  541
  542type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  543type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  544
  545#[derive(Default)]
  546struct ScrollbarMarkerState {
  547    scrollbar_size: Size<Pixels>,
  548    dirty: bool,
  549    markers: Arc<[PaintQuad]>,
  550    pending_refresh: Option<Task<Result<()>>>,
  551}
  552
  553impl ScrollbarMarkerState {
  554    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  555        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  556    }
  557}
  558
  559#[derive(Clone, Debug)]
  560struct RunnableTasks {
  561    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  562    offset: multi_buffer::Anchor,
  563    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  564    column: u32,
  565    // Values of all named captures, including those starting with '_'
  566    extra_variables: HashMap<String, String>,
  567    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  568    context_range: Range<BufferOffset>,
  569}
  570
  571impl RunnableTasks {
  572    fn resolve<'a>(
  573        &'a self,
  574        cx: &'a task::TaskContext,
  575    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  576        self.templates.iter().filter_map(|(kind, template)| {
  577            template
  578                .resolve_task(&kind.to_id_base(), cx)
  579                .map(|task| (kind.clone(), task))
  580        })
  581    }
  582}
  583
  584#[derive(Clone)]
  585struct ResolvedTasks {
  586    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  587    position: Anchor,
  588}
  589#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  590struct BufferOffset(usize);
  591
  592// Addons allow storing per-editor state in other crates (e.g. Vim)
  593pub trait Addon: 'static {
  594    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  595
  596    fn render_buffer_header_controls(
  597        &self,
  598        _: &ExcerptInfo,
  599        _: &Window,
  600        _: &App,
  601    ) -> Option<AnyElement> {
  602        None
  603    }
  604
  605    fn to_any(&self) -> &dyn std::any::Any;
  606}
  607
  608/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  609///
  610/// See the [module level documentation](self) for more information.
  611pub struct Editor {
  612    focus_handle: FocusHandle,
  613    last_focused_descendant: Option<WeakFocusHandle>,
  614    /// The text buffer being edited
  615    buffer: Entity<MultiBuffer>,
  616    /// Map of how text in the buffer should be displayed.
  617    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  618    pub display_map: Entity<DisplayMap>,
  619    pub selections: SelectionsCollection,
  620    pub scroll_manager: ScrollManager,
  621    /// When inline assist editors are linked, they all render cursors because
  622    /// typing enters text into each of them, even the ones that aren't focused.
  623    pub(crate) show_cursor_when_unfocused: bool,
  624    columnar_selection_tail: Option<Anchor>,
  625    add_selections_state: Option<AddSelectionsState>,
  626    select_next_state: Option<SelectNextState>,
  627    select_prev_state: Option<SelectNextState>,
  628    selection_history: SelectionHistory,
  629    autoclose_regions: Vec<AutocloseRegion>,
  630    snippet_stack: InvalidationStack<SnippetState>,
  631    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  632    ime_transaction: Option<TransactionId>,
  633    active_diagnostics: Option<ActiveDiagnosticGroup>,
  634    show_inline_diagnostics: bool,
  635    inline_diagnostics_update: Task<()>,
  636    inline_diagnostics_enabled: bool,
  637    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  638    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  639    hard_wrap: Option<usize>,
  640
  641    // TODO: make this a access method
  642    pub project: Option<Entity<Project>>,
  643    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  644    completion_provider: Option<Box<dyn CompletionProvider>>,
  645    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  646    blink_manager: Entity<BlinkManager>,
  647    show_cursor_names: bool,
  648    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  649    pub show_local_selections: bool,
  650    mode: EditorMode,
  651    show_breadcrumbs: bool,
  652    show_gutter: bool,
  653    show_scrollbars: bool,
  654    show_line_numbers: Option<bool>,
  655    use_relative_line_numbers: Option<bool>,
  656    show_git_diff_gutter: Option<bool>,
  657    show_code_actions: Option<bool>,
  658    show_runnables: Option<bool>,
  659    show_wrap_guides: Option<bool>,
  660    show_indent_guides: Option<bool>,
  661    placeholder_text: Option<Arc<str>>,
  662    highlight_order: usize,
  663    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  664    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  665    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  666    scrollbar_marker_state: ScrollbarMarkerState,
  667    active_indent_guides_state: ActiveIndentGuidesState,
  668    nav_history: Option<ItemNavHistory>,
  669    context_menu: RefCell<Option<CodeContextMenu>>,
  670    mouse_context_menu: Option<MouseContextMenu>,
  671    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  672    signature_help_state: SignatureHelpState,
  673    auto_signature_help: Option<bool>,
  674    find_all_references_task_sources: Vec<Anchor>,
  675    next_completion_id: CompletionId,
  676    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  677    code_actions_task: Option<Task<Result<()>>>,
  678    selection_highlight_task: Option<Task<()>>,
  679    document_highlights_task: Option<Task<()>>,
  680    linked_editing_range_task: Option<Task<Option<()>>>,
  681    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  682    pending_rename: Option<RenameState>,
  683    searchable: bool,
  684    cursor_shape: CursorShape,
  685    current_line_highlight: Option<CurrentLineHighlight>,
  686    collapse_matches: bool,
  687    autoindent_mode: Option<AutoindentMode>,
  688    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  689    input_enabled: bool,
  690    use_modal_editing: bool,
  691    read_only: bool,
  692    leader_peer_id: Option<PeerId>,
  693    remote_id: Option<ViewId>,
  694    hover_state: HoverState,
  695    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  696    gutter_hovered: bool,
  697    hovered_link_state: Option<HoveredLinkState>,
  698    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  699    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  700    active_inline_completion: Option<InlineCompletionState>,
  701    /// Used to prevent flickering as the user types while the menu is open
  702    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  703    edit_prediction_settings: EditPredictionSettings,
  704    inline_completions_hidden_for_vim_mode: bool,
  705    show_inline_completions_override: Option<bool>,
  706    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  707    edit_prediction_preview: EditPredictionPreview,
  708    edit_prediction_indent_conflict: bool,
  709    edit_prediction_requires_modifier_in_indent_conflict: bool,
  710    inlay_hint_cache: InlayHintCache,
  711    next_inlay_id: usize,
  712    _subscriptions: Vec<Subscription>,
  713    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  714    gutter_dimensions: GutterDimensions,
  715    style: Option<EditorStyle>,
  716    text_style_refinement: Option<TextStyleRefinement>,
  717    next_editor_action_id: EditorActionId,
  718    editor_actions:
  719        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  720    use_autoclose: bool,
  721    use_auto_surround: bool,
  722    auto_replace_emoji_shortcode: bool,
  723    show_git_blame_gutter: bool,
  724    show_git_blame_inline: bool,
  725    show_git_blame_inline_delay_task: Option<Task<()>>,
  726    git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
  727    git_blame_inline_enabled: bool,
  728    serialize_dirty_buffers: bool,
  729    show_selection_menu: Option<bool>,
  730    blame: Option<Entity<GitBlame>>,
  731    blame_subscription: Option<Subscription>,
  732    custom_context_menu: Option<
  733        Box<
  734            dyn 'static
  735                + Fn(
  736                    &mut Self,
  737                    DisplayPoint,
  738                    &mut Window,
  739                    &mut Context<Self>,
  740                ) -> Option<Entity<ui::ContextMenu>>,
  741        >,
  742    >,
  743    last_bounds: Option<Bounds<Pixels>>,
  744    last_position_map: Option<Rc<PositionMap>>,
  745    expect_bounds_change: Option<Bounds<Pixels>>,
  746    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  747    tasks_update_task: Option<Task<()>>,
  748    in_project_search: bool,
  749    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  750    breadcrumb_header: Option<String>,
  751    focused_block: Option<FocusedBlock>,
  752    next_scroll_position: NextScrollCursorCenterTopBottom,
  753    addons: HashMap<TypeId, Box<dyn Addon>>,
  754    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  755    load_diff_task: Option<Shared<Task<()>>>,
  756    selection_mark_mode: bool,
  757    toggle_fold_multiple_buffers: Task<()>,
  758    _scroll_cursor_center_top_bottom_task: Task<()>,
  759    serialize_selections: Task<()>,
  760}
  761
  762#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  763enum NextScrollCursorCenterTopBottom {
  764    #[default]
  765    Center,
  766    Top,
  767    Bottom,
  768}
  769
  770impl NextScrollCursorCenterTopBottom {
  771    fn next(&self) -> Self {
  772        match self {
  773            Self::Center => Self::Top,
  774            Self::Top => Self::Bottom,
  775            Self::Bottom => Self::Center,
  776        }
  777    }
  778}
  779
  780#[derive(Clone)]
  781pub struct EditorSnapshot {
  782    pub mode: EditorMode,
  783    show_gutter: bool,
  784    show_line_numbers: Option<bool>,
  785    show_git_diff_gutter: Option<bool>,
  786    show_code_actions: Option<bool>,
  787    show_runnables: Option<bool>,
  788    git_blame_gutter_max_author_length: Option<usize>,
  789    pub display_snapshot: DisplaySnapshot,
  790    pub placeholder_text: Option<Arc<str>>,
  791    is_focused: bool,
  792    scroll_anchor: ScrollAnchor,
  793    ongoing_scroll: OngoingScroll,
  794    current_line_highlight: CurrentLineHighlight,
  795    gutter_hovered: bool,
  796}
  797
  798const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  799
  800#[derive(Default, Debug, Clone, Copy)]
  801pub struct GutterDimensions {
  802    pub left_padding: Pixels,
  803    pub right_padding: Pixels,
  804    pub width: Pixels,
  805    pub margin: Pixels,
  806    pub git_blame_entries_width: Option<Pixels>,
  807}
  808
  809impl GutterDimensions {
  810    /// The full width of the space taken up by the gutter.
  811    pub fn full_width(&self) -> Pixels {
  812        self.margin + self.width
  813    }
  814
  815    /// The width of the space reserved for the fold indicators,
  816    /// use alongside 'justify_end' and `gutter_width` to
  817    /// right align content with the line numbers
  818    pub fn fold_area_width(&self) -> Pixels {
  819        self.margin + self.right_padding
  820    }
  821}
  822
  823#[derive(Debug)]
  824pub struct RemoteSelection {
  825    pub replica_id: ReplicaId,
  826    pub selection: Selection<Anchor>,
  827    pub cursor_shape: CursorShape,
  828    pub peer_id: PeerId,
  829    pub line_mode: bool,
  830    pub participant_index: Option<ParticipantIndex>,
  831    pub user_name: Option<SharedString>,
  832}
  833
  834#[derive(Clone, Debug)]
  835struct SelectionHistoryEntry {
  836    selections: Arc<[Selection<Anchor>]>,
  837    select_next_state: Option<SelectNextState>,
  838    select_prev_state: Option<SelectNextState>,
  839    add_selections_state: Option<AddSelectionsState>,
  840}
  841
  842enum SelectionHistoryMode {
  843    Normal,
  844    Undoing,
  845    Redoing,
  846}
  847
  848#[derive(Clone, PartialEq, Eq, Hash)]
  849struct HoveredCursor {
  850    replica_id: u16,
  851    selection_id: usize,
  852}
  853
  854impl Default for SelectionHistoryMode {
  855    fn default() -> Self {
  856        Self::Normal
  857    }
  858}
  859
  860#[derive(Default)]
  861struct SelectionHistory {
  862    #[allow(clippy::type_complexity)]
  863    selections_by_transaction:
  864        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  865    mode: SelectionHistoryMode,
  866    undo_stack: VecDeque<SelectionHistoryEntry>,
  867    redo_stack: VecDeque<SelectionHistoryEntry>,
  868}
  869
  870impl SelectionHistory {
  871    fn insert_transaction(
  872        &mut self,
  873        transaction_id: TransactionId,
  874        selections: Arc<[Selection<Anchor>]>,
  875    ) {
  876        self.selections_by_transaction
  877            .insert(transaction_id, (selections, None));
  878    }
  879
  880    #[allow(clippy::type_complexity)]
  881    fn transaction(
  882        &self,
  883        transaction_id: TransactionId,
  884    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  885        self.selections_by_transaction.get(&transaction_id)
  886    }
  887
  888    #[allow(clippy::type_complexity)]
  889    fn transaction_mut(
  890        &mut self,
  891        transaction_id: TransactionId,
  892    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  893        self.selections_by_transaction.get_mut(&transaction_id)
  894    }
  895
  896    fn push(&mut self, entry: SelectionHistoryEntry) {
  897        if !entry.selections.is_empty() {
  898            match self.mode {
  899                SelectionHistoryMode::Normal => {
  900                    self.push_undo(entry);
  901                    self.redo_stack.clear();
  902                }
  903                SelectionHistoryMode::Undoing => self.push_redo(entry),
  904                SelectionHistoryMode::Redoing => self.push_undo(entry),
  905            }
  906        }
  907    }
  908
  909    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  910        if self
  911            .undo_stack
  912            .back()
  913            .map_or(true, |e| e.selections != entry.selections)
  914        {
  915            self.undo_stack.push_back(entry);
  916            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  917                self.undo_stack.pop_front();
  918            }
  919        }
  920    }
  921
  922    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  923        if self
  924            .redo_stack
  925            .back()
  926            .map_or(true, |e| e.selections != entry.selections)
  927        {
  928            self.redo_stack.push_back(entry);
  929            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  930                self.redo_stack.pop_front();
  931            }
  932        }
  933    }
  934}
  935
  936struct RowHighlight {
  937    index: usize,
  938    range: Range<Anchor>,
  939    color: Hsla,
  940    should_autoscroll: bool,
  941}
  942
  943#[derive(Clone, Debug)]
  944struct AddSelectionsState {
  945    above: bool,
  946    stack: Vec<usize>,
  947}
  948
  949#[derive(Clone)]
  950struct SelectNextState {
  951    query: AhoCorasick,
  952    wordwise: bool,
  953    done: bool,
  954}
  955
  956impl std::fmt::Debug for SelectNextState {
  957    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  958        f.debug_struct(std::any::type_name::<Self>())
  959            .field("wordwise", &self.wordwise)
  960            .field("done", &self.done)
  961            .finish()
  962    }
  963}
  964
  965#[derive(Debug)]
  966struct AutocloseRegion {
  967    selection_id: usize,
  968    range: Range<Anchor>,
  969    pair: BracketPair,
  970}
  971
  972#[derive(Debug)]
  973struct SnippetState {
  974    ranges: Vec<Vec<Range<Anchor>>>,
  975    active_index: usize,
  976    choices: Vec<Option<Vec<String>>>,
  977}
  978
  979#[doc(hidden)]
  980pub struct RenameState {
  981    pub range: Range<Anchor>,
  982    pub old_name: Arc<str>,
  983    pub editor: Entity<Editor>,
  984    block_id: CustomBlockId,
  985}
  986
  987struct InvalidationStack<T>(Vec<T>);
  988
  989struct RegisteredInlineCompletionProvider {
  990    provider: Arc<dyn InlineCompletionProviderHandle>,
  991    _subscription: Subscription,
  992}
  993
  994#[derive(Debug, PartialEq, Eq)]
  995struct ActiveDiagnosticGroup {
  996    primary_range: Range<Anchor>,
  997    primary_message: String,
  998    group_id: usize,
  999    blocks: HashMap<CustomBlockId, Diagnostic>,
 1000    is_valid: bool,
 1001}
 1002
 1003#[derive(Serialize, Deserialize, Clone, Debug)]
 1004pub struct ClipboardSelection {
 1005    /// The number of bytes in this selection.
 1006    pub len: usize,
 1007    /// Whether this was a full-line selection.
 1008    pub is_entire_line: bool,
 1009    /// The indentation of the first line when this content was originally copied.
 1010    pub first_line_indent: u32,
 1011}
 1012
 1013#[derive(Debug)]
 1014pub(crate) struct NavigationData {
 1015    cursor_anchor: Anchor,
 1016    cursor_position: Point,
 1017    scroll_anchor: ScrollAnchor,
 1018    scroll_top_row: u32,
 1019}
 1020
 1021#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1022pub enum GotoDefinitionKind {
 1023    Symbol,
 1024    Declaration,
 1025    Type,
 1026    Implementation,
 1027}
 1028
 1029#[derive(Debug, Clone)]
 1030enum InlayHintRefreshReason {
 1031    ModifiersChanged(bool),
 1032    Toggle(bool),
 1033    SettingsChange(InlayHintSettings),
 1034    NewLinesShown,
 1035    BufferEdited(HashSet<Arc<Language>>),
 1036    RefreshRequested,
 1037    ExcerptsRemoved(Vec<ExcerptId>),
 1038}
 1039
 1040impl InlayHintRefreshReason {
 1041    fn description(&self) -> &'static str {
 1042        match self {
 1043            Self::ModifiersChanged(_) => "modifiers changed",
 1044            Self::Toggle(_) => "toggle",
 1045            Self::SettingsChange(_) => "settings change",
 1046            Self::NewLinesShown => "new lines shown",
 1047            Self::BufferEdited(_) => "buffer edited",
 1048            Self::RefreshRequested => "refresh requested",
 1049            Self::ExcerptsRemoved(_) => "excerpts removed",
 1050        }
 1051    }
 1052}
 1053
 1054pub enum FormatTarget {
 1055    Buffers,
 1056    Ranges(Vec<Range<MultiBufferPoint>>),
 1057}
 1058
 1059pub(crate) struct FocusedBlock {
 1060    id: BlockId,
 1061    focus_handle: WeakFocusHandle,
 1062}
 1063
 1064#[derive(Clone)]
 1065enum JumpData {
 1066    MultiBufferRow {
 1067        row: MultiBufferRow,
 1068        line_offset_from_top: u32,
 1069    },
 1070    MultiBufferPoint {
 1071        excerpt_id: ExcerptId,
 1072        position: Point,
 1073        anchor: text::Anchor,
 1074        line_offset_from_top: u32,
 1075    },
 1076}
 1077
 1078pub enum MultibufferSelectionMode {
 1079    First,
 1080    All,
 1081}
 1082
 1083impl Editor {
 1084    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1085        let buffer = cx.new(|cx| Buffer::local("", cx));
 1086        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1087        Self::new(
 1088            EditorMode::SingleLine { auto_width: false },
 1089            buffer,
 1090            None,
 1091            false,
 1092            window,
 1093            cx,
 1094        )
 1095    }
 1096
 1097    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1098        let buffer = cx.new(|cx| Buffer::local("", cx));
 1099        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1100        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1101    }
 1102
 1103    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1104        let buffer = cx.new(|cx| Buffer::local("", cx));
 1105        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1106        Self::new(
 1107            EditorMode::SingleLine { auto_width: true },
 1108            buffer,
 1109            None,
 1110            false,
 1111            window,
 1112            cx,
 1113        )
 1114    }
 1115
 1116    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1117        let buffer = cx.new(|cx| Buffer::local("", cx));
 1118        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1119        Self::new(
 1120            EditorMode::AutoHeight { max_lines },
 1121            buffer,
 1122            None,
 1123            false,
 1124            window,
 1125            cx,
 1126        )
 1127    }
 1128
 1129    pub fn for_buffer(
 1130        buffer: Entity<Buffer>,
 1131        project: Option<Entity<Project>>,
 1132        window: &mut Window,
 1133        cx: &mut Context<Self>,
 1134    ) -> Self {
 1135        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1136        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1137    }
 1138
 1139    pub fn for_multibuffer(
 1140        buffer: Entity<MultiBuffer>,
 1141        project: Option<Entity<Project>>,
 1142        show_excerpt_controls: bool,
 1143        window: &mut Window,
 1144        cx: &mut Context<Self>,
 1145    ) -> Self {
 1146        Self::new(
 1147            EditorMode::Full,
 1148            buffer,
 1149            project,
 1150            show_excerpt_controls,
 1151            window,
 1152            cx,
 1153        )
 1154    }
 1155
 1156    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1157        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1158        let mut clone = Self::new(
 1159            self.mode,
 1160            self.buffer.clone(),
 1161            self.project.clone(),
 1162            show_excerpt_controls,
 1163            window,
 1164            cx,
 1165        );
 1166        self.display_map.update(cx, |display_map, cx| {
 1167            let snapshot = display_map.snapshot(cx);
 1168            clone.display_map.update(cx, |display_map, cx| {
 1169                display_map.set_state(&snapshot, cx);
 1170            });
 1171        });
 1172        clone.selections.clone_state(&self.selections);
 1173        clone.scroll_manager.clone_state(&self.scroll_manager);
 1174        clone.searchable = self.searchable;
 1175        clone
 1176    }
 1177
 1178    pub fn new(
 1179        mode: EditorMode,
 1180        buffer: Entity<MultiBuffer>,
 1181        project: Option<Entity<Project>>,
 1182        show_excerpt_controls: bool,
 1183        window: &mut Window,
 1184        cx: &mut Context<Self>,
 1185    ) -> Self {
 1186        let style = window.text_style();
 1187        let font_size = style.font_size.to_pixels(window.rem_size());
 1188        let editor = cx.entity().downgrade();
 1189        let fold_placeholder = FoldPlaceholder {
 1190            constrain_width: true,
 1191            render: Arc::new(move |fold_id, fold_range, cx| {
 1192                let editor = editor.clone();
 1193                div()
 1194                    .id(fold_id)
 1195                    .bg(cx.theme().colors().ghost_element_background)
 1196                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1197                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1198                    .rounded_sm()
 1199                    .size_full()
 1200                    .cursor_pointer()
 1201                    .child("")
 1202                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1203                    .on_click(move |_, _window, cx| {
 1204                        editor
 1205                            .update(cx, |editor, cx| {
 1206                                editor.unfold_ranges(
 1207                                    &[fold_range.start..fold_range.end],
 1208                                    true,
 1209                                    false,
 1210                                    cx,
 1211                                );
 1212                                cx.stop_propagation();
 1213                            })
 1214                            .ok();
 1215                    })
 1216                    .into_any()
 1217            }),
 1218            merge_adjacent: true,
 1219            ..Default::default()
 1220        };
 1221        let display_map = cx.new(|cx| {
 1222            DisplayMap::new(
 1223                buffer.clone(),
 1224                style.font(),
 1225                font_size,
 1226                None,
 1227                show_excerpt_controls,
 1228                FILE_HEADER_HEIGHT,
 1229                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1230                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1231                fold_placeholder,
 1232                cx,
 1233            )
 1234        });
 1235
 1236        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1237
 1238        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1239
 1240        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1241            .then(|| language_settings::SoftWrap::None);
 1242
 1243        let mut project_subscriptions = Vec::new();
 1244        if mode == EditorMode::Full {
 1245            if let Some(project) = project.as_ref() {
 1246                project_subscriptions.push(cx.subscribe_in(
 1247                    project,
 1248                    window,
 1249                    |editor, _, event, window, cx| {
 1250                        if let project::Event::RefreshInlayHints = event {
 1251                            editor
 1252                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1253                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1254                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1255                                let focus_handle = editor.focus_handle(cx);
 1256                                if focus_handle.is_focused(window) {
 1257                                    let snapshot = buffer.read(cx).snapshot();
 1258                                    for (range, snippet) in snippet_edits {
 1259                                        let editor_range =
 1260                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1261                                        editor
 1262                                            .insert_snippet(
 1263                                                &[editor_range],
 1264                                                snippet.clone(),
 1265                                                window,
 1266                                                cx,
 1267                                            )
 1268                                            .ok();
 1269                                    }
 1270                                }
 1271                            }
 1272                        }
 1273                    },
 1274                ));
 1275                if let Some(task_inventory) = project
 1276                    .read(cx)
 1277                    .task_store()
 1278                    .read(cx)
 1279                    .task_inventory()
 1280                    .cloned()
 1281                {
 1282                    project_subscriptions.push(cx.observe_in(
 1283                        &task_inventory,
 1284                        window,
 1285                        |editor, _, window, cx| {
 1286                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1287                        },
 1288                    ));
 1289                }
 1290            }
 1291        }
 1292
 1293        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1294
 1295        let inlay_hint_settings =
 1296            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1297        let focus_handle = cx.focus_handle();
 1298        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1299            .detach();
 1300        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1301            .detach();
 1302        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1303            .detach();
 1304        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1305            .detach();
 1306
 1307        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1308            Some(false)
 1309        } else {
 1310            None
 1311        };
 1312
 1313        let mut code_action_providers = Vec::new();
 1314        let mut load_uncommitted_diff = None;
 1315        if let Some(project) = project.clone() {
 1316            load_uncommitted_diff = Some(
 1317                get_uncommitted_diff_for_buffer(
 1318                    &project,
 1319                    buffer.read(cx).all_buffers(),
 1320                    buffer.clone(),
 1321                    cx,
 1322                )
 1323                .shared(),
 1324            );
 1325            code_action_providers.push(Rc::new(project) as Rc<_>);
 1326        }
 1327
 1328        let mut this = Self {
 1329            focus_handle,
 1330            show_cursor_when_unfocused: false,
 1331            last_focused_descendant: None,
 1332            buffer: buffer.clone(),
 1333            display_map: display_map.clone(),
 1334            selections,
 1335            scroll_manager: ScrollManager::new(cx),
 1336            columnar_selection_tail: None,
 1337            add_selections_state: None,
 1338            select_next_state: None,
 1339            select_prev_state: None,
 1340            selection_history: Default::default(),
 1341            autoclose_regions: Default::default(),
 1342            snippet_stack: Default::default(),
 1343            select_larger_syntax_node_stack: Vec::new(),
 1344            ime_transaction: Default::default(),
 1345            active_diagnostics: None,
 1346            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1347            inline_diagnostics_update: Task::ready(()),
 1348            inline_diagnostics: Vec::new(),
 1349            soft_wrap_mode_override,
 1350            hard_wrap: None,
 1351            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1352            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1353            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1354            project,
 1355            blink_manager: blink_manager.clone(),
 1356            show_local_selections: true,
 1357            show_scrollbars: true,
 1358            mode,
 1359            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1360            show_gutter: mode == EditorMode::Full,
 1361            show_line_numbers: None,
 1362            use_relative_line_numbers: None,
 1363            show_git_diff_gutter: None,
 1364            show_code_actions: None,
 1365            show_runnables: None,
 1366            show_wrap_guides: None,
 1367            show_indent_guides,
 1368            placeholder_text: None,
 1369            highlight_order: 0,
 1370            highlighted_rows: HashMap::default(),
 1371            background_highlights: Default::default(),
 1372            gutter_highlights: TreeMap::default(),
 1373            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1374            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1375            nav_history: None,
 1376            context_menu: RefCell::new(None),
 1377            mouse_context_menu: None,
 1378            completion_tasks: Default::default(),
 1379            signature_help_state: SignatureHelpState::default(),
 1380            auto_signature_help: None,
 1381            find_all_references_task_sources: Vec::new(),
 1382            next_completion_id: 0,
 1383            next_inlay_id: 0,
 1384            code_action_providers,
 1385            available_code_actions: Default::default(),
 1386            code_actions_task: Default::default(),
 1387            selection_highlight_task: Default::default(),
 1388            document_highlights_task: Default::default(),
 1389            linked_editing_range_task: Default::default(),
 1390            pending_rename: Default::default(),
 1391            searchable: true,
 1392            cursor_shape: EditorSettings::get_global(cx)
 1393                .cursor_shape
 1394                .unwrap_or_default(),
 1395            current_line_highlight: None,
 1396            autoindent_mode: Some(AutoindentMode::EachLine),
 1397            collapse_matches: false,
 1398            workspace: None,
 1399            input_enabled: true,
 1400            use_modal_editing: mode == EditorMode::Full,
 1401            read_only: false,
 1402            use_autoclose: true,
 1403            use_auto_surround: true,
 1404            auto_replace_emoji_shortcode: false,
 1405            leader_peer_id: None,
 1406            remote_id: None,
 1407            hover_state: Default::default(),
 1408            pending_mouse_down: None,
 1409            hovered_link_state: Default::default(),
 1410            edit_prediction_provider: None,
 1411            active_inline_completion: None,
 1412            stale_inline_completion_in_menu: None,
 1413            edit_prediction_preview: EditPredictionPreview::Inactive {
 1414                released_too_fast: false,
 1415            },
 1416            inline_diagnostics_enabled: mode == EditorMode::Full,
 1417            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1418
 1419            gutter_hovered: false,
 1420            pixel_position_of_newest_cursor: None,
 1421            last_bounds: None,
 1422            last_position_map: None,
 1423            expect_bounds_change: None,
 1424            gutter_dimensions: GutterDimensions::default(),
 1425            style: None,
 1426            show_cursor_names: false,
 1427            hovered_cursors: Default::default(),
 1428            next_editor_action_id: EditorActionId::default(),
 1429            editor_actions: Rc::default(),
 1430            inline_completions_hidden_for_vim_mode: false,
 1431            show_inline_completions_override: None,
 1432            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1433            edit_prediction_settings: EditPredictionSettings::Disabled,
 1434            edit_prediction_indent_conflict: false,
 1435            edit_prediction_requires_modifier_in_indent_conflict: true,
 1436            custom_context_menu: None,
 1437            show_git_blame_gutter: false,
 1438            show_git_blame_inline: false,
 1439            show_selection_menu: None,
 1440            show_git_blame_inline_delay_task: None,
 1441            git_blame_inline_tooltip: None,
 1442            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1443            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1444                .session
 1445                .restore_unsaved_buffers,
 1446            blame: None,
 1447            blame_subscription: None,
 1448            tasks: Default::default(),
 1449            _subscriptions: vec![
 1450                cx.observe(&buffer, Self::on_buffer_changed),
 1451                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1452                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1453                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1454                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1455                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1456                cx.observe_window_activation(window, |editor, window, cx| {
 1457                    let active = window.is_window_active();
 1458                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1459                        if active {
 1460                            blink_manager.enable(cx);
 1461                        } else {
 1462                            blink_manager.disable(cx);
 1463                        }
 1464                    });
 1465                }),
 1466            ],
 1467            tasks_update_task: None,
 1468            linked_edit_ranges: Default::default(),
 1469            in_project_search: false,
 1470            previous_search_ranges: None,
 1471            breadcrumb_header: None,
 1472            focused_block: None,
 1473            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1474            addons: HashMap::default(),
 1475            registered_buffers: HashMap::default(),
 1476            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1477            selection_mark_mode: false,
 1478            toggle_fold_multiple_buffers: Task::ready(()),
 1479            serialize_selections: Task::ready(()),
 1480            text_style_refinement: None,
 1481            load_diff_task: load_uncommitted_diff,
 1482        };
 1483        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1484        this._subscriptions.extend(project_subscriptions);
 1485
 1486        this.end_selection(window, cx);
 1487        this.scroll_manager.show_scrollbar(window, cx);
 1488
 1489        if mode == EditorMode::Full {
 1490            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1491            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1492
 1493            if this.git_blame_inline_enabled {
 1494                this.git_blame_inline_enabled = true;
 1495                this.start_git_blame_inline(false, window, cx);
 1496            }
 1497
 1498            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1499                if let Some(project) = this.project.as_ref() {
 1500                    let handle = project.update(cx, |project, cx| {
 1501                        project.register_buffer_with_language_servers(&buffer, cx)
 1502                    });
 1503                    this.registered_buffers
 1504                        .insert(buffer.read(cx).remote_id(), handle);
 1505                }
 1506            }
 1507        }
 1508
 1509        this.report_editor_event("Editor Opened", None, cx);
 1510        this
 1511    }
 1512
 1513    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1514        self.mouse_context_menu
 1515            .as_ref()
 1516            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1517    }
 1518
 1519    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1520        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1521    }
 1522
 1523    fn key_context_internal(
 1524        &self,
 1525        has_active_edit_prediction: bool,
 1526        window: &Window,
 1527        cx: &App,
 1528    ) -> KeyContext {
 1529        let mut key_context = KeyContext::new_with_defaults();
 1530        key_context.add("Editor");
 1531        let mode = match self.mode {
 1532            EditorMode::SingleLine { .. } => "single_line",
 1533            EditorMode::AutoHeight { .. } => "auto_height",
 1534            EditorMode::Full => "full",
 1535        };
 1536
 1537        if EditorSettings::jupyter_enabled(cx) {
 1538            key_context.add("jupyter");
 1539        }
 1540
 1541        key_context.set("mode", mode);
 1542        if self.pending_rename.is_some() {
 1543            key_context.add("renaming");
 1544        }
 1545
 1546        match self.context_menu.borrow().as_ref() {
 1547            Some(CodeContextMenu::Completions(_)) => {
 1548                key_context.add("menu");
 1549                key_context.add("showing_completions");
 1550            }
 1551            Some(CodeContextMenu::CodeActions(_)) => {
 1552                key_context.add("menu");
 1553                key_context.add("showing_code_actions")
 1554            }
 1555            None => {}
 1556        }
 1557
 1558        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1559        if !self.focus_handle(cx).contains_focused(window, cx)
 1560            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1561        {
 1562            for addon in self.addons.values() {
 1563                addon.extend_key_context(&mut key_context, cx)
 1564            }
 1565        }
 1566
 1567        if let Some(extension) = self
 1568            .buffer
 1569            .read(cx)
 1570            .as_singleton()
 1571            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1572        {
 1573            key_context.set("extension", extension.to_string());
 1574        }
 1575
 1576        if has_active_edit_prediction {
 1577            if self.edit_prediction_in_conflict() {
 1578                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1579            } else {
 1580                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1581                key_context.add("copilot_suggestion");
 1582            }
 1583        }
 1584
 1585        if self.selection_mark_mode {
 1586            key_context.add("selection_mode");
 1587        }
 1588
 1589        key_context
 1590    }
 1591
 1592    pub fn edit_prediction_in_conflict(&self) -> bool {
 1593        if !self.show_edit_predictions_in_menu() {
 1594            return false;
 1595        }
 1596
 1597        let showing_completions = self
 1598            .context_menu
 1599            .borrow()
 1600            .as_ref()
 1601            .map_or(false, |context| {
 1602                matches!(context, CodeContextMenu::Completions(_))
 1603            });
 1604
 1605        showing_completions
 1606            || self.edit_prediction_requires_modifier()
 1607            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1608            // bindings to insert tab characters.
 1609            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1610    }
 1611
 1612    pub fn accept_edit_prediction_keybind(
 1613        &self,
 1614        window: &Window,
 1615        cx: &App,
 1616    ) -> AcceptEditPredictionBinding {
 1617        let key_context = self.key_context_internal(true, window, cx);
 1618        let in_conflict = self.edit_prediction_in_conflict();
 1619
 1620        AcceptEditPredictionBinding(
 1621            window
 1622                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1623                .into_iter()
 1624                .filter(|binding| {
 1625                    !in_conflict
 1626                        || binding
 1627                            .keystrokes()
 1628                            .first()
 1629                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1630                })
 1631                .rev()
 1632                .min_by_key(|binding| {
 1633                    binding
 1634                        .keystrokes()
 1635                        .first()
 1636                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1637                }),
 1638        )
 1639    }
 1640
 1641    pub fn new_file(
 1642        workspace: &mut Workspace,
 1643        _: &workspace::NewFile,
 1644        window: &mut Window,
 1645        cx: &mut Context<Workspace>,
 1646    ) {
 1647        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1648            "Failed to create buffer",
 1649            window,
 1650            cx,
 1651            |e, _, _| match e.error_code() {
 1652                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1653                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1654                e.error_tag("required").unwrap_or("the latest version")
 1655            )),
 1656                _ => None,
 1657            },
 1658        );
 1659    }
 1660
 1661    pub fn new_in_workspace(
 1662        workspace: &mut Workspace,
 1663        window: &mut Window,
 1664        cx: &mut Context<Workspace>,
 1665    ) -> Task<Result<Entity<Editor>>> {
 1666        let project = workspace.project().clone();
 1667        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1668
 1669        cx.spawn_in(window, |workspace, mut cx| async move {
 1670            let buffer = create.await?;
 1671            workspace.update_in(&mut cx, |workspace, window, cx| {
 1672                let editor =
 1673                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1674                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1675                editor
 1676            })
 1677        })
 1678    }
 1679
 1680    fn new_file_vertical(
 1681        workspace: &mut Workspace,
 1682        _: &workspace::NewFileSplitVertical,
 1683        window: &mut Window,
 1684        cx: &mut Context<Workspace>,
 1685    ) {
 1686        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1687    }
 1688
 1689    fn new_file_horizontal(
 1690        workspace: &mut Workspace,
 1691        _: &workspace::NewFileSplitHorizontal,
 1692        window: &mut Window,
 1693        cx: &mut Context<Workspace>,
 1694    ) {
 1695        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1696    }
 1697
 1698    fn new_file_in_direction(
 1699        workspace: &mut Workspace,
 1700        direction: SplitDirection,
 1701        window: &mut Window,
 1702        cx: &mut Context<Workspace>,
 1703    ) {
 1704        let project = workspace.project().clone();
 1705        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1706
 1707        cx.spawn_in(window, |workspace, mut cx| async move {
 1708            let buffer = create.await?;
 1709            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1710                workspace.split_item(
 1711                    direction,
 1712                    Box::new(
 1713                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1714                    ),
 1715                    window,
 1716                    cx,
 1717                )
 1718            })?;
 1719            anyhow::Ok(())
 1720        })
 1721        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1722            match e.error_code() {
 1723                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1724                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1725                e.error_tag("required").unwrap_or("the latest version")
 1726            )),
 1727                _ => None,
 1728            }
 1729        });
 1730    }
 1731
 1732    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1733        self.leader_peer_id
 1734    }
 1735
 1736    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1737        &self.buffer
 1738    }
 1739
 1740    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1741        self.workspace.as_ref()?.0.upgrade()
 1742    }
 1743
 1744    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1745        self.buffer().read(cx).title(cx)
 1746    }
 1747
 1748    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1749        let git_blame_gutter_max_author_length = self
 1750            .render_git_blame_gutter(cx)
 1751            .then(|| {
 1752                if let Some(blame) = self.blame.as_ref() {
 1753                    let max_author_length =
 1754                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1755                    Some(max_author_length)
 1756                } else {
 1757                    None
 1758                }
 1759            })
 1760            .flatten();
 1761
 1762        EditorSnapshot {
 1763            mode: self.mode,
 1764            show_gutter: self.show_gutter,
 1765            show_line_numbers: self.show_line_numbers,
 1766            show_git_diff_gutter: self.show_git_diff_gutter,
 1767            show_code_actions: self.show_code_actions,
 1768            show_runnables: self.show_runnables,
 1769            git_blame_gutter_max_author_length,
 1770            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1771            scroll_anchor: self.scroll_manager.anchor(),
 1772            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1773            placeholder_text: self.placeholder_text.clone(),
 1774            is_focused: self.focus_handle.is_focused(window),
 1775            current_line_highlight: self
 1776                .current_line_highlight
 1777                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1778            gutter_hovered: self.gutter_hovered,
 1779        }
 1780    }
 1781
 1782    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1783        self.buffer.read(cx).language_at(point, cx)
 1784    }
 1785
 1786    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1787        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1788    }
 1789
 1790    pub fn active_excerpt(
 1791        &self,
 1792        cx: &App,
 1793    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1794        self.buffer
 1795            .read(cx)
 1796            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1797    }
 1798
 1799    pub fn mode(&self) -> EditorMode {
 1800        self.mode
 1801    }
 1802
 1803    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1804        self.collaboration_hub.as_deref()
 1805    }
 1806
 1807    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1808        self.collaboration_hub = Some(hub);
 1809    }
 1810
 1811    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1812        self.in_project_search = in_project_search;
 1813    }
 1814
 1815    pub fn set_custom_context_menu(
 1816        &mut self,
 1817        f: impl 'static
 1818            + Fn(
 1819                &mut Self,
 1820                DisplayPoint,
 1821                &mut Window,
 1822                &mut Context<Self>,
 1823            ) -> Option<Entity<ui::ContextMenu>>,
 1824    ) {
 1825        self.custom_context_menu = Some(Box::new(f))
 1826    }
 1827
 1828    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1829        self.completion_provider = provider;
 1830    }
 1831
 1832    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1833        self.semantics_provider.clone()
 1834    }
 1835
 1836    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1837        self.semantics_provider = provider;
 1838    }
 1839
 1840    pub fn set_edit_prediction_provider<T>(
 1841        &mut self,
 1842        provider: Option<Entity<T>>,
 1843        window: &mut Window,
 1844        cx: &mut Context<Self>,
 1845    ) where
 1846        T: EditPredictionProvider,
 1847    {
 1848        self.edit_prediction_provider =
 1849            provider.map(|provider| RegisteredInlineCompletionProvider {
 1850                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1851                    if this.focus_handle.is_focused(window) {
 1852                        this.update_visible_inline_completion(window, cx);
 1853                    }
 1854                }),
 1855                provider: Arc::new(provider),
 1856            });
 1857        self.update_edit_prediction_settings(cx);
 1858        self.refresh_inline_completion(false, false, window, cx);
 1859    }
 1860
 1861    pub fn placeholder_text(&self) -> Option<&str> {
 1862        self.placeholder_text.as_deref()
 1863    }
 1864
 1865    pub fn set_placeholder_text(
 1866        &mut self,
 1867        placeholder_text: impl Into<Arc<str>>,
 1868        cx: &mut Context<Self>,
 1869    ) {
 1870        let placeholder_text = Some(placeholder_text.into());
 1871        if self.placeholder_text != placeholder_text {
 1872            self.placeholder_text = placeholder_text;
 1873            cx.notify();
 1874        }
 1875    }
 1876
 1877    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1878        self.cursor_shape = cursor_shape;
 1879
 1880        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1881        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1882
 1883        cx.notify();
 1884    }
 1885
 1886    pub fn set_current_line_highlight(
 1887        &mut self,
 1888        current_line_highlight: Option<CurrentLineHighlight>,
 1889    ) {
 1890        self.current_line_highlight = current_line_highlight;
 1891    }
 1892
 1893    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1894        self.collapse_matches = collapse_matches;
 1895    }
 1896
 1897    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1898        let buffers = self.buffer.read(cx).all_buffers();
 1899        let Some(project) = self.project.as_ref() else {
 1900            return;
 1901        };
 1902        project.update(cx, |project, cx| {
 1903            for buffer in buffers {
 1904                self.registered_buffers
 1905                    .entry(buffer.read(cx).remote_id())
 1906                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1907            }
 1908        })
 1909    }
 1910
 1911    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1912        if self.collapse_matches {
 1913            return range.start..range.start;
 1914        }
 1915        range.clone()
 1916    }
 1917
 1918    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1919        if self.display_map.read(cx).clip_at_line_ends != clip {
 1920            self.display_map
 1921                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1922        }
 1923    }
 1924
 1925    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1926        self.input_enabled = input_enabled;
 1927    }
 1928
 1929    pub fn set_inline_completions_hidden_for_vim_mode(
 1930        &mut self,
 1931        hidden: bool,
 1932        window: &mut Window,
 1933        cx: &mut Context<Self>,
 1934    ) {
 1935        if hidden != self.inline_completions_hidden_for_vim_mode {
 1936            self.inline_completions_hidden_for_vim_mode = hidden;
 1937            if hidden {
 1938                self.update_visible_inline_completion(window, cx);
 1939            } else {
 1940                self.refresh_inline_completion(true, false, window, cx);
 1941            }
 1942        }
 1943    }
 1944
 1945    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1946        self.menu_inline_completions_policy = value;
 1947    }
 1948
 1949    pub fn set_autoindent(&mut self, autoindent: bool) {
 1950        if autoindent {
 1951            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1952        } else {
 1953            self.autoindent_mode = None;
 1954        }
 1955    }
 1956
 1957    pub fn read_only(&self, cx: &App) -> bool {
 1958        self.read_only || self.buffer.read(cx).read_only()
 1959    }
 1960
 1961    pub fn set_read_only(&mut self, read_only: bool) {
 1962        self.read_only = read_only;
 1963    }
 1964
 1965    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1966        self.use_autoclose = autoclose;
 1967    }
 1968
 1969    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1970        self.use_auto_surround = auto_surround;
 1971    }
 1972
 1973    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1974        self.auto_replace_emoji_shortcode = auto_replace;
 1975    }
 1976
 1977    pub fn toggle_edit_predictions(
 1978        &mut self,
 1979        _: &ToggleEditPrediction,
 1980        window: &mut Window,
 1981        cx: &mut Context<Self>,
 1982    ) {
 1983        if self.show_inline_completions_override.is_some() {
 1984            self.set_show_edit_predictions(None, window, cx);
 1985        } else {
 1986            let show_edit_predictions = !self.edit_predictions_enabled();
 1987            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1988        }
 1989    }
 1990
 1991    pub fn set_show_edit_predictions(
 1992        &mut self,
 1993        show_edit_predictions: Option<bool>,
 1994        window: &mut Window,
 1995        cx: &mut Context<Self>,
 1996    ) {
 1997        self.show_inline_completions_override = show_edit_predictions;
 1998        self.update_edit_prediction_settings(cx);
 1999
 2000        if let Some(false) = show_edit_predictions {
 2001            self.discard_inline_completion(false, cx);
 2002        } else {
 2003            self.refresh_inline_completion(false, true, window, cx);
 2004        }
 2005    }
 2006
 2007    fn inline_completions_disabled_in_scope(
 2008        &self,
 2009        buffer: &Entity<Buffer>,
 2010        buffer_position: language::Anchor,
 2011        cx: &App,
 2012    ) -> bool {
 2013        let snapshot = buffer.read(cx).snapshot();
 2014        let settings = snapshot.settings_at(buffer_position, cx);
 2015
 2016        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2017            return false;
 2018        };
 2019
 2020        scope.override_name().map_or(false, |scope_name| {
 2021            settings
 2022                .edit_predictions_disabled_in
 2023                .iter()
 2024                .any(|s| s == scope_name)
 2025        })
 2026    }
 2027
 2028    pub fn set_use_modal_editing(&mut self, to: bool) {
 2029        self.use_modal_editing = to;
 2030    }
 2031
 2032    pub fn use_modal_editing(&self) -> bool {
 2033        self.use_modal_editing
 2034    }
 2035
 2036    fn selections_did_change(
 2037        &mut self,
 2038        local: bool,
 2039        old_cursor_position: &Anchor,
 2040        show_completions: bool,
 2041        window: &mut Window,
 2042        cx: &mut Context<Self>,
 2043    ) {
 2044        window.invalidate_character_coordinates();
 2045
 2046        // Copy selections to primary selection buffer
 2047        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2048        if local {
 2049            let selections = self.selections.all::<usize>(cx);
 2050            let buffer_handle = self.buffer.read(cx).read(cx);
 2051
 2052            let mut text = String::new();
 2053            for (index, selection) in selections.iter().enumerate() {
 2054                let text_for_selection = buffer_handle
 2055                    .text_for_range(selection.start..selection.end)
 2056                    .collect::<String>();
 2057
 2058                text.push_str(&text_for_selection);
 2059                if index != selections.len() - 1 {
 2060                    text.push('\n');
 2061                }
 2062            }
 2063
 2064            if !text.is_empty() {
 2065                cx.write_to_primary(ClipboardItem::new_string(text));
 2066            }
 2067        }
 2068
 2069        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2070            self.buffer.update(cx, |buffer, cx| {
 2071                buffer.set_active_selections(
 2072                    &self.selections.disjoint_anchors(),
 2073                    self.selections.line_mode,
 2074                    self.cursor_shape,
 2075                    cx,
 2076                )
 2077            });
 2078        }
 2079        let display_map = self
 2080            .display_map
 2081            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2082        let buffer = &display_map.buffer_snapshot;
 2083        self.add_selections_state = None;
 2084        self.select_next_state = None;
 2085        self.select_prev_state = None;
 2086        self.select_larger_syntax_node_stack.clear();
 2087        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2088        self.snippet_stack
 2089            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2090        self.take_rename(false, window, cx);
 2091
 2092        let new_cursor_position = self.selections.newest_anchor().head();
 2093
 2094        self.push_to_nav_history(
 2095            *old_cursor_position,
 2096            Some(new_cursor_position.to_point(buffer)),
 2097            cx,
 2098        );
 2099
 2100        if local {
 2101            let new_cursor_position = self.selections.newest_anchor().head();
 2102            let mut context_menu = self.context_menu.borrow_mut();
 2103            let completion_menu = match context_menu.as_ref() {
 2104                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2105                _ => {
 2106                    *context_menu = None;
 2107                    None
 2108                }
 2109            };
 2110            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2111                if !self.registered_buffers.contains_key(&buffer_id) {
 2112                    if let Some(project) = self.project.as_ref() {
 2113                        project.update(cx, |project, cx| {
 2114                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2115                                return;
 2116                            };
 2117                            self.registered_buffers.insert(
 2118                                buffer_id,
 2119                                project.register_buffer_with_language_servers(&buffer, cx),
 2120                            );
 2121                        })
 2122                    }
 2123                }
 2124            }
 2125
 2126            if let Some(completion_menu) = completion_menu {
 2127                let cursor_position = new_cursor_position.to_offset(buffer);
 2128                let (word_range, kind) =
 2129                    buffer.surrounding_word(completion_menu.initial_position, true);
 2130                if kind == Some(CharKind::Word)
 2131                    && word_range.to_inclusive().contains(&cursor_position)
 2132                {
 2133                    let mut completion_menu = completion_menu.clone();
 2134                    drop(context_menu);
 2135
 2136                    let query = Self::completion_query(buffer, cursor_position);
 2137                    cx.spawn(move |this, mut cx| async move {
 2138                        completion_menu
 2139                            .filter(query.as_deref(), cx.background_executor().clone())
 2140                            .await;
 2141
 2142                        this.update(&mut cx, |this, cx| {
 2143                            let mut context_menu = this.context_menu.borrow_mut();
 2144                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2145                            else {
 2146                                return;
 2147                            };
 2148
 2149                            if menu.id > completion_menu.id {
 2150                                return;
 2151                            }
 2152
 2153                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2154                            drop(context_menu);
 2155                            cx.notify();
 2156                        })
 2157                    })
 2158                    .detach();
 2159
 2160                    if show_completions {
 2161                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2162                    }
 2163                } else {
 2164                    drop(context_menu);
 2165                    self.hide_context_menu(window, cx);
 2166                }
 2167            } else {
 2168                drop(context_menu);
 2169            }
 2170
 2171            hide_hover(self, cx);
 2172
 2173            if old_cursor_position.to_display_point(&display_map).row()
 2174                != new_cursor_position.to_display_point(&display_map).row()
 2175            {
 2176                self.available_code_actions.take();
 2177            }
 2178            self.refresh_code_actions(window, cx);
 2179            self.refresh_document_highlights(cx);
 2180            self.refresh_selected_text_highlights(window, cx);
 2181            refresh_matching_bracket_highlights(self, window, cx);
 2182            self.update_visible_inline_completion(window, cx);
 2183            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2184            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2185            if self.git_blame_inline_enabled {
 2186                self.start_inline_blame_timer(window, cx);
 2187            }
 2188        }
 2189
 2190        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2191        cx.emit(EditorEvent::SelectionsChanged { local });
 2192
 2193        let selections = &self.selections.disjoint;
 2194        if selections.len() == 1 {
 2195            cx.emit(SearchEvent::ActiveMatchChanged)
 2196        }
 2197        if local
 2198            && self.is_singleton(cx)
 2199            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2200        {
 2201            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2202                let background_executor = cx.background_executor().clone();
 2203                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2204                let snapshot = self.buffer().read(cx).snapshot(cx);
 2205                let selections = selections.clone();
 2206                self.serialize_selections = cx.background_spawn(async move {
 2207                    background_executor.timer(Duration::from_millis(100)).await;
 2208                    let selections = selections
 2209                        .iter()
 2210                        .map(|selection| {
 2211                            (
 2212                                selection.start.to_offset(&snapshot),
 2213                                selection.end.to_offset(&snapshot),
 2214                            )
 2215                        })
 2216                        .collect();
 2217                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2218                        .await
 2219                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2220                        .log_err();
 2221                });
 2222            }
 2223        }
 2224
 2225        cx.notify();
 2226    }
 2227
 2228    pub fn sync_selections(
 2229        &mut self,
 2230        other: Entity<Editor>,
 2231        cx: &mut Context<Self>,
 2232    ) -> gpui::Subscription {
 2233        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2234        self.selections.change_with(cx, |selections| {
 2235            selections.select_anchors(other_selections);
 2236        });
 2237
 2238        let other_subscription =
 2239            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2240                EditorEvent::SelectionsChanged { local: true } => {
 2241                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2242                    if other_selections.is_empty() {
 2243                        return;
 2244                    }
 2245                    this.selections.change_with(cx, |selections| {
 2246                        selections.select_anchors(other_selections);
 2247                    });
 2248                }
 2249                _ => {}
 2250            });
 2251
 2252        let this_subscription =
 2253            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2254                EditorEvent::SelectionsChanged { local: true } => {
 2255                    let these_selections = this.selections.disjoint.to_vec();
 2256                    if these_selections.is_empty() {
 2257                        return;
 2258                    }
 2259                    other.update(cx, |other_editor, cx| {
 2260                        other_editor.selections.change_with(cx, |selections| {
 2261                            selections.select_anchors(these_selections);
 2262                        })
 2263                    });
 2264                }
 2265                _ => {}
 2266            });
 2267
 2268        Subscription::join(other_subscription, this_subscription)
 2269    }
 2270
 2271    pub fn change_selections<R>(
 2272        &mut self,
 2273        autoscroll: Option<Autoscroll>,
 2274        window: &mut Window,
 2275        cx: &mut Context<Self>,
 2276        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2277    ) -> R {
 2278        self.change_selections_inner(autoscroll, true, window, cx, change)
 2279    }
 2280
 2281    fn change_selections_inner<R>(
 2282        &mut self,
 2283        autoscroll: Option<Autoscroll>,
 2284        request_completions: bool,
 2285        window: &mut Window,
 2286        cx: &mut Context<Self>,
 2287        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2288    ) -> R {
 2289        let old_cursor_position = self.selections.newest_anchor().head();
 2290        self.push_to_selection_history();
 2291
 2292        let (changed, result) = self.selections.change_with(cx, change);
 2293
 2294        if changed {
 2295            if let Some(autoscroll) = autoscroll {
 2296                self.request_autoscroll(autoscroll, cx);
 2297            }
 2298            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2299
 2300            if self.should_open_signature_help_automatically(
 2301                &old_cursor_position,
 2302                self.signature_help_state.backspace_pressed(),
 2303                cx,
 2304            ) {
 2305                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2306            }
 2307            self.signature_help_state.set_backspace_pressed(false);
 2308        }
 2309
 2310        result
 2311    }
 2312
 2313    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2314    where
 2315        I: IntoIterator<Item = (Range<S>, T)>,
 2316        S: ToOffset,
 2317        T: Into<Arc<str>>,
 2318    {
 2319        if self.read_only(cx) {
 2320            return;
 2321        }
 2322
 2323        self.buffer
 2324            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2325    }
 2326
 2327    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2328    where
 2329        I: IntoIterator<Item = (Range<S>, T)>,
 2330        S: ToOffset,
 2331        T: Into<Arc<str>>,
 2332    {
 2333        if self.read_only(cx) {
 2334            return;
 2335        }
 2336
 2337        self.buffer.update(cx, |buffer, cx| {
 2338            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2339        });
 2340    }
 2341
 2342    pub fn edit_with_block_indent<I, S, T>(
 2343        &mut self,
 2344        edits: I,
 2345        original_indent_columns: Vec<Option<u32>>,
 2346        cx: &mut Context<Self>,
 2347    ) where
 2348        I: IntoIterator<Item = (Range<S>, T)>,
 2349        S: ToOffset,
 2350        T: Into<Arc<str>>,
 2351    {
 2352        if self.read_only(cx) {
 2353            return;
 2354        }
 2355
 2356        self.buffer.update(cx, |buffer, cx| {
 2357            buffer.edit(
 2358                edits,
 2359                Some(AutoindentMode::Block {
 2360                    original_indent_columns,
 2361                }),
 2362                cx,
 2363            )
 2364        });
 2365    }
 2366
 2367    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2368        self.hide_context_menu(window, cx);
 2369
 2370        match phase {
 2371            SelectPhase::Begin {
 2372                position,
 2373                add,
 2374                click_count,
 2375            } => self.begin_selection(position, add, click_count, window, cx),
 2376            SelectPhase::BeginColumnar {
 2377                position,
 2378                goal_column,
 2379                reset,
 2380            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2381            SelectPhase::Extend {
 2382                position,
 2383                click_count,
 2384            } => self.extend_selection(position, click_count, window, cx),
 2385            SelectPhase::Update {
 2386                position,
 2387                goal_column,
 2388                scroll_delta,
 2389            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2390            SelectPhase::End => self.end_selection(window, cx),
 2391        }
 2392    }
 2393
 2394    fn extend_selection(
 2395        &mut self,
 2396        position: DisplayPoint,
 2397        click_count: usize,
 2398        window: &mut Window,
 2399        cx: &mut Context<Self>,
 2400    ) {
 2401        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2402        let tail = self.selections.newest::<usize>(cx).tail();
 2403        self.begin_selection(position, false, click_count, window, cx);
 2404
 2405        let position = position.to_offset(&display_map, Bias::Left);
 2406        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2407
 2408        let mut pending_selection = self
 2409            .selections
 2410            .pending_anchor()
 2411            .expect("extend_selection not called with pending selection");
 2412        if position >= tail {
 2413            pending_selection.start = tail_anchor;
 2414        } else {
 2415            pending_selection.end = tail_anchor;
 2416            pending_selection.reversed = true;
 2417        }
 2418
 2419        let mut pending_mode = self.selections.pending_mode().unwrap();
 2420        match &mut pending_mode {
 2421            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2422            _ => {}
 2423        }
 2424
 2425        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2426            s.set_pending(pending_selection, pending_mode)
 2427        });
 2428    }
 2429
 2430    fn begin_selection(
 2431        &mut self,
 2432        position: DisplayPoint,
 2433        add: bool,
 2434        click_count: usize,
 2435        window: &mut Window,
 2436        cx: &mut Context<Self>,
 2437    ) {
 2438        if !self.focus_handle.is_focused(window) {
 2439            self.last_focused_descendant = None;
 2440            window.focus(&self.focus_handle);
 2441        }
 2442
 2443        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2444        let buffer = &display_map.buffer_snapshot;
 2445        let newest_selection = self.selections.newest_anchor().clone();
 2446        let position = display_map.clip_point(position, Bias::Left);
 2447
 2448        let start;
 2449        let end;
 2450        let mode;
 2451        let mut auto_scroll;
 2452        match click_count {
 2453            1 => {
 2454                start = buffer.anchor_before(position.to_point(&display_map));
 2455                end = start;
 2456                mode = SelectMode::Character;
 2457                auto_scroll = true;
 2458            }
 2459            2 => {
 2460                let range = movement::surrounding_word(&display_map, position);
 2461                start = buffer.anchor_before(range.start.to_point(&display_map));
 2462                end = buffer.anchor_before(range.end.to_point(&display_map));
 2463                mode = SelectMode::Word(start..end);
 2464                auto_scroll = true;
 2465            }
 2466            3 => {
 2467                let position = display_map
 2468                    .clip_point(position, Bias::Left)
 2469                    .to_point(&display_map);
 2470                let line_start = display_map.prev_line_boundary(position).0;
 2471                let next_line_start = buffer.clip_point(
 2472                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2473                    Bias::Left,
 2474                );
 2475                start = buffer.anchor_before(line_start);
 2476                end = buffer.anchor_before(next_line_start);
 2477                mode = SelectMode::Line(start..end);
 2478                auto_scroll = true;
 2479            }
 2480            _ => {
 2481                start = buffer.anchor_before(0);
 2482                end = buffer.anchor_before(buffer.len());
 2483                mode = SelectMode::All;
 2484                auto_scroll = false;
 2485            }
 2486        }
 2487        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2488
 2489        let point_to_delete: Option<usize> = {
 2490            let selected_points: Vec<Selection<Point>> =
 2491                self.selections.disjoint_in_range(start..end, cx);
 2492
 2493            if !add || click_count > 1 {
 2494                None
 2495            } else if !selected_points.is_empty() {
 2496                Some(selected_points[0].id)
 2497            } else {
 2498                let clicked_point_already_selected =
 2499                    self.selections.disjoint.iter().find(|selection| {
 2500                        selection.start.to_point(buffer) == start.to_point(buffer)
 2501                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2502                    });
 2503
 2504                clicked_point_already_selected.map(|selection| selection.id)
 2505            }
 2506        };
 2507
 2508        let selections_count = self.selections.count();
 2509
 2510        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2511            if let Some(point_to_delete) = point_to_delete {
 2512                s.delete(point_to_delete);
 2513
 2514                if selections_count == 1 {
 2515                    s.set_pending_anchor_range(start..end, mode);
 2516                }
 2517            } else {
 2518                if !add {
 2519                    s.clear_disjoint();
 2520                } else if click_count > 1 {
 2521                    s.delete(newest_selection.id)
 2522                }
 2523
 2524                s.set_pending_anchor_range(start..end, mode);
 2525            }
 2526        });
 2527    }
 2528
 2529    fn begin_columnar_selection(
 2530        &mut self,
 2531        position: DisplayPoint,
 2532        goal_column: u32,
 2533        reset: bool,
 2534        window: &mut Window,
 2535        cx: &mut Context<Self>,
 2536    ) {
 2537        if !self.focus_handle.is_focused(window) {
 2538            self.last_focused_descendant = None;
 2539            window.focus(&self.focus_handle);
 2540        }
 2541
 2542        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2543
 2544        if reset {
 2545            let pointer_position = display_map
 2546                .buffer_snapshot
 2547                .anchor_before(position.to_point(&display_map));
 2548
 2549            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2550                s.clear_disjoint();
 2551                s.set_pending_anchor_range(
 2552                    pointer_position..pointer_position,
 2553                    SelectMode::Character,
 2554                );
 2555            });
 2556        }
 2557
 2558        let tail = self.selections.newest::<Point>(cx).tail();
 2559        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2560
 2561        if !reset {
 2562            self.select_columns(
 2563                tail.to_display_point(&display_map),
 2564                position,
 2565                goal_column,
 2566                &display_map,
 2567                window,
 2568                cx,
 2569            );
 2570        }
 2571    }
 2572
 2573    fn update_selection(
 2574        &mut self,
 2575        position: DisplayPoint,
 2576        goal_column: u32,
 2577        scroll_delta: gpui::Point<f32>,
 2578        window: &mut Window,
 2579        cx: &mut Context<Self>,
 2580    ) {
 2581        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2582
 2583        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2584            let tail = tail.to_display_point(&display_map);
 2585            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2586        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2587            let buffer = self.buffer.read(cx).snapshot(cx);
 2588            let head;
 2589            let tail;
 2590            let mode = self.selections.pending_mode().unwrap();
 2591            match &mode {
 2592                SelectMode::Character => {
 2593                    head = position.to_point(&display_map);
 2594                    tail = pending.tail().to_point(&buffer);
 2595                }
 2596                SelectMode::Word(original_range) => {
 2597                    let original_display_range = original_range.start.to_display_point(&display_map)
 2598                        ..original_range.end.to_display_point(&display_map);
 2599                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2600                        ..original_display_range.end.to_point(&display_map);
 2601                    if movement::is_inside_word(&display_map, position)
 2602                        || original_display_range.contains(&position)
 2603                    {
 2604                        let word_range = movement::surrounding_word(&display_map, position);
 2605                        if word_range.start < original_display_range.start {
 2606                            head = word_range.start.to_point(&display_map);
 2607                        } else {
 2608                            head = word_range.end.to_point(&display_map);
 2609                        }
 2610                    } else {
 2611                        head = position.to_point(&display_map);
 2612                    }
 2613
 2614                    if head <= original_buffer_range.start {
 2615                        tail = original_buffer_range.end;
 2616                    } else {
 2617                        tail = original_buffer_range.start;
 2618                    }
 2619                }
 2620                SelectMode::Line(original_range) => {
 2621                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2622
 2623                    let position = display_map
 2624                        .clip_point(position, Bias::Left)
 2625                        .to_point(&display_map);
 2626                    let line_start = display_map.prev_line_boundary(position).0;
 2627                    let next_line_start = buffer.clip_point(
 2628                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2629                        Bias::Left,
 2630                    );
 2631
 2632                    if line_start < original_range.start {
 2633                        head = line_start
 2634                    } else {
 2635                        head = next_line_start
 2636                    }
 2637
 2638                    if head <= original_range.start {
 2639                        tail = original_range.end;
 2640                    } else {
 2641                        tail = original_range.start;
 2642                    }
 2643                }
 2644                SelectMode::All => {
 2645                    return;
 2646                }
 2647            };
 2648
 2649            if head < tail {
 2650                pending.start = buffer.anchor_before(head);
 2651                pending.end = buffer.anchor_before(tail);
 2652                pending.reversed = true;
 2653            } else {
 2654                pending.start = buffer.anchor_before(tail);
 2655                pending.end = buffer.anchor_before(head);
 2656                pending.reversed = false;
 2657            }
 2658
 2659            self.change_selections(None, window, cx, |s| {
 2660                s.set_pending(pending, mode);
 2661            });
 2662        } else {
 2663            log::error!("update_selection dispatched with no pending selection");
 2664            return;
 2665        }
 2666
 2667        self.apply_scroll_delta(scroll_delta, window, cx);
 2668        cx.notify();
 2669    }
 2670
 2671    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2672        self.columnar_selection_tail.take();
 2673        if self.selections.pending_anchor().is_some() {
 2674            let selections = self.selections.all::<usize>(cx);
 2675            self.change_selections(None, window, cx, |s| {
 2676                s.select(selections);
 2677                s.clear_pending();
 2678            });
 2679        }
 2680    }
 2681
 2682    fn select_columns(
 2683        &mut self,
 2684        tail: DisplayPoint,
 2685        head: DisplayPoint,
 2686        goal_column: u32,
 2687        display_map: &DisplaySnapshot,
 2688        window: &mut Window,
 2689        cx: &mut Context<Self>,
 2690    ) {
 2691        let start_row = cmp::min(tail.row(), head.row());
 2692        let end_row = cmp::max(tail.row(), head.row());
 2693        let start_column = cmp::min(tail.column(), goal_column);
 2694        let end_column = cmp::max(tail.column(), goal_column);
 2695        let reversed = start_column < tail.column();
 2696
 2697        let selection_ranges = (start_row.0..=end_row.0)
 2698            .map(DisplayRow)
 2699            .filter_map(|row| {
 2700                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2701                    let start = display_map
 2702                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2703                        .to_point(display_map);
 2704                    let end = display_map
 2705                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2706                        .to_point(display_map);
 2707                    if reversed {
 2708                        Some(end..start)
 2709                    } else {
 2710                        Some(start..end)
 2711                    }
 2712                } else {
 2713                    None
 2714                }
 2715            })
 2716            .collect::<Vec<_>>();
 2717
 2718        self.change_selections(None, window, cx, |s| {
 2719            s.select_ranges(selection_ranges);
 2720        });
 2721        cx.notify();
 2722    }
 2723
 2724    pub fn has_pending_nonempty_selection(&self) -> bool {
 2725        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2726            Some(Selection { start, end, .. }) => start != end,
 2727            None => false,
 2728        };
 2729
 2730        pending_nonempty_selection
 2731            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2732    }
 2733
 2734    pub fn has_pending_selection(&self) -> bool {
 2735        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2736    }
 2737
 2738    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2739        self.selection_mark_mode = false;
 2740
 2741        if self.clear_expanded_diff_hunks(cx) {
 2742            cx.notify();
 2743            return;
 2744        }
 2745        if self.dismiss_menus_and_popups(true, window, cx) {
 2746            return;
 2747        }
 2748
 2749        if self.mode == EditorMode::Full
 2750            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2751        {
 2752            return;
 2753        }
 2754
 2755        cx.propagate();
 2756    }
 2757
 2758    pub fn dismiss_menus_and_popups(
 2759        &mut self,
 2760        is_user_requested: bool,
 2761        window: &mut Window,
 2762        cx: &mut Context<Self>,
 2763    ) -> bool {
 2764        if self.take_rename(false, window, cx).is_some() {
 2765            return true;
 2766        }
 2767
 2768        if hide_hover(self, cx) {
 2769            return true;
 2770        }
 2771
 2772        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2773            return true;
 2774        }
 2775
 2776        if self.hide_context_menu(window, cx).is_some() {
 2777            return true;
 2778        }
 2779
 2780        if self.mouse_context_menu.take().is_some() {
 2781            return true;
 2782        }
 2783
 2784        if is_user_requested && self.discard_inline_completion(true, cx) {
 2785            return true;
 2786        }
 2787
 2788        if self.snippet_stack.pop().is_some() {
 2789            return true;
 2790        }
 2791
 2792        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2793            self.dismiss_diagnostics(cx);
 2794            return true;
 2795        }
 2796
 2797        false
 2798    }
 2799
 2800    fn linked_editing_ranges_for(
 2801        &self,
 2802        selection: Range<text::Anchor>,
 2803        cx: &App,
 2804    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2805        if self.linked_edit_ranges.is_empty() {
 2806            return None;
 2807        }
 2808        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2809            selection.end.buffer_id.and_then(|end_buffer_id| {
 2810                if selection.start.buffer_id != Some(end_buffer_id) {
 2811                    return None;
 2812                }
 2813                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2814                let snapshot = buffer.read(cx).snapshot();
 2815                self.linked_edit_ranges
 2816                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2817                    .map(|ranges| (ranges, snapshot, buffer))
 2818            })?;
 2819        use text::ToOffset as TO;
 2820        // find offset from the start of current range to current cursor position
 2821        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2822
 2823        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2824        let start_difference = start_offset - start_byte_offset;
 2825        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2826        let end_difference = end_offset - start_byte_offset;
 2827        // Current range has associated linked ranges.
 2828        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2829        for range in linked_ranges.iter() {
 2830            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2831            let end_offset = start_offset + end_difference;
 2832            let start_offset = start_offset + start_difference;
 2833            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2834                continue;
 2835            }
 2836            if self.selections.disjoint_anchor_ranges().any(|s| {
 2837                if s.start.buffer_id != selection.start.buffer_id
 2838                    || s.end.buffer_id != selection.end.buffer_id
 2839                {
 2840                    return false;
 2841                }
 2842                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2843                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2844            }) {
 2845                continue;
 2846            }
 2847            let start = buffer_snapshot.anchor_after(start_offset);
 2848            let end = buffer_snapshot.anchor_after(end_offset);
 2849            linked_edits
 2850                .entry(buffer.clone())
 2851                .or_default()
 2852                .push(start..end);
 2853        }
 2854        Some(linked_edits)
 2855    }
 2856
 2857    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2858        let text: Arc<str> = text.into();
 2859
 2860        if self.read_only(cx) {
 2861            return;
 2862        }
 2863
 2864        let selections = self.selections.all_adjusted(cx);
 2865        let mut bracket_inserted = false;
 2866        let mut edits = Vec::new();
 2867        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2868        let mut new_selections = Vec::with_capacity(selections.len());
 2869        let mut new_autoclose_regions = Vec::new();
 2870        let snapshot = self.buffer.read(cx).read(cx);
 2871
 2872        for (selection, autoclose_region) in
 2873            self.selections_with_autoclose_regions(selections, &snapshot)
 2874        {
 2875            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2876                // Determine if the inserted text matches the opening or closing
 2877                // bracket of any of this language's bracket pairs.
 2878                let mut bracket_pair = None;
 2879                let mut is_bracket_pair_start = false;
 2880                let mut is_bracket_pair_end = false;
 2881                if !text.is_empty() {
 2882                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2883                    //  and they are removing the character that triggered IME popup.
 2884                    for (pair, enabled) in scope.brackets() {
 2885                        if !pair.close && !pair.surround {
 2886                            continue;
 2887                        }
 2888
 2889                        if enabled && pair.start.ends_with(text.as_ref()) {
 2890                            let prefix_len = pair.start.len() - text.len();
 2891                            let preceding_text_matches_prefix = prefix_len == 0
 2892                                || (selection.start.column >= (prefix_len as u32)
 2893                                    && snapshot.contains_str_at(
 2894                                        Point::new(
 2895                                            selection.start.row,
 2896                                            selection.start.column - (prefix_len as u32),
 2897                                        ),
 2898                                        &pair.start[..prefix_len],
 2899                                    ));
 2900                            if preceding_text_matches_prefix {
 2901                                bracket_pair = Some(pair.clone());
 2902                                is_bracket_pair_start = true;
 2903                                break;
 2904                            }
 2905                        }
 2906                        if pair.end.as_str() == text.as_ref() {
 2907                            bracket_pair = Some(pair.clone());
 2908                            is_bracket_pair_end = true;
 2909                            break;
 2910                        }
 2911                    }
 2912                }
 2913
 2914                if let Some(bracket_pair) = bracket_pair {
 2915                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 2916                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2917                    let auto_surround =
 2918                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2919                    if selection.is_empty() {
 2920                        if is_bracket_pair_start {
 2921                            // If the inserted text is a suffix of an opening bracket and the
 2922                            // selection is preceded by the rest of the opening bracket, then
 2923                            // insert the closing bracket.
 2924                            let following_text_allows_autoclose = snapshot
 2925                                .chars_at(selection.start)
 2926                                .next()
 2927                                .map_or(true, |c| scope.should_autoclose_before(c));
 2928
 2929                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2930                                && bracket_pair.start.len() == 1
 2931                            {
 2932                                let target = bracket_pair.start.chars().next().unwrap();
 2933                                let current_line_count = snapshot
 2934                                    .reversed_chars_at(selection.start)
 2935                                    .take_while(|&c| c != '\n')
 2936                                    .filter(|&c| c == target)
 2937                                    .count();
 2938                                current_line_count % 2 == 1
 2939                            } else {
 2940                                false
 2941                            };
 2942
 2943                            if autoclose
 2944                                && bracket_pair.close
 2945                                && following_text_allows_autoclose
 2946                                && !is_closing_quote
 2947                            {
 2948                                let anchor = snapshot.anchor_before(selection.end);
 2949                                new_selections.push((selection.map(|_| anchor), text.len()));
 2950                                new_autoclose_regions.push((
 2951                                    anchor,
 2952                                    text.len(),
 2953                                    selection.id,
 2954                                    bracket_pair.clone(),
 2955                                ));
 2956                                edits.push((
 2957                                    selection.range(),
 2958                                    format!("{}{}", text, bracket_pair.end).into(),
 2959                                ));
 2960                                bracket_inserted = true;
 2961                                continue;
 2962                            }
 2963                        }
 2964
 2965                        if let Some(region) = autoclose_region {
 2966                            // If the selection is followed by an auto-inserted closing bracket,
 2967                            // then don't insert that closing bracket again; just move the selection
 2968                            // past the closing bracket.
 2969                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2970                                && text.as_ref() == region.pair.end.as_str();
 2971                            if should_skip {
 2972                                let anchor = snapshot.anchor_after(selection.end);
 2973                                new_selections
 2974                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2975                                continue;
 2976                            }
 2977                        }
 2978
 2979                        let always_treat_brackets_as_autoclosed = snapshot
 2980                            .language_settings_at(selection.start, cx)
 2981                            .always_treat_brackets_as_autoclosed;
 2982                        if always_treat_brackets_as_autoclosed
 2983                            && is_bracket_pair_end
 2984                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2985                        {
 2986                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2987                            // and the inserted text is a closing bracket and the selection is followed
 2988                            // by the closing bracket then move the selection past the closing bracket.
 2989                            let anchor = snapshot.anchor_after(selection.end);
 2990                            new_selections.push((selection.map(|_| anchor), text.len()));
 2991                            continue;
 2992                        }
 2993                    }
 2994                    // If an opening bracket is 1 character long and is typed while
 2995                    // text is selected, then surround that text with the bracket pair.
 2996                    else if auto_surround
 2997                        && bracket_pair.surround
 2998                        && is_bracket_pair_start
 2999                        && bracket_pair.start.chars().count() == 1
 3000                    {
 3001                        edits.push((selection.start..selection.start, text.clone()));
 3002                        edits.push((
 3003                            selection.end..selection.end,
 3004                            bracket_pair.end.as_str().into(),
 3005                        ));
 3006                        bracket_inserted = true;
 3007                        new_selections.push((
 3008                            Selection {
 3009                                id: selection.id,
 3010                                start: snapshot.anchor_after(selection.start),
 3011                                end: snapshot.anchor_before(selection.end),
 3012                                reversed: selection.reversed,
 3013                                goal: selection.goal,
 3014                            },
 3015                            0,
 3016                        ));
 3017                        continue;
 3018                    }
 3019                }
 3020            }
 3021
 3022            if self.auto_replace_emoji_shortcode
 3023                && selection.is_empty()
 3024                && text.as_ref().ends_with(':')
 3025            {
 3026                if let Some(possible_emoji_short_code) =
 3027                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3028                {
 3029                    if !possible_emoji_short_code.is_empty() {
 3030                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3031                            let emoji_shortcode_start = Point::new(
 3032                                selection.start.row,
 3033                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3034                            );
 3035
 3036                            // Remove shortcode from buffer
 3037                            edits.push((
 3038                                emoji_shortcode_start..selection.start,
 3039                                "".to_string().into(),
 3040                            ));
 3041                            new_selections.push((
 3042                                Selection {
 3043                                    id: selection.id,
 3044                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3045                                    end: snapshot.anchor_before(selection.start),
 3046                                    reversed: selection.reversed,
 3047                                    goal: selection.goal,
 3048                                },
 3049                                0,
 3050                            ));
 3051
 3052                            // Insert emoji
 3053                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3054                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3055                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3056
 3057                            continue;
 3058                        }
 3059                    }
 3060                }
 3061            }
 3062
 3063            // If not handling any auto-close operation, then just replace the selected
 3064            // text with the given input and move the selection to the end of the
 3065            // newly inserted text.
 3066            let anchor = snapshot.anchor_after(selection.end);
 3067            if !self.linked_edit_ranges.is_empty() {
 3068                let start_anchor = snapshot.anchor_before(selection.start);
 3069
 3070                let is_word_char = text.chars().next().map_or(true, |char| {
 3071                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3072                    classifier.is_word(char)
 3073                });
 3074
 3075                if is_word_char {
 3076                    if let Some(ranges) = self
 3077                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3078                    {
 3079                        for (buffer, edits) in ranges {
 3080                            linked_edits
 3081                                .entry(buffer.clone())
 3082                                .or_default()
 3083                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3084                        }
 3085                    }
 3086                }
 3087            }
 3088
 3089            new_selections.push((selection.map(|_| anchor), 0));
 3090            edits.push((selection.start..selection.end, text.clone()));
 3091        }
 3092
 3093        drop(snapshot);
 3094
 3095        self.transact(window, cx, |this, window, cx| {
 3096            this.buffer.update(cx, |buffer, cx| {
 3097                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3098            });
 3099            for (buffer, edits) in linked_edits {
 3100                buffer.update(cx, |buffer, cx| {
 3101                    let snapshot = buffer.snapshot();
 3102                    let edits = edits
 3103                        .into_iter()
 3104                        .map(|(range, text)| {
 3105                            use text::ToPoint as TP;
 3106                            let end_point = TP::to_point(&range.end, &snapshot);
 3107                            let start_point = TP::to_point(&range.start, &snapshot);
 3108                            (start_point..end_point, text)
 3109                        })
 3110                        .sorted_by_key(|(range, _)| range.start)
 3111                        .collect::<Vec<_>>();
 3112                    buffer.edit(edits, None, cx);
 3113                })
 3114            }
 3115            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3116            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3117            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3118            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3119                .zip(new_selection_deltas)
 3120                .map(|(selection, delta)| Selection {
 3121                    id: selection.id,
 3122                    start: selection.start + delta,
 3123                    end: selection.end + delta,
 3124                    reversed: selection.reversed,
 3125                    goal: SelectionGoal::None,
 3126                })
 3127                .collect::<Vec<_>>();
 3128
 3129            let mut i = 0;
 3130            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3131                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3132                let start = map.buffer_snapshot.anchor_before(position);
 3133                let end = map.buffer_snapshot.anchor_after(position);
 3134                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3135                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3136                        Ordering::Less => i += 1,
 3137                        Ordering::Greater => break,
 3138                        Ordering::Equal => {
 3139                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3140                                Ordering::Less => i += 1,
 3141                                Ordering::Equal => break,
 3142                                Ordering::Greater => break,
 3143                            }
 3144                        }
 3145                    }
 3146                }
 3147                this.autoclose_regions.insert(
 3148                    i,
 3149                    AutocloseRegion {
 3150                        selection_id,
 3151                        range: start..end,
 3152                        pair,
 3153                    },
 3154                );
 3155            }
 3156
 3157            let had_active_inline_completion = this.has_active_inline_completion();
 3158            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3159                s.select(new_selections)
 3160            });
 3161
 3162            if !bracket_inserted {
 3163                if let Some(on_type_format_task) =
 3164                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3165                {
 3166                    on_type_format_task.detach_and_log_err(cx);
 3167                }
 3168            }
 3169
 3170            let editor_settings = EditorSettings::get_global(cx);
 3171            if bracket_inserted
 3172                && (editor_settings.auto_signature_help
 3173                    || editor_settings.show_signature_help_after_edits)
 3174            {
 3175                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3176            }
 3177
 3178            let trigger_in_words =
 3179                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3180            if this.hard_wrap.is_some() {
 3181                let latest: Range<Point> = this.selections.newest(cx).range();
 3182                if latest.is_empty()
 3183                    && this
 3184                        .buffer()
 3185                        .read(cx)
 3186                        .snapshot(cx)
 3187                        .line_len(MultiBufferRow(latest.start.row))
 3188                        == latest.start.column
 3189                {
 3190                    this.rewrap_impl(true, cx)
 3191                }
 3192            }
 3193            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3194            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3195            this.refresh_inline_completion(true, false, window, cx);
 3196        });
 3197    }
 3198
 3199    fn find_possible_emoji_shortcode_at_position(
 3200        snapshot: &MultiBufferSnapshot,
 3201        position: Point,
 3202    ) -> Option<String> {
 3203        let mut chars = Vec::new();
 3204        let mut found_colon = false;
 3205        for char in snapshot.reversed_chars_at(position).take(100) {
 3206            // Found a possible emoji shortcode in the middle of the buffer
 3207            if found_colon {
 3208                if char.is_whitespace() {
 3209                    chars.reverse();
 3210                    return Some(chars.iter().collect());
 3211                }
 3212                // If the previous character is not a whitespace, we are in the middle of a word
 3213                // and we only want to complete the shortcode if the word is made up of other emojis
 3214                let mut containing_word = String::new();
 3215                for ch in snapshot
 3216                    .reversed_chars_at(position)
 3217                    .skip(chars.len() + 1)
 3218                    .take(100)
 3219                {
 3220                    if ch.is_whitespace() {
 3221                        break;
 3222                    }
 3223                    containing_word.push(ch);
 3224                }
 3225                let containing_word = containing_word.chars().rev().collect::<String>();
 3226                if util::word_consists_of_emojis(containing_word.as_str()) {
 3227                    chars.reverse();
 3228                    return Some(chars.iter().collect());
 3229                }
 3230            }
 3231
 3232            if char.is_whitespace() || !char.is_ascii() {
 3233                return None;
 3234            }
 3235            if char == ':' {
 3236                found_colon = true;
 3237            } else {
 3238                chars.push(char);
 3239            }
 3240        }
 3241        // Found a possible emoji shortcode at the beginning of the buffer
 3242        chars.reverse();
 3243        Some(chars.iter().collect())
 3244    }
 3245
 3246    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3247        self.transact(window, cx, |this, window, cx| {
 3248            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3249                let selections = this.selections.all::<usize>(cx);
 3250                let multi_buffer = this.buffer.read(cx);
 3251                let buffer = multi_buffer.snapshot(cx);
 3252                selections
 3253                    .iter()
 3254                    .map(|selection| {
 3255                        let start_point = selection.start.to_point(&buffer);
 3256                        let mut indent =
 3257                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3258                        indent.len = cmp::min(indent.len, start_point.column);
 3259                        let start = selection.start;
 3260                        let end = selection.end;
 3261                        let selection_is_empty = start == end;
 3262                        let language_scope = buffer.language_scope_at(start);
 3263                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3264                            &language_scope
 3265                        {
 3266                            let insert_extra_newline =
 3267                                insert_extra_newline_brackets(&buffer, start..end, language)
 3268                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3269
 3270                            // Comment extension on newline is allowed only for cursor selections
 3271                            let comment_delimiter = maybe!({
 3272                                if !selection_is_empty {
 3273                                    return None;
 3274                                }
 3275
 3276                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3277                                    return None;
 3278                                }
 3279
 3280                                let delimiters = language.line_comment_prefixes();
 3281                                let max_len_of_delimiter =
 3282                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3283                                let (snapshot, range) =
 3284                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3285
 3286                                let mut index_of_first_non_whitespace = 0;
 3287                                let comment_candidate = snapshot
 3288                                    .chars_for_range(range)
 3289                                    .skip_while(|c| {
 3290                                        let should_skip = c.is_whitespace();
 3291                                        if should_skip {
 3292                                            index_of_first_non_whitespace += 1;
 3293                                        }
 3294                                        should_skip
 3295                                    })
 3296                                    .take(max_len_of_delimiter)
 3297                                    .collect::<String>();
 3298                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3299                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3300                                })?;
 3301                                let cursor_is_placed_after_comment_marker =
 3302                                    index_of_first_non_whitespace + comment_prefix.len()
 3303                                        <= start_point.column as usize;
 3304                                if cursor_is_placed_after_comment_marker {
 3305                                    Some(comment_prefix.clone())
 3306                                } else {
 3307                                    None
 3308                                }
 3309                            });
 3310                            (comment_delimiter, insert_extra_newline)
 3311                        } else {
 3312                            (None, false)
 3313                        };
 3314
 3315                        let capacity_for_delimiter = comment_delimiter
 3316                            .as_deref()
 3317                            .map(str::len)
 3318                            .unwrap_or_default();
 3319                        let mut new_text =
 3320                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3321                        new_text.push('\n');
 3322                        new_text.extend(indent.chars());
 3323                        if let Some(delimiter) = &comment_delimiter {
 3324                            new_text.push_str(delimiter);
 3325                        }
 3326                        if insert_extra_newline {
 3327                            new_text = new_text.repeat(2);
 3328                        }
 3329
 3330                        let anchor = buffer.anchor_after(end);
 3331                        let new_selection = selection.map(|_| anchor);
 3332                        (
 3333                            (start..end, new_text),
 3334                            (insert_extra_newline, new_selection),
 3335                        )
 3336                    })
 3337                    .unzip()
 3338            };
 3339
 3340            this.edit_with_autoindent(edits, cx);
 3341            let buffer = this.buffer.read(cx).snapshot(cx);
 3342            let new_selections = selection_fixup_info
 3343                .into_iter()
 3344                .map(|(extra_newline_inserted, new_selection)| {
 3345                    let mut cursor = new_selection.end.to_point(&buffer);
 3346                    if extra_newline_inserted {
 3347                        cursor.row -= 1;
 3348                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3349                    }
 3350                    new_selection.map(|_| cursor)
 3351                })
 3352                .collect();
 3353
 3354            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3355                s.select(new_selections)
 3356            });
 3357            this.refresh_inline_completion(true, false, window, cx);
 3358        });
 3359    }
 3360
 3361    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3362        let buffer = self.buffer.read(cx);
 3363        let snapshot = buffer.snapshot(cx);
 3364
 3365        let mut edits = Vec::new();
 3366        let mut rows = Vec::new();
 3367
 3368        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3369            let cursor = selection.head();
 3370            let row = cursor.row;
 3371
 3372            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3373
 3374            let newline = "\n".to_string();
 3375            edits.push((start_of_line..start_of_line, newline));
 3376
 3377            rows.push(row + rows_inserted as u32);
 3378        }
 3379
 3380        self.transact(window, cx, |editor, window, cx| {
 3381            editor.edit(edits, cx);
 3382
 3383            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3384                let mut index = 0;
 3385                s.move_cursors_with(|map, _, _| {
 3386                    let row = rows[index];
 3387                    index += 1;
 3388
 3389                    let point = Point::new(row, 0);
 3390                    let boundary = map.next_line_boundary(point).1;
 3391                    let clipped = map.clip_point(boundary, Bias::Left);
 3392
 3393                    (clipped, SelectionGoal::None)
 3394                });
 3395            });
 3396
 3397            let mut indent_edits = Vec::new();
 3398            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3399            for row in rows {
 3400                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3401                for (row, indent) in indents {
 3402                    if indent.len == 0 {
 3403                        continue;
 3404                    }
 3405
 3406                    let text = match indent.kind {
 3407                        IndentKind::Space => " ".repeat(indent.len as usize),
 3408                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3409                    };
 3410                    let point = Point::new(row.0, 0);
 3411                    indent_edits.push((point..point, text));
 3412                }
 3413            }
 3414            editor.edit(indent_edits, cx);
 3415        });
 3416    }
 3417
 3418    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3419        let buffer = self.buffer.read(cx);
 3420        let snapshot = buffer.snapshot(cx);
 3421
 3422        let mut edits = Vec::new();
 3423        let mut rows = Vec::new();
 3424        let mut rows_inserted = 0;
 3425
 3426        for selection in self.selections.all_adjusted(cx) {
 3427            let cursor = selection.head();
 3428            let row = cursor.row;
 3429
 3430            let point = Point::new(row + 1, 0);
 3431            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3432
 3433            let newline = "\n".to_string();
 3434            edits.push((start_of_line..start_of_line, newline));
 3435
 3436            rows_inserted += 1;
 3437            rows.push(row + rows_inserted);
 3438        }
 3439
 3440        self.transact(window, cx, |editor, window, cx| {
 3441            editor.edit(edits, cx);
 3442
 3443            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3444                let mut index = 0;
 3445                s.move_cursors_with(|map, _, _| {
 3446                    let row = rows[index];
 3447                    index += 1;
 3448
 3449                    let point = Point::new(row, 0);
 3450                    let boundary = map.next_line_boundary(point).1;
 3451                    let clipped = map.clip_point(boundary, Bias::Left);
 3452
 3453                    (clipped, SelectionGoal::None)
 3454                });
 3455            });
 3456
 3457            let mut indent_edits = Vec::new();
 3458            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3459            for row in rows {
 3460                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3461                for (row, indent) in indents {
 3462                    if indent.len == 0 {
 3463                        continue;
 3464                    }
 3465
 3466                    let text = match indent.kind {
 3467                        IndentKind::Space => " ".repeat(indent.len as usize),
 3468                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3469                    };
 3470                    let point = Point::new(row.0, 0);
 3471                    indent_edits.push((point..point, text));
 3472                }
 3473            }
 3474            editor.edit(indent_edits, cx);
 3475        });
 3476    }
 3477
 3478    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3479        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3480            original_indent_columns: Vec::new(),
 3481        });
 3482        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3483    }
 3484
 3485    fn insert_with_autoindent_mode(
 3486        &mut self,
 3487        text: &str,
 3488        autoindent_mode: Option<AutoindentMode>,
 3489        window: &mut Window,
 3490        cx: &mut Context<Self>,
 3491    ) {
 3492        if self.read_only(cx) {
 3493            return;
 3494        }
 3495
 3496        let text: Arc<str> = text.into();
 3497        self.transact(window, cx, |this, window, cx| {
 3498            let old_selections = this.selections.all_adjusted(cx);
 3499            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3500                let anchors = {
 3501                    let snapshot = buffer.read(cx);
 3502                    old_selections
 3503                        .iter()
 3504                        .map(|s| {
 3505                            let anchor = snapshot.anchor_after(s.head());
 3506                            s.map(|_| anchor)
 3507                        })
 3508                        .collect::<Vec<_>>()
 3509                };
 3510                buffer.edit(
 3511                    old_selections
 3512                        .iter()
 3513                        .map(|s| (s.start..s.end, text.clone())),
 3514                    autoindent_mode,
 3515                    cx,
 3516                );
 3517                anchors
 3518            });
 3519
 3520            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3521                s.select_anchors(selection_anchors);
 3522            });
 3523
 3524            cx.notify();
 3525        });
 3526    }
 3527
 3528    fn trigger_completion_on_input(
 3529        &mut self,
 3530        text: &str,
 3531        trigger_in_words: bool,
 3532        window: &mut Window,
 3533        cx: &mut Context<Self>,
 3534    ) {
 3535        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3536            self.show_completions(
 3537                &ShowCompletions {
 3538                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3539                },
 3540                window,
 3541                cx,
 3542            );
 3543        } else {
 3544            self.hide_context_menu(window, cx);
 3545        }
 3546    }
 3547
 3548    fn is_completion_trigger(
 3549        &self,
 3550        text: &str,
 3551        trigger_in_words: bool,
 3552        cx: &mut Context<Self>,
 3553    ) -> bool {
 3554        let position = self.selections.newest_anchor().head();
 3555        let multibuffer = self.buffer.read(cx);
 3556        let Some(buffer) = position
 3557            .buffer_id
 3558            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3559        else {
 3560            return false;
 3561        };
 3562
 3563        if let Some(completion_provider) = &self.completion_provider {
 3564            completion_provider.is_completion_trigger(
 3565                &buffer,
 3566                position.text_anchor,
 3567                text,
 3568                trigger_in_words,
 3569                cx,
 3570            )
 3571        } else {
 3572            false
 3573        }
 3574    }
 3575
 3576    /// If any empty selections is touching the start of its innermost containing autoclose
 3577    /// region, expand it to select the brackets.
 3578    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3579        let selections = self.selections.all::<usize>(cx);
 3580        let buffer = self.buffer.read(cx).read(cx);
 3581        let new_selections = self
 3582            .selections_with_autoclose_regions(selections, &buffer)
 3583            .map(|(mut selection, region)| {
 3584                if !selection.is_empty() {
 3585                    return selection;
 3586                }
 3587
 3588                if let Some(region) = region {
 3589                    let mut range = region.range.to_offset(&buffer);
 3590                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3591                        range.start -= region.pair.start.len();
 3592                        if buffer.contains_str_at(range.start, &region.pair.start)
 3593                            && buffer.contains_str_at(range.end, &region.pair.end)
 3594                        {
 3595                            range.end += region.pair.end.len();
 3596                            selection.start = range.start;
 3597                            selection.end = range.end;
 3598
 3599                            return selection;
 3600                        }
 3601                    }
 3602                }
 3603
 3604                let always_treat_brackets_as_autoclosed = buffer
 3605                    .language_settings_at(selection.start, cx)
 3606                    .always_treat_brackets_as_autoclosed;
 3607
 3608                if !always_treat_brackets_as_autoclosed {
 3609                    return selection;
 3610                }
 3611
 3612                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3613                    for (pair, enabled) in scope.brackets() {
 3614                        if !enabled || !pair.close {
 3615                            continue;
 3616                        }
 3617
 3618                        if buffer.contains_str_at(selection.start, &pair.end) {
 3619                            let pair_start_len = pair.start.len();
 3620                            if buffer.contains_str_at(
 3621                                selection.start.saturating_sub(pair_start_len),
 3622                                &pair.start,
 3623                            ) {
 3624                                selection.start -= pair_start_len;
 3625                                selection.end += pair.end.len();
 3626
 3627                                return selection;
 3628                            }
 3629                        }
 3630                    }
 3631                }
 3632
 3633                selection
 3634            })
 3635            .collect();
 3636
 3637        drop(buffer);
 3638        self.change_selections(None, window, cx, |selections| {
 3639            selections.select(new_selections)
 3640        });
 3641    }
 3642
 3643    /// Iterate the given selections, and for each one, find the smallest surrounding
 3644    /// autoclose region. This uses the ordering of the selections and the autoclose
 3645    /// regions to avoid repeated comparisons.
 3646    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3647        &'a self,
 3648        selections: impl IntoIterator<Item = Selection<D>>,
 3649        buffer: &'a MultiBufferSnapshot,
 3650    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3651        let mut i = 0;
 3652        let mut regions = self.autoclose_regions.as_slice();
 3653        selections.into_iter().map(move |selection| {
 3654            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3655
 3656            let mut enclosing = None;
 3657            while let Some(pair_state) = regions.get(i) {
 3658                if pair_state.range.end.to_offset(buffer) < range.start {
 3659                    regions = &regions[i + 1..];
 3660                    i = 0;
 3661                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3662                    break;
 3663                } else {
 3664                    if pair_state.selection_id == selection.id {
 3665                        enclosing = Some(pair_state);
 3666                    }
 3667                    i += 1;
 3668                }
 3669            }
 3670
 3671            (selection, enclosing)
 3672        })
 3673    }
 3674
 3675    /// Remove any autoclose regions that no longer contain their selection.
 3676    fn invalidate_autoclose_regions(
 3677        &mut self,
 3678        mut selections: &[Selection<Anchor>],
 3679        buffer: &MultiBufferSnapshot,
 3680    ) {
 3681        self.autoclose_regions.retain(|state| {
 3682            let mut i = 0;
 3683            while let Some(selection) = selections.get(i) {
 3684                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3685                    selections = &selections[1..];
 3686                    continue;
 3687                }
 3688                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3689                    break;
 3690                }
 3691                if selection.id == state.selection_id {
 3692                    return true;
 3693                } else {
 3694                    i += 1;
 3695                }
 3696            }
 3697            false
 3698        });
 3699    }
 3700
 3701    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3702        let offset = position.to_offset(buffer);
 3703        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3704        if offset > word_range.start && kind == Some(CharKind::Word) {
 3705            Some(
 3706                buffer
 3707                    .text_for_range(word_range.start..offset)
 3708                    .collect::<String>(),
 3709            )
 3710        } else {
 3711            None
 3712        }
 3713    }
 3714
 3715    pub fn toggle_inlay_hints(
 3716        &mut self,
 3717        _: &ToggleInlayHints,
 3718        _: &mut Window,
 3719        cx: &mut Context<Self>,
 3720    ) {
 3721        self.refresh_inlay_hints(
 3722            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 3723            cx,
 3724        );
 3725    }
 3726
 3727    pub fn inlay_hints_enabled(&self) -> bool {
 3728        self.inlay_hint_cache.enabled
 3729    }
 3730
 3731    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3732        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3733            return;
 3734        }
 3735
 3736        let reason_description = reason.description();
 3737        let ignore_debounce = matches!(
 3738            reason,
 3739            InlayHintRefreshReason::SettingsChange(_)
 3740                | InlayHintRefreshReason::Toggle(_)
 3741                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3742                | InlayHintRefreshReason::ModifiersChanged(_)
 3743        );
 3744        let (invalidate_cache, required_languages) = match reason {
 3745            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 3746                match self.inlay_hint_cache.modifiers_override(enabled) {
 3747                    Some(enabled) => {
 3748                        if enabled {
 3749                            (InvalidationStrategy::RefreshRequested, None)
 3750                        } else {
 3751                            self.splice_inlays(
 3752                                &self
 3753                                    .visible_inlay_hints(cx)
 3754                                    .iter()
 3755                                    .map(|inlay| inlay.id)
 3756                                    .collect::<Vec<InlayId>>(),
 3757                                Vec::new(),
 3758                                cx,
 3759                            );
 3760                            return;
 3761                        }
 3762                    }
 3763                    None => return,
 3764                }
 3765            }
 3766            InlayHintRefreshReason::Toggle(enabled) => {
 3767                if self.inlay_hint_cache.toggle(enabled) {
 3768                    if enabled {
 3769                        (InvalidationStrategy::RefreshRequested, None)
 3770                    } else {
 3771                        self.splice_inlays(
 3772                            &self
 3773                                .visible_inlay_hints(cx)
 3774                                .iter()
 3775                                .map(|inlay| inlay.id)
 3776                                .collect::<Vec<InlayId>>(),
 3777                            Vec::new(),
 3778                            cx,
 3779                        );
 3780                        return;
 3781                    }
 3782                } else {
 3783                    return;
 3784                }
 3785            }
 3786            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3787                match self.inlay_hint_cache.update_settings(
 3788                    &self.buffer,
 3789                    new_settings,
 3790                    self.visible_inlay_hints(cx),
 3791                    cx,
 3792                ) {
 3793                    ControlFlow::Break(Some(InlaySplice {
 3794                        to_remove,
 3795                        to_insert,
 3796                    })) => {
 3797                        self.splice_inlays(&to_remove, to_insert, cx);
 3798                        return;
 3799                    }
 3800                    ControlFlow::Break(None) => return,
 3801                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3802                }
 3803            }
 3804            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3805                if let Some(InlaySplice {
 3806                    to_remove,
 3807                    to_insert,
 3808                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3809                {
 3810                    self.splice_inlays(&to_remove, to_insert, cx);
 3811                }
 3812                return;
 3813            }
 3814            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3815            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3816                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3817            }
 3818            InlayHintRefreshReason::RefreshRequested => {
 3819                (InvalidationStrategy::RefreshRequested, None)
 3820            }
 3821        };
 3822
 3823        if let Some(InlaySplice {
 3824            to_remove,
 3825            to_insert,
 3826        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3827            reason_description,
 3828            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3829            invalidate_cache,
 3830            ignore_debounce,
 3831            cx,
 3832        ) {
 3833            self.splice_inlays(&to_remove, to_insert, cx);
 3834        }
 3835    }
 3836
 3837    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3838        self.display_map
 3839            .read(cx)
 3840            .current_inlays()
 3841            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3842            .cloned()
 3843            .collect()
 3844    }
 3845
 3846    pub fn excerpts_for_inlay_hints_query(
 3847        &self,
 3848        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3849        cx: &mut Context<Editor>,
 3850    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3851        let Some(project) = self.project.as_ref() else {
 3852            return HashMap::default();
 3853        };
 3854        let project = project.read(cx);
 3855        let multi_buffer = self.buffer().read(cx);
 3856        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3857        let multi_buffer_visible_start = self
 3858            .scroll_manager
 3859            .anchor()
 3860            .anchor
 3861            .to_point(&multi_buffer_snapshot);
 3862        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3863            multi_buffer_visible_start
 3864                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3865            Bias::Left,
 3866        );
 3867        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3868        multi_buffer_snapshot
 3869            .range_to_buffer_ranges(multi_buffer_visible_range)
 3870            .into_iter()
 3871            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3872            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3873                let buffer_file = project::File::from_dyn(buffer.file())?;
 3874                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3875                let worktree_entry = buffer_worktree
 3876                    .read(cx)
 3877                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3878                if worktree_entry.is_ignored {
 3879                    return None;
 3880                }
 3881
 3882                let language = buffer.language()?;
 3883                if let Some(restrict_to_languages) = restrict_to_languages {
 3884                    if !restrict_to_languages.contains(language) {
 3885                        return None;
 3886                    }
 3887                }
 3888                Some((
 3889                    excerpt_id,
 3890                    (
 3891                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3892                        buffer.version().clone(),
 3893                        excerpt_visible_range,
 3894                    ),
 3895                ))
 3896            })
 3897            .collect()
 3898    }
 3899
 3900    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3901        TextLayoutDetails {
 3902            text_system: window.text_system().clone(),
 3903            editor_style: self.style.clone().unwrap(),
 3904            rem_size: window.rem_size(),
 3905            scroll_anchor: self.scroll_manager.anchor(),
 3906            visible_rows: self.visible_line_count(),
 3907            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3908        }
 3909    }
 3910
 3911    pub fn splice_inlays(
 3912        &self,
 3913        to_remove: &[InlayId],
 3914        to_insert: Vec<Inlay>,
 3915        cx: &mut Context<Self>,
 3916    ) {
 3917        self.display_map.update(cx, |display_map, cx| {
 3918            display_map.splice_inlays(to_remove, to_insert, cx)
 3919        });
 3920        cx.notify();
 3921    }
 3922
 3923    fn trigger_on_type_formatting(
 3924        &self,
 3925        input: String,
 3926        window: &mut Window,
 3927        cx: &mut Context<Self>,
 3928    ) -> Option<Task<Result<()>>> {
 3929        if input.len() != 1 {
 3930            return None;
 3931        }
 3932
 3933        let project = self.project.as_ref()?;
 3934        let position = self.selections.newest_anchor().head();
 3935        let (buffer, buffer_position) = self
 3936            .buffer
 3937            .read(cx)
 3938            .text_anchor_for_position(position, cx)?;
 3939
 3940        let settings = language_settings::language_settings(
 3941            buffer
 3942                .read(cx)
 3943                .language_at(buffer_position)
 3944                .map(|l| l.name()),
 3945            buffer.read(cx).file(),
 3946            cx,
 3947        );
 3948        if !settings.use_on_type_format {
 3949            return None;
 3950        }
 3951
 3952        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3953        // hence we do LSP request & edit on host side only — add formats to host's history.
 3954        let push_to_lsp_host_history = true;
 3955        // If this is not the host, append its history with new edits.
 3956        let push_to_client_history = project.read(cx).is_via_collab();
 3957
 3958        let on_type_formatting = project.update(cx, |project, cx| {
 3959            project.on_type_format(
 3960                buffer.clone(),
 3961                buffer_position,
 3962                input,
 3963                push_to_lsp_host_history,
 3964                cx,
 3965            )
 3966        });
 3967        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3968            if let Some(transaction) = on_type_formatting.await? {
 3969                if push_to_client_history {
 3970                    buffer
 3971                        .update(&mut cx, |buffer, _| {
 3972                            buffer.push_transaction(transaction, Instant::now());
 3973                        })
 3974                        .ok();
 3975                }
 3976                editor.update(&mut cx, |editor, cx| {
 3977                    editor.refresh_document_highlights(cx);
 3978                })?;
 3979            }
 3980            Ok(())
 3981        }))
 3982    }
 3983
 3984    pub fn show_completions(
 3985        &mut self,
 3986        options: &ShowCompletions,
 3987        window: &mut Window,
 3988        cx: &mut Context<Self>,
 3989    ) {
 3990        if self.pending_rename.is_some() {
 3991            return;
 3992        }
 3993
 3994        let Some(provider) = self.completion_provider.as_ref() else {
 3995            return;
 3996        };
 3997
 3998        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3999            return;
 4000        }
 4001
 4002        let position = self.selections.newest_anchor().head();
 4003        if position.diff_base_anchor.is_some() {
 4004            return;
 4005        }
 4006        let (buffer, buffer_position) =
 4007            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4008                output
 4009            } else {
 4010                return;
 4011            };
 4012        let show_completion_documentation = buffer
 4013            .read(cx)
 4014            .snapshot()
 4015            .settings_at(buffer_position, cx)
 4016            .show_completion_documentation;
 4017
 4018        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4019
 4020        let trigger_kind = match &options.trigger {
 4021            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4022                CompletionTriggerKind::TRIGGER_CHARACTER
 4023            }
 4024            _ => CompletionTriggerKind::INVOKED,
 4025        };
 4026        let completion_context = CompletionContext {
 4027            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4028                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4029                    Some(String::from(trigger))
 4030                } else {
 4031                    None
 4032                }
 4033            }),
 4034            trigger_kind,
 4035        };
 4036        let completions =
 4037            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 4038        let sort_completions = provider.sort_completions();
 4039
 4040        let id = post_inc(&mut self.next_completion_id);
 4041        let task = cx.spawn_in(window, |editor, mut cx| {
 4042            async move {
 4043                editor.update(&mut cx, |this, _| {
 4044                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4045                })?;
 4046                let completions = completions.await.log_err();
 4047                let menu = if let Some(completions) = completions {
 4048                    let mut menu = CompletionsMenu::new(
 4049                        id,
 4050                        sort_completions,
 4051                        show_completion_documentation,
 4052                        position,
 4053                        buffer.clone(),
 4054                        completions.into(),
 4055                    );
 4056
 4057                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4058                        .await;
 4059
 4060                    menu.visible().then_some(menu)
 4061                } else {
 4062                    None
 4063                };
 4064
 4065                editor.update_in(&mut cx, |editor, window, cx| {
 4066                    match editor.context_menu.borrow().as_ref() {
 4067                        None => {}
 4068                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4069                            if prev_menu.id > id {
 4070                                return;
 4071                            }
 4072                        }
 4073                        _ => return,
 4074                    }
 4075
 4076                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4077                        let mut menu = menu.unwrap();
 4078                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4079
 4080                        *editor.context_menu.borrow_mut() =
 4081                            Some(CodeContextMenu::Completions(menu));
 4082
 4083                        if editor.show_edit_predictions_in_menu() {
 4084                            editor.update_visible_inline_completion(window, cx);
 4085                        } else {
 4086                            editor.discard_inline_completion(false, cx);
 4087                        }
 4088
 4089                        cx.notify();
 4090                    } else if editor.completion_tasks.len() <= 1 {
 4091                        // If there are no more completion tasks and the last menu was
 4092                        // empty, we should hide it.
 4093                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4094                        // If it was already hidden and we don't show inline
 4095                        // completions in the menu, we should also show the
 4096                        // inline-completion when available.
 4097                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4098                            editor.update_visible_inline_completion(window, cx);
 4099                        }
 4100                    }
 4101                })?;
 4102
 4103                Ok::<_, anyhow::Error>(())
 4104            }
 4105            .log_err()
 4106        });
 4107
 4108        self.completion_tasks.push((id, task));
 4109    }
 4110
 4111    pub fn confirm_completion(
 4112        &mut self,
 4113        action: &ConfirmCompletion,
 4114        window: &mut Window,
 4115        cx: &mut Context<Self>,
 4116    ) -> Option<Task<Result<()>>> {
 4117        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4118    }
 4119
 4120    pub fn compose_completion(
 4121        &mut self,
 4122        action: &ComposeCompletion,
 4123        window: &mut Window,
 4124        cx: &mut Context<Self>,
 4125    ) -> Option<Task<Result<()>>> {
 4126        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4127    }
 4128
 4129    fn do_completion(
 4130        &mut self,
 4131        item_ix: Option<usize>,
 4132        intent: CompletionIntent,
 4133        window: &mut Window,
 4134        cx: &mut Context<Editor>,
 4135    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4136        use language::ToOffset as _;
 4137
 4138        let completions_menu =
 4139            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4140                menu
 4141            } else {
 4142                return None;
 4143            };
 4144
 4145        let entries = completions_menu.entries.borrow();
 4146        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4147        if self.show_edit_predictions_in_menu() {
 4148            self.discard_inline_completion(true, cx);
 4149        }
 4150        let candidate_id = mat.candidate_id;
 4151        drop(entries);
 4152
 4153        let buffer_handle = completions_menu.buffer;
 4154        let completion = completions_menu
 4155            .completions
 4156            .borrow()
 4157            .get(candidate_id)?
 4158            .clone();
 4159        cx.stop_propagation();
 4160
 4161        let snippet;
 4162        let text;
 4163
 4164        if completion.is_snippet() {
 4165            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4166            text = snippet.as_ref().unwrap().text.clone();
 4167        } else {
 4168            snippet = None;
 4169            text = completion.new_text.clone();
 4170        };
 4171        let selections = self.selections.all::<usize>(cx);
 4172        let buffer = buffer_handle.read(cx);
 4173        let old_range = completion.old_range.to_offset(buffer);
 4174        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4175
 4176        let newest_selection = self.selections.newest_anchor();
 4177        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4178            return None;
 4179        }
 4180
 4181        let lookbehind = newest_selection
 4182            .start
 4183            .text_anchor
 4184            .to_offset(buffer)
 4185            .saturating_sub(old_range.start);
 4186        let lookahead = old_range
 4187            .end
 4188            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4189        let mut common_prefix_len = old_text
 4190            .bytes()
 4191            .zip(text.bytes())
 4192            .take_while(|(a, b)| a == b)
 4193            .count();
 4194
 4195        let snapshot = self.buffer.read(cx).snapshot(cx);
 4196        let mut range_to_replace: Option<Range<isize>> = None;
 4197        let mut ranges = Vec::new();
 4198        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4199        for selection in &selections {
 4200            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4201                let start = selection.start.saturating_sub(lookbehind);
 4202                let end = selection.end + lookahead;
 4203                if selection.id == newest_selection.id {
 4204                    range_to_replace = Some(
 4205                        ((start + common_prefix_len) as isize - selection.start as isize)
 4206                            ..(end as isize - selection.start as isize),
 4207                    );
 4208                }
 4209                ranges.push(start + common_prefix_len..end);
 4210            } else {
 4211                common_prefix_len = 0;
 4212                ranges.clear();
 4213                ranges.extend(selections.iter().map(|s| {
 4214                    if s.id == newest_selection.id {
 4215                        range_to_replace = Some(
 4216                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4217                                - selection.start as isize
 4218                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4219                                    - selection.start as isize,
 4220                        );
 4221                        old_range.clone()
 4222                    } else {
 4223                        s.start..s.end
 4224                    }
 4225                }));
 4226                break;
 4227            }
 4228            if !self.linked_edit_ranges.is_empty() {
 4229                let start_anchor = snapshot.anchor_before(selection.head());
 4230                let end_anchor = snapshot.anchor_after(selection.tail());
 4231                if let Some(ranges) = self
 4232                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4233                {
 4234                    for (buffer, edits) in ranges {
 4235                        linked_edits.entry(buffer.clone()).or_default().extend(
 4236                            edits
 4237                                .into_iter()
 4238                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4239                        );
 4240                    }
 4241                }
 4242            }
 4243        }
 4244        let text = &text[common_prefix_len..];
 4245
 4246        cx.emit(EditorEvent::InputHandled {
 4247            utf16_range_to_replace: range_to_replace,
 4248            text: text.into(),
 4249        });
 4250
 4251        self.transact(window, cx, |this, window, cx| {
 4252            if let Some(mut snippet) = snippet {
 4253                snippet.text = text.to_string();
 4254                for tabstop in snippet
 4255                    .tabstops
 4256                    .iter_mut()
 4257                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4258                {
 4259                    tabstop.start -= common_prefix_len as isize;
 4260                    tabstop.end -= common_prefix_len as isize;
 4261                }
 4262
 4263                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4264            } else {
 4265                this.buffer.update(cx, |buffer, cx| {
 4266                    buffer.edit(
 4267                        ranges.iter().map(|range| (range.clone(), text)),
 4268                        this.autoindent_mode.clone(),
 4269                        cx,
 4270                    );
 4271                });
 4272            }
 4273            for (buffer, edits) in linked_edits {
 4274                buffer.update(cx, |buffer, cx| {
 4275                    let snapshot = buffer.snapshot();
 4276                    let edits = edits
 4277                        .into_iter()
 4278                        .map(|(range, text)| {
 4279                            use text::ToPoint as TP;
 4280                            let end_point = TP::to_point(&range.end, &snapshot);
 4281                            let start_point = TP::to_point(&range.start, &snapshot);
 4282                            (start_point..end_point, text)
 4283                        })
 4284                        .sorted_by_key(|(range, _)| range.start)
 4285                        .collect::<Vec<_>>();
 4286                    buffer.edit(edits, None, cx);
 4287                })
 4288            }
 4289
 4290            this.refresh_inline_completion(true, false, window, cx);
 4291        });
 4292
 4293        let show_new_completions_on_confirm = completion
 4294            .confirm
 4295            .as_ref()
 4296            .map_or(false, |confirm| confirm(intent, window, cx));
 4297        if show_new_completions_on_confirm {
 4298            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4299        }
 4300
 4301        let provider = self.completion_provider.as_ref()?;
 4302        drop(completion);
 4303        let apply_edits = provider.apply_additional_edits_for_completion(
 4304            buffer_handle,
 4305            completions_menu.completions.clone(),
 4306            candidate_id,
 4307            true,
 4308            cx,
 4309        );
 4310
 4311        let editor_settings = EditorSettings::get_global(cx);
 4312        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4313            // After the code completion is finished, users often want to know what signatures are needed.
 4314            // so we should automatically call signature_help
 4315            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4316        }
 4317
 4318        Some(cx.foreground_executor().spawn(async move {
 4319            apply_edits.await?;
 4320            Ok(())
 4321        }))
 4322    }
 4323
 4324    pub fn toggle_code_actions(
 4325        &mut self,
 4326        action: &ToggleCodeActions,
 4327        window: &mut Window,
 4328        cx: &mut Context<Self>,
 4329    ) {
 4330        let mut context_menu = self.context_menu.borrow_mut();
 4331        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4332            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4333                // Toggle if we're selecting the same one
 4334                *context_menu = None;
 4335                cx.notify();
 4336                return;
 4337            } else {
 4338                // Otherwise, clear it and start a new one
 4339                *context_menu = None;
 4340                cx.notify();
 4341            }
 4342        }
 4343        drop(context_menu);
 4344        let snapshot = self.snapshot(window, cx);
 4345        let deployed_from_indicator = action.deployed_from_indicator;
 4346        let mut task = self.code_actions_task.take();
 4347        let action = action.clone();
 4348        cx.spawn_in(window, |editor, mut cx| async move {
 4349            while let Some(prev_task) = task {
 4350                prev_task.await.log_err();
 4351                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4352            }
 4353
 4354            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4355                if editor.focus_handle.is_focused(window) {
 4356                    let multibuffer_point = action
 4357                        .deployed_from_indicator
 4358                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4359                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4360                    let (buffer, buffer_row) = snapshot
 4361                        .buffer_snapshot
 4362                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4363                        .and_then(|(buffer_snapshot, range)| {
 4364                            editor
 4365                                .buffer
 4366                                .read(cx)
 4367                                .buffer(buffer_snapshot.remote_id())
 4368                                .map(|buffer| (buffer, range.start.row))
 4369                        })?;
 4370                    let (_, code_actions) = editor
 4371                        .available_code_actions
 4372                        .clone()
 4373                        .and_then(|(location, code_actions)| {
 4374                            let snapshot = location.buffer.read(cx).snapshot();
 4375                            let point_range = location.range.to_point(&snapshot);
 4376                            let point_range = point_range.start.row..=point_range.end.row;
 4377                            if point_range.contains(&buffer_row) {
 4378                                Some((location, code_actions))
 4379                            } else {
 4380                                None
 4381                            }
 4382                        })
 4383                        .unzip();
 4384                    let buffer_id = buffer.read(cx).remote_id();
 4385                    let tasks = editor
 4386                        .tasks
 4387                        .get(&(buffer_id, buffer_row))
 4388                        .map(|t| Arc::new(t.to_owned()));
 4389                    if tasks.is_none() && code_actions.is_none() {
 4390                        return None;
 4391                    }
 4392
 4393                    editor.completion_tasks.clear();
 4394                    editor.discard_inline_completion(false, cx);
 4395                    let task_context =
 4396                        tasks
 4397                            .as_ref()
 4398                            .zip(editor.project.clone())
 4399                            .map(|(tasks, project)| {
 4400                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4401                            });
 4402
 4403                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4404                        let task_context = match task_context {
 4405                            Some(task_context) => task_context.await,
 4406                            None => None,
 4407                        };
 4408                        let resolved_tasks =
 4409                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4410                                Rc::new(ResolvedTasks {
 4411                                    templates: tasks.resolve(&task_context).collect(),
 4412                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4413                                        multibuffer_point.row,
 4414                                        tasks.column,
 4415                                    )),
 4416                                })
 4417                            });
 4418                        let spawn_straight_away = resolved_tasks
 4419                            .as_ref()
 4420                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4421                            && code_actions
 4422                                .as_ref()
 4423                                .map_or(true, |actions| actions.is_empty());
 4424                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4425                            *editor.context_menu.borrow_mut() =
 4426                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4427                                    buffer,
 4428                                    actions: CodeActionContents {
 4429                                        tasks: resolved_tasks,
 4430                                        actions: code_actions,
 4431                                    },
 4432                                    selected_item: Default::default(),
 4433                                    scroll_handle: UniformListScrollHandle::default(),
 4434                                    deployed_from_indicator,
 4435                                }));
 4436                            if spawn_straight_away {
 4437                                if let Some(task) = editor.confirm_code_action(
 4438                                    &ConfirmCodeAction { item_ix: Some(0) },
 4439                                    window,
 4440                                    cx,
 4441                                ) {
 4442                                    cx.notify();
 4443                                    return task;
 4444                                }
 4445                            }
 4446                            cx.notify();
 4447                            Task::ready(Ok(()))
 4448                        }) {
 4449                            task.await
 4450                        } else {
 4451                            Ok(())
 4452                        }
 4453                    }))
 4454                } else {
 4455                    Some(Task::ready(Ok(())))
 4456                }
 4457            })?;
 4458            if let Some(task) = spawned_test_task {
 4459                task.await?;
 4460            }
 4461
 4462            Ok::<_, anyhow::Error>(())
 4463        })
 4464        .detach_and_log_err(cx);
 4465    }
 4466
 4467    pub fn confirm_code_action(
 4468        &mut self,
 4469        action: &ConfirmCodeAction,
 4470        window: &mut Window,
 4471        cx: &mut Context<Self>,
 4472    ) -> Option<Task<Result<()>>> {
 4473        let actions_menu =
 4474            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4475                menu
 4476            } else {
 4477                return None;
 4478            };
 4479        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4480        let action = actions_menu.actions.get(action_ix)?;
 4481        let title = action.label();
 4482        let buffer = actions_menu.buffer;
 4483        let workspace = self.workspace()?;
 4484
 4485        match action {
 4486            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4487                workspace.update(cx, |workspace, cx| {
 4488                    workspace::tasks::schedule_resolved_task(
 4489                        workspace,
 4490                        task_source_kind,
 4491                        resolved_task,
 4492                        false,
 4493                        cx,
 4494                    );
 4495
 4496                    Some(Task::ready(Ok(())))
 4497                })
 4498            }
 4499            CodeActionsItem::CodeAction {
 4500                excerpt_id,
 4501                action,
 4502                provider,
 4503            } => {
 4504                let apply_code_action =
 4505                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4506                let workspace = workspace.downgrade();
 4507                Some(cx.spawn_in(window, |editor, cx| async move {
 4508                    let project_transaction = apply_code_action.await?;
 4509                    Self::open_project_transaction(
 4510                        &editor,
 4511                        workspace,
 4512                        project_transaction,
 4513                        title,
 4514                        cx,
 4515                    )
 4516                    .await
 4517                }))
 4518            }
 4519        }
 4520    }
 4521
 4522    pub async fn open_project_transaction(
 4523        this: &WeakEntity<Editor>,
 4524        workspace: WeakEntity<Workspace>,
 4525        transaction: ProjectTransaction,
 4526        title: String,
 4527        mut cx: AsyncWindowContext,
 4528    ) -> Result<()> {
 4529        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4530        cx.update(|_, cx| {
 4531            entries.sort_unstable_by_key(|(buffer, _)| {
 4532                buffer.read(cx).file().map(|f| f.path().clone())
 4533            });
 4534        })?;
 4535
 4536        // If the project transaction's edits are all contained within this editor, then
 4537        // avoid opening a new editor to display them.
 4538
 4539        if let Some((buffer, transaction)) = entries.first() {
 4540            if entries.len() == 1 {
 4541                let excerpt = this.update(&mut cx, |editor, cx| {
 4542                    editor
 4543                        .buffer()
 4544                        .read(cx)
 4545                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4546                })?;
 4547                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4548                    if excerpted_buffer == *buffer {
 4549                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4550                            let excerpt_range = excerpt_range.to_offset(buffer);
 4551                            buffer
 4552                                .edited_ranges_for_transaction::<usize>(transaction)
 4553                                .all(|range| {
 4554                                    excerpt_range.start <= range.start
 4555                                        && excerpt_range.end >= range.end
 4556                                })
 4557                        })?;
 4558
 4559                        if all_edits_within_excerpt {
 4560                            return Ok(());
 4561                        }
 4562                    }
 4563                }
 4564            }
 4565        } else {
 4566            return Ok(());
 4567        }
 4568
 4569        let mut ranges_to_highlight = Vec::new();
 4570        let excerpt_buffer = cx.new(|cx| {
 4571            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4572            for (buffer_handle, transaction) in &entries {
 4573                let buffer = buffer_handle.read(cx);
 4574                ranges_to_highlight.extend(
 4575                    multibuffer.push_excerpts_with_context_lines(
 4576                        buffer_handle.clone(),
 4577                        buffer
 4578                            .edited_ranges_for_transaction::<usize>(transaction)
 4579                            .collect(),
 4580                        DEFAULT_MULTIBUFFER_CONTEXT,
 4581                        cx,
 4582                    ),
 4583                );
 4584            }
 4585            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4586            multibuffer
 4587        })?;
 4588
 4589        workspace.update_in(&mut cx, |workspace, window, cx| {
 4590            let project = workspace.project().clone();
 4591            let editor = cx
 4592                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4593            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4594            editor.update(cx, |editor, cx| {
 4595                editor.highlight_background::<Self>(
 4596                    &ranges_to_highlight,
 4597                    |theme| theme.editor_highlighted_line_background,
 4598                    cx,
 4599                );
 4600            });
 4601        })?;
 4602
 4603        Ok(())
 4604    }
 4605
 4606    pub fn clear_code_action_providers(&mut self) {
 4607        self.code_action_providers.clear();
 4608        self.available_code_actions.take();
 4609    }
 4610
 4611    pub fn add_code_action_provider(
 4612        &mut self,
 4613        provider: Rc<dyn CodeActionProvider>,
 4614        window: &mut Window,
 4615        cx: &mut Context<Self>,
 4616    ) {
 4617        if self
 4618            .code_action_providers
 4619            .iter()
 4620            .any(|existing_provider| existing_provider.id() == provider.id())
 4621        {
 4622            return;
 4623        }
 4624
 4625        self.code_action_providers.push(provider);
 4626        self.refresh_code_actions(window, cx);
 4627    }
 4628
 4629    pub fn remove_code_action_provider(
 4630        &mut self,
 4631        id: Arc<str>,
 4632        window: &mut Window,
 4633        cx: &mut Context<Self>,
 4634    ) {
 4635        self.code_action_providers
 4636            .retain(|provider| provider.id() != id);
 4637        self.refresh_code_actions(window, cx);
 4638    }
 4639
 4640    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4641        let buffer = self.buffer.read(cx);
 4642        let newest_selection = self.selections.newest_anchor().clone();
 4643        if newest_selection.head().diff_base_anchor.is_some() {
 4644            return None;
 4645        }
 4646        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4647        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4648        if start_buffer != end_buffer {
 4649            return None;
 4650        }
 4651
 4652        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4653            cx.background_executor()
 4654                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4655                .await;
 4656
 4657            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4658                let providers = this.code_action_providers.clone();
 4659                let tasks = this
 4660                    .code_action_providers
 4661                    .iter()
 4662                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4663                    .collect::<Vec<_>>();
 4664                (providers, tasks)
 4665            })?;
 4666
 4667            let mut actions = Vec::new();
 4668            for (provider, provider_actions) in
 4669                providers.into_iter().zip(future::join_all(tasks).await)
 4670            {
 4671                if let Some(provider_actions) = provider_actions.log_err() {
 4672                    actions.extend(provider_actions.into_iter().map(|action| {
 4673                        AvailableCodeAction {
 4674                            excerpt_id: newest_selection.start.excerpt_id,
 4675                            action,
 4676                            provider: provider.clone(),
 4677                        }
 4678                    }));
 4679                }
 4680            }
 4681
 4682            this.update(&mut cx, |this, cx| {
 4683                this.available_code_actions = if actions.is_empty() {
 4684                    None
 4685                } else {
 4686                    Some((
 4687                        Location {
 4688                            buffer: start_buffer,
 4689                            range: start..end,
 4690                        },
 4691                        actions.into(),
 4692                    ))
 4693                };
 4694                cx.notify();
 4695            })
 4696        }));
 4697        None
 4698    }
 4699
 4700    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4701        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4702            self.show_git_blame_inline = false;
 4703
 4704            self.show_git_blame_inline_delay_task =
 4705                Some(cx.spawn_in(window, |this, mut cx| async move {
 4706                    cx.background_executor().timer(delay).await;
 4707
 4708                    this.update(&mut cx, |this, cx| {
 4709                        this.show_git_blame_inline = true;
 4710                        cx.notify();
 4711                    })
 4712                    .log_err();
 4713                }));
 4714        }
 4715    }
 4716
 4717    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4718        if self.pending_rename.is_some() {
 4719            return None;
 4720        }
 4721
 4722        let provider = self.semantics_provider.clone()?;
 4723        let buffer = self.buffer.read(cx);
 4724        let newest_selection = self.selections.newest_anchor().clone();
 4725        let cursor_position = newest_selection.head();
 4726        let (cursor_buffer, cursor_buffer_position) =
 4727            buffer.text_anchor_for_position(cursor_position, cx)?;
 4728        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4729        if cursor_buffer != tail_buffer {
 4730            return None;
 4731        }
 4732        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4733        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4734            cx.background_executor()
 4735                .timer(Duration::from_millis(debounce))
 4736                .await;
 4737
 4738            let highlights = if let Some(highlights) = cx
 4739                .update(|cx| {
 4740                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4741                })
 4742                .ok()
 4743                .flatten()
 4744            {
 4745                highlights.await.log_err()
 4746            } else {
 4747                None
 4748            };
 4749
 4750            if let Some(highlights) = highlights {
 4751                this.update(&mut cx, |this, cx| {
 4752                    if this.pending_rename.is_some() {
 4753                        return;
 4754                    }
 4755
 4756                    let buffer_id = cursor_position.buffer_id;
 4757                    let buffer = this.buffer.read(cx);
 4758                    if !buffer
 4759                        .text_anchor_for_position(cursor_position, cx)
 4760                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4761                    {
 4762                        return;
 4763                    }
 4764
 4765                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4766                    let mut write_ranges = Vec::new();
 4767                    let mut read_ranges = Vec::new();
 4768                    for highlight in highlights {
 4769                        for (excerpt_id, excerpt_range) in
 4770                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4771                        {
 4772                            let start = highlight
 4773                                .range
 4774                                .start
 4775                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4776                            let end = highlight
 4777                                .range
 4778                                .end
 4779                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4780                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4781                                continue;
 4782                            }
 4783
 4784                            let range = Anchor {
 4785                                buffer_id,
 4786                                excerpt_id,
 4787                                text_anchor: start,
 4788                                diff_base_anchor: None,
 4789                            }..Anchor {
 4790                                buffer_id,
 4791                                excerpt_id,
 4792                                text_anchor: end,
 4793                                diff_base_anchor: None,
 4794                            };
 4795                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4796                                write_ranges.push(range);
 4797                            } else {
 4798                                read_ranges.push(range);
 4799                            }
 4800                        }
 4801                    }
 4802
 4803                    this.highlight_background::<DocumentHighlightRead>(
 4804                        &read_ranges,
 4805                        |theme| theme.editor_document_highlight_read_background,
 4806                        cx,
 4807                    );
 4808                    this.highlight_background::<DocumentHighlightWrite>(
 4809                        &write_ranges,
 4810                        |theme| theme.editor_document_highlight_write_background,
 4811                        cx,
 4812                    );
 4813                    cx.notify();
 4814                })
 4815                .log_err();
 4816            }
 4817        }));
 4818        None
 4819    }
 4820
 4821    pub fn refresh_selected_text_highlights(
 4822        &mut self,
 4823        window: &mut Window,
 4824        cx: &mut Context<Editor>,
 4825    ) {
 4826        self.selection_highlight_task.take();
 4827        if !EditorSettings::get_global(cx).selection_highlight {
 4828            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4829            return;
 4830        }
 4831        if self.selections.count() != 1 || self.selections.line_mode {
 4832            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4833            return;
 4834        }
 4835        let selection = self.selections.newest::<Point>(cx);
 4836        if selection.is_empty() || selection.start.row != selection.end.row {
 4837            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4838            return;
 4839        }
 4840        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4841        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4842            cx.background_executor()
 4843                .timer(Duration::from_millis(debounce))
 4844                .await;
 4845            let Some(Some(matches_task)) = editor
 4846                .update_in(&mut cx, |editor, _, cx| {
 4847                    if editor.selections.count() != 1 || editor.selections.line_mode {
 4848                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4849                        return None;
 4850                    }
 4851                    let selection = editor.selections.newest::<Point>(cx);
 4852                    if selection.is_empty() || selection.start.row != selection.end.row {
 4853                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4854                        return None;
 4855                    }
 4856                    let buffer = editor.buffer().read(cx).snapshot(cx);
 4857                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 4858                    if query.trim().is_empty() {
 4859                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4860                        return None;
 4861                    }
 4862                    Some(cx.background_spawn(async move {
 4863                        let mut ranges = Vec::new();
 4864                        let selection_anchors = selection.range().to_anchors(&buffer);
 4865                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 4866                            for (search_buffer, search_range, excerpt_id) in
 4867                                buffer.range_to_buffer_ranges(range)
 4868                            {
 4869                                ranges.extend(
 4870                                    project::search::SearchQuery::text(
 4871                                        query.clone(),
 4872                                        false,
 4873                                        false,
 4874                                        false,
 4875                                        Default::default(),
 4876                                        Default::default(),
 4877                                        None,
 4878                                    )
 4879                                    .unwrap()
 4880                                    .search(search_buffer, Some(search_range.clone()))
 4881                                    .await
 4882                                    .into_iter()
 4883                                    .filter_map(
 4884                                        |match_range| {
 4885                                            let start = search_buffer.anchor_after(
 4886                                                search_range.start + match_range.start,
 4887                                            );
 4888                                            let end = search_buffer.anchor_before(
 4889                                                search_range.start + match_range.end,
 4890                                            );
 4891                                            let range = Anchor::range_in_buffer(
 4892                                                excerpt_id,
 4893                                                search_buffer.remote_id(),
 4894                                                start..end,
 4895                                            );
 4896                                            (range != selection_anchors).then_some(range)
 4897                                        },
 4898                                    ),
 4899                                );
 4900                            }
 4901                        }
 4902                        ranges
 4903                    }))
 4904                })
 4905                .log_err()
 4906            else {
 4907                return;
 4908            };
 4909            let matches = matches_task.await;
 4910            editor
 4911                .update_in(&mut cx, |editor, _, cx| {
 4912                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4913                    if !matches.is_empty() {
 4914                        editor.highlight_background::<SelectedTextHighlight>(
 4915                            &matches,
 4916                            |theme| theme.editor_document_highlight_bracket_background,
 4917                            cx,
 4918                        )
 4919                    }
 4920                })
 4921                .log_err();
 4922        }));
 4923    }
 4924
 4925    pub fn refresh_inline_completion(
 4926        &mut self,
 4927        debounce: bool,
 4928        user_requested: bool,
 4929        window: &mut Window,
 4930        cx: &mut Context<Self>,
 4931    ) -> Option<()> {
 4932        let provider = self.edit_prediction_provider()?;
 4933        let cursor = self.selections.newest_anchor().head();
 4934        let (buffer, cursor_buffer_position) =
 4935            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4936
 4937        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4938            self.discard_inline_completion(false, cx);
 4939            return None;
 4940        }
 4941
 4942        if !user_requested
 4943            && (!self.should_show_edit_predictions()
 4944                || !self.is_focused(window)
 4945                || buffer.read(cx).is_empty())
 4946        {
 4947            self.discard_inline_completion(false, cx);
 4948            return None;
 4949        }
 4950
 4951        self.update_visible_inline_completion(window, cx);
 4952        provider.refresh(
 4953            self.project.clone(),
 4954            buffer,
 4955            cursor_buffer_position,
 4956            debounce,
 4957            cx,
 4958        );
 4959        Some(())
 4960    }
 4961
 4962    fn show_edit_predictions_in_menu(&self) -> bool {
 4963        match self.edit_prediction_settings {
 4964            EditPredictionSettings::Disabled => false,
 4965            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4966        }
 4967    }
 4968
 4969    pub fn edit_predictions_enabled(&self) -> bool {
 4970        match self.edit_prediction_settings {
 4971            EditPredictionSettings::Disabled => false,
 4972            EditPredictionSettings::Enabled { .. } => true,
 4973        }
 4974    }
 4975
 4976    fn edit_prediction_requires_modifier(&self) -> bool {
 4977        match self.edit_prediction_settings {
 4978            EditPredictionSettings::Disabled => false,
 4979            EditPredictionSettings::Enabled {
 4980                preview_requires_modifier,
 4981                ..
 4982            } => preview_requires_modifier,
 4983        }
 4984    }
 4985
 4986    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 4987        if self.edit_prediction_provider.is_none() {
 4988            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 4989        } else {
 4990            let selection = self.selections.newest_anchor();
 4991            let cursor = selection.head();
 4992
 4993            if let Some((buffer, cursor_buffer_position)) =
 4994                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4995            {
 4996                self.edit_prediction_settings =
 4997                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 4998            }
 4999        }
 5000    }
 5001
 5002    fn edit_prediction_settings_at_position(
 5003        &self,
 5004        buffer: &Entity<Buffer>,
 5005        buffer_position: language::Anchor,
 5006        cx: &App,
 5007    ) -> EditPredictionSettings {
 5008        if self.mode != EditorMode::Full
 5009            || !self.show_inline_completions_override.unwrap_or(true)
 5010            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5011        {
 5012            return EditPredictionSettings::Disabled;
 5013        }
 5014
 5015        let buffer = buffer.read(cx);
 5016
 5017        let file = buffer.file();
 5018
 5019        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5020            return EditPredictionSettings::Disabled;
 5021        };
 5022
 5023        let by_provider = matches!(
 5024            self.menu_inline_completions_policy,
 5025            MenuInlineCompletionsPolicy::ByProvider
 5026        );
 5027
 5028        let show_in_menu = by_provider
 5029            && self
 5030                .edit_prediction_provider
 5031                .as_ref()
 5032                .map_or(false, |provider| {
 5033                    provider.provider.show_completions_in_menu()
 5034                });
 5035
 5036        let preview_requires_modifier =
 5037            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5038
 5039        EditPredictionSettings::Enabled {
 5040            show_in_menu,
 5041            preview_requires_modifier,
 5042        }
 5043    }
 5044
 5045    fn should_show_edit_predictions(&self) -> bool {
 5046        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5047    }
 5048
 5049    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5050        matches!(
 5051            self.edit_prediction_preview,
 5052            EditPredictionPreview::Active { .. }
 5053        )
 5054    }
 5055
 5056    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5057        let cursor = self.selections.newest_anchor().head();
 5058        if let Some((buffer, cursor_position)) =
 5059            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5060        {
 5061            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5062        } else {
 5063            false
 5064        }
 5065    }
 5066
 5067    fn edit_predictions_enabled_in_buffer(
 5068        &self,
 5069        buffer: &Entity<Buffer>,
 5070        buffer_position: language::Anchor,
 5071        cx: &App,
 5072    ) -> bool {
 5073        maybe!({
 5074            let provider = self.edit_prediction_provider()?;
 5075            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5076                return Some(false);
 5077            }
 5078            let buffer = buffer.read(cx);
 5079            let Some(file) = buffer.file() else {
 5080                return Some(true);
 5081            };
 5082            let settings = all_language_settings(Some(file), cx);
 5083            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5084        })
 5085        .unwrap_or(false)
 5086    }
 5087
 5088    fn cycle_inline_completion(
 5089        &mut self,
 5090        direction: Direction,
 5091        window: &mut Window,
 5092        cx: &mut Context<Self>,
 5093    ) -> Option<()> {
 5094        let provider = self.edit_prediction_provider()?;
 5095        let cursor = self.selections.newest_anchor().head();
 5096        let (buffer, cursor_buffer_position) =
 5097            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5098        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5099            return None;
 5100        }
 5101
 5102        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5103        self.update_visible_inline_completion(window, cx);
 5104
 5105        Some(())
 5106    }
 5107
 5108    pub fn show_inline_completion(
 5109        &mut self,
 5110        _: &ShowEditPrediction,
 5111        window: &mut Window,
 5112        cx: &mut Context<Self>,
 5113    ) {
 5114        if !self.has_active_inline_completion() {
 5115            self.refresh_inline_completion(false, true, window, cx);
 5116            return;
 5117        }
 5118
 5119        self.update_visible_inline_completion(window, cx);
 5120    }
 5121
 5122    pub fn display_cursor_names(
 5123        &mut self,
 5124        _: &DisplayCursorNames,
 5125        window: &mut Window,
 5126        cx: &mut Context<Self>,
 5127    ) {
 5128        self.show_cursor_names(window, cx);
 5129    }
 5130
 5131    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5132        self.show_cursor_names = true;
 5133        cx.notify();
 5134        cx.spawn_in(window, |this, mut cx| async move {
 5135            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5136            this.update(&mut cx, |this, cx| {
 5137                this.show_cursor_names = false;
 5138                cx.notify()
 5139            })
 5140            .ok()
 5141        })
 5142        .detach();
 5143    }
 5144
 5145    pub fn next_edit_prediction(
 5146        &mut self,
 5147        _: &NextEditPrediction,
 5148        window: &mut Window,
 5149        cx: &mut Context<Self>,
 5150    ) {
 5151        if self.has_active_inline_completion() {
 5152            self.cycle_inline_completion(Direction::Next, window, cx);
 5153        } else {
 5154            let is_copilot_disabled = self
 5155                .refresh_inline_completion(false, true, window, cx)
 5156                .is_none();
 5157            if is_copilot_disabled {
 5158                cx.propagate();
 5159            }
 5160        }
 5161    }
 5162
 5163    pub fn previous_edit_prediction(
 5164        &mut self,
 5165        _: &PreviousEditPrediction,
 5166        window: &mut Window,
 5167        cx: &mut Context<Self>,
 5168    ) {
 5169        if self.has_active_inline_completion() {
 5170            self.cycle_inline_completion(Direction::Prev, window, cx);
 5171        } else {
 5172            let is_copilot_disabled = self
 5173                .refresh_inline_completion(false, true, window, cx)
 5174                .is_none();
 5175            if is_copilot_disabled {
 5176                cx.propagate();
 5177            }
 5178        }
 5179    }
 5180
 5181    pub fn accept_edit_prediction(
 5182        &mut self,
 5183        _: &AcceptEditPrediction,
 5184        window: &mut Window,
 5185        cx: &mut Context<Self>,
 5186    ) {
 5187        if self.show_edit_predictions_in_menu() {
 5188            self.hide_context_menu(window, cx);
 5189        }
 5190
 5191        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5192            return;
 5193        };
 5194
 5195        self.report_inline_completion_event(
 5196            active_inline_completion.completion_id.clone(),
 5197            true,
 5198            cx,
 5199        );
 5200
 5201        match &active_inline_completion.completion {
 5202            InlineCompletion::Move { target, .. } => {
 5203                let target = *target;
 5204
 5205                if let Some(position_map) = &self.last_position_map {
 5206                    if position_map
 5207                        .visible_row_range
 5208                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5209                        || !self.edit_prediction_requires_modifier()
 5210                    {
 5211                        self.unfold_ranges(&[target..target], true, false, cx);
 5212                        // Note that this is also done in vim's handler of the Tab action.
 5213                        self.change_selections(
 5214                            Some(Autoscroll::newest()),
 5215                            window,
 5216                            cx,
 5217                            |selections| {
 5218                                selections.select_anchor_ranges([target..target]);
 5219                            },
 5220                        );
 5221                        self.clear_row_highlights::<EditPredictionPreview>();
 5222
 5223                        self.edit_prediction_preview
 5224                            .set_previous_scroll_position(None);
 5225                    } else {
 5226                        self.edit_prediction_preview
 5227                            .set_previous_scroll_position(Some(
 5228                                position_map.snapshot.scroll_anchor,
 5229                            ));
 5230
 5231                        self.highlight_rows::<EditPredictionPreview>(
 5232                            target..target,
 5233                            cx.theme().colors().editor_highlighted_line_background,
 5234                            true,
 5235                            cx,
 5236                        );
 5237                        self.request_autoscroll(Autoscroll::fit(), cx);
 5238                    }
 5239                }
 5240            }
 5241            InlineCompletion::Edit { edits, .. } => {
 5242                if let Some(provider) = self.edit_prediction_provider() {
 5243                    provider.accept(cx);
 5244                }
 5245
 5246                let snapshot = self.buffer.read(cx).snapshot(cx);
 5247                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5248
 5249                self.buffer.update(cx, |buffer, cx| {
 5250                    buffer.edit(edits.iter().cloned(), None, cx)
 5251                });
 5252
 5253                self.change_selections(None, window, cx, |s| {
 5254                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5255                });
 5256
 5257                self.update_visible_inline_completion(window, cx);
 5258                if self.active_inline_completion.is_none() {
 5259                    self.refresh_inline_completion(true, true, window, cx);
 5260                }
 5261
 5262                cx.notify();
 5263            }
 5264        }
 5265
 5266        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5267    }
 5268
 5269    pub fn accept_partial_inline_completion(
 5270        &mut self,
 5271        _: &AcceptPartialEditPrediction,
 5272        window: &mut Window,
 5273        cx: &mut Context<Self>,
 5274    ) {
 5275        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5276            return;
 5277        };
 5278        if self.selections.count() != 1 {
 5279            return;
 5280        }
 5281
 5282        self.report_inline_completion_event(
 5283            active_inline_completion.completion_id.clone(),
 5284            true,
 5285            cx,
 5286        );
 5287
 5288        match &active_inline_completion.completion {
 5289            InlineCompletion::Move { target, .. } => {
 5290                let target = *target;
 5291                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5292                    selections.select_anchor_ranges([target..target]);
 5293                });
 5294            }
 5295            InlineCompletion::Edit { edits, .. } => {
 5296                // Find an insertion that starts at the cursor position.
 5297                let snapshot = self.buffer.read(cx).snapshot(cx);
 5298                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5299                let insertion = edits.iter().find_map(|(range, text)| {
 5300                    let range = range.to_offset(&snapshot);
 5301                    if range.is_empty() && range.start == cursor_offset {
 5302                        Some(text)
 5303                    } else {
 5304                        None
 5305                    }
 5306                });
 5307
 5308                if let Some(text) = insertion {
 5309                    let mut partial_completion = text
 5310                        .chars()
 5311                        .by_ref()
 5312                        .take_while(|c| c.is_alphabetic())
 5313                        .collect::<String>();
 5314                    if partial_completion.is_empty() {
 5315                        partial_completion = text
 5316                            .chars()
 5317                            .by_ref()
 5318                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5319                            .collect::<String>();
 5320                    }
 5321
 5322                    cx.emit(EditorEvent::InputHandled {
 5323                        utf16_range_to_replace: None,
 5324                        text: partial_completion.clone().into(),
 5325                    });
 5326
 5327                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5328
 5329                    self.refresh_inline_completion(true, true, window, cx);
 5330                    cx.notify();
 5331                } else {
 5332                    self.accept_edit_prediction(&Default::default(), window, cx);
 5333                }
 5334            }
 5335        }
 5336    }
 5337
 5338    fn discard_inline_completion(
 5339        &mut self,
 5340        should_report_inline_completion_event: bool,
 5341        cx: &mut Context<Self>,
 5342    ) -> bool {
 5343        if should_report_inline_completion_event {
 5344            let completion_id = self
 5345                .active_inline_completion
 5346                .as_ref()
 5347                .and_then(|active_completion| active_completion.completion_id.clone());
 5348
 5349            self.report_inline_completion_event(completion_id, false, cx);
 5350        }
 5351
 5352        if let Some(provider) = self.edit_prediction_provider() {
 5353            provider.discard(cx);
 5354        }
 5355
 5356        self.take_active_inline_completion(cx)
 5357    }
 5358
 5359    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5360        let Some(provider) = self.edit_prediction_provider() else {
 5361            return;
 5362        };
 5363
 5364        let Some((_, buffer, _)) = self
 5365            .buffer
 5366            .read(cx)
 5367            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5368        else {
 5369            return;
 5370        };
 5371
 5372        let extension = buffer
 5373            .read(cx)
 5374            .file()
 5375            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5376
 5377        let event_type = match accepted {
 5378            true => "Edit Prediction Accepted",
 5379            false => "Edit Prediction Discarded",
 5380        };
 5381        telemetry::event!(
 5382            event_type,
 5383            provider = provider.name(),
 5384            prediction_id = id,
 5385            suggestion_accepted = accepted,
 5386            file_extension = extension,
 5387        );
 5388    }
 5389
 5390    pub fn has_active_inline_completion(&self) -> bool {
 5391        self.active_inline_completion.is_some()
 5392    }
 5393
 5394    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5395        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5396            return false;
 5397        };
 5398
 5399        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5400        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5401        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5402        true
 5403    }
 5404
 5405    /// Returns true when we're displaying the edit prediction popover below the cursor
 5406    /// like we are not previewing and the LSP autocomplete menu is visible
 5407    /// or we are in `when_holding_modifier` mode.
 5408    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5409        if self.edit_prediction_preview_is_active()
 5410            || !self.show_edit_predictions_in_menu()
 5411            || !self.edit_predictions_enabled()
 5412        {
 5413            return false;
 5414        }
 5415
 5416        if self.has_visible_completions_menu() {
 5417            return true;
 5418        }
 5419
 5420        has_completion && self.edit_prediction_requires_modifier()
 5421    }
 5422
 5423    fn handle_modifiers_changed(
 5424        &mut self,
 5425        modifiers: Modifiers,
 5426        position_map: &PositionMap,
 5427        window: &mut Window,
 5428        cx: &mut Context<Self>,
 5429    ) {
 5430        if self.show_edit_predictions_in_menu() {
 5431            self.update_edit_prediction_preview(&modifiers, window, cx);
 5432        }
 5433
 5434        self.update_selection_mode(&modifiers, position_map, window, cx);
 5435
 5436        let mouse_position = window.mouse_position();
 5437        if !position_map.text_hitbox.is_hovered(window) {
 5438            return;
 5439        }
 5440
 5441        self.update_hovered_link(
 5442            position_map.point_for_position(mouse_position),
 5443            &position_map.snapshot,
 5444            modifiers,
 5445            window,
 5446            cx,
 5447        )
 5448    }
 5449
 5450    fn update_selection_mode(
 5451        &mut self,
 5452        modifiers: &Modifiers,
 5453        position_map: &PositionMap,
 5454        window: &mut Window,
 5455        cx: &mut Context<Self>,
 5456    ) {
 5457        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5458            return;
 5459        }
 5460
 5461        let mouse_position = window.mouse_position();
 5462        let point_for_position = position_map.point_for_position(mouse_position);
 5463        let position = point_for_position.previous_valid;
 5464
 5465        self.select(
 5466            SelectPhase::BeginColumnar {
 5467                position,
 5468                reset: false,
 5469                goal_column: point_for_position.exact_unclipped.column(),
 5470            },
 5471            window,
 5472            cx,
 5473        );
 5474    }
 5475
 5476    fn update_edit_prediction_preview(
 5477        &mut self,
 5478        modifiers: &Modifiers,
 5479        window: &mut Window,
 5480        cx: &mut Context<Self>,
 5481    ) {
 5482        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5483        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5484            return;
 5485        };
 5486
 5487        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5488            if matches!(
 5489                self.edit_prediction_preview,
 5490                EditPredictionPreview::Inactive { .. }
 5491            ) {
 5492                self.edit_prediction_preview = EditPredictionPreview::Active {
 5493                    previous_scroll_position: None,
 5494                    since: Instant::now(),
 5495                };
 5496
 5497                self.update_visible_inline_completion(window, cx);
 5498                cx.notify();
 5499            }
 5500        } else if let EditPredictionPreview::Active {
 5501            previous_scroll_position,
 5502            since,
 5503        } = self.edit_prediction_preview
 5504        {
 5505            if let (Some(previous_scroll_position), Some(position_map)) =
 5506                (previous_scroll_position, self.last_position_map.as_ref())
 5507            {
 5508                self.set_scroll_position(
 5509                    previous_scroll_position
 5510                        .scroll_position(&position_map.snapshot.display_snapshot),
 5511                    window,
 5512                    cx,
 5513                );
 5514            }
 5515
 5516            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 5517                released_too_fast: since.elapsed() < Duration::from_millis(200),
 5518            };
 5519            self.clear_row_highlights::<EditPredictionPreview>();
 5520            self.update_visible_inline_completion(window, cx);
 5521            cx.notify();
 5522        }
 5523    }
 5524
 5525    fn update_visible_inline_completion(
 5526        &mut self,
 5527        _window: &mut Window,
 5528        cx: &mut Context<Self>,
 5529    ) -> Option<()> {
 5530        let selection = self.selections.newest_anchor();
 5531        let cursor = selection.head();
 5532        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5533        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5534        let excerpt_id = cursor.excerpt_id;
 5535
 5536        let show_in_menu = self.show_edit_predictions_in_menu();
 5537        let completions_menu_has_precedence = !show_in_menu
 5538            && (self.context_menu.borrow().is_some()
 5539                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5540
 5541        if completions_menu_has_precedence
 5542            || !offset_selection.is_empty()
 5543            || self
 5544                .active_inline_completion
 5545                .as_ref()
 5546                .map_or(false, |completion| {
 5547                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5548                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5549                    !invalidation_range.contains(&offset_selection.head())
 5550                })
 5551        {
 5552            self.discard_inline_completion(false, cx);
 5553            return None;
 5554        }
 5555
 5556        self.take_active_inline_completion(cx);
 5557        let Some(provider) = self.edit_prediction_provider() else {
 5558            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5559            return None;
 5560        };
 5561
 5562        let (buffer, cursor_buffer_position) =
 5563            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5564
 5565        self.edit_prediction_settings =
 5566            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5567
 5568        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 5569
 5570        if self.edit_prediction_indent_conflict {
 5571            let cursor_point = cursor.to_point(&multibuffer);
 5572
 5573            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 5574
 5575            if let Some((_, indent)) = indents.iter().next() {
 5576                if indent.len == cursor_point.column {
 5577                    self.edit_prediction_indent_conflict = false;
 5578                }
 5579            }
 5580        }
 5581
 5582        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5583        let edits = inline_completion
 5584            .edits
 5585            .into_iter()
 5586            .flat_map(|(range, new_text)| {
 5587                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5588                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5589                Some((start..end, new_text))
 5590            })
 5591            .collect::<Vec<_>>();
 5592        if edits.is_empty() {
 5593            return None;
 5594        }
 5595
 5596        let first_edit_start = edits.first().unwrap().0.start;
 5597        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5598        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5599
 5600        let last_edit_end = edits.last().unwrap().0.end;
 5601        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5602        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5603
 5604        let cursor_row = cursor.to_point(&multibuffer).row;
 5605
 5606        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5607
 5608        let mut inlay_ids = Vec::new();
 5609        let invalidation_row_range;
 5610        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5611            Some(cursor_row..edit_end_row)
 5612        } else if cursor_row > edit_end_row {
 5613            Some(edit_start_row..cursor_row)
 5614        } else {
 5615            None
 5616        };
 5617        let is_move =
 5618            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5619        let completion = if is_move {
 5620            invalidation_row_range =
 5621                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5622            let target = first_edit_start;
 5623            InlineCompletion::Move { target, snapshot }
 5624        } else {
 5625            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5626                && !self.inline_completions_hidden_for_vim_mode;
 5627
 5628            if show_completions_in_buffer {
 5629                if edits
 5630                    .iter()
 5631                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5632                {
 5633                    let mut inlays = Vec::new();
 5634                    for (range, new_text) in &edits {
 5635                        let inlay = Inlay::inline_completion(
 5636                            post_inc(&mut self.next_inlay_id),
 5637                            range.start,
 5638                            new_text.as_str(),
 5639                        );
 5640                        inlay_ids.push(inlay.id);
 5641                        inlays.push(inlay);
 5642                    }
 5643
 5644                    self.splice_inlays(&[], inlays, cx);
 5645                } else {
 5646                    let background_color = cx.theme().status().deleted_background;
 5647                    self.highlight_text::<InlineCompletionHighlight>(
 5648                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5649                        HighlightStyle {
 5650                            background_color: Some(background_color),
 5651                            ..Default::default()
 5652                        },
 5653                        cx,
 5654                    );
 5655                }
 5656            }
 5657
 5658            invalidation_row_range = edit_start_row..edit_end_row;
 5659
 5660            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5661                if provider.show_tab_accept_marker() {
 5662                    EditDisplayMode::TabAccept
 5663                } else {
 5664                    EditDisplayMode::Inline
 5665                }
 5666            } else {
 5667                EditDisplayMode::DiffPopover
 5668            };
 5669
 5670            InlineCompletion::Edit {
 5671                edits,
 5672                edit_preview: inline_completion.edit_preview,
 5673                display_mode,
 5674                snapshot,
 5675            }
 5676        };
 5677
 5678        let invalidation_range = multibuffer
 5679            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5680            ..multibuffer.anchor_after(Point::new(
 5681                invalidation_row_range.end,
 5682                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5683            ));
 5684
 5685        self.stale_inline_completion_in_menu = None;
 5686        self.active_inline_completion = Some(InlineCompletionState {
 5687            inlay_ids,
 5688            completion,
 5689            completion_id: inline_completion.id,
 5690            invalidation_range,
 5691        });
 5692
 5693        cx.notify();
 5694
 5695        Some(())
 5696    }
 5697
 5698    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5699        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5700    }
 5701
 5702    fn render_code_actions_indicator(
 5703        &self,
 5704        _style: &EditorStyle,
 5705        row: DisplayRow,
 5706        is_active: bool,
 5707        cx: &mut Context<Self>,
 5708    ) -> Option<IconButton> {
 5709        if self.available_code_actions.is_some() {
 5710            Some(
 5711                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5712                    .shape(ui::IconButtonShape::Square)
 5713                    .icon_size(IconSize::XSmall)
 5714                    .icon_color(Color::Muted)
 5715                    .toggle_state(is_active)
 5716                    .tooltip({
 5717                        let focus_handle = self.focus_handle.clone();
 5718                        move |window, cx| {
 5719                            Tooltip::for_action_in(
 5720                                "Toggle Code Actions",
 5721                                &ToggleCodeActions {
 5722                                    deployed_from_indicator: None,
 5723                                },
 5724                                &focus_handle,
 5725                                window,
 5726                                cx,
 5727                            )
 5728                        }
 5729                    })
 5730                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5731                        window.focus(&editor.focus_handle(cx));
 5732                        editor.toggle_code_actions(
 5733                            &ToggleCodeActions {
 5734                                deployed_from_indicator: Some(row),
 5735                            },
 5736                            window,
 5737                            cx,
 5738                        );
 5739                    })),
 5740            )
 5741        } else {
 5742            None
 5743        }
 5744    }
 5745
 5746    fn clear_tasks(&mut self) {
 5747        self.tasks.clear()
 5748    }
 5749
 5750    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5751        if self.tasks.insert(key, value).is_some() {
 5752            // This case should hopefully be rare, but just in case...
 5753            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5754        }
 5755    }
 5756
 5757    fn build_tasks_context(
 5758        project: &Entity<Project>,
 5759        buffer: &Entity<Buffer>,
 5760        buffer_row: u32,
 5761        tasks: &Arc<RunnableTasks>,
 5762        cx: &mut Context<Self>,
 5763    ) -> Task<Option<task::TaskContext>> {
 5764        let position = Point::new(buffer_row, tasks.column);
 5765        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5766        let location = Location {
 5767            buffer: buffer.clone(),
 5768            range: range_start..range_start,
 5769        };
 5770        // Fill in the environmental variables from the tree-sitter captures
 5771        let mut captured_task_variables = TaskVariables::default();
 5772        for (capture_name, value) in tasks.extra_variables.clone() {
 5773            captured_task_variables.insert(
 5774                task::VariableName::Custom(capture_name.into()),
 5775                value.clone(),
 5776            );
 5777        }
 5778        project.update(cx, |project, cx| {
 5779            project.task_store().update(cx, |task_store, cx| {
 5780                task_store.task_context_for_location(captured_task_variables, location, cx)
 5781            })
 5782        })
 5783    }
 5784
 5785    pub fn spawn_nearest_task(
 5786        &mut self,
 5787        action: &SpawnNearestTask,
 5788        window: &mut Window,
 5789        cx: &mut Context<Self>,
 5790    ) {
 5791        let Some((workspace, _)) = self.workspace.clone() else {
 5792            return;
 5793        };
 5794        let Some(project) = self.project.clone() else {
 5795            return;
 5796        };
 5797
 5798        // Try to find a closest, enclosing node using tree-sitter that has a
 5799        // task
 5800        let Some((buffer, buffer_row, tasks)) = self
 5801            .find_enclosing_node_task(cx)
 5802            // Or find the task that's closest in row-distance.
 5803            .or_else(|| self.find_closest_task(cx))
 5804        else {
 5805            return;
 5806        };
 5807
 5808        let reveal_strategy = action.reveal;
 5809        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5810        cx.spawn_in(window, |_, mut cx| async move {
 5811            let context = task_context.await?;
 5812            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5813
 5814            let resolved = resolved_task.resolved.as_mut()?;
 5815            resolved.reveal = reveal_strategy;
 5816
 5817            workspace
 5818                .update(&mut cx, |workspace, cx| {
 5819                    workspace::tasks::schedule_resolved_task(
 5820                        workspace,
 5821                        task_source_kind,
 5822                        resolved_task,
 5823                        false,
 5824                        cx,
 5825                    );
 5826                })
 5827                .ok()
 5828        })
 5829        .detach();
 5830    }
 5831
 5832    fn find_closest_task(
 5833        &mut self,
 5834        cx: &mut Context<Self>,
 5835    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5836        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5837
 5838        let ((buffer_id, row), tasks) = self
 5839            .tasks
 5840            .iter()
 5841            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5842
 5843        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5844        let tasks = Arc::new(tasks.to_owned());
 5845        Some((buffer, *row, tasks))
 5846    }
 5847
 5848    fn find_enclosing_node_task(
 5849        &mut self,
 5850        cx: &mut Context<Self>,
 5851    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5852        let snapshot = self.buffer.read(cx).snapshot(cx);
 5853        let offset = self.selections.newest::<usize>(cx).head();
 5854        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5855        let buffer_id = excerpt.buffer().remote_id();
 5856
 5857        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5858        let mut cursor = layer.node().walk();
 5859
 5860        while cursor.goto_first_child_for_byte(offset).is_some() {
 5861            if cursor.node().end_byte() == offset {
 5862                cursor.goto_next_sibling();
 5863            }
 5864        }
 5865
 5866        // Ascend to the smallest ancestor that contains the range and has a task.
 5867        loop {
 5868            let node = cursor.node();
 5869            let node_range = node.byte_range();
 5870            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5871
 5872            // Check if this node contains our offset
 5873            if node_range.start <= offset && node_range.end >= offset {
 5874                // If it contains offset, check for task
 5875                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5876                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5877                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5878                }
 5879            }
 5880
 5881            if !cursor.goto_parent() {
 5882                break;
 5883            }
 5884        }
 5885        None
 5886    }
 5887
 5888    fn render_run_indicator(
 5889        &self,
 5890        _style: &EditorStyle,
 5891        is_active: bool,
 5892        row: DisplayRow,
 5893        cx: &mut Context<Self>,
 5894    ) -> IconButton {
 5895        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5896            .shape(ui::IconButtonShape::Square)
 5897            .icon_size(IconSize::XSmall)
 5898            .icon_color(Color::Muted)
 5899            .toggle_state(is_active)
 5900            .on_click(cx.listener(move |editor, _e, window, cx| {
 5901                window.focus(&editor.focus_handle(cx));
 5902                editor.toggle_code_actions(
 5903                    &ToggleCodeActions {
 5904                        deployed_from_indicator: Some(row),
 5905                    },
 5906                    window,
 5907                    cx,
 5908                );
 5909            }))
 5910    }
 5911
 5912    pub fn context_menu_visible(&self) -> bool {
 5913        !self.edit_prediction_preview_is_active()
 5914            && self
 5915                .context_menu
 5916                .borrow()
 5917                .as_ref()
 5918                .map_or(false, |menu| menu.visible())
 5919    }
 5920
 5921    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5922        self.context_menu
 5923            .borrow()
 5924            .as_ref()
 5925            .map(|menu| menu.origin())
 5926    }
 5927
 5928    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 5929    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 5930
 5931    #[allow(clippy::too_many_arguments)]
 5932    fn render_edit_prediction_popover(
 5933        &mut self,
 5934        text_bounds: &Bounds<Pixels>,
 5935        content_origin: gpui::Point<Pixels>,
 5936        editor_snapshot: &EditorSnapshot,
 5937        visible_row_range: Range<DisplayRow>,
 5938        scroll_top: f32,
 5939        scroll_bottom: f32,
 5940        line_layouts: &[LineWithInvisibles],
 5941        line_height: Pixels,
 5942        scroll_pixel_position: gpui::Point<Pixels>,
 5943        newest_selection_head: Option<DisplayPoint>,
 5944        editor_width: Pixels,
 5945        style: &EditorStyle,
 5946        window: &mut Window,
 5947        cx: &mut App,
 5948    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5949        let active_inline_completion = self.active_inline_completion.as_ref()?;
 5950
 5951        if self.edit_prediction_visible_in_cursor_popover(true) {
 5952            return None;
 5953        }
 5954
 5955        match &active_inline_completion.completion {
 5956            InlineCompletion::Move { target, .. } => {
 5957                let target_display_point = target.to_display_point(editor_snapshot);
 5958
 5959                if self.edit_prediction_requires_modifier() {
 5960                    if !self.edit_prediction_preview_is_active() {
 5961                        return None;
 5962                    }
 5963
 5964                    self.render_edit_prediction_modifier_jump_popover(
 5965                        text_bounds,
 5966                        content_origin,
 5967                        visible_row_range,
 5968                        line_layouts,
 5969                        line_height,
 5970                        scroll_pixel_position,
 5971                        newest_selection_head,
 5972                        target_display_point,
 5973                        window,
 5974                        cx,
 5975                    )
 5976                } else {
 5977                    self.render_edit_prediction_eager_jump_popover(
 5978                        text_bounds,
 5979                        content_origin,
 5980                        editor_snapshot,
 5981                        visible_row_range,
 5982                        scroll_top,
 5983                        scroll_bottom,
 5984                        line_height,
 5985                        scroll_pixel_position,
 5986                        target_display_point,
 5987                        editor_width,
 5988                        window,
 5989                        cx,
 5990                    )
 5991                }
 5992            }
 5993            InlineCompletion::Edit {
 5994                display_mode: EditDisplayMode::Inline,
 5995                ..
 5996            } => None,
 5997            InlineCompletion::Edit {
 5998                display_mode: EditDisplayMode::TabAccept,
 5999                edits,
 6000                ..
 6001            } => {
 6002                let range = &edits.first()?.0;
 6003                let target_display_point = range.end.to_display_point(editor_snapshot);
 6004
 6005                self.render_edit_prediction_end_of_line_popover(
 6006                    "Accept",
 6007                    editor_snapshot,
 6008                    visible_row_range,
 6009                    target_display_point,
 6010                    line_height,
 6011                    scroll_pixel_position,
 6012                    content_origin,
 6013                    editor_width,
 6014                    window,
 6015                    cx,
 6016                )
 6017            }
 6018            InlineCompletion::Edit {
 6019                edits,
 6020                edit_preview,
 6021                display_mode: EditDisplayMode::DiffPopover,
 6022                snapshot,
 6023            } => self.render_edit_prediction_diff_popover(
 6024                text_bounds,
 6025                content_origin,
 6026                editor_snapshot,
 6027                visible_row_range,
 6028                line_layouts,
 6029                line_height,
 6030                scroll_pixel_position,
 6031                newest_selection_head,
 6032                editor_width,
 6033                style,
 6034                edits,
 6035                edit_preview,
 6036                snapshot,
 6037                window,
 6038                cx,
 6039            ),
 6040        }
 6041    }
 6042
 6043    #[allow(clippy::too_many_arguments)]
 6044    fn render_edit_prediction_modifier_jump_popover(
 6045        &mut self,
 6046        text_bounds: &Bounds<Pixels>,
 6047        content_origin: gpui::Point<Pixels>,
 6048        visible_row_range: Range<DisplayRow>,
 6049        line_layouts: &[LineWithInvisibles],
 6050        line_height: Pixels,
 6051        scroll_pixel_position: gpui::Point<Pixels>,
 6052        newest_selection_head: Option<DisplayPoint>,
 6053        target_display_point: DisplayPoint,
 6054        window: &mut Window,
 6055        cx: &mut App,
 6056    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6057        let scrolled_content_origin =
 6058            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 6059
 6060        const SCROLL_PADDING_Y: Pixels = px(12.);
 6061
 6062        if target_display_point.row() < visible_row_range.start {
 6063            return self.render_edit_prediction_scroll_popover(
 6064                |_| SCROLL_PADDING_Y,
 6065                IconName::ArrowUp,
 6066                visible_row_range,
 6067                line_layouts,
 6068                newest_selection_head,
 6069                scrolled_content_origin,
 6070                window,
 6071                cx,
 6072            );
 6073        } else if target_display_point.row() >= visible_row_range.end {
 6074            return self.render_edit_prediction_scroll_popover(
 6075                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 6076                IconName::ArrowDown,
 6077                visible_row_range,
 6078                line_layouts,
 6079                newest_selection_head,
 6080                scrolled_content_origin,
 6081                window,
 6082                cx,
 6083            );
 6084        }
 6085
 6086        const POLE_WIDTH: Pixels = px(2.);
 6087
 6088        let line_layout =
 6089            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 6090        let target_column = target_display_point.column() as usize;
 6091
 6092        let target_x = line_layout.x_for_index(target_column);
 6093        let target_y =
 6094            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 6095
 6096        let flag_on_right = target_x < text_bounds.size.width / 2.;
 6097
 6098        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 6099        border_color.l += 0.001;
 6100
 6101        let mut element = v_flex()
 6102            .items_end()
 6103            .when(flag_on_right, |el| el.items_start())
 6104            .child(if flag_on_right {
 6105                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6106                    .rounded_bl(px(0.))
 6107                    .rounded_tl(px(0.))
 6108                    .border_l_2()
 6109                    .border_color(border_color)
 6110            } else {
 6111                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6112                    .rounded_br(px(0.))
 6113                    .rounded_tr(px(0.))
 6114                    .border_r_2()
 6115                    .border_color(border_color)
 6116            })
 6117            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 6118            .into_any();
 6119
 6120        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6121
 6122        let mut origin = scrolled_content_origin + point(target_x, target_y)
 6123            - point(
 6124                if flag_on_right {
 6125                    POLE_WIDTH
 6126                } else {
 6127                    size.width - POLE_WIDTH
 6128                },
 6129                size.height - line_height,
 6130            );
 6131
 6132        origin.x = origin.x.max(content_origin.x);
 6133
 6134        element.prepaint_at(origin, window, cx);
 6135
 6136        Some((element, origin))
 6137    }
 6138
 6139    #[allow(clippy::too_many_arguments)]
 6140    fn render_edit_prediction_scroll_popover(
 6141        &mut self,
 6142        to_y: impl Fn(Size<Pixels>) -> Pixels,
 6143        scroll_icon: IconName,
 6144        visible_row_range: Range<DisplayRow>,
 6145        line_layouts: &[LineWithInvisibles],
 6146        newest_selection_head: Option<DisplayPoint>,
 6147        scrolled_content_origin: gpui::Point<Pixels>,
 6148        window: &mut Window,
 6149        cx: &mut App,
 6150    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6151        let mut element = self
 6152            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 6153            .into_any();
 6154
 6155        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6156
 6157        let cursor = newest_selection_head?;
 6158        let cursor_row_layout =
 6159            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6160        let cursor_column = cursor.column() as usize;
 6161
 6162        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6163
 6164        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6165
 6166        element.prepaint_at(origin, window, cx);
 6167        Some((element, origin))
 6168    }
 6169
 6170    #[allow(clippy::too_many_arguments)]
 6171    fn render_edit_prediction_eager_jump_popover(
 6172        &mut self,
 6173        text_bounds: &Bounds<Pixels>,
 6174        content_origin: gpui::Point<Pixels>,
 6175        editor_snapshot: &EditorSnapshot,
 6176        visible_row_range: Range<DisplayRow>,
 6177        scroll_top: f32,
 6178        scroll_bottom: f32,
 6179        line_height: Pixels,
 6180        scroll_pixel_position: gpui::Point<Pixels>,
 6181        target_display_point: DisplayPoint,
 6182        editor_width: Pixels,
 6183        window: &mut Window,
 6184        cx: &mut App,
 6185    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6186        if target_display_point.row().as_f32() < scroll_top {
 6187            let mut element = self
 6188                .render_edit_prediction_line_popover(
 6189                    "Jump to Edit",
 6190                    Some(IconName::ArrowUp),
 6191                    window,
 6192                    cx,
 6193                )?
 6194                .into_any();
 6195
 6196            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6197            let offset = point(
 6198                (text_bounds.size.width - size.width) / 2.,
 6199                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6200            );
 6201
 6202            let origin = text_bounds.origin + offset;
 6203            element.prepaint_at(origin, window, cx);
 6204            Some((element, origin))
 6205        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6206            let mut element = self
 6207                .render_edit_prediction_line_popover(
 6208                    "Jump to Edit",
 6209                    Some(IconName::ArrowDown),
 6210                    window,
 6211                    cx,
 6212                )?
 6213                .into_any();
 6214
 6215            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6216            let offset = point(
 6217                (text_bounds.size.width - size.width) / 2.,
 6218                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6219            );
 6220
 6221            let origin = text_bounds.origin + offset;
 6222            element.prepaint_at(origin, window, cx);
 6223            Some((element, origin))
 6224        } else {
 6225            self.render_edit_prediction_end_of_line_popover(
 6226                "Jump to Edit",
 6227                editor_snapshot,
 6228                visible_row_range,
 6229                target_display_point,
 6230                line_height,
 6231                scroll_pixel_position,
 6232                content_origin,
 6233                editor_width,
 6234                window,
 6235                cx,
 6236            )
 6237        }
 6238    }
 6239
 6240    #[allow(clippy::too_many_arguments)]
 6241    fn render_edit_prediction_end_of_line_popover(
 6242        self: &mut Editor,
 6243        label: &'static str,
 6244        editor_snapshot: &EditorSnapshot,
 6245        visible_row_range: Range<DisplayRow>,
 6246        target_display_point: DisplayPoint,
 6247        line_height: Pixels,
 6248        scroll_pixel_position: gpui::Point<Pixels>,
 6249        content_origin: gpui::Point<Pixels>,
 6250        editor_width: Pixels,
 6251        window: &mut Window,
 6252        cx: &mut App,
 6253    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6254        let target_line_end = DisplayPoint::new(
 6255            target_display_point.row(),
 6256            editor_snapshot.line_len(target_display_point.row()),
 6257        );
 6258
 6259        let mut element = self
 6260            .render_edit_prediction_line_popover(label, None, window, cx)?
 6261            .into_any();
 6262
 6263        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6264
 6265        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 6266
 6267        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 6268        let mut origin = start_point
 6269            + line_origin
 6270            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 6271        origin.x = origin.x.max(content_origin.x);
 6272
 6273        let max_x = content_origin.x + editor_width - size.width;
 6274
 6275        if origin.x > max_x {
 6276            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 6277
 6278            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 6279                origin.y += offset;
 6280                IconName::ArrowUp
 6281            } else {
 6282                origin.y -= offset;
 6283                IconName::ArrowDown
 6284            };
 6285
 6286            element = self
 6287                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 6288                .into_any();
 6289
 6290            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6291
 6292            origin.x = content_origin.x + editor_width - size.width - px(2.);
 6293        }
 6294
 6295        element.prepaint_at(origin, window, cx);
 6296        Some((element, origin))
 6297    }
 6298
 6299    #[allow(clippy::too_many_arguments)]
 6300    fn render_edit_prediction_diff_popover(
 6301        self: &Editor,
 6302        text_bounds: &Bounds<Pixels>,
 6303        content_origin: gpui::Point<Pixels>,
 6304        editor_snapshot: &EditorSnapshot,
 6305        visible_row_range: Range<DisplayRow>,
 6306        line_layouts: &[LineWithInvisibles],
 6307        line_height: Pixels,
 6308        scroll_pixel_position: gpui::Point<Pixels>,
 6309        newest_selection_head: Option<DisplayPoint>,
 6310        editor_width: Pixels,
 6311        style: &EditorStyle,
 6312        edits: &Vec<(Range<Anchor>, String)>,
 6313        edit_preview: &Option<language::EditPreview>,
 6314        snapshot: &language::BufferSnapshot,
 6315        window: &mut Window,
 6316        cx: &mut App,
 6317    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6318        let edit_start = edits
 6319            .first()
 6320            .unwrap()
 6321            .0
 6322            .start
 6323            .to_display_point(editor_snapshot);
 6324        let edit_end = edits
 6325            .last()
 6326            .unwrap()
 6327            .0
 6328            .end
 6329            .to_display_point(editor_snapshot);
 6330
 6331        let is_visible = visible_row_range.contains(&edit_start.row())
 6332            || visible_row_range.contains(&edit_end.row());
 6333        if !is_visible {
 6334            return None;
 6335        }
 6336
 6337        let highlighted_edits =
 6338            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 6339
 6340        let styled_text = highlighted_edits.to_styled_text(&style.text);
 6341        let line_count = highlighted_edits.text.lines().count();
 6342
 6343        const BORDER_WIDTH: Pixels = px(1.);
 6344
 6345        let mut element = h_flex()
 6346            .items_start()
 6347            .child(
 6348                h_flex()
 6349                    .bg(cx.theme().colors().editor_background)
 6350                    .border(BORDER_WIDTH)
 6351                    .shadow_sm()
 6352                    .border_color(cx.theme().colors().border)
 6353                    .rounded_l_lg()
 6354                    .when(line_count > 1, |el| el.rounded_br_lg())
 6355                    .pr_1()
 6356                    .child(styled_text),
 6357            )
 6358            .child(
 6359                h_flex()
 6360                    .h(line_height + BORDER_WIDTH * px(2.))
 6361                    .px_1p5()
 6362                    .gap_1()
 6363                    // Workaround: For some reason, there's a gap if we don't do this
 6364                    .ml(-BORDER_WIDTH)
 6365                    .shadow(smallvec![gpui::BoxShadow {
 6366                        color: gpui::black().opacity(0.05),
 6367                        offset: point(px(1.), px(1.)),
 6368                        blur_radius: px(2.),
 6369                        spread_radius: px(0.),
 6370                    }])
 6371                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 6372                    .border(BORDER_WIDTH)
 6373                    .border_color(cx.theme().colors().border)
 6374                    .rounded_r_lg()
 6375                    .children(self.render_edit_prediction_accept_keybind(window, cx)),
 6376            )
 6377            .into_any();
 6378
 6379        let longest_row =
 6380            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 6381        let longest_line_width = if visible_row_range.contains(&longest_row) {
 6382            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 6383        } else {
 6384            layout_line(
 6385                longest_row,
 6386                editor_snapshot,
 6387                style,
 6388                editor_width,
 6389                |_| false,
 6390                window,
 6391                cx,
 6392            )
 6393            .width
 6394        };
 6395
 6396        let viewport_bounds =
 6397            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 6398                right: -EditorElement::SCROLLBAR_WIDTH,
 6399                ..Default::default()
 6400            });
 6401
 6402        let x_after_longest =
 6403            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 6404                - scroll_pixel_position.x;
 6405
 6406        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6407
 6408        // Fully visible if it can be displayed within the window (allow overlapping other
 6409        // panes). However, this is only allowed if the popover starts within text_bounds.
 6410        let can_position_to_the_right = x_after_longest < text_bounds.right()
 6411            && x_after_longest + element_bounds.width < viewport_bounds.right();
 6412
 6413        let mut origin = if can_position_to_the_right {
 6414            point(
 6415                x_after_longest,
 6416                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 6417                    - scroll_pixel_position.y,
 6418            )
 6419        } else {
 6420            let cursor_row = newest_selection_head.map(|head| head.row());
 6421            let above_edit = edit_start
 6422                .row()
 6423                .0
 6424                .checked_sub(line_count as u32)
 6425                .map(DisplayRow);
 6426            let below_edit = Some(edit_end.row() + 1);
 6427            let above_cursor =
 6428                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 6429            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 6430
 6431            // Place the edit popover adjacent to the edit if there is a location
 6432            // available that is onscreen and does not obscure the cursor. Otherwise,
 6433            // place it adjacent to the cursor.
 6434            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 6435                .into_iter()
 6436                .flatten()
 6437                .find(|&start_row| {
 6438                    let end_row = start_row + line_count as u32;
 6439                    visible_row_range.contains(&start_row)
 6440                        && visible_row_range.contains(&end_row)
 6441                        && cursor_row.map_or(true, |cursor_row| {
 6442                            !((start_row..end_row).contains(&cursor_row))
 6443                        })
 6444                })?;
 6445
 6446            content_origin
 6447                + point(
 6448                    -scroll_pixel_position.x,
 6449                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 6450                )
 6451        };
 6452
 6453        origin.x -= BORDER_WIDTH;
 6454
 6455        window.defer_draw(element, origin, 1);
 6456
 6457        // Do not return an element, since it will already be drawn due to defer_draw.
 6458        None
 6459    }
 6460
 6461    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 6462        px(30.)
 6463    }
 6464
 6465    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 6466        if self.read_only(cx) {
 6467            cx.theme().players().read_only()
 6468        } else {
 6469            self.style.as_ref().unwrap().local_player
 6470        }
 6471    }
 6472
 6473    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 6474        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 6475        let accept_keystroke = accept_binding.keystroke()?;
 6476
 6477        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6478
 6479        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 6480            Color::Accent
 6481        } else {
 6482            Color::Muted
 6483        };
 6484
 6485        h_flex()
 6486            .px_0p5()
 6487            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 6488            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6489            .text_size(TextSize::XSmall.rems(cx))
 6490            .child(h_flex().children(ui::render_modifiers(
 6491                &accept_keystroke.modifiers,
 6492                PlatformStyle::platform(),
 6493                Some(modifiers_color),
 6494                Some(IconSize::XSmall.rems().into()),
 6495                true,
 6496            )))
 6497            .when(is_platform_style_mac, |parent| {
 6498                parent.child(accept_keystroke.key.clone())
 6499            })
 6500            .when(!is_platform_style_mac, |parent| {
 6501                parent.child(
 6502                    Key::new(
 6503                        util::capitalize(&accept_keystroke.key),
 6504                        Some(Color::Default),
 6505                    )
 6506                    .size(Some(IconSize::XSmall.rems().into())),
 6507                )
 6508            })
 6509            .into()
 6510    }
 6511
 6512    fn render_edit_prediction_line_popover(
 6513        &self,
 6514        label: impl Into<SharedString>,
 6515        icon: Option<IconName>,
 6516        window: &mut Window,
 6517        cx: &App,
 6518    ) -> Option<Div> {
 6519        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 6520
 6521        let result = h_flex()
 6522            .py_0p5()
 6523            .pl_1()
 6524            .pr(padding_right)
 6525            .gap_1()
 6526            .rounded(px(6.))
 6527            .border_1()
 6528            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6529            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 6530            .shadow_sm()
 6531            .children(self.render_edit_prediction_accept_keybind(window, cx))
 6532            .child(Label::new(label).size(LabelSize::Small))
 6533            .when_some(icon, |element, icon| {
 6534                element.child(
 6535                    div()
 6536                        .mt(px(1.5))
 6537                        .child(Icon::new(icon).size(IconSize::Small)),
 6538                )
 6539            });
 6540
 6541        Some(result)
 6542    }
 6543
 6544    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 6545        let accent_color = cx.theme().colors().text_accent;
 6546        let editor_bg_color = cx.theme().colors().editor_background;
 6547        editor_bg_color.blend(accent_color.opacity(0.1))
 6548    }
 6549
 6550    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 6551        let accent_color = cx.theme().colors().text_accent;
 6552        let editor_bg_color = cx.theme().colors().editor_background;
 6553        editor_bg_color.blend(accent_color.opacity(0.6))
 6554    }
 6555
 6556    #[allow(clippy::too_many_arguments)]
 6557    fn render_edit_prediction_cursor_popover(
 6558        &self,
 6559        min_width: Pixels,
 6560        max_width: Pixels,
 6561        cursor_point: Point,
 6562        style: &EditorStyle,
 6563        accept_keystroke: Option<&gpui::Keystroke>,
 6564        _window: &Window,
 6565        cx: &mut Context<Editor>,
 6566    ) -> Option<AnyElement> {
 6567        let provider = self.edit_prediction_provider.as_ref()?;
 6568
 6569        if provider.provider.needs_terms_acceptance(cx) {
 6570            return Some(
 6571                h_flex()
 6572                    .min_w(min_width)
 6573                    .flex_1()
 6574                    .px_2()
 6575                    .py_1()
 6576                    .gap_3()
 6577                    .elevation_2(cx)
 6578                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 6579                    .id("accept-terms")
 6580                    .cursor_pointer()
 6581                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 6582                    .on_click(cx.listener(|this, _event, window, cx| {
 6583                        cx.stop_propagation();
 6584                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 6585                        window.dispatch_action(
 6586                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 6587                            cx,
 6588                        );
 6589                    }))
 6590                    .child(
 6591                        h_flex()
 6592                            .flex_1()
 6593                            .gap_2()
 6594                            .child(Icon::new(IconName::ZedPredict))
 6595                            .child(Label::new("Accept Terms of Service"))
 6596                            .child(div().w_full())
 6597                            .child(
 6598                                Icon::new(IconName::ArrowUpRight)
 6599                                    .color(Color::Muted)
 6600                                    .size(IconSize::Small),
 6601                            )
 6602                            .into_any_element(),
 6603                    )
 6604                    .into_any(),
 6605            );
 6606        }
 6607
 6608        let is_refreshing = provider.provider.is_refreshing(cx);
 6609
 6610        fn pending_completion_container() -> Div {
 6611            h_flex()
 6612                .h_full()
 6613                .flex_1()
 6614                .gap_2()
 6615                .child(Icon::new(IconName::ZedPredict))
 6616        }
 6617
 6618        let completion = match &self.active_inline_completion {
 6619            Some(prediction) => {
 6620                if !self.has_visible_completions_menu() {
 6621                    const RADIUS: Pixels = px(6.);
 6622                    const BORDER_WIDTH: Pixels = px(1.);
 6623
 6624                    return Some(
 6625                        h_flex()
 6626                            .elevation_2(cx)
 6627                            .border(BORDER_WIDTH)
 6628                            .border_color(cx.theme().colors().border)
 6629                            .rounded(RADIUS)
 6630                            .rounded_tl(px(0.))
 6631                            .overflow_hidden()
 6632                            .child(div().px_1p5().child(match &prediction.completion {
 6633                                InlineCompletion::Move { target, snapshot } => {
 6634                                    use text::ToPoint as _;
 6635                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 6636                                    {
 6637                                        Icon::new(IconName::ZedPredictDown)
 6638                                    } else {
 6639                                        Icon::new(IconName::ZedPredictUp)
 6640                                    }
 6641                                }
 6642                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 6643                            }))
 6644                            .child(
 6645                                h_flex()
 6646                                    .gap_1()
 6647                                    .py_1()
 6648                                    .px_2()
 6649                                    .rounded_r(RADIUS - BORDER_WIDTH)
 6650                                    .border_l_1()
 6651                                    .border_color(cx.theme().colors().border)
 6652                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6653                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 6654                                        el.child(
 6655                                            Label::new("Hold")
 6656                                                .size(LabelSize::Small)
 6657                                                .line_height_style(LineHeightStyle::UiLabel),
 6658                                        )
 6659                                    })
 6660                                    .child(h_flex().children(ui::render_modifiers(
 6661                                        &accept_keystroke?.modifiers,
 6662                                        PlatformStyle::platform(),
 6663                                        Some(Color::Default),
 6664                                        Some(IconSize::XSmall.rems().into()),
 6665                                        false,
 6666                                    ))),
 6667                            )
 6668                            .into_any(),
 6669                    );
 6670                }
 6671
 6672                self.render_edit_prediction_cursor_popover_preview(
 6673                    prediction,
 6674                    cursor_point,
 6675                    style,
 6676                    cx,
 6677                )?
 6678            }
 6679
 6680            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 6681                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 6682                    stale_completion,
 6683                    cursor_point,
 6684                    style,
 6685                    cx,
 6686                )?,
 6687
 6688                None => {
 6689                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6690                }
 6691            },
 6692
 6693            None => pending_completion_container().child(Label::new("No Prediction")),
 6694        };
 6695
 6696        let completion = if is_refreshing {
 6697            completion
 6698                .with_animation(
 6699                    "loading-completion",
 6700                    Animation::new(Duration::from_secs(2))
 6701                        .repeat()
 6702                        .with_easing(pulsating_between(0.4, 0.8)),
 6703                    |label, delta| label.opacity(delta),
 6704                )
 6705                .into_any_element()
 6706        } else {
 6707            completion.into_any_element()
 6708        };
 6709
 6710        let has_completion = self.active_inline_completion.is_some();
 6711
 6712        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6713        Some(
 6714            h_flex()
 6715                .min_w(min_width)
 6716                .max_w(max_width)
 6717                .flex_1()
 6718                .elevation_2(cx)
 6719                .border_color(cx.theme().colors().border)
 6720                .child(
 6721                    div()
 6722                        .flex_1()
 6723                        .py_1()
 6724                        .px_2()
 6725                        .overflow_hidden()
 6726                        .child(completion),
 6727                )
 6728                .when_some(accept_keystroke, |el, accept_keystroke| {
 6729                    if !accept_keystroke.modifiers.modified() {
 6730                        return el;
 6731                    }
 6732
 6733                    el.child(
 6734                        h_flex()
 6735                            .h_full()
 6736                            .border_l_1()
 6737                            .rounded_r_lg()
 6738                            .border_color(cx.theme().colors().border)
 6739                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6740                            .gap_1()
 6741                            .py_1()
 6742                            .px_2()
 6743                            .child(
 6744                                h_flex()
 6745                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6746                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6747                                    .child(h_flex().children(ui::render_modifiers(
 6748                                        &accept_keystroke.modifiers,
 6749                                        PlatformStyle::platform(),
 6750                                        Some(if !has_completion {
 6751                                            Color::Muted
 6752                                        } else {
 6753                                            Color::Default
 6754                                        }),
 6755                                        None,
 6756                                        false,
 6757                                    ))),
 6758                            )
 6759                            .child(Label::new("Preview").into_any_element())
 6760                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6761                    )
 6762                })
 6763                .into_any(),
 6764        )
 6765    }
 6766
 6767    fn render_edit_prediction_cursor_popover_preview(
 6768        &self,
 6769        completion: &InlineCompletionState,
 6770        cursor_point: Point,
 6771        style: &EditorStyle,
 6772        cx: &mut Context<Editor>,
 6773    ) -> Option<Div> {
 6774        use text::ToPoint as _;
 6775
 6776        fn render_relative_row_jump(
 6777            prefix: impl Into<String>,
 6778            current_row: u32,
 6779            target_row: u32,
 6780        ) -> Div {
 6781            let (row_diff, arrow) = if target_row < current_row {
 6782                (current_row - target_row, IconName::ArrowUp)
 6783            } else {
 6784                (target_row - current_row, IconName::ArrowDown)
 6785            };
 6786
 6787            h_flex()
 6788                .child(
 6789                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6790                        .color(Color::Muted)
 6791                        .size(LabelSize::Small),
 6792                )
 6793                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6794        }
 6795
 6796        match &completion.completion {
 6797            InlineCompletion::Move {
 6798                target, snapshot, ..
 6799            } => Some(
 6800                h_flex()
 6801                    .px_2()
 6802                    .gap_2()
 6803                    .flex_1()
 6804                    .child(
 6805                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6806                            Icon::new(IconName::ZedPredictDown)
 6807                        } else {
 6808                            Icon::new(IconName::ZedPredictUp)
 6809                        },
 6810                    )
 6811                    .child(Label::new("Jump to Edit")),
 6812            ),
 6813
 6814            InlineCompletion::Edit {
 6815                edits,
 6816                edit_preview,
 6817                snapshot,
 6818                display_mode: _,
 6819            } => {
 6820                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6821
 6822                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6823                    &snapshot,
 6824                    &edits,
 6825                    edit_preview.as_ref()?,
 6826                    true,
 6827                    cx,
 6828                )
 6829                .first_line_preview();
 6830
 6831                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6832                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 6833
 6834                let preview = h_flex()
 6835                    .gap_1()
 6836                    .min_w_16()
 6837                    .child(styled_text)
 6838                    .when(has_more_lines, |parent| parent.child(""));
 6839
 6840                let left = if first_edit_row != cursor_point.row {
 6841                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6842                        .into_any_element()
 6843                } else {
 6844                    Icon::new(IconName::ZedPredict).into_any_element()
 6845                };
 6846
 6847                Some(
 6848                    h_flex()
 6849                        .h_full()
 6850                        .flex_1()
 6851                        .gap_2()
 6852                        .pr_1()
 6853                        .overflow_x_hidden()
 6854                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6855                        .child(left)
 6856                        .child(preview),
 6857                )
 6858            }
 6859        }
 6860    }
 6861
 6862    fn render_context_menu(
 6863        &self,
 6864        style: &EditorStyle,
 6865        max_height_in_lines: u32,
 6866        y_flipped: bool,
 6867        window: &mut Window,
 6868        cx: &mut Context<Editor>,
 6869    ) -> Option<AnyElement> {
 6870        let menu = self.context_menu.borrow();
 6871        let menu = menu.as_ref()?;
 6872        if !menu.visible() {
 6873            return None;
 6874        };
 6875        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6876    }
 6877
 6878    fn render_context_menu_aside(
 6879        &mut self,
 6880        max_size: Size<Pixels>,
 6881        window: &mut Window,
 6882        cx: &mut Context<Editor>,
 6883    ) -> Option<AnyElement> {
 6884        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 6885            if menu.visible() {
 6886                menu.render_aside(self, max_size, window, cx)
 6887            } else {
 6888                None
 6889            }
 6890        })
 6891    }
 6892
 6893    fn hide_context_menu(
 6894        &mut self,
 6895        window: &mut Window,
 6896        cx: &mut Context<Self>,
 6897    ) -> Option<CodeContextMenu> {
 6898        cx.notify();
 6899        self.completion_tasks.clear();
 6900        let context_menu = self.context_menu.borrow_mut().take();
 6901        self.stale_inline_completion_in_menu.take();
 6902        self.update_visible_inline_completion(window, cx);
 6903        context_menu
 6904    }
 6905
 6906    fn show_snippet_choices(
 6907        &mut self,
 6908        choices: &Vec<String>,
 6909        selection: Range<Anchor>,
 6910        cx: &mut Context<Self>,
 6911    ) {
 6912        if selection.start.buffer_id.is_none() {
 6913            return;
 6914        }
 6915        let buffer_id = selection.start.buffer_id.unwrap();
 6916        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6917        let id = post_inc(&mut self.next_completion_id);
 6918
 6919        if let Some(buffer) = buffer {
 6920            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6921                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6922            ));
 6923        }
 6924    }
 6925
 6926    pub fn insert_snippet(
 6927        &mut self,
 6928        insertion_ranges: &[Range<usize>],
 6929        snippet: Snippet,
 6930        window: &mut Window,
 6931        cx: &mut Context<Self>,
 6932    ) -> Result<()> {
 6933        struct Tabstop<T> {
 6934            is_end_tabstop: bool,
 6935            ranges: Vec<Range<T>>,
 6936            choices: Option<Vec<String>>,
 6937        }
 6938
 6939        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6940            let snippet_text: Arc<str> = snippet.text.clone().into();
 6941            buffer.edit(
 6942                insertion_ranges
 6943                    .iter()
 6944                    .cloned()
 6945                    .map(|range| (range, snippet_text.clone())),
 6946                Some(AutoindentMode::EachLine),
 6947                cx,
 6948            );
 6949
 6950            let snapshot = &*buffer.read(cx);
 6951            let snippet = &snippet;
 6952            snippet
 6953                .tabstops
 6954                .iter()
 6955                .map(|tabstop| {
 6956                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6957                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6958                    });
 6959                    let mut tabstop_ranges = tabstop
 6960                        .ranges
 6961                        .iter()
 6962                        .flat_map(|tabstop_range| {
 6963                            let mut delta = 0_isize;
 6964                            insertion_ranges.iter().map(move |insertion_range| {
 6965                                let insertion_start = insertion_range.start as isize + delta;
 6966                                delta +=
 6967                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6968
 6969                                let start = ((insertion_start + tabstop_range.start) as usize)
 6970                                    .min(snapshot.len());
 6971                                let end = ((insertion_start + tabstop_range.end) as usize)
 6972                                    .min(snapshot.len());
 6973                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6974                            })
 6975                        })
 6976                        .collect::<Vec<_>>();
 6977                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6978
 6979                    Tabstop {
 6980                        is_end_tabstop,
 6981                        ranges: tabstop_ranges,
 6982                        choices: tabstop.choices.clone(),
 6983                    }
 6984                })
 6985                .collect::<Vec<_>>()
 6986        });
 6987        if let Some(tabstop) = tabstops.first() {
 6988            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6989                s.select_ranges(tabstop.ranges.iter().cloned());
 6990            });
 6991
 6992            if let Some(choices) = &tabstop.choices {
 6993                if let Some(selection) = tabstop.ranges.first() {
 6994                    self.show_snippet_choices(choices, selection.clone(), cx)
 6995                }
 6996            }
 6997
 6998            // If we're already at the last tabstop and it's at the end of the snippet,
 6999            // we're done, we don't need to keep the state around.
 7000            if !tabstop.is_end_tabstop {
 7001                let choices = tabstops
 7002                    .iter()
 7003                    .map(|tabstop| tabstop.choices.clone())
 7004                    .collect();
 7005
 7006                let ranges = tabstops
 7007                    .into_iter()
 7008                    .map(|tabstop| tabstop.ranges)
 7009                    .collect::<Vec<_>>();
 7010
 7011                self.snippet_stack.push(SnippetState {
 7012                    active_index: 0,
 7013                    ranges,
 7014                    choices,
 7015                });
 7016            }
 7017
 7018            // Check whether the just-entered snippet ends with an auto-closable bracket.
 7019            if self.autoclose_regions.is_empty() {
 7020                let snapshot = self.buffer.read(cx).snapshot(cx);
 7021                for selection in &mut self.selections.all::<Point>(cx) {
 7022                    let selection_head = selection.head();
 7023                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 7024                        continue;
 7025                    };
 7026
 7027                    let mut bracket_pair = None;
 7028                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 7029                    let prev_chars = snapshot
 7030                        .reversed_chars_at(selection_head)
 7031                        .collect::<String>();
 7032                    for (pair, enabled) in scope.brackets() {
 7033                        if enabled
 7034                            && pair.close
 7035                            && prev_chars.starts_with(pair.start.as_str())
 7036                            && next_chars.starts_with(pair.end.as_str())
 7037                        {
 7038                            bracket_pair = Some(pair.clone());
 7039                            break;
 7040                        }
 7041                    }
 7042                    if let Some(pair) = bracket_pair {
 7043                        let start = snapshot.anchor_after(selection_head);
 7044                        let end = snapshot.anchor_after(selection_head);
 7045                        self.autoclose_regions.push(AutocloseRegion {
 7046                            selection_id: selection.id,
 7047                            range: start..end,
 7048                            pair,
 7049                        });
 7050                    }
 7051                }
 7052            }
 7053        }
 7054        Ok(())
 7055    }
 7056
 7057    pub fn move_to_next_snippet_tabstop(
 7058        &mut self,
 7059        window: &mut Window,
 7060        cx: &mut Context<Self>,
 7061    ) -> bool {
 7062        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 7063    }
 7064
 7065    pub fn move_to_prev_snippet_tabstop(
 7066        &mut self,
 7067        window: &mut Window,
 7068        cx: &mut Context<Self>,
 7069    ) -> bool {
 7070        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 7071    }
 7072
 7073    pub fn move_to_snippet_tabstop(
 7074        &mut self,
 7075        bias: Bias,
 7076        window: &mut Window,
 7077        cx: &mut Context<Self>,
 7078    ) -> bool {
 7079        if let Some(mut snippet) = self.snippet_stack.pop() {
 7080            match bias {
 7081                Bias::Left => {
 7082                    if snippet.active_index > 0 {
 7083                        snippet.active_index -= 1;
 7084                    } else {
 7085                        self.snippet_stack.push(snippet);
 7086                        return false;
 7087                    }
 7088                }
 7089                Bias::Right => {
 7090                    if snippet.active_index + 1 < snippet.ranges.len() {
 7091                        snippet.active_index += 1;
 7092                    } else {
 7093                        self.snippet_stack.push(snippet);
 7094                        return false;
 7095                    }
 7096                }
 7097            }
 7098            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 7099                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7100                    s.select_anchor_ranges(current_ranges.iter().cloned())
 7101                });
 7102
 7103                if let Some(choices) = &snippet.choices[snippet.active_index] {
 7104                    if let Some(selection) = current_ranges.first() {
 7105                        self.show_snippet_choices(&choices, selection.clone(), cx);
 7106                    }
 7107                }
 7108
 7109                // If snippet state is not at the last tabstop, push it back on the stack
 7110                if snippet.active_index + 1 < snippet.ranges.len() {
 7111                    self.snippet_stack.push(snippet);
 7112                }
 7113                return true;
 7114            }
 7115        }
 7116
 7117        false
 7118    }
 7119
 7120    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 7121        self.transact(window, cx, |this, window, cx| {
 7122            this.select_all(&SelectAll, window, cx);
 7123            this.insert("", window, cx);
 7124        });
 7125    }
 7126
 7127    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 7128        self.transact(window, cx, |this, window, cx| {
 7129            this.select_autoclose_pair(window, cx);
 7130            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 7131            if !this.linked_edit_ranges.is_empty() {
 7132                let selections = this.selections.all::<MultiBufferPoint>(cx);
 7133                let snapshot = this.buffer.read(cx).snapshot(cx);
 7134
 7135                for selection in selections.iter() {
 7136                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 7137                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 7138                    if selection_start.buffer_id != selection_end.buffer_id {
 7139                        continue;
 7140                    }
 7141                    if let Some(ranges) =
 7142                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 7143                    {
 7144                        for (buffer, entries) in ranges {
 7145                            linked_ranges.entry(buffer).or_default().extend(entries);
 7146                        }
 7147                    }
 7148                }
 7149            }
 7150
 7151            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7152            if !this.selections.line_mode {
 7153                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 7154                for selection in &mut selections {
 7155                    if selection.is_empty() {
 7156                        let old_head = selection.head();
 7157                        let mut new_head =
 7158                            movement::left(&display_map, old_head.to_display_point(&display_map))
 7159                                .to_point(&display_map);
 7160                        if let Some((buffer, line_buffer_range)) = display_map
 7161                            .buffer_snapshot
 7162                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 7163                        {
 7164                            let indent_size =
 7165                                buffer.indent_size_for_line(line_buffer_range.start.row);
 7166                            let indent_len = match indent_size.kind {
 7167                                IndentKind::Space => {
 7168                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 7169                                }
 7170                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 7171                            };
 7172                            if old_head.column <= indent_size.len && old_head.column > 0 {
 7173                                let indent_len = indent_len.get();
 7174                                new_head = cmp::min(
 7175                                    new_head,
 7176                                    MultiBufferPoint::new(
 7177                                        old_head.row,
 7178                                        ((old_head.column - 1) / indent_len) * indent_len,
 7179                                    ),
 7180                                );
 7181                            }
 7182                        }
 7183
 7184                        selection.set_head(new_head, SelectionGoal::None);
 7185                    }
 7186                }
 7187            }
 7188
 7189            this.signature_help_state.set_backspace_pressed(true);
 7190            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7191                s.select(selections)
 7192            });
 7193            this.insert("", window, cx);
 7194            let empty_str: Arc<str> = Arc::from("");
 7195            for (buffer, edits) in linked_ranges {
 7196                let snapshot = buffer.read(cx).snapshot();
 7197                use text::ToPoint as TP;
 7198
 7199                let edits = edits
 7200                    .into_iter()
 7201                    .map(|range| {
 7202                        let end_point = TP::to_point(&range.end, &snapshot);
 7203                        let mut start_point = TP::to_point(&range.start, &snapshot);
 7204
 7205                        if end_point == start_point {
 7206                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 7207                                .saturating_sub(1);
 7208                            start_point =
 7209                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 7210                        };
 7211
 7212                        (start_point..end_point, empty_str.clone())
 7213                    })
 7214                    .sorted_by_key(|(range, _)| range.start)
 7215                    .collect::<Vec<_>>();
 7216                buffer.update(cx, |this, cx| {
 7217                    this.edit(edits, None, cx);
 7218                })
 7219            }
 7220            this.refresh_inline_completion(true, false, window, cx);
 7221            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 7222        });
 7223    }
 7224
 7225    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 7226        self.transact(window, cx, |this, window, cx| {
 7227            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7228                let line_mode = s.line_mode;
 7229                s.move_with(|map, selection| {
 7230                    if selection.is_empty() && !line_mode {
 7231                        let cursor = movement::right(map, selection.head());
 7232                        selection.end = cursor;
 7233                        selection.reversed = true;
 7234                        selection.goal = SelectionGoal::None;
 7235                    }
 7236                })
 7237            });
 7238            this.insert("", window, cx);
 7239            this.refresh_inline_completion(true, false, window, cx);
 7240        });
 7241    }
 7242
 7243    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 7244        if self.move_to_prev_snippet_tabstop(window, cx) {
 7245            return;
 7246        }
 7247
 7248        self.outdent(&Outdent, window, cx);
 7249    }
 7250
 7251    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 7252        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 7253            return;
 7254        }
 7255
 7256        let mut selections = self.selections.all_adjusted(cx);
 7257        let buffer = self.buffer.read(cx);
 7258        let snapshot = buffer.snapshot(cx);
 7259        let rows_iter = selections.iter().map(|s| s.head().row);
 7260        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 7261
 7262        let mut edits = Vec::new();
 7263        let mut prev_edited_row = 0;
 7264        let mut row_delta = 0;
 7265        for selection in &mut selections {
 7266            if selection.start.row != prev_edited_row {
 7267                row_delta = 0;
 7268            }
 7269            prev_edited_row = selection.end.row;
 7270
 7271            // If the selection is non-empty, then increase the indentation of the selected lines.
 7272            if !selection.is_empty() {
 7273                row_delta =
 7274                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7275                continue;
 7276            }
 7277
 7278            // If the selection is empty and the cursor is in the leading whitespace before the
 7279            // suggested indentation, then auto-indent the line.
 7280            let cursor = selection.head();
 7281            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 7282            if let Some(suggested_indent) =
 7283                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 7284            {
 7285                if cursor.column < suggested_indent.len
 7286                    && cursor.column <= current_indent.len
 7287                    && current_indent.len <= suggested_indent.len
 7288                {
 7289                    selection.start = Point::new(cursor.row, suggested_indent.len);
 7290                    selection.end = selection.start;
 7291                    if row_delta == 0 {
 7292                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 7293                            cursor.row,
 7294                            current_indent,
 7295                            suggested_indent,
 7296                        ));
 7297                        row_delta = suggested_indent.len - current_indent.len;
 7298                    }
 7299                    continue;
 7300                }
 7301            }
 7302
 7303            // Otherwise, insert a hard or soft tab.
 7304            let settings = buffer.language_settings_at(cursor, cx);
 7305            let tab_size = if settings.hard_tabs {
 7306                IndentSize::tab()
 7307            } else {
 7308                let tab_size = settings.tab_size.get();
 7309                let char_column = snapshot
 7310                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 7311                    .flat_map(str::chars)
 7312                    .count()
 7313                    + row_delta as usize;
 7314                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 7315                IndentSize::spaces(chars_to_next_tab_stop)
 7316            };
 7317            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 7318            selection.end = selection.start;
 7319            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 7320            row_delta += tab_size.len;
 7321        }
 7322
 7323        self.transact(window, cx, |this, window, cx| {
 7324            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7325            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7326                s.select(selections)
 7327            });
 7328            this.refresh_inline_completion(true, false, window, cx);
 7329        });
 7330    }
 7331
 7332    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 7333        if self.read_only(cx) {
 7334            return;
 7335        }
 7336        let mut selections = self.selections.all::<Point>(cx);
 7337        let mut prev_edited_row = 0;
 7338        let mut row_delta = 0;
 7339        let mut edits = Vec::new();
 7340        let buffer = self.buffer.read(cx);
 7341        let snapshot = buffer.snapshot(cx);
 7342        for selection in &mut selections {
 7343            if selection.start.row != prev_edited_row {
 7344                row_delta = 0;
 7345            }
 7346            prev_edited_row = selection.end.row;
 7347
 7348            row_delta =
 7349                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7350        }
 7351
 7352        self.transact(window, cx, |this, window, cx| {
 7353            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7354            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7355                s.select(selections)
 7356            });
 7357        });
 7358    }
 7359
 7360    fn indent_selection(
 7361        buffer: &MultiBuffer,
 7362        snapshot: &MultiBufferSnapshot,
 7363        selection: &mut Selection<Point>,
 7364        edits: &mut Vec<(Range<Point>, String)>,
 7365        delta_for_start_row: u32,
 7366        cx: &App,
 7367    ) -> u32 {
 7368        let settings = buffer.language_settings_at(selection.start, cx);
 7369        let tab_size = settings.tab_size.get();
 7370        let indent_kind = if settings.hard_tabs {
 7371            IndentKind::Tab
 7372        } else {
 7373            IndentKind::Space
 7374        };
 7375        let mut start_row = selection.start.row;
 7376        let mut end_row = selection.end.row + 1;
 7377
 7378        // If a selection ends at the beginning of a line, don't indent
 7379        // that last line.
 7380        if selection.end.column == 0 && selection.end.row > selection.start.row {
 7381            end_row -= 1;
 7382        }
 7383
 7384        // Avoid re-indenting a row that has already been indented by a
 7385        // previous selection, but still update this selection's column
 7386        // to reflect that indentation.
 7387        if delta_for_start_row > 0 {
 7388            start_row += 1;
 7389            selection.start.column += delta_for_start_row;
 7390            if selection.end.row == selection.start.row {
 7391                selection.end.column += delta_for_start_row;
 7392            }
 7393        }
 7394
 7395        let mut delta_for_end_row = 0;
 7396        let has_multiple_rows = start_row + 1 != end_row;
 7397        for row in start_row..end_row {
 7398            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 7399            let indent_delta = match (current_indent.kind, indent_kind) {
 7400                (IndentKind::Space, IndentKind::Space) => {
 7401                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 7402                    IndentSize::spaces(columns_to_next_tab_stop)
 7403                }
 7404                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 7405                (_, IndentKind::Tab) => IndentSize::tab(),
 7406            };
 7407
 7408            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 7409                0
 7410            } else {
 7411                selection.start.column
 7412            };
 7413            let row_start = Point::new(row, start);
 7414            edits.push((
 7415                row_start..row_start,
 7416                indent_delta.chars().collect::<String>(),
 7417            ));
 7418
 7419            // Update this selection's endpoints to reflect the indentation.
 7420            if row == selection.start.row {
 7421                selection.start.column += indent_delta.len;
 7422            }
 7423            if row == selection.end.row {
 7424                selection.end.column += indent_delta.len;
 7425                delta_for_end_row = indent_delta.len;
 7426            }
 7427        }
 7428
 7429        if selection.start.row == selection.end.row {
 7430            delta_for_start_row + delta_for_end_row
 7431        } else {
 7432            delta_for_end_row
 7433        }
 7434    }
 7435
 7436    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 7437        if self.read_only(cx) {
 7438            return;
 7439        }
 7440        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7441        let selections = self.selections.all::<Point>(cx);
 7442        let mut deletion_ranges = Vec::new();
 7443        let mut last_outdent = None;
 7444        {
 7445            let buffer = self.buffer.read(cx);
 7446            let snapshot = buffer.snapshot(cx);
 7447            for selection in &selections {
 7448                let settings = buffer.language_settings_at(selection.start, cx);
 7449                let tab_size = settings.tab_size.get();
 7450                let mut rows = selection.spanned_rows(false, &display_map);
 7451
 7452                // Avoid re-outdenting a row that has already been outdented by a
 7453                // previous selection.
 7454                if let Some(last_row) = last_outdent {
 7455                    if last_row == rows.start {
 7456                        rows.start = rows.start.next_row();
 7457                    }
 7458                }
 7459                let has_multiple_rows = rows.len() > 1;
 7460                for row in rows.iter_rows() {
 7461                    let indent_size = snapshot.indent_size_for_line(row);
 7462                    if indent_size.len > 0 {
 7463                        let deletion_len = match indent_size.kind {
 7464                            IndentKind::Space => {
 7465                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 7466                                if columns_to_prev_tab_stop == 0 {
 7467                                    tab_size
 7468                                } else {
 7469                                    columns_to_prev_tab_stop
 7470                                }
 7471                            }
 7472                            IndentKind::Tab => 1,
 7473                        };
 7474                        let start = if has_multiple_rows
 7475                            || deletion_len > selection.start.column
 7476                            || indent_size.len < selection.start.column
 7477                        {
 7478                            0
 7479                        } else {
 7480                            selection.start.column - deletion_len
 7481                        };
 7482                        deletion_ranges.push(
 7483                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 7484                        );
 7485                        last_outdent = Some(row);
 7486                    }
 7487                }
 7488            }
 7489        }
 7490
 7491        self.transact(window, cx, |this, window, cx| {
 7492            this.buffer.update(cx, |buffer, cx| {
 7493                let empty_str: Arc<str> = Arc::default();
 7494                buffer.edit(
 7495                    deletion_ranges
 7496                        .into_iter()
 7497                        .map(|range| (range, empty_str.clone())),
 7498                    None,
 7499                    cx,
 7500                );
 7501            });
 7502            let selections = this.selections.all::<usize>(cx);
 7503            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7504                s.select(selections)
 7505            });
 7506        });
 7507    }
 7508
 7509    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 7510        if self.read_only(cx) {
 7511            return;
 7512        }
 7513        let selections = self
 7514            .selections
 7515            .all::<usize>(cx)
 7516            .into_iter()
 7517            .map(|s| s.range());
 7518
 7519        self.transact(window, cx, |this, window, cx| {
 7520            this.buffer.update(cx, |buffer, cx| {
 7521                buffer.autoindent_ranges(selections, cx);
 7522            });
 7523            let selections = this.selections.all::<usize>(cx);
 7524            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7525                s.select(selections)
 7526            });
 7527        });
 7528    }
 7529
 7530    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 7531        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7532        let selections = self.selections.all::<Point>(cx);
 7533
 7534        let mut new_cursors = Vec::new();
 7535        let mut edit_ranges = Vec::new();
 7536        let mut selections = selections.iter().peekable();
 7537        while let Some(selection) = selections.next() {
 7538            let mut rows = selection.spanned_rows(false, &display_map);
 7539            let goal_display_column = selection.head().to_display_point(&display_map).column();
 7540
 7541            // Accumulate contiguous regions of rows that we want to delete.
 7542            while let Some(next_selection) = selections.peek() {
 7543                let next_rows = next_selection.spanned_rows(false, &display_map);
 7544                if next_rows.start <= rows.end {
 7545                    rows.end = next_rows.end;
 7546                    selections.next().unwrap();
 7547                } else {
 7548                    break;
 7549                }
 7550            }
 7551
 7552            let buffer = &display_map.buffer_snapshot;
 7553            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 7554            let edit_end;
 7555            let cursor_buffer_row;
 7556            if buffer.max_point().row >= rows.end.0 {
 7557                // If there's a line after the range, delete the \n from the end of the row range
 7558                // and position the cursor on the next line.
 7559                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 7560                cursor_buffer_row = rows.end;
 7561            } else {
 7562                // If there isn't a line after the range, delete the \n from the line before the
 7563                // start of the row range and position the cursor there.
 7564                edit_start = edit_start.saturating_sub(1);
 7565                edit_end = buffer.len();
 7566                cursor_buffer_row = rows.start.previous_row();
 7567            }
 7568
 7569            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 7570            *cursor.column_mut() =
 7571                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 7572
 7573            new_cursors.push((
 7574                selection.id,
 7575                buffer.anchor_after(cursor.to_point(&display_map)),
 7576            ));
 7577            edit_ranges.push(edit_start..edit_end);
 7578        }
 7579
 7580        self.transact(window, cx, |this, window, cx| {
 7581            let buffer = this.buffer.update(cx, |buffer, cx| {
 7582                let empty_str: Arc<str> = Arc::default();
 7583                buffer.edit(
 7584                    edit_ranges
 7585                        .into_iter()
 7586                        .map(|range| (range, empty_str.clone())),
 7587                    None,
 7588                    cx,
 7589                );
 7590                buffer.snapshot(cx)
 7591            });
 7592            let new_selections = new_cursors
 7593                .into_iter()
 7594                .map(|(id, cursor)| {
 7595                    let cursor = cursor.to_point(&buffer);
 7596                    Selection {
 7597                        id,
 7598                        start: cursor,
 7599                        end: cursor,
 7600                        reversed: false,
 7601                        goal: SelectionGoal::None,
 7602                    }
 7603                })
 7604                .collect();
 7605
 7606            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7607                s.select(new_selections);
 7608            });
 7609        });
 7610    }
 7611
 7612    pub fn join_lines_impl(
 7613        &mut self,
 7614        insert_whitespace: bool,
 7615        window: &mut Window,
 7616        cx: &mut Context<Self>,
 7617    ) {
 7618        if self.read_only(cx) {
 7619            return;
 7620        }
 7621        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 7622        for selection in self.selections.all::<Point>(cx) {
 7623            let start = MultiBufferRow(selection.start.row);
 7624            // Treat single line selections as if they include the next line. Otherwise this action
 7625            // would do nothing for single line selections individual cursors.
 7626            let end = if selection.start.row == selection.end.row {
 7627                MultiBufferRow(selection.start.row + 1)
 7628            } else {
 7629                MultiBufferRow(selection.end.row)
 7630            };
 7631
 7632            if let Some(last_row_range) = row_ranges.last_mut() {
 7633                if start <= last_row_range.end {
 7634                    last_row_range.end = end;
 7635                    continue;
 7636                }
 7637            }
 7638            row_ranges.push(start..end);
 7639        }
 7640
 7641        let snapshot = self.buffer.read(cx).snapshot(cx);
 7642        let mut cursor_positions = Vec::new();
 7643        for row_range in &row_ranges {
 7644            let anchor = snapshot.anchor_before(Point::new(
 7645                row_range.end.previous_row().0,
 7646                snapshot.line_len(row_range.end.previous_row()),
 7647            ));
 7648            cursor_positions.push(anchor..anchor);
 7649        }
 7650
 7651        self.transact(window, cx, |this, window, cx| {
 7652            for row_range in row_ranges.into_iter().rev() {
 7653                for row in row_range.iter_rows().rev() {
 7654                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 7655                    let next_line_row = row.next_row();
 7656                    let indent = snapshot.indent_size_for_line(next_line_row);
 7657                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7658
 7659                    let replace =
 7660                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7661                            " "
 7662                        } else {
 7663                            ""
 7664                        };
 7665
 7666                    this.buffer.update(cx, |buffer, cx| {
 7667                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7668                    });
 7669                }
 7670            }
 7671
 7672            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7673                s.select_anchor_ranges(cursor_positions)
 7674            });
 7675        });
 7676    }
 7677
 7678    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7679        self.join_lines_impl(true, window, cx);
 7680    }
 7681
 7682    pub fn sort_lines_case_sensitive(
 7683        &mut self,
 7684        _: &SortLinesCaseSensitive,
 7685        window: &mut Window,
 7686        cx: &mut Context<Self>,
 7687    ) {
 7688        self.manipulate_lines(window, cx, |lines| lines.sort())
 7689    }
 7690
 7691    pub fn sort_lines_case_insensitive(
 7692        &mut self,
 7693        _: &SortLinesCaseInsensitive,
 7694        window: &mut Window,
 7695        cx: &mut Context<Self>,
 7696    ) {
 7697        self.manipulate_lines(window, cx, |lines| {
 7698            lines.sort_by_key(|line| line.to_lowercase())
 7699        })
 7700    }
 7701
 7702    pub fn unique_lines_case_insensitive(
 7703        &mut self,
 7704        _: &UniqueLinesCaseInsensitive,
 7705        window: &mut Window,
 7706        cx: &mut Context<Self>,
 7707    ) {
 7708        self.manipulate_lines(window, cx, |lines| {
 7709            let mut seen = HashSet::default();
 7710            lines.retain(|line| seen.insert(line.to_lowercase()));
 7711        })
 7712    }
 7713
 7714    pub fn unique_lines_case_sensitive(
 7715        &mut self,
 7716        _: &UniqueLinesCaseSensitive,
 7717        window: &mut Window,
 7718        cx: &mut Context<Self>,
 7719    ) {
 7720        self.manipulate_lines(window, cx, |lines| {
 7721            let mut seen = HashSet::default();
 7722            lines.retain(|line| seen.insert(*line));
 7723        })
 7724    }
 7725
 7726    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7727        let Some(project) = self.project.clone() else {
 7728            return;
 7729        };
 7730        self.reload(project, window, cx)
 7731            .detach_and_notify_err(window, cx);
 7732    }
 7733
 7734    pub fn restore_file(
 7735        &mut self,
 7736        _: &::git::RestoreFile,
 7737        window: &mut Window,
 7738        cx: &mut Context<Self>,
 7739    ) {
 7740        let mut buffer_ids = HashSet::default();
 7741        let snapshot = self.buffer().read(cx).snapshot(cx);
 7742        for selection in self.selections.all::<usize>(cx) {
 7743            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 7744        }
 7745
 7746        let buffer = self.buffer().read(cx);
 7747        let ranges = buffer_ids
 7748            .into_iter()
 7749            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 7750            .collect::<Vec<_>>();
 7751
 7752        self.restore_hunks_in_ranges(ranges, window, cx);
 7753    }
 7754
 7755    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 7756        let selections = self
 7757            .selections
 7758            .all(cx)
 7759            .into_iter()
 7760            .map(|s| s.range())
 7761            .collect();
 7762        self.restore_hunks_in_ranges(selections, window, cx);
 7763    }
 7764
 7765    fn restore_hunks_in_ranges(
 7766        &mut self,
 7767        ranges: Vec<Range<Point>>,
 7768        window: &mut Window,
 7769        cx: &mut Context<Editor>,
 7770    ) {
 7771        let mut revert_changes = HashMap::default();
 7772        let chunk_by = self
 7773            .snapshot(window, cx)
 7774            .hunks_for_ranges(ranges)
 7775            .into_iter()
 7776            .chunk_by(|hunk| hunk.buffer_id);
 7777        for (buffer_id, hunks) in &chunk_by {
 7778            let hunks = hunks.collect::<Vec<_>>();
 7779            for hunk in &hunks {
 7780                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 7781            }
 7782            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 7783        }
 7784        drop(chunk_by);
 7785        if !revert_changes.is_empty() {
 7786            self.transact(window, cx, |editor, window, cx| {
 7787                editor.restore(revert_changes, window, cx);
 7788            });
 7789        }
 7790    }
 7791
 7792    pub fn open_active_item_in_terminal(
 7793        &mut self,
 7794        _: &OpenInTerminal,
 7795        window: &mut Window,
 7796        cx: &mut Context<Self>,
 7797    ) {
 7798        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7799            let project_path = buffer.read(cx).project_path(cx)?;
 7800            let project = self.project.as_ref()?.read(cx);
 7801            let entry = project.entry_for_path(&project_path, cx)?;
 7802            let parent = match &entry.canonical_path {
 7803                Some(canonical_path) => canonical_path.to_path_buf(),
 7804                None => project.absolute_path(&project_path, cx)?,
 7805            }
 7806            .parent()?
 7807            .to_path_buf();
 7808            Some(parent)
 7809        }) {
 7810            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7811        }
 7812    }
 7813
 7814    pub fn prepare_restore_change(
 7815        &self,
 7816        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7817        hunk: &MultiBufferDiffHunk,
 7818        cx: &mut App,
 7819    ) -> Option<()> {
 7820        if hunk.is_created_file() {
 7821            return None;
 7822        }
 7823        let buffer = self.buffer.read(cx);
 7824        let diff = buffer.diff_for(hunk.buffer_id)?;
 7825        let buffer = buffer.buffer(hunk.buffer_id)?;
 7826        let buffer = buffer.read(cx);
 7827        let original_text = diff
 7828            .read(cx)
 7829            .base_text()
 7830            .as_rope()
 7831            .slice(hunk.diff_base_byte_range.clone());
 7832        let buffer_snapshot = buffer.snapshot();
 7833        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7834        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7835            probe
 7836                .0
 7837                .start
 7838                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7839                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7840        }) {
 7841            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7842            Some(())
 7843        } else {
 7844            None
 7845        }
 7846    }
 7847
 7848    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7849        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7850    }
 7851
 7852    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7853        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7854    }
 7855
 7856    fn manipulate_lines<Fn>(
 7857        &mut self,
 7858        window: &mut Window,
 7859        cx: &mut Context<Self>,
 7860        mut callback: Fn,
 7861    ) where
 7862        Fn: FnMut(&mut Vec<&str>),
 7863    {
 7864        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7865        let buffer = self.buffer.read(cx).snapshot(cx);
 7866
 7867        let mut edits = Vec::new();
 7868
 7869        let selections = self.selections.all::<Point>(cx);
 7870        let mut selections = selections.iter().peekable();
 7871        let mut contiguous_row_selections = Vec::new();
 7872        let mut new_selections = Vec::new();
 7873        let mut added_lines = 0;
 7874        let mut removed_lines = 0;
 7875
 7876        while let Some(selection) = selections.next() {
 7877            let (start_row, end_row) = consume_contiguous_rows(
 7878                &mut contiguous_row_selections,
 7879                selection,
 7880                &display_map,
 7881                &mut selections,
 7882            );
 7883
 7884            let start_point = Point::new(start_row.0, 0);
 7885            let end_point = Point::new(
 7886                end_row.previous_row().0,
 7887                buffer.line_len(end_row.previous_row()),
 7888            );
 7889            let text = buffer
 7890                .text_for_range(start_point..end_point)
 7891                .collect::<String>();
 7892
 7893            let mut lines = text.split('\n').collect_vec();
 7894
 7895            let lines_before = lines.len();
 7896            callback(&mut lines);
 7897            let lines_after = lines.len();
 7898
 7899            edits.push((start_point..end_point, lines.join("\n")));
 7900
 7901            // Selections must change based on added and removed line count
 7902            let start_row =
 7903                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7904            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7905            new_selections.push(Selection {
 7906                id: selection.id,
 7907                start: start_row,
 7908                end: end_row,
 7909                goal: SelectionGoal::None,
 7910                reversed: selection.reversed,
 7911            });
 7912
 7913            if lines_after > lines_before {
 7914                added_lines += lines_after - lines_before;
 7915            } else if lines_before > lines_after {
 7916                removed_lines += lines_before - lines_after;
 7917            }
 7918        }
 7919
 7920        self.transact(window, cx, |this, window, cx| {
 7921            let buffer = this.buffer.update(cx, |buffer, cx| {
 7922                buffer.edit(edits, None, cx);
 7923                buffer.snapshot(cx)
 7924            });
 7925
 7926            // Recalculate offsets on newly edited buffer
 7927            let new_selections = new_selections
 7928                .iter()
 7929                .map(|s| {
 7930                    let start_point = Point::new(s.start.0, 0);
 7931                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7932                    Selection {
 7933                        id: s.id,
 7934                        start: buffer.point_to_offset(start_point),
 7935                        end: buffer.point_to_offset(end_point),
 7936                        goal: s.goal,
 7937                        reversed: s.reversed,
 7938                    }
 7939                })
 7940                .collect();
 7941
 7942            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7943                s.select(new_selections);
 7944            });
 7945
 7946            this.request_autoscroll(Autoscroll::fit(), cx);
 7947        });
 7948    }
 7949
 7950    pub fn convert_to_upper_case(
 7951        &mut self,
 7952        _: &ConvertToUpperCase,
 7953        window: &mut Window,
 7954        cx: &mut Context<Self>,
 7955    ) {
 7956        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7957    }
 7958
 7959    pub fn convert_to_lower_case(
 7960        &mut self,
 7961        _: &ConvertToLowerCase,
 7962        window: &mut Window,
 7963        cx: &mut Context<Self>,
 7964    ) {
 7965        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7966    }
 7967
 7968    pub fn convert_to_title_case(
 7969        &mut self,
 7970        _: &ConvertToTitleCase,
 7971        window: &mut Window,
 7972        cx: &mut Context<Self>,
 7973    ) {
 7974        self.manipulate_text(window, cx, |text| {
 7975            text.split('\n')
 7976                .map(|line| line.to_case(Case::Title))
 7977                .join("\n")
 7978        })
 7979    }
 7980
 7981    pub fn convert_to_snake_case(
 7982        &mut self,
 7983        _: &ConvertToSnakeCase,
 7984        window: &mut Window,
 7985        cx: &mut Context<Self>,
 7986    ) {
 7987        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7988    }
 7989
 7990    pub fn convert_to_kebab_case(
 7991        &mut self,
 7992        _: &ConvertToKebabCase,
 7993        window: &mut Window,
 7994        cx: &mut Context<Self>,
 7995    ) {
 7996        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7997    }
 7998
 7999    pub fn convert_to_upper_camel_case(
 8000        &mut self,
 8001        _: &ConvertToUpperCamelCase,
 8002        window: &mut Window,
 8003        cx: &mut Context<Self>,
 8004    ) {
 8005        self.manipulate_text(window, cx, |text| {
 8006            text.split('\n')
 8007                .map(|line| line.to_case(Case::UpperCamel))
 8008                .join("\n")
 8009        })
 8010    }
 8011
 8012    pub fn convert_to_lower_camel_case(
 8013        &mut self,
 8014        _: &ConvertToLowerCamelCase,
 8015        window: &mut Window,
 8016        cx: &mut Context<Self>,
 8017    ) {
 8018        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 8019    }
 8020
 8021    pub fn convert_to_opposite_case(
 8022        &mut self,
 8023        _: &ConvertToOppositeCase,
 8024        window: &mut Window,
 8025        cx: &mut Context<Self>,
 8026    ) {
 8027        self.manipulate_text(window, cx, |text| {
 8028            text.chars()
 8029                .fold(String::with_capacity(text.len()), |mut t, c| {
 8030                    if c.is_uppercase() {
 8031                        t.extend(c.to_lowercase());
 8032                    } else {
 8033                        t.extend(c.to_uppercase());
 8034                    }
 8035                    t
 8036                })
 8037        })
 8038    }
 8039
 8040    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 8041    where
 8042        Fn: FnMut(&str) -> String,
 8043    {
 8044        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8045        let buffer = self.buffer.read(cx).snapshot(cx);
 8046
 8047        let mut new_selections = Vec::new();
 8048        let mut edits = Vec::new();
 8049        let mut selection_adjustment = 0i32;
 8050
 8051        for selection in self.selections.all::<usize>(cx) {
 8052            let selection_is_empty = selection.is_empty();
 8053
 8054            let (start, end) = if selection_is_empty {
 8055                let word_range = movement::surrounding_word(
 8056                    &display_map,
 8057                    selection.start.to_display_point(&display_map),
 8058                );
 8059                let start = word_range.start.to_offset(&display_map, Bias::Left);
 8060                let end = word_range.end.to_offset(&display_map, Bias::Left);
 8061                (start, end)
 8062            } else {
 8063                (selection.start, selection.end)
 8064            };
 8065
 8066            let text = buffer.text_for_range(start..end).collect::<String>();
 8067            let old_length = text.len() as i32;
 8068            let text = callback(&text);
 8069
 8070            new_selections.push(Selection {
 8071                start: (start as i32 - selection_adjustment) as usize,
 8072                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 8073                goal: SelectionGoal::None,
 8074                ..selection
 8075            });
 8076
 8077            selection_adjustment += old_length - text.len() as i32;
 8078
 8079            edits.push((start..end, text));
 8080        }
 8081
 8082        self.transact(window, cx, |this, window, cx| {
 8083            this.buffer.update(cx, |buffer, cx| {
 8084                buffer.edit(edits, None, cx);
 8085            });
 8086
 8087            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8088                s.select(new_selections);
 8089            });
 8090
 8091            this.request_autoscroll(Autoscroll::fit(), cx);
 8092        });
 8093    }
 8094
 8095    pub fn duplicate(
 8096        &mut self,
 8097        upwards: bool,
 8098        whole_lines: bool,
 8099        window: &mut Window,
 8100        cx: &mut Context<Self>,
 8101    ) {
 8102        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8103        let buffer = &display_map.buffer_snapshot;
 8104        let selections = self.selections.all::<Point>(cx);
 8105
 8106        let mut edits = Vec::new();
 8107        let mut selections_iter = selections.iter().peekable();
 8108        while let Some(selection) = selections_iter.next() {
 8109            let mut rows = selection.spanned_rows(false, &display_map);
 8110            // duplicate line-wise
 8111            if whole_lines || selection.start == selection.end {
 8112                // Avoid duplicating the same lines twice.
 8113                while let Some(next_selection) = selections_iter.peek() {
 8114                    let next_rows = next_selection.spanned_rows(false, &display_map);
 8115                    if next_rows.start < rows.end {
 8116                        rows.end = next_rows.end;
 8117                        selections_iter.next().unwrap();
 8118                    } else {
 8119                        break;
 8120                    }
 8121                }
 8122
 8123                // Copy the text from the selected row region and splice it either at the start
 8124                // or end of the region.
 8125                let start = Point::new(rows.start.0, 0);
 8126                let end = Point::new(
 8127                    rows.end.previous_row().0,
 8128                    buffer.line_len(rows.end.previous_row()),
 8129                );
 8130                let text = buffer
 8131                    .text_for_range(start..end)
 8132                    .chain(Some("\n"))
 8133                    .collect::<String>();
 8134                let insert_location = if upwards {
 8135                    Point::new(rows.end.0, 0)
 8136                } else {
 8137                    start
 8138                };
 8139                edits.push((insert_location..insert_location, text));
 8140            } else {
 8141                // duplicate character-wise
 8142                let start = selection.start;
 8143                let end = selection.end;
 8144                let text = buffer.text_for_range(start..end).collect::<String>();
 8145                edits.push((selection.end..selection.end, text));
 8146            }
 8147        }
 8148
 8149        self.transact(window, cx, |this, _, cx| {
 8150            this.buffer.update(cx, |buffer, cx| {
 8151                buffer.edit(edits, None, cx);
 8152            });
 8153
 8154            this.request_autoscroll(Autoscroll::fit(), cx);
 8155        });
 8156    }
 8157
 8158    pub fn duplicate_line_up(
 8159        &mut self,
 8160        _: &DuplicateLineUp,
 8161        window: &mut Window,
 8162        cx: &mut Context<Self>,
 8163    ) {
 8164        self.duplicate(true, true, window, cx);
 8165    }
 8166
 8167    pub fn duplicate_line_down(
 8168        &mut self,
 8169        _: &DuplicateLineDown,
 8170        window: &mut Window,
 8171        cx: &mut Context<Self>,
 8172    ) {
 8173        self.duplicate(false, true, window, cx);
 8174    }
 8175
 8176    pub fn duplicate_selection(
 8177        &mut self,
 8178        _: &DuplicateSelection,
 8179        window: &mut Window,
 8180        cx: &mut Context<Self>,
 8181    ) {
 8182        self.duplicate(false, false, window, cx);
 8183    }
 8184
 8185    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 8186        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8187        let buffer = self.buffer.read(cx).snapshot(cx);
 8188
 8189        let mut edits = Vec::new();
 8190        let mut unfold_ranges = Vec::new();
 8191        let mut refold_creases = Vec::new();
 8192
 8193        let selections = self.selections.all::<Point>(cx);
 8194        let mut selections = selections.iter().peekable();
 8195        let mut contiguous_row_selections = Vec::new();
 8196        let mut new_selections = Vec::new();
 8197
 8198        while let Some(selection) = selections.next() {
 8199            // Find all the selections that span a contiguous row range
 8200            let (start_row, end_row) = consume_contiguous_rows(
 8201                &mut contiguous_row_selections,
 8202                selection,
 8203                &display_map,
 8204                &mut selections,
 8205            );
 8206
 8207            // Move the text spanned by the row range to be before the line preceding the row range
 8208            if start_row.0 > 0 {
 8209                let range_to_move = Point::new(
 8210                    start_row.previous_row().0,
 8211                    buffer.line_len(start_row.previous_row()),
 8212                )
 8213                    ..Point::new(
 8214                        end_row.previous_row().0,
 8215                        buffer.line_len(end_row.previous_row()),
 8216                    );
 8217                let insertion_point = display_map
 8218                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 8219                    .0;
 8220
 8221                // Don't move lines across excerpts
 8222                if buffer
 8223                    .excerpt_containing(insertion_point..range_to_move.end)
 8224                    .is_some()
 8225                {
 8226                    let text = buffer
 8227                        .text_for_range(range_to_move.clone())
 8228                        .flat_map(|s| s.chars())
 8229                        .skip(1)
 8230                        .chain(['\n'])
 8231                        .collect::<String>();
 8232
 8233                    edits.push((
 8234                        buffer.anchor_after(range_to_move.start)
 8235                            ..buffer.anchor_before(range_to_move.end),
 8236                        String::new(),
 8237                    ));
 8238                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8239                    edits.push((insertion_anchor..insertion_anchor, text));
 8240
 8241                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 8242
 8243                    // Move selections up
 8244                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8245                        |mut selection| {
 8246                            selection.start.row -= row_delta;
 8247                            selection.end.row -= row_delta;
 8248                            selection
 8249                        },
 8250                    ));
 8251
 8252                    // Move folds up
 8253                    unfold_ranges.push(range_to_move.clone());
 8254                    for fold in display_map.folds_in_range(
 8255                        buffer.anchor_before(range_to_move.start)
 8256                            ..buffer.anchor_after(range_to_move.end),
 8257                    ) {
 8258                        let mut start = fold.range.start.to_point(&buffer);
 8259                        let mut end = fold.range.end.to_point(&buffer);
 8260                        start.row -= row_delta;
 8261                        end.row -= row_delta;
 8262                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8263                    }
 8264                }
 8265            }
 8266
 8267            // If we didn't move line(s), preserve the existing selections
 8268            new_selections.append(&mut contiguous_row_selections);
 8269        }
 8270
 8271        self.transact(window, cx, |this, window, cx| {
 8272            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8273            this.buffer.update(cx, |buffer, cx| {
 8274                for (range, text) in edits {
 8275                    buffer.edit([(range, text)], None, cx);
 8276                }
 8277            });
 8278            this.fold_creases(refold_creases, true, window, cx);
 8279            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8280                s.select(new_selections);
 8281            })
 8282        });
 8283    }
 8284
 8285    pub fn move_line_down(
 8286        &mut self,
 8287        _: &MoveLineDown,
 8288        window: &mut Window,
 8289        cx: &mut Context<Self>,
 8290    ) {
 8291        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8292        let buffer = self.buffer.read(cx).snapshot(cx);
 8293
 8294        let mut edits = Vec::new();
 8295        let mut unfold_ranges = Vec::new();
 8296        let mut refold_creases = Vec::new();
 8297
 8298        let selections = self.selections.all::<Point>(cx);
 8299        let mut selections = selections.iter().peekable();
 8300        let mut contiguous_row_selections = Vec::new();
 8301        let mut new_selections = Vec::new();
 8302
 8303        while let Some(selection) = selections.next() {
 8304            // Find all the selections that span a contiguous row range
 8305            let (start_row, end_row) = consume_contiguous_rows(
 8306                &mut contiguous_row_selections,
 8307                selection,
 8308                &display_map,
 8309                &mut selections,
 8310            );
 8311
 8312            // Move the text spanned by the row range to be after the last line of the row range
 8313            if end_row.0 <= buffer.max_point().row {
 8314                let range_to_move =
 8315                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 8316                let insertion_point = display_map
 8317                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 8318                    .0;
 8319
 8320                // Don't move lines across excerpt boundaries
 8321                if buffer
 8322                    .excerpt_containing(range_to_move.start..insertion_point)
 8323                    .is_some()
 8324                {
 8325                    let mut text = String::from("\n");
 8326                    text.extend(buffer.text_for_range(range_to_move.clone()));
 8327                    text.pop(); // Drop trailing newline
 8328                    edits.push((
 8329                        buffer.anchor_after(range_to_move.start)
 8330                            ..buffer.anchor_before(range_to_move.end),
 8331                        String::new(),
 8332                    ));
 8333                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8334                    edits.push((insertion_anchor..insertion_anchor, text));
 8335
 8336                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 8337
 8338                    // Move selections down
 8339                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8340                        |mut selection| {
 8341                            selection.start.row += row_delta;
 8342                            selection.end.row += row_delta;
 8343                            selection
 8344                        },
 8345                    ));
 8346
 8347                    // Move folds down
 8348                    unfold_ranges.push(range_to_move.clone());
 8349                    for fold in display_map.folds_in_range(
 8350                        buffer.anchor_before(range_to_move.start)
 8351                            ..buffer.anchor_after(range_to_move.end),
 8352                    ) {
 8353                        let mut start = fold.range.start.to_point(&buffer);
 8354                        let mut end = fold.range.end.to_point(&buffer);
 8355                        start.row += row_delta;
 8356                        end.row += row_delta;
 8357                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8358                    }
 8359                }
 8360            }
 8361
 8362            // If we didn't move line(s), preserve the existing selections
 8363            new_selections.append(&mut contiguous_row_selections);
 8364        }
 8365
 8366        self.transact(window, cx, |this, window, cx| {
 8367            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8368            this.buffer.update(cx, |buffer, cx| {
 8369                for (range, text) in edits {
 8370                    buffer.edit([(range, text)], None, cx);
 8371                }
 8372            });
 8373            this.fold_creases(refold_creases, true, window, cx);
 8374            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8375                s.select(new_selections)
 8376            });
 8377        });
 8378    }
 8379
 8380    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 8381        let text_layout_details = &self.text_layout_details(window);
 8382        self.transact(window, cx, |this, window, cx| {
 8383            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8384                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 8385                let line_mode = s.line_mode;
 8386                s.move_with(|display_map, selection| {
 8387                    if !selection.is_empty() || line_mode {
 8388                        return;
 8389                    }
 8390
 8391                    let mut head = selection.head();
 8392                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 8393                    if head.column() == display_map.line_len(head.row()) {
 8394                        transpose_offset = display_map
 8395                            .buffer_snapshot
 8396                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8397                    }
 8398
 8399                    if transpose_offset == 0 {
 8400                        return;
 8401                    }
 8402
 8403                    *head.column_mut() += 1;
 8404                    head = display_map.clip_point(head, Bias::Right);
 8405                    let goal = SelectionGoal::HorizontalPosition(
 8406                        display_map
 8407                            .x_for_display_point(head, text_layout_details)
 8408                            .into(),
 8409                    );
 8410                    selection.collapse_to(head, goal);
 8411
 8412                    let transpose_start = display_map
 8413                        .buffer_snapshot
 8414                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8415                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 8416                        let transpose_end = display_map
 8417                            .buffer_snapshot
 8418                            .clip_offset(transpose_offset + 1, Bias::Right);
 8419                        if let Some(ch) =
 8420                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 8421                        {
 8422                            edits.push((transpose_start..transpose_offset, String::new()));
 8423                            edits.push((transpose_end..transpose_end, ch.to_string()));
 8424                        }
 8425                    }
 8426                });
 8427                edits
 8428            });
 8429            this.buffer
 8430                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8431            let selections = this.selections.all::<usize>(cx);
 8432            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8433                s.select(selections);
 8434            });
 8435        });
 8436    }
 8437
 8438    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 8439        self.rewrap_impl(false, cx)
 8440    }
 8441
 8442    pub fn rewrap_impl(&mut self, override_language_settings: bool, cx: &mut Context<Self>) {
 8443        let buffer = self.buffer.read(cx).snapshot(cx);
 8444        let selections = self.selections.all::<Point>(cx);
 8445        let mut selections = selections.iter().peekable();
 8446
 8447        let mut edits = Vec::new();
 8448        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 8449
 8450        while let Some(selection) = selections.next() {
 8451            let mut start_row = selection.start.row;
 8452            let mut end_row = selection.end.row;
 8453
 8454            // Skip selections that overlap with a range that has already been rewrapped.
 8455            let selection_range = start_row..end_row;
 8456            if rewrapped_row_ranges
 8457                .iter()
 8458                .any(|range| range.overlaps(&selection_range))
 8459            {
 8460                continue;
 8461            }
 8462
 8463            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 8464
 8465            // Since not all lines in the selection may be at the same indent
 8466            // level, choose the indent size that is the most common between all
 8467            // of the lines.
 8468            //
 8469            // If there is a tie, we use the deepest indent.
 8470            let (indent_size, indent_end) = {
 8471                let mut indent_size_occurrences = HashMap::default();
 8472                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 8473
 8474                for row in start_row..=end_row {
 8475                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 8476                    rows_by_indent_size.entry(indent).or_default().push(row);
 8477                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 8478                }
 8479
 8480                let indent_size = indent_size_occurrences
 8481                    .into_iter()
 8482                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 8483                    .map(|(indent, _)| indent)
 8484                    .unwrap_or_default();
 8485                let row = rows_by_indent_size[&indent_size][0];
 8486                let indent_end = Point::new(row, indent_size.len);
 8487
 8488                (indent_size, indent_end)
 8489            };
 8490
 8491            let mut line_prefix = indent_size.chars().collect::<String>();
 8492
 8493            let mut inside_comment = false;
 8494            if let Some(comment_prefix) =
 8495                buffer
 8496                    .language_scope_at(selection.head())
 8497                    .and_then(|language| {
 8498                        language
 8499                            .line_comment_prefixes()
 8500                            .iter()
 8501                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 8502                            .cloned()
 8503                    })
 8504            {
 8505                line_prefix.push_str(&comment_prefix);
 8506                inside_comment = true;
 8507            }
 8508
 8509            let language_settings = buffer.language_settings_at(selection.head(), cx);
 8510            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 8511                RewrapBehavior::InComments => inside_comment,
 8512                RewrapBehavior::InSelections => !selection.is_empty(),
 8513                RewrapBehavior::Anywhere => true,
 8514            };
 8515
 8516            let should_rewrap = override_language_settings
 8517                || allow_rewrap_based_on_language
 8518                || self.hard_wrap.is_some();
 8519            if !should_rewrap {
 8520                continue;
 8521            }
 8522
 8523            if selection.is_empty() {
 8524                'expand_upwards: while start_row > 0 {
 8525                    let prev_row = start_row - 1;
 8526                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 8527                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 8528                    {
 8529                        start_row = prev_row;
 8530                    } else {
 8531                        break 'expand_upwards;
 8532                    }
 8533                }
 8534
 8535                'expand_downwards: while end_row < buffer.max_point().row {
 8536                    let next_row = end_row + 1;
 8537                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 8538                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 8539                    {
 8540                        end_row = next_row;
 8541                    } else {
 8542                        break 'expand_downwards;
 8543                    }
 8544                }
 8545            }
 8546
 8547            let start = Point::new(start_row, 0);
 8548            let start_offset = start.to_offset(&buffer);
 8549            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 8550            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 8551            let Some(lines_without_prefixes) = selection_text
 8552                .lines()
 8553                .map(|line| {
 8554                    line.strip_prefix(&line_prefix)
 8555                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 8556                        .ok_or_else(|| {
 8557                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 8558                        })
 8559                })
 8560                .collect::<Result<Vec<_>, _>>()
 8561                .log_err()
 8562            else {
 8563                continue;
 8564            };
 8565
 8566            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
 8567                buffer
 8568                    .language_settings_at(Point::new(start_row, 0), cx)
 8569                    .preferred_line_length as usize
 8570            });
 8571            let wrapped_text = wrap_with_prefix(
 8572                line_prefix,
 8573                lines_without_prefixes.join(" "),
 8574                wrap_column,
 8575                tab_size,
 8576            );
 8577
 8578            // TODO: should always use char-based diff while still supporting cursor behavior that
 8579            // matches vim.
 8580            let mut diff_options = DiffOptions::default();
 8581            if override_language_settings {
 8582                diff_options.max_word_diff_len = 0;
 8583                diff_options.max_word_diff_line_count = 0;
 8584            } else {
 8585                diff_options.max_word_diff_len = usize::MAX;
 8586                diff_options.max_word_diff_line_count = usize::MAX;
 8587            }
 8588
 8589            for (old_range, new_text) in
 8590                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 8591            {
 8592                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 8593                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 8594                edits.push((edit_start..edit_end, new_text));
 8595            }
 8596
 8597            rewrapped_row_ranges.push(start_row..=end_row);
 8598        }
 8599
 8600        self.buffer
 8601            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8602    }
 8603
 8604    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 8605        let mut text = String::new();
 8606        let buffer = self.buffer.read(cx).snapshot(cx);
 8607        let mut selections = self.selections.all::<Point>(cx);
 8608        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8609        {
 8610            let max_point = buffer.max_point();
 8611            let mut is_first = true;
 8612            for selection in &mut selections {
 8613                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8614                if is_entire_line {
 8615                    selection.start = Point::new(selection.start.row, 0);
 8616                    if !selection.is_empty() && selection.end.column == 0 {
 8617                        selection.end = cmp::min(max_point, selection.end);
 8618                    } else {
 8619                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 8620                    }
 8621                    selection.goal = SelectionGoal::None;
 8622                }
 8623                if is_first {
 8624                    is_first = false;
 8625                } else {
 8626                    text += "\n";
 8627                }
 8628                let mut len = 0;
 8629                for chunk in buffer.text_for_range(selection.start..selection.end) {
 8630                    text.push_str(chunk);
 8631                    len += chunk.len();
 8632                }
 8633                clipboard_selections.push(ClipboardSelection {
 8634                    len,
 8635                    is_entire_line,
 8636                    first_line_indent: buffer
 8637                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 8638                        .len,
 8639                });
 8640            }
 8641        }
 8642
 8643        self.transact(window, cx, |this, window, cx| {
 8644            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8645                s.select(selections);
 8646            });
 8647            this.insert("", window, cx);
 8648        });
 8649        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 8650    }
 8651
 8652    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8653        let item = self.cut_common(window, cx);
 8654        cx.write_to_clipboard(item);
 8655    }
 8656
 8657    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8658        self.change_selections(None, window, cx, |s| {
 8659            s.move_with(|snapshot, sel| {
 8660                if sel.is_empty() {
 8661                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8662                }
 8663            });
 8664        });
 8665        let item = self.cut_common(window, cx);
 8666        cx.set_global(KillRing(item))
 8667    }
 8668
 8669    pub fn kill_ring_yank(
 8670        &mut self,
 8671        _: &KillRingYank,
 8672        window: &mut Window,
 8673        cx: &mut Context<Self>,
 8674    ) {
 8675        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8676            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8677                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8678            } else {
 8679                return;
 8680            }
 8681        } else {
 8682            return;
 8683        };
 8684        self.do_paste(&text, metadata, false, window, cx);
 8685    }
 8686
 8687    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8688        let selections = self.selections.all::<Point>(cx);
 8689        let buffer = self.buffer.read(cx).read(cx);
 8690        let mut text = String::new();
 8691
 8692        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8693        {
 8694            let max_point = buffer.max_point();
 8695            let mut is_first = true;
 8696            for selection in selections.iter() {
 8697                let mut start = selection.start;
 8698                let mut end = selection.end;
 8699                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8700                if is_entire_line {
 8701                    start = Point::new(start.row, 0);
 8702                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8703                }
 8704                if is_first {
 8705                    is_first = false;
 8706                } else {
 8707                    text += "\n";
 8708                }
 8709                let mut len = 0;
 8710                for chunk in buffer.text_for_range(start..end) {
 8711                    text.push_str(chunk);
 8712                    len += chunk.len();
 8713                }
 8714                clipboard_selections.push(ClipboardSelection {
 8715                    len,
 8716                    is_entire_line,
 8717                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 8718                });
 8719            }
 8720        }
 8721
 8722        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8723            text,
 8724            clipboard_selections,
 8725        ));
 8726    }
 8727
 8728    pub fn do_paste(
 8729        &mut self,
 8730        text: &String,
 8731        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8732        handle_entire_lines: bool,
 8733        window: &mut Window,
 8734        cx: &mut Context<Self>,
 8735    ) {
 8736        if self.read_only(cx) {
 8737            return;
 8738        }
 8739
 8740        let clipboard_text = Cow::Borrowed(text);
 8741
 8742        self.transact(window, cx, |this, window, cx| {
 8743            if let Some(mut clipboard_selections) = clipboard_selections {
 8744                let old_selections = this.selections.all::<usize>(cx);
 8745                let all_selections_were_entire_line =
 8746                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8747                let first_selection_indent_column =
 8748                    clipboard_selections.first().map(|s| s.first_line_indent);
 8749                if clipboard_selections.len() != old_selections.len() {
 8750                    clipboard_selections.drain(..);
 8751                }
 8752                let cursor_offset = this.selections.last::<usize>(cx).head();
 8753                let mut auto_indent_on_paste = true;
 8754
 8755                this.buffer.update(cx, |buffer, cx| {
 8756                    let snapshot = buffer.read(cx);
 8757                    auto_indent_on_paste = snapshot
 8758                        .language_settings_at(cursor_offset, cx)
 8759                        .auto_indent_on_paste;
 8760
 8761                    let mut start_offset = 0;
 8762                    let mut edits = Vec::new();
 8763                    let mut original_indent_columns = Vec::new();
 8764                    for (ix, selection) in old_selections.iter().enumerate() {
 8765                        let to_insert;
 8766                        let entire_line;
 8767                        let original_indent_column;
 8768                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8769                            let end_offset = start_offset + clipboard_selection.len;
 8770                            to_insert = &clipboard_text[start_offset..end_offset];
 8771                            entire_line = clipboard_selection.is_entire_line;
 8772                            start_offset = end_offset + 1;
 8773                            original_indent_column = Some(clipboard_selection.first_line_indent);
 8774                        } else {
 8775                            to_insert = clipboard_text.as_str();
 8776                            entire_line = all_selections_were_entire_line;
 8777                            original_indent_column = first_selection_indent_column
 8778                        }
 8779
 8780                        // If the corresponding selection was empty when this slice of the
 8781                        // clipboard text was written, then the entire line containing the
 8782                        // selection was copied. If this selection is also currently empty,
 8783                        // then paste the line before the current line of the buffer.
 8784                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8785                            let column = selection.start.to_point(&snapshot).column as usize;
 8786                            let line_start = selection.start - column;
 8787                            line_start..line_start
 8788                        } else {
 8789                            selection.range()
 8790                        };
 8791
 8792                        edits.push((range, to_insert));
 8793                        original_indent_columns.push(original_indent_column);
 8794                    }
 8795                    drop(snapshot);
 8796
 8797                    buffer.edit(
 8798                        edits,
 8799                        if auto_indent_on_paste {
 8800                            Some(AutoindentMode::Block {
 8801                                original_indent_columns,
 8802                            })
 8803                        } else {
 8804                            None
 8805                        },
 8806                        cx,
 8807                    );
 8808                });
 8809
 8810                let selections = this.selections.all::<usize>(cx);
 8811                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8812                    s.select(selections)
 8813                });
 8814            } else {
 8815                this.insert(&clipboard_text, window, cx);
 8816            }
 8817        });
 8818    }
 8819
 8820    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8821        if let Some(item) = cx.read_from_clipboard() {
 8822            let entries = item.entries();
 8823
 8824            match entries.first() {
 8825                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8826                // of all the pasted entries.
 8827                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8828                    .do_paste(
 8829                        clipboard_string.text(),
 8830                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8831                        true,
 8832                        window,
 8833                        cx,
 8834                    ),
 8835                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8836            }
 8837        }
 8838    }
 8839
 8840    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8841        if self.read_only(cx) {
 8842            return;
 8843        }
 8844
 8845        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8846            if let Some((selections, _)) =
 8847                self.selection_history.transaction(transaction_id).cloned()
 8848            {
 8849                self.change_selections(None, window, cx, |s| {
 8850                    s.select_anchors(selections.to_vec());
 8851                });
 8852            } else {
 8853                log::error!(
 8854                    "No entry in selection_history found for undo. \
 8855                     This may correspond to a bug where undo does not update the selection. \
 8856                     If this is occurring, please add details to \
 8857                     https://github.com/zed-industries/zed/issues/22692"
 8858                );
 8859            }
 8860            self.request_autoscroll(Autoscroll::fit(), cx);
 8861            self.unmark_text(window, cx);
 8862            self.refresh_inline_completion(true, false, window, cx);
 8863            cx.emit(EditorEvent::Edited { transaction_id });
 8864            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8865        }
 8866    }
 8867
 8868    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8869        if self.read_only(cx) {
 8870            return;
 8871        }
 8872
 8873        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8874            if let Some((_, Some(selections))) =
 8875                self.selection_history.transaction(transaction_id).cloned()
 8876            {
 8877                self.change_selections(None, window, cx, |s| {
 8878                    s.select_anchors(selections.to_vec());
 8879                });
 8880            } else {
 8881                log::error!(
 8882                    "No entry in selection_history found for redo. \
 8883                     This may correspond to a bug where undo does not update the selection. \
 8884                     If this is occurring, please add details to \
 8885                     https://github.com/zed-industries/zed/issues/22692"
 8886                );
 8887            }
 8888            self.request_autoscroll(Autoscroll::fit(), cx);
 8889            self.unmark_text(window, cx);
 8890            self.refresh_inline_completion(true, false, window, cx);
 8891            cx.emit(EditorEvent::Edited { transaction_id });
 8892        }
 8893    }
 8894
 8895    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8896        self.buffer
 8897            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8898    }
 8899
 8900    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8901        self.buffer
 8902            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8903    }
 8904
 8905    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8906        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8907            let line_mode = s.line_mode;
 8908            s.move_with(|map, selection| {
 8909                let cursor = if selection.is_empty() && !line_mode {
 8910                    movement::left(map, selection.start)
 8911                } else {
 8912                    selection.start
 8913                };
 8914                selection.collapse_to(cursor, SelectionGoal::None);
 8915            });
 8916        })
 8917    }
 8918
 8919    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8920        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8921            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8922        })
 8923    }
 8924
 8925    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8926        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8927            let line_mode = s.line_mode;
 8928            s.move_with(|map, selection| {
 8929                let cursor = if selection.is_empty() && !line_mode {
 8930                    movement::right(map, selection.end)
 8931                } else {
 8932                    selection.end
 8933                };
 8934                selection.collapse_to(cursor, SelectionGoal::None)
 8935            });
 8936        })
 8937    }
 8938
 8939    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8940        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8941            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8942        })
 8943    }
 8944
 8945    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8946        if self.take_rename(true, window, cx).is_some() {
 8947            return;
 8948        }
 8949
 8950        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8951            cx.propagate();
 8952            return;
 8953        }
 8954
 8955        let text_layout_details = &self.text_layout_details(window);
 8956        let selection_count = self.selections.count();
 8957        let first_selection = self.selections.first_anchor();
 8958
 8959        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8960            let line_mode = s.line_mode;
 8961            s.move_with(|map, selection| {
 8962                if !selection.is_empty() && !line_mode {
 8963                    selection.goal = SelectionGoal::None;
 8964                }
 8965                let (cursor, goal) = movement::up(
 8966                    map,
 8967                    selection.start,
 8968                    selection.goal,
 8969                    false,
 8970                    text_layout_details,
 8971                );
 8972                selection.collapse_to(cursor, goal);
 8973            });
 8974        });
 8975
 8976        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8977        {
 8978            cx.propagate();
 8979        }
 8980    }
 8981
 8982    pub fn move_up_by_lines(
 8983        &mut self,
 8984        action: &MoveUpByLines,
 8985        window: &mut Window,
 8986        cx: &mut Context<Self>,
 8987    ) {
 8988        if self.take_rename(true, window, cx).is_some() {
 8989            return;
 8990        }
 8991
 8992        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8993            cx.propagate();
 8994            return;
 8995        }
 8996
 8997        let text_layout_details = &self.text_layout_details(window);
 8998
 8999        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9000            let line_mode = s.line_mode;
 9001            s.move_with(|map, selection| {
 9002                if !selection.is_empty() && !line_mode {
 9003                    selection.goal = SelectionGoal::None;
 9004                }
 9005                let (cursor, goal) = movement::up_by_rows(
 9006                    map,
 9007                    selection.start,
 9008                    action.lines,
 9009                    selection.goal,
 9010                    false,
 9011                    text_layout_details,
 9012                );
 9013                selection.collapse_to(cursor, goal);
 9014            });
 9015        })
 9016    }
 9017
 9018    pub fn move_down_by_lines(
 9019        &mut self,
 9020        action: &MoveDownByLines,
 9021        window: &mut Window,
 9022        cx: &mut Context<Self>,
 9023    ) {
 9024        if self.take_rename(true, window, cx).is_some() {
 9025            return;
 9026        }
 9027
 9028        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9029            cx.propagate();
 9030            return;
 9031        }
 9032
 9033        let text_layout_details = &self.text_layout_details(window);
 9034
 9035        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9036            let line_mode = s.line_mode;
 9037            s.move_with(|map, selection| {
 9038                if !selection.is_empty() && !line_mode {
 9039                    selection.goal = SelectionGoal::None;
 9040                }
 9041                let (cursor, goal) = movement::down_by_rows(
 9042                    map,
 9043                    selection.start,
 9044                    action.lines,
 9045                    selection.goal,
 9046                    false,
 9047                    text_layout_details,
 9048                );
 9049                selection.collapse_to(cursor, goal);
 9050            });
 9051        })
 9052    }
 9053
 9054    pub fn select_down_by_lines(
 9055        &mut self,
 9056        action: &SelectDownByLines,
 9057        window: &mut Window,
 9058        cx: &mut Context<Self>,
 9059    ) {
 9060        let text_layout_details = &self.text_layout_details(window);
 9061        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9062            s.move_heads_with(|map, head, goal| {
 9063                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9064            })
 9065        })
 9066    }
 9067
 9068    pub fn select_up_by_lines(
 9069        &mut self,
 9070        action: &SelectUpByLines,
 9071        window: &mut Window,
 9072        cx: &mut Context<Self>,
 9073    ) {
 9074        let text_layout_details = &self.text_layout_details(window);
 9075        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9076            s.move_heads_with(|map, head, goal| {
 9077                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9078            })
 9079        })
 9080    }
 9081
 9082    pub fn select_page_up(
 9083        &mut self,
 9084        _: &SelectPageUp,
 9085        window: &mut Window,
 9086        cx: &mut Context<Self>,
 9087    ) {
 9088        let Some(row_count) = self.visible_row_count() else {
 9089            return;
 9090        };
 9091
 9092        let text_layout_details = &self.text_layout_details(window);
 9093
 9094        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9095            s.move_heads_with(|map, head, goal| {
 9096                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 9097            })
 9098        })
 9099    }
 9100
 9101    pub fn move_page_up(
 9102        &mut self,
 9103        action: &MovePageUp,
 9104        window: &mut Window,
 9105        cx: &mut Context<Self>,
 9106    ) {
 9107        if self.take_rename(true, window, cx).is_some() {
 9108            return;
 9109        }
 9110
 9111        if self
 9112            .context_menu
 9113            .borrow_mut()
 9114            .as_mut()
 9115            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 9116            .unwrap_or(false)
 9117        {
 9118            return;
 9119        }
 9120
 9121        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9122            cx.propagate();
 9123            return;
 9124        }
 9125
 9126        let Some(row_count) = self.visible_row_count() else {
 9127            return;
 9128        };
 9129
 9130        let autoscroll = if action.center_cursor {
 9131            Autoscroll::center()
 9132        } else {
 9133            Autoscroll::fit()
 9134        };
 9135
 9136        let text_layout_details = &self.text_layout_details(window);
 9137
 9138        self.change_selections(Some(autoscroll), window, cx, |s| {
 9139            let line_mode = s.line_mode;
 9140            s.move_with(|map, selection| {
 9141                if !selection.is_empty() && !line_mode {
 9142                    selection.goal = SelectionGoal::None;
 9143                }
 9144                let (cursor, goal) = movement::up_by_rows(
 9145                    map,
 9146                    selection.end,
 9147                    row_count,
 9148                    selection.goal,
 9149                    false,
 9150                    text_layout_details,
 9151                );
 9152                selection.collapse_to(cursor, goal);
 9153            });
 9154        });
 9155    }
 9156
 9157    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 9158        let text_layout_details = &self.text_layout_details(window);
 9159        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9160            s.move_heads_with(|map, head, goal| {
 9161                movement::up(map, head, goal, false, text_layout_details)
 9162            })
 9163        })
 9164    }
 9165
 9166    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 9167        self.take_rename(true, window, cx);
 9168
 9169        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9170            cx.propagate();
 9171            return;
 9172        }
 9173
 9174        let text_layout_details = &self.text_layout_details(window);
 9175        let selection_count = self.selections.count();
 9176        let first_selection = self.selections.first_anchor();
 9177
 9178        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9179            let line_mode = s.line_mode;
 9180            s.move_with(|map, selection| {
 9181                if !selection.is_empty() && !line_mode {
 9182                    selection.goal = SelectionGoal::None;
 9183                }
 9184                let (cursor, goal) = movement::down(
 9185                    map,
 9186                    selection.end,
 9187                    selection.goal,
 9188                    false,
 9189                    text_layout_details,
 9190                );
 9191                selection.collapse_to(cursor, goal);
 9192            });
 9193        });
 9194
 9195        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9196        {
 9197            cx.propagate();
 9198        }
 9199    }
 9200
 9201    pub fn select_page_down(
 9202        &mut self,
 9203        _: &SelectPageDown,
 9204        window: &mut Window,
 9205        cx: &mut Context<Self>,
 9206    ) {
 9207        let Some(row_count) = self.visible_row_count() else {
 9208            return;
 9209        };
 9210
 9211        let text_layout_details = &self.text_layout_details(window);
 9212
 9213        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9214            s.move_heads_with(|map, head, goal| {
 9215                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 9216            })
 9217        })
 9218    }
 9219
 9220    pub fn move_page_down(
 9221        &mut self,
 9222        action: &MovePageDown,
 9223        window: &mut Window,
 9224        cx: &mut Context<Self>,
 9225    ) {
 9226        if self.take_rename(true, window, cx).is_some() {
 9227            return;
 9228        }
 9229
 9230        if self
 9231            .context_menu
 9232            .borrow_mut()
 9233            .as_mut()
 9234            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 9235            .unwrap_or(false)
 9236        {
 9237            return;
 9238        }
 9239
 9240        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9241            cx.propagate();
 9242            return;
 9243        }
 9244
 9245        let Some(row_count) = self.visible_row_count() else {
 9246            return;
 9247        };
 9248
 9249        let autoscroll = if action.center_cursor {
 9250            Autoscroll::center()
 9251        } else {
 9252            Autoscroll::fit()
 9253        };
 9254
 9255        let text_layout_details = &self.text_layout_details(window);
 9256        self.change_selections(Some(autoscroll), window, cx, |s| {
 9257            let line_mode = s.line_mode;
 9258            s.move_with(|map, selection| {
 9259                if !selection.is_empty() && !line_mode {
 9260                    selection.goal = SelectionGoal::None;
 9261                }
 9262                let (cursor, goal) = movement::down_by_rows(
 9263                    map,
 9264                    selection.end,
 9265                    row_count,
 9266                    selection.goal,
 9267                    false,
 9268                    text_layout_details,
 9269                );
 9270                selection.collapse_to(cursor, goal);
 9271            });
 9272        });
 9273    }
 9274
 9275    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 9276        let text_layout_details = &self.text_layout_details(window);
 9277        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9278            s.move_heads_with(|map, head, goal| {
 9279                movement::down(map, head, goal, false, text_layout_details)
 9280            })
 9281        });
 9282    }
 9283
 9284    pub fn context_menu_first(
 9285        &mut self,
 9286        _: &ContextMenuFirst,
 9287        _window: &mut Window,
 9288        cx: &mut Context<Self>,
 9289    ) {
 9290        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9291            context_menu.select_first(self.completion_provider.as_deref(), cx);
 9292        }
 9293    }
 9294
 9295    pub fn context_menu_prev(
 9296        &mut self,
 9297        _: &ContextMenuPrevious,
 9298        _window: &mut Window,
 9299        cx: &mut Context<Self>,
 9300    ) {
 9301        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9302            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 9303        }
 9304    }
 9305
 9306    pub fn context_menu_next(
 9307        &mut self,
 9308        _: &ContextMenuNext,
 9309        _window: &mut Window,
 9310        cx: &mut Context<Self>,
 9311    ) {
 9312        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9313            context_menu.select_next(self.completion_provider.as_deref(), cx);
 9314        }
 9315    }
 9316
 9317    pub fn context_menu_last(
 9318        &mut self,
 9319        _: &ContextMenuLast,
 9320        _window: &mut Window,
 9321        cx: &mut Context<Self>,
 9322    ) {
 9323        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9324            context_menu.select_last(self.completion_provider.as_deref(), cx);
 9325        }
 9326    }
 9327
 9328    pub fn move_to_previous_word_start(
 9329        &mut self,
 9330        _: &MoveToPreviousWordStart,
 9331        window: &mut Window,
 9332        cx: &mut Context<Self>,
 9333    ) {
 9334        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9335            s.move_cursors_with(|map, head, _| {
 9336                (
 9337                    movement::previous_word_start(map, head),
 9338                    SelectionGoal::None,
 9339                )
 9340            });
 9341        })
 9342    }
 9343
 9344    pub fn move_to_previous_subword_start(
 9345        &mut self,
 9346        _: &MoveToPreviousSubwordStart,
 9347        window: &mut Window,
 9348        cx: &mut Context<Self>,
 9349    ) {
 9350        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9351            s.move_cursors_with(|map, head, _| {
 9352                (
 9353                    movement::previous_subword_start(map, head),
 9354                    SelectionGoal::None,
 9355                )
 9356            });
 9357        })
 9358    }
 9359
 9360    pub fn select_to_previous_word_start(
 9361        &mut self,
 9362        _: &SelectToPreviousWordStart,
 9363        window: &mut Window,
 9364        cx: &mut Context<Self>,
 9365    ) {
 9366        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9367            s.move_heads_with(|map, head, _| {
 9368                (
 9369                    movement::previous_word_start(map, head),
 9370                    SelectionGoal::None,
 9371                )
 9372            });
 9373        })
 9374    }
 9375
 9376    pub fn select_to_previous_subword_start(
 9377        &mut self,
 9378        _: &SelectToPreviousSubwordStart,
 9379        window: &mut Window,
 9380        cx: &mut Context<Self>,
 9381    ) {
 9382        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9383            s.move_heads_with(|map, head, _| {
 9384                (
 9385                    movement::previous_subword_start(map, head),
 9386                    SelectionGoal::None,
 9387                )
 9388            });
 9389        })
 9390    }
 9391
 9392    pub fn delete_to_previous_word_start(
 9393        &mut self,
 9394        action: &DeleteToPreviousWordStart,
 9395        window: &mut Window,
 9396        cx: &mut Context<Self>,
 9397    ) {
 9398        self.transact(window, cx, |this, window, cx| {
 9399            this.select_autoclose_pair(window, cx);
 9400            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9401                let line_mode = s.line_mode;
 9402                s.move_with(|map, selection| {
 9403                    if selection.is_empty() && !line_mode {
 9404                        let cursor = if action.ignore_newlines {
 9405                            movement::previous_word_start(map, selection.head())
 9406                        } else {
 9407                            movement::previous_word_start_or_newline(map, selection.head())
 9408                        };
 9409                        selection.set_head(cursor, SelectionGoal::None);
 9410                    }
 9411                });
 9412            });
 9413            this.insert("", window, cx);
 9414        });
 9415    }
 9416
 9417    pub fn delete_to_previous_subword_start(
 9418        &mut self,
 9419        _: &DeleteToPreviousSubwordStart,
 9420        window: &mut Window,
 9421        cx: &mut Context<Self>,
 9422    ) {
 9423        self.transact(window, cx, |this, window, cx| {
 9424            this.select_autoclose_pair(window, cx);
 9425            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9426                let line_mode = s.line_mode;
 9427                s.move_with(|map, selection| {
 9428                    if selection.is_empty() && !line_mode {
 9429                        let cursor = movement::previous_subword_start(map, selection.head());
 9430                        selection.set_head(cursor, SelectionGoal::None);
 9431                    }
 9432                });
 9433            });
 9434            this.insert("", window, cx);
 9435        });
 9436    }
 9437
 9438    pub fn move_to_next_word_end(
 9439        &mut self,
 9440        _: &MoveToNextWordEnd,
 9441        window: &mut Window,
 9442        cx: &mut Context<Self>,
 9443    ) {
 9444        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9445            s.move_cursors_with(|map, head, _| {
 9446                (movement::next_word_end(map, head), SelectionGoal::None)
 9447            });
 9448        })
 9449    }
 9450
 9451    pub fn move_to_next_subword_end(
 9452        &mut self,
 9453        _: &MoveToNextSubwordEnd,
 9454        window: &mut Window,
 9455        cx: &mut Context<Self>,
 9456    ) {
 9457        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9458            s.move_cursors_with(|map, head, _| {
 9459                (movement::next_subword_end(map, head), SelectionGoal::None)
 9460            });
 9461        })
 9462    }
 9463
 9464    pub fn select_to_next_word_end(
 9465        &mut self,
 9466        _: &SelectToNextWordEnd,
 9467        window: &mut Window,
 9468        cx: &mut Context<Self>,
 9469    ) {
 9470        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9471            s.move_heads_with(|map, head, _| {
 9472                (movement::next_word_end(map, head), SelectionGoal::None)
 9473            });
 9474        })
 9475    }
 9476
 9477    pub fn select_to_next_subword_end(
 9478        &mut self,
 9479        _: &SelectToNextSubwordEnd,
 9480        window: &mut Window,
 9481        cx: &mut Context<Self>,
 9482    ) {
 9483        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9484            s.move_heads_with(|map, head, _| {
 9485                (movement::next_subword_end(map, head), SelectionGoal::None)
 9486            });
 9487        })
 9488    }
 9489
 9490    pub fn delete_to_next_word_end(
 9491        &mut self,
 9492        action: &DeleteToNextWordEnd,
 9493        window: &mut Window,
 9494        cx: &mut Context<Self>,
 9495    ) {
 9496        self.transact(window, cx, |this, window, cx| {
 9497            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9498                let line_mode = s.line_mode;
 9499                s.move_with(|map, selection| {
 9500                    if selection.is_empty() && !line_mode {
 9501                        let cursor = if action.ignore_newlines {
 9502                            movement::next_word_end(map, selection.head())
 9503                        } else {
 9504                            movement::next_word_end_or_newline(map, selection.head())
 9505                        };
 9506                        selection.set_head(cursor, SelectionGoal::None);
 9507                    }
 9508                });
 9509            });
 9510            this.insert("", window, cx);
 9511        });
 9512    }
 9513
 9514    pub fn delete_to_next_subword_end(
 9515        &mut self,
 9516        _: &DeleteToNextSubwordEnd,
 9517        window: &mut Window,
 9518        cx: &mut Context<Self>,
 9519    ) {
 9520        self.transact(window, cx, |this, window, cx| {
 9521            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9522                s.move_with(|map, selection| {
 9523                    if selection.is_empty() {
 9524                        let cursor = movement::next_subword_end(map, selection.head());
 9525                        selection.set_head(cursor, SelectionGoal::None);
 9526                    }
 9527                });
 9528            });
 9529            this.insert("", window, cx);
 9530        });
 9531    }
 9532
 9533    pub fn move_to_beginning_of_line(
 9534        &mut self,
 9535        action: &MoveToBeginningOfLine,
 9536        window: &mut Window,
 9537        cx: &mut Context<Self>,
 9538    ) {
 9539        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9540            s.move_cursors_with(|map, head, _| {
 9541                (
 9542                    movement::indented_line_beginning(
 9543                        map,
 9544                        head,
 9545                        action.stop_at_soft_wraps,
 9546                        action.stop_at_indent,
 9547                    ),
 9548                    SelectionGoal::None,
 9549                )
 9550            });
 9551        })
 9552    }
 9553
 9554    pub fn select_to_beginning_of_line(
 9555        &mut self,
 9556        action: &SelectToBeginningOfLine,
 9557        window: &mut Window,
 9558        cx: &mut Context<Self>,
 9559    ) {
 9560        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9561            s.move_heads_with(|map, head, _| {
 9562                (
 9563                    movement::indented_line_beginning(
 9564                        map,
 9565                        head,
 9566                        action.stop_at_soft_wraps,
 9567                        action.stop_at_indent,
 9568                    ),
 9569                    SelectionGoal::None,
 9570                )
 9571            });
 9572        });
 9573    }
 9574
 9575    pub fn delete_to_beginning_of_line(
 9576        &mut self,
 9577        action: &DeleteToBeginningOfLine,
 9578        window: &mut Window,
 9579        cx: &mut Context<Self>,
 9580    ) {
 9581        self.transact(window, cx, |this, window, cx| {
 9582            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9583                s.move_with(|_, selection| {
 9584                    selection.reversed = true;
 9585                });
 9586            });
 9587
 9588            this.select_to_beginning_of_line(
 9589                &SelectToBeginningOfLine {
 9590                    stop_at_soft_wraps: false,
 9591                    stop_at_indent: action.stop_at_indent,
 9592                },
 9593                window,
 9594                cx,
 9595            );
 9596            this.backspace(&Backspace, window, cx);
 9597        });
 9598    }
 9599
 9600    pub fn move_to_end_of_line(
 9601        &mut self,
 9602        action: &MoveToEndOfLine,
 9603        window: &mut Window,
 9604        cx: &mut Context<Self>,
 9605    ) {
 9606        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9607            s.move_cursors_with(|map, head, _| {
 9608                (
 9609                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9610                    SelectionGoal::None,
 9611                )
 9612            });
 9613        })
 9614    }
 9615
 9616    pub fn select_to_end_of_line(
 9617        &mut self,
 9618        action: &SelectToEndOfLine,
 9619        window: &mut Window,
 9620        cx: &mut Context<Self>,
 9621    ) {
 9622        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9623            s.move_heads_with(|map, head, _| {
 9624                (
 9625                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9626                    SelectionGoal::None,
 9627                )
 9628            });
 9629        })
 9630    }
 9631
 9632    pub fn delete_to_end_of_line(
 9633        &mut self,
 9634        _: &DeleteToEndOfLine,
 9635        window: &mut Window,
 9636        cx: &mut Context<Self>,
 9637    ) {
 9638        self.transact(window, cx, |this, window, cx| {
 9639            this.select_to_end_of_line(
 9640                &SelectToEndOfLine {
 9641                    stop_at_soft_wraps: false,
 9642                },
 9643                window,
 9644                cx,
 9645            );
 9646            this.delete(&Delete, window, cx);
 9647        });
 9648    }
 9649
 9650    pub fn cut_to_end_of_line(
 9651        &mut self,
 9652        _: &CutToEndOfLine,
 9653        window: &mut Window,
 9654        cx: &mut Context<Self>,
 9655    ) {
 9656        self.transact(window, cx, |this, window, cx| {
 9657            this.select_to_end_of_line(
 9658                &SelectToEndOfLine {
 9659                    stop_at_soft_wraps: false,
 9660                },
 9661                window,
 9662                cx,
 9663            );
 9664            this.cut(&Cut, window, cx);
 9665        });
 9666    }
 9667
 9668    pub fn move_to_start_of_paragraph(
 9669        &mut self,
 9670        _: &MoveToStartOfParagraph,
 9671        window: &mut Window,
 9672        cx: &mut Context<Self>,
 9673    ) {
 9674        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9675            cx.propagate();
 9676            return;
 9677        }
 9678
 9679        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9680            s.move_with(|map, selection| {
 9681                selection.collapse_to(
 9682                    movement::start_of_paragraph(map, selection.head(), 1),
 9683                    SelectionGoal::None,
 9684                )
 9685            });
 9686        })
 9687    }
 9688
 9689    pub fn move_to_end_of_paragraph(
 9690        &mut self,
 9691        _: &MoveToEndOfParagraph,
 9692        window: &mut Window,
 9693        cx: &mut Context<Self>,
 9694    ) {
 9695        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9696            cx.propagate();
 9697            return;
 9698        }
 9699
 9700        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9701            s.move_with(|map, selection| {
 9702                selection.collapse_to(
 9703                    movement::end_of_paragraph(map, selection.head(), 1),
 9704                    SelectionGoal::None,
 9705                )
 9706            });
 9707        })
 9708    }
 9709
 9710    pub fn select_to_start_of_paragraph(
 9711        &mut self,
 9712        _: &SelectToStartOfParagraph,
 9713        window: &mut Window,
 9714        cx: &mut Context<Self>,
 9715    ) {
 9716        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9717            cx.propagate();
 9718            return;
 9719        }
 9720
 9721        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9722            s.move_heads_with(|map, head, _| {
 9723                (
 9724                    movement::start_of_paragraph(map, head, 1),
 9725                    SelectionGoal::None,
 9726                )
 9727            });
 9728        })
 9729    }
 9730
 9731    pub fn select_to_end_of_paragraph(
 9732        &mut self,
 9733        _: &SelectToEndOfParagraph,
 9734        window: &mut Window,
 9735        cx: &mut Context<Self>,
 9736    ) {
 9737        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9738            cx.propagate();
 9739            return;
 9740        }
 9741
 9742        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9743            s.move_heads_with(|map, head, _| {
 9744                (
 9745                    movement::end_of_paragraph(map, head, 1),
 9746                    SelectionGoal::None,
 9747                )
 9748            });
 9749        })
 9750    }
 9751
 9752    pub fn move_to_start_of_excerpt(
 9753        &mut self,
 9754        _: &MoveToStartOfExcerpt,
 9755        window: &mut Window,
 9756        cx: &mut Context<Self>,
 9757    ) {
 9758        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9759            cx.propagate();
 9760            return;
 9761        }
 9762
 9763        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9764            s.move_with(|map, selection| {
 9765                selection.collapse_to(
 9766                    movement::start_of_excerpt(
 9767                        map,
 9768                        selection.head(),
 9769                        workspace::searchable::Direction::Prev,
 9770                    ),
 9771                    SelectionGoal::None,
 9772                )
 9773            });
 9774        })
 9775    }
 9776
 9777    pub fn move_to_end_of_excerpt(
 9778        &mut self,
 9779        _: &MoveToEndOfExcerpt,
 9780        window: &mut Window,
 9781        cx: &mut Context<Self>,
 9782    ) {
 9783        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9784            cx.propagate();
 9785            return;
 9786        }
 9787
 9788        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9789            s.move_with(|map, selection| {
 9790                selection.collapse_to(
 9791                    movement::end_of_excerpt(
 9792                        map,
 9793                        selection.head(),
 9794                        workspace::searchable::Direction::Next,
 9795                    ),
 9796                    SelectionGoal::None,
 9797                )
 9798            });
 9799        })
 9800    }
 9801
 9802    pub fn select_to_start_of_excerpt(
 9803        &mut self,
 9804        _: &SelectToStartOfExcerpt,
 9805        window: &mut Window,
 9806        cx: &mut Context<Self>,
 9807    ) {
 9808        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9809            cx.propagate();
 9810            return;
 9811        }
 9812
 9813        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9814            s.move_heads_with(|map, head, _| {
 9815                (
 9816                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
 9817                    SelectionGoal::None,
 9818                )
 9819            });
 9820        })
 9821    }
 9822
 9823    pub fn select_to_end_of_excerpt(
 9824        &mut self,
 9825        _: &SelectToEndOfExcerpt,
 9826        window: &mut Window,
 9827        cx: &mut Context<Self>,
 9828    ) {
 9829        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9830            cx.propagate();
 9831            return;
 9832        }
 9833
 9834        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9835            s.move_heads_with(|map, head, _| {
 9836                (
 9837                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
 9838                    SelectionGoal::None,
 9839                )
 9840            });
 9841        })
 9842    }
 9843
 9844    pub fn move_to_beginning(
 9845        &mut self,
 9846        _: &MoveToBeginning,
 9847        window: &mut Window,
 9848        cx: &mut Context<Self>,
 9849    ) {
 9850        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9851            cx.propagate();
 9852            return;
 9853        }
 9854
 9855        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9856            s.select_ranges(vec![0..0]);
 9857        });
 9858    }
 9859
 9860    pub fn select_to_beginning(
 9861        &mut self,
 9862        _: &SelectToBeginning,
 9863        window: &mut Window,
 9864        cx: &mut Context<Self>,
 9865    ) {
 9866        let mut selection = self.selections.last::<Point>(cx);
 9867        selection.set_head(Point::zero(), SelectionGoal::None);
 9868
 9869        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9870            s.select(vec![selection]);
 9871        });
 9872    }
 9873
 9874    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9875        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9876            cx.propagate();
 9877            return;
 9878        }
 9879
 9880        let cursor = self.buffer.read(cx).read(cx).len();
 9881        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9882            s.select_ranges(vec![cursor..cursor])
 9883        });
 9884    }
 9885
 9886    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9887        self.nav_history = nav_history;
 9888    }
 9889
 9890    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9891        self.nav_history.as_ref()
 9892    }
 9893
 9894    fn push_to_nav_history(
 9895        &mut self,
 9896        cursor_anchor: Anchor,
 9897        new_position: Option<Point>,
 9898        cx: &mut Context<Self>,
 9899    ) {
 9900        if let Some(nav_history) = self.nav_history.as_mut() {
 9901            let buffer = self.buffer.read(cx).read(cx);
 9902            let cursor_position = cursor_anchor.to_point(&buffer);
 9903            let scroll_state = self.scroll_manager.anchor();
 9904            let scroll_top_row = scroll_state.top_row(&buffer);
 9905            drop(buffer);
 9906
 9907            if let Some(new_position) = new_position {
 9908                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9909                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9910                    return;
 9911                }
 9912            }
 9913
 9914            nav_history.push(
 9915                Some(NavigationData {
 9916                    cursor_anchor,
 9917                    cursor_position,
 9918                    scroll_anchor: scroll_state,
 9919                    scroll_top_row,
 9920                }),
 9921                cx,
 9922            );
 9923        }
 9924    }
 9925
 9926    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9927        let buffer = self.buffer.read(cx).snapshot(cx);
 9928        let mut selection = self.selections.first::<usize>(cx);
 9929        selection.set_head(buffer.len(), SelectionGoal::None);
 9930        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9931            s.select(vec![selection]);
 9932        });
 9933    }
 9934
 9935    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9936        let end = self.buffer.read(cx).read(cx).len();
 9937        self.change_selections(None, window, cx, |s| {
 9938            s.select_ranges(vec![0..end]);
 9939        });
 9940    }
 9941
 9942    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9943        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9944        let mut selections = self.selections.all::<Point>(cx);
 9945        let max_point = display_map.buffer_snapshot.max_point();
 9946        for selection in &mut selections {
 9947            let rows = selection.spanned_rows(true, &display_map);
 9948            selection.start = Point::new(rows.start.0, 0);
 9949            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9950            selection.reversed = false;
 9951        }
 9952        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9953            s.select(selections);
 9954        });
 9955    }
 9956
 9957    pub fn split_selection_into_lines(
 9958        &mut self,
 9959        _: &SplitSelectionIntoLines,
 9960        window: &mut Window,
 9961        cx: &mut Context<Self>,
 9962    ) {
 9963        let selections = self
 9964            .selections
 9965            .all::<Point>(cx)
 9966            .into_iter()
 9967            .map(|selection| selection.start..selection.end)
 9968            .collect::<Vec<_>>();
 9969        self.unfold_ranges(&selections, true, true, cx);
 9970
 9971        let mut new_selection_ranges = Vec::new();
 9972        {
 9973            let buffer = self.buffer.read(cx).read(cx);
 9974            for selection in selections {
 9975                for row in selection.start.row..selection.end.row {
 9976                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9977                    new_selection_ranges.push(cursor..cursor);
 9978                }
 9979
 9980                let is_multiline_selection = selection.start.row != selection.end.row;
 9981                // Don't insert last one if it's a multi-line selection ending at the start of a line,
 9982                // so this action feels more ergonomic when paired with other selection operations
 9983                let should_skip_last = is_multiline_selection && selection.end.column == 0;
 9984                if !should_skip_last {
 9985                    new_selection_ranges.push(selection.end..selection.end);
 9986                }
 9987            }
 9988        }
 9989        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9990            s.select_ranges(new_selection_ranges);
 9991        });
 9992    }
 9993
 9994    pub fn add_selection_above(
 9995        &mut self,
 9996        _: &AddSelectionAbove,
 9997        window: &mut Window,
 9998        cx: &mut Context<Self>,
 9999    ) {
10000        self.add_selection(true, window, cx);
10001    }
10002
10003    pub fn add_selection_below(
10004        &mut self,
10005        _: &AddSelectionBelow,
10006        window: &mut Window,
10007        cx: &mut Context<Self>,
10008    ) {
10009        self.add_selection(false, window, cx);
10010    }
10011
10012    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
10013        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10014        let mut selections = self.selections.all::<Point>(cx);
10015        let text_layout_details = self.text_layout_details(window);
10016        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10017            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10018            let range = oldest_selection.display_range(&display_map).sorted();
10019
10020            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10021            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10022            let positions = start_x.min(end_x)..start_x.max(end_x);
10023
10024            selections.clear();
10025            let mut stack = Vec::new();
10026            for row in range.start.row().0..=range.end.row().0 {
10027                if let Some(selection) = self.selections.build_columnar_selection(
10028                    &display_map,
10029                    DisplayRow(row),
10030                    &positions,
10031                    oldest_selection.reversed,
10032                    &text_layout_details,
10033                ) {
10034                    stack.push(selection.id);
10035                    selections.push(selection);
10036                }
10037            }
10038
10039            if above {
10040                stack.reverse();
10041            }
10042
10043            AddSelectionsState { above, stack }
10044        });
10045
10046        let last_added_selection = *state.stack.last().unwrap();
10047        let mut new_selections = Vec::new();
10048        if above == state.above {
10049            let end_row = if above {
10050                DisplayRow(0)
10051            } else {
10052                display_map.max_point().row()
10053            };
10054
10055            'outer: for selection in selections {
10056                if selection.id == last_added_selection {
10057                    let range = selection.display_range(&display_map).sorted();
10058                    debug_assert_eq!(range.start.row(), range.end.row());
10059                    let mut row = range.start.row();
10060                    let positions =
10061                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10062                            px(start)..px(end)
10063                        } else {
10064                            let start_x =
10065                                display_map.x_for_display_point(range.start, &text_layout_details);
10066                            let end_x =
10067                                display_map.x_for_display_point(range.end, &text_layout_details);
10068                            start_x.min(end_x)..start_x.max(end_x)
10069                        };
10070
10071                    while row != end_row {
10072                        if above {
10073                            row.0 -= 1;
10074                        } else {
10075                            row.0 += 1;
10076                        }
10077
10078                        if let Some(new_selection) = self.selections.build_columnar_selection(
10079                            &display_map,
10080                            row,
10081                            &positions,
10082                            selection.reversed,
10083                            &text_layout_details,
10084                        ) {
10085                            state.stack.push(new_selection.id);
10086                            if above {
10087                                new_selections.push(new_selection);
10088                                new_selections.push(selection);
10089                            } else {
10090                                new_selections.push(selection);
10091                                new_selections.push(new_selection);
10092                            }
10093
10094                            continue 'outer;
10095                        }
10096                    }
10097                }
10098
10099                new_selections.push(selection);
10100            }
10101        } else {
10102            new_selections = selections;
10103            new_selections.retain(|s| s.id != last_added_selection);
10104            state.stack.pop();
10105        }
10106
10107        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10108            s.select(new_selections);
10109        });
10110        if state.stack.len() > 1 {
10111            self.add_selections_state = Some(state);
10112        }
10113    }
10114
10115    pub fn select_next_match_internal(
10116        &mut self,
10117        display_map: &DisplaySnapshot,
10118        replace_newest: bool,
10119        autoscroll: Option<Autoscroll>,
10120        window: &mut Window,
10121        cx: &mut Context<Self>,
10122    ) -> Result<()> {
10123        fn select_next_match_ranges(
10124            this: &mut Editor,
10125            range: Range<usize>,
10126            replace_newest: bool,
10127            auto_scroll: Option<Autoscroll>,
10128            window: &mut Window,
10129            cx: &mut Context<Editor>,
10130        ) {
10131            this.unfold_ranges(&[range.clone()], false, true, cx);
10132            this.change_selections(auto_scroll, window, cx, |s| {
10133                if replace_newest {
10134                    s.delete(s.newest_anchor().id);
10135                }
10136                s.insert_range(range.clone());
10137            });
10138        }
10139
10140        let buffer = &display_map.buffer_snapshot;
10141        let mut selections = self.selections.all::<usize>(cx);
10142        if let Some(mut select_next_state) = self.select_next_state.take() {
10143            let query = &select_next_state.query;
10144            if !select_next_state.done {
10145                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10146                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10147                let mut next_selected_range = None;
10148
10149                let bytes_after_last_selection =
10150                    buffer.bytes_in_range(last_selection.end..buffer.len());
10151                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10152                let query_matches = query
10153                    .stream_find_iter(bytes_after_last_selection)
10154                    .map(|result| (last_selection.end, result))
10155                    .chain(
10156                        query
10157                            .stream_find_iter(bytes_before_first_selection)
10158                            .map(|result| (0, result)),
10159                    );
10160
10161                for (start_offset, query_match) in query_matches {
10162                    let query_match = query_match.unwrap(); // can only fail due to I/O
10163                    let offset_range =
10164                        start_offset + query_match.start()..start_offset + query_match.end();
10165                    let display_range = offset_range.start.to_display_point(display_map)
10166                        ..offset_range.end.to_display_point(display_map);
10167
10168                    if !select_next_state.wordwise
10169                        || (!movement::is_inside_word(display_map, display_range.start)
10170                            && !movement::is_inside_word(display_map, display_range.end))
10171                    {
10172                        // TODO: This is n^2, because we might check all the selections
10173                        if !selections
10174                            .iter()
10175                            .any(|selection| selection.range().overlaps(&offset_range))
10176                        {
10177                            next_selected_range = Some(offset_range);
10178                            break;
10179                        }
10180                    }
10181                }
10182
10183                if let Some(next_selected_range) = next_selected_range {
10184                    select_next_match_ranges(
10185                        self,
10186                        next_selected_range,
10187                        replace_newest,
10188                        autoscroll,
10189                        window,
10190                        cx,
10191                    );
10192                } else {
10193                    select_next_state.done = true;
10194                }
10195            }
10196
10197            self.select_next_state = Some(select_next_state);
10198        } else {
10199            let mut only_carets = true;
10200            let mut same_text_selected = true;
10201            let mut selected_text = None;
10202
10203            let mut selections_iter = selections.iter().peekable();
10204            while let Some(selection) = selections_iter.next() {
10205                if selection.start != selection.end {
10206                    only_carets = false;
10207                }
10208
10209                if same_text_selected {
10210                    if selected_text.is_none() {
10211                        selected_text =
10212                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10213                    }
10214
10215                    if let Some(next_selection) = selections_iter.peek() {
10216                        if next_selection.range().len() == selection.range().len() {
10217                            let next_selected_text = buffer
10218                                .text_for_range(next_selection.range())
10219                                .collect::<String>();
10220                            if Some(next_selected_text) != selected_text {
10221                                same_text_selected = false;
10222                                selected_text = None;
10223                            }
10224                        } else {
10225                            same_text_selected = false;
10226                            selected_text = None;
10227                        }
10228                    }
10229                }
10230            }
10231
10232            if only_carets {
10233                for selection in &mut selections {
10234                    let word_range = movement::surrounding_word(
10235                        display_map,
10236                        selection.start.to_display_point(display_map),
10237                    );
10238                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
10239                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
10240                    selection.goal = SelectionGoal::None;
10241                    selection.reversed = false;
10242                    select_next_match_ranges(
10243                        self,
10244                        selection.start..selection.end,
10245                        replace_newest,
10246                        autoscroll,
10247                        window,
10248                        cx,
10249                    );
10250                }
10251
10252                if selections.len() == 1 {
10253                    let selection = selections
10254                        .last()
10255                        .expect("ensured that there's only one selection");
10256                    let query = buffer
10257                        .text_for_range(selection.start..selection.end)
10258                        .collect::<String>();
10259                    let is_empty = query.is_empty();
10260                    let select_state = SelectNextState {
10261                        query: AhoCorasick::new(&[query])?,
10262                        wordwise: true,
10263                        done: is_empty,
10264                    };
10265                    self.select_next_state = Some(select_state);
10266                } else {
10267                    self.select_next_state = None;
10268                }
10269            } else if let Some(selected_text) = selected_text {
10270                self.select_next_state = Some(SelectNextState {
10271                    query: AhoCorasick::new(&[selected_text])?,
10272                    wordwise: false,
10273                    done: false,
10274                });
10275                self.select_next_match_internal(
10276                    display_map,
10277                    replace_newest,
10278                    autoscroll,
10279                    window,
10280                    cx,
10281                )?;
10282            }
10283        }
10284        Ok(())
10285    }
10286
10287    pub fn select_all_matches(
10288        &mut self,
10289        _action: &SelectAllMatches,
10290        window: &mut Window,
10291        cx: &mut Context<Self>,
10292    ) -> Result<()> {
10293        self.push_to_selection_history();
10294        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10295
10296        self.select_next_match_internal(&display_map, false, None, window, cx)?;
10297        let Some(select_next_state) = self.select_next_state.as_mut() else {
10298            return Ok(());
10299        };
10300        if select_next_state.done {
10301            return Ok(());
10302        }
10303
10304        let mut new_selections = self.selections.all::<usize>(cx);
10305
10306        let buffer = &display_map.buffer_snapshot;
10307        let query_matches = select_next_state
10308            .query
10309            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10310
10311        for query_match in query_matches {
10312            let query_match = query_match.unwrap(); // can only fail due to I/O
10313            let offset_range = query_match.start()..query_match.end();
10314            let display_range = offset_range.start.to_display_point(&display_map)
10315                ..offset_range.end.to_display_point(&display_map);
10316
10317            if !select_next_state.wordwise
10318                || (!movement::is_inside_word(&display_map, display_range.start)
10319                    && !movement::is_inside_word(&display_map, display_range.end))
10320            {
10321                self.selections.change_with(cx, |selections| {
10322                    new_selections.push(Selection {
10323                        id: selections.new_selection_id(),
10324                        start: offset_range.start,
10325                        end: offset_range.end,
10326                        reversed: false,
10327                        goal: SelectionGoal::None,
10328                    });
10329                });
10330            }
10331        }
10332
10333        new_selections.sort_by_key(|selection| selection.start);
10334        let mut ix = 0;
10335        while ix + 1 < new_selections.len() {
10336            let current_selection = &new_selections[ix];
10337            let next_selection = &new_selections[ix + 1];
10338            if current_selection.range().overlaps(&next_selection.range()) {
10339                if current_selection.id < next_selection.id {
10340                    new_selections.remove(ix + 1);
10341                } else {
10342                    new_selections.remove(ix);
10343                }
10344            } else {
10345                ix += 1;
10346            }
10347        }
10348
10349        let reversed = self.selections.oldest::<usize>(cx).reversed;
10350
10351        for selection in new_selections.iter_mut() {
10352            selection.reversed = reversed;
10353        }
10354
10355        select_next_state.done = true;
10356        self.unfold_ranges(
10357            &new_selections
10358                .iter()
10359                .map(|selection| selection.range())
10360                .collect::<Vec<_>>(),
10361            false,
10362            false,
10363            cx,
10364        );
10365        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10366            selections.select(new_selections)
10367        });
10368
10369        Ok(())
10370    }
10371
10372    pub fn select_next(
10373        &mut self,
10374        action: &SelectNext,
10375        window: &mut Window,
10376        cx: &mut Context<Self>,
10377    ) -> Result<()> {
10378        self.push_to_selection_history();
10379        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10380        self.select_next_match_internal(
10381            &display_map,
10382            action.replace_newest,
10383            Some(Autoscroll::newest()),
10384            window,
10385            cx,
10386        )?;
10387        Ok(())
10388    }
10389
10390    pub fn select_previous(
10391        &mut self,
10392        action: &SelectPrevious,
10393        window: &mut Window,
10394        cx: &mut Context<Self>,
10395    ) -> Result<()> {
10396        self.push_to_selection_history();
10397        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10398        let buffer = &display_map.buffer_snapshot;
10399        let mut selections = self.selections.all::<usize>(cx);
10400        if let Some(mut select_prev_state) = self.select_prev_state.take() {
10401            let query = &select_prev_state.query;
10402            if !select_prev_state.done {
10403                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10404                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10405                let mut next_selected_range = None;
10406                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10407                let bytes_before_last_selection =
10408                    buffer.reversed_bytes_in_range(0..last_selection.start);
10409                let bytes_after_first_selection =
10410                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10411                let query_matches = query
10412                    .stream_find_iter(bytes_before_last_selection)
10413                    .map(|result| (last_selection.start, result))
10414                    .chain(
10415                        query
10416                            .stream_find_iter(bytes_after_first_selection)
10417                            .map(|result| (buffer.len(), result)),
10418                    );
10419                for (end_offset, query_match) in query_matches {
10420                    let query_match = query_match.unwrap(); // can only fail due to I/O
10421                    let offset_range =
10422                        end_offset - query_match.end()..end_offset - query_match.start();
10423                    let display_range = offset_range.start.to_display_point(&display_map)
10424                        ..offset_range.end.to_display_point(&display_map);
10425
10426                    if !select_prev_state.wordwise
10427                        || (!movement::is_inside_word(&display_map, display_range.start)
10428                            && !movement::is_inside_word(&display_map, display_range.end))
10429                    {
10430                        next_selected_range = Some(offset_range);
10431                        break;
10432                    }
10433                }
10434
10435                if let Some(next_selected_range) = next_selected_range {
10436                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10437                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10438                        if action.replace_newest {
10439                            s.delete(s.newest_anchor().id);
10440                        }
10441                        s.insert_range(next_selected_range);
10442                    });
10443                } else {
10444                    select_prev_state.done = true;
10445                }
10446            }
10447
10448            self.select_prev_state = Some(select_prev_state);
10449        } else {
10450            let mut only_carets = true;
10451            let mut same_text_selected = true;
10452            let mut selected_text = None;
10453
10454            let mut selections_iter = selections.iter().peekable();
10455            while let Some(selection) = selections_iter.next() {
10456                if selection.start != selection.end {
10457                    only_carets = false;
10458                }
10459
10460                if same_text_selected {
10461                    if selected_text.is_none() {
10462                        selected_text =
10463                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10464                    }
10465
10466                    if let Some(next_selection) = selections_iter.peek() {
10467                        if next_selection.range().len() == selection.range().len() {
10468                            let next_selected_text = buffer
10469                                .text_for_range(next_selection.range())
10470                                .collect::<String>();
10471                            if Some(next_selected_text) != selected_text {
10472                                same_text_selected = false;
10473                                selected_text = None;
10474                            }
10475                        } else {
10476                            same_text_selected = false;
10477                            selected_text = None;
10478                        }
10479                    }
10480                }
10481            }
10482
10483            if only_carets {
10484                for selection in &mut selections {
10485                    let word_range = movement::surrounding_word(
10486                        &display_map,
10487                        selection.start.to_display_point(&display_map),
10488                    );
10489                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10490                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10491                    selection.goal = SelectionGoal::None;
10492                    selection.reversed = false;
10493                }
10494                if selections.len() == 1 {
10495                    let selection = selections
10496                        .last()
10497                        .expect("ensured that there's only one selection");
10498                    let query = buffer
10499                        .text_for_range(selection.start..selection.end)
10500                        .collect::<String>();
10501                    let is_empty = query.is_empty();
10502                    let select_state = SelectNextState {
10503                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10504                        wordwise: true,
10505                        done: is_empty,
10506                    };
10507                    self.select_prev_state = Some(select_state);
10508                } else {
10509                    self.select_prev_state = None;
10510                }
10511
10512                self.unfold_ranges(
10513                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10514                    false,
10515                    true,
10516                    cx,
10517                );
10518                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10519                    s.select(selections);
10520                });
10521            } else if let Some(selected_text) = selected_text {
10522                self.select_prev_state = Some(SelectNextState {
10523                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10524                    wordwise: false,
10525                    done: false,
10526                });
10527                self.select_previous(action, window, cx)?;
10528            }
10529        }
10530        Ok(())
10531    }
10532
10533    pub fn toggle_comments(
10534        &mut self,
10535        action: &ToggleComments,
10536        window: &mut Window,
10537        cx: &mut Context<Self>,
10538    ) {
10539        if self.read_only(cx) {
10540            return;
10541        }
10542        let text_layout_details = &self.text_layout_details(window);
10543        self.transact(window, cx, |this, window, cx| {
10544            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10545            let mut edits = Vec::new();
10546            let mut selection_edit_ranges = Vec::new();
10547            let mut last_toggled_row = None;
10548            let snapshot = this.buffer.read(cx).read(cx);
10549            let empty_str: Arc<str> = Arc::default();
10550            let mut suffixes_inserted = Vec::new();
10551            let ignore_indent = action.ignore_indent;
10552
10553            fn comment_prefix_range(
10554                snapshot: &MultiBufferSnapshot,
10555                row: MultiBufferRow,
10556                comment_prefix: &str,
10557                comment_prefix_whitespace: &str,
10558                ignore_indent: bool,
10559            ) -> Range<Point> {
10560                let indent_size = if ignore_indent {
10561                    0
10562                } else {
10563                    snapshot.indent_size_for_line(row).len
10564                };
10565
10566                let start = Point::new(row.0, indent_size);
10567
10568                let mut line_bytes = snapshot
10569                    .bytes_in_range(start..snapshot.max_point())
10570                    .flatten()
10571                    .copied();
10572
10573                // If this line currently begins with the line comment prefix, then record
10574                // the range containing the prefix.
10575                if line_bytes
10576                    .by_ref()
10577                    .take(comment_prefix.len())
10578                    .eq(comment_prefix.bytes())
10579                {
10580                    // Include any whitespace that matches the comment prefix.
10581                    let matching_whitespace_len = line_bytes
10582                        .zip(comment_prefix_whitespace.bytes())
10583                        .take_while(|(a, b)| a == b)
10584                        .count() as u32;
10585                    let end = Point::new(
10586                        start.row,
10587                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10588                    );
10589                    start..end
10590                } else {
10591                    start..start
10592                }
10593            }
10594
10595            fn comment_suffix_range(
10596                snapshot: &MultiBufferSnapshot,
10597                row: MultiBufferRow,
10598                comment_suffix: &str,
10599                comment_suffix_has_leading_space: bool,
10600            ) -> Range<Point> {
10601                let end = Point::new(row.0, snapshot.line_len(row));
10602                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10603
10604                let mut line_end_bytes = snapshot
10605                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10606                    .flatten()
10607                    .copied();
10608
10609                let leading_space_len = if suffix_start_column > 0
10610                    && line_end_bytes.next() == Some(b' ')
10611                    && comment_suffix_has_leading_space
10612                {
10613                    1
10614                } else {
10615                    0
10616                };
10617
10618                // If this line currently begins with the line comment prefix, then record
10619                // the range containing the prefix.
10620                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10621                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
10622                    start..end
10623                } else {
10624                    end..end
10625                }
10626            }
10627
10628            // TODO: Handle selections that cross excerpts
10629            for selection in &mut selections {
10630                let start_column = snapshot
10631                    .indent_size_for_line(MultiBufferRow(selection.start.row))
10632                    .len;
10633                let language = if let Some(language) =
10634                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10635                {
10636                    language
10637                } else {
10638                    continue;
10639                };
10640
10641                selection_edit_ranges.clear();
10642
10643                // If multiple selections contain a given row, avoid processing that
10644                // row more than once.
10645                let mut start_row = MultiBufferRow(selection.start.row);
10646                if last_toggled_row == Some(start_row) {
10647                    start_row = start_row.next_row();
10648                }
10649                let end_row =
10650                    if selection.end.row > selection.start.row && selection.end.column == 0 {
10651                        MultiBufferRow(selection.end.row - 1)
10652                    } else {
10653                        MultiBufferRow(selection.end.row)
10654                    };
10655                last_toggled_row = Some(end_row);
10656
10657                if start_row > end_row {
10658                    continue;
10659                }
10660
10661                // If the language has line comments, toggle those.
10662                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10663
10664                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10665                if ignore_indent {
10666                    full_comment_prefixes = full_comment_prefixes
10667                        .into_iter()
10668                        .map(|s| Arc::from(s.trim_end()))
10669                        .collect();
10670                }
10671
10672                if !full_comment_prefixes.is_empty() {
10673                    let first_prefix = full_comment_prefixes
10674                        .first()
10675                        .expect("prefixes is non-empty");
10676                    let prefix_trimmed_lengths = full_comment_prefixes
10677                        .iter()
10678                        .map(|p| p.trim_end_matches(' ').len())
10679                        .collect::<SmallVec<[usize; 4]>>();
10680
10681                    let mut all_selection_lines_are_comments = true;
10682
10683                    for row in start_row.0..=end_row.0 {
10684                        let row = MultiBufferRow(row);
10685                        if start_row < end_row && snapshot.is_line_blank(row) {
10686                            continue;
10687                        }
10688
10689                        let prefix_range = full_comment_prefixes
10690                            .iter()
10691                            .zip(prefix_trimmed_lengths.iter().copied())
10692                            .map(|(prefix, trimmed_prefix_len)| {
10693                                comment_prefix_range(
10694                                    snapshot.deref(),
10695                                    row,
10696                                    &prefix[..trimmed_prefix_len],
10697                                    &prefix[trimmed_prefix_len..],
10698                                    ignore_indent,
10699                                )
10700                            })
10701                            .max_by_key(|range| range.end.column - range.start.column)
10702                            .expect("prefixes is non-empty");
10703
10704                        if prefix_range.is_empty() {
10705                            all_selection_lines_are_comments = false;
10706                        }
10707
10708                        selection_edit_ranges.push(prefix_range);
10709                    }
10710
10711                    if all_selection_lines_are_comments {
10712                        edits.extend(
10713                            selection_edit_ranges
10714                                .iter()
10715                                .cloned()
10716                                .map(|range| (range, empty_str.clone())),
10717                        );
10718                    } else {
10719                        let min_column = selection_edit_ranges
10720                            .iter()
10721                            .map(|range| range.start.column)
10722                            .min()
10723                            .unwrap_or(0);
10724                        edits.extend(selection_edit_ranges.iter().map(|range| {
10725                            let position = Point::new(range.start.row, min_column);
10726                            (position..position, first_prefix.clone())
10727                        }));
10728                    }
10729                } else if let Some((full_comment_prefix, comment_suffix)) =
10730                    language.block_comment_delimiters()
10731                {
10732                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10733                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10734                    let prefix_range = comment_prefix_range(
10735                        snapshot.deref(),
10736                        start_row,
10737                        comment_prefix,
10738                        comment_prefix_whitespace,
10739                        ignore_indent,
10740                    );
10741                    let suffix_range = comment_suffix_range(
10742                        snapshot.deref(),
10743                        end_row,
10744                        comment_suffix.trim_start_matches(' '),
10745                        comment_suffix.starts_with(' '),
10746                    );
10747
10748                    if prefix_range.is_empty() || suffix_range.is_empty() {
10749                        edits.push((
10750                            prefix_range.start..prefix_range.start,
10751                            full_comment_prefix.clone(),
10752                        ));
10753                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10754                        suffixes_inserted.push((end_row, comment_suffix.len()));
10755                    } else {
10756                        edits.push((prefix_range, empty_str.clone()));
10757                        edits.push((suffix_range, empty_str.clone()));
10758                    }
10759                } else {
10760                    continue;
10761                }
10762            }
10763
10764            drop(snapshot);
10765            this.buffer.update(cx, |buffer, cx| {
10766                buffer.edit(edits, None, cx);
10767            });
10768
10769            // Adjust selections so that they end before any comment suffixes that
10770            // were inserted.
10771            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10772            let mut selections = this.selections.all::<Point>(cx);
10773            let snapshot = this.buffer.read(cx).read(cx);
10774            for selection in &mut selections {
10775                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10776                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10777                        Ordering::Less => {
10778                            suffixes_inserted.next();
10779                            continue;
10780                        }
10781                        Ordering::Greater => break,
10782                        Ordering::Equal => {
10783                            if selection.end.column == snapshot.line_len(row) {
10784                                if selection.is_empty() {
10785                                    selection.start.column -= suffix_len as u32;
10786                                }
10787                                selection.end.column -= suffix_len as u32;
10788                            }
10789                            break;
10790                        }
10791                    }
10792                }
10793            }
10794
10795            drop(snapshot);
10796            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10797                s.select(selections)
10798            });
10799
10800            let selections = this.selections.all::<Point>(cx);
10801            let selections_on_single_row = selections.windows(2).all(|selections| {
10802                selections[0].start.row == selections[1].start.row
10803                    && selections[0].end.row == selections[1].end.row
10804                    && selections[0].start.row == selections[0].end.row
10805            });
10806            let selections_selecting = selections
10807                .iter()
10808                .any(|selection| selection.start != selection.end);
10809            let advance_downwards = action.advance_downwards
10810                && selections_on_single_row
10811                && !selections_selecting
10812                && !matches!(this.mode, EditorMode::SingleLine { .. });
10813
10814            if advance_downwards {
10815                let snapshot = this.buffer.read(cx).snapshot(cx);
10816
10817                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10818                    s.move_cursors_with(|display_snapshot, display_point, _| {
10819                        let mut point = display_point.to_point(display_snapshot);
10820                        point.row += 1;
10821                        point = snapshot.clip_point(point, Bias::Left);
10822                        let display_point = point.to_display_point(display_snapshot);
10823                        let goal = SelectionGoal::HorizontalPosition(
10824                            display_snapshot
10825                                .x_for_display_point(display_point, text_layout_details)
10826                                .into(),
10827                        );
10828                        (display_point, goal)
10829                    })
10830                });
10831            }
10832        });
10833    }
10834
10835    pub fn select_enclosing_symbol(
10836        &mut self,
10837        _: &SelectEnclosingSymbol,
10838        window: &mut Window,
10839        cx: &mut Context<Self>,
10840    ) {
10841        let buffer = self.buffer.read(cx).snapshot(cx);
10842        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10843
10844        fn update_selection(
10845            selection: &Selection<usize>,
10846            buffer_snap: &MultiBufferSnapshot,
10847        ) -> Option<Selection<usize>> {
10848            let cursor = selection.head();
10849            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10850            for symbol in symbols.iter().rev() {
10851                let start = symbol.range.start.to_offset(buffer_snap);
10852                let end = symbol.range.end.to_offset(buffer_snap);
10853                let new_range = start..end;
10854                if start < selection.start || end > selection.end {
10855                    return Some(Selection {
10856                        id: selection.id,
10857                        start: new_range.start,
10858                        end: new_range.end,
10859                        goal: SelectionGoal::None,
10860                        reversed: selection.reversed,
10861                    });
10862                }
10863            }
10864            None
10865        }
10866
10867        let mut selected_larger_symbol = false;
10868        let new_selections = old_selections
10869            .iter()
10870            .map(|selection| match update_selection(selection, &buffer) {
10871                Some(new_selection) => {
10872                    if new_selection.range() != selection.range() {
10873                        selected_larger_symbol = true;
10874                    }
10875                    new_selection
10876                }
10877                None => selection.clone(),
10878            })
10879            .collect::<Vec<_>>();
10880
10881        if selected_larger_symbol {
10882            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10883                s.select(new_selections);
10884            });
10885        }
10886    }
10887
10888    pub fn select_larger_syntax_node(
10889        &mut self,
10890        _: &SelectLargerSyntaxNode,
10891        window: &mut Window,
10892        cx: &mut Context<Self>,
10893    ) {
10894        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10895        let buffer = self.buffer.read(cx).snapshot(cx);
10896        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10897
10898        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10899        let mut selected_larger_node = false;
10900        let new_selections = old_selections
10901            .iter()
10902            .map(|selection| {
10903                let old_range = selection.start..selection.end;
10904                let mut new_range = old_range.clone();
10905                let mut new_node = None;
10906                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10907                {
10908                    new_node = Some(node);
10909                    new_range = match containing_range {
10910                        MultiOrSingleBufferOffsetRange::Single(_) => break,
10911                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
10912                    };
10913                    if !display_map.intersects_fold(new_range.start)
10914                        && !display_map.intersects_fold(new_range.end)
10915                    {
10916                        break;
10917                    }
10918                }
10919
10920                if let Some(node) = new_node {
10921                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10922                    // nodes. Parent and grandparent are also logged because this operation will not
10923                    // visit nodes that have the same range as their parent.
10924                    log::info!("Node: {node:?}");
10925                    let parent = node.parent();
10926                    log::info!("Parent: {parent:?}");
10927                    let grandparent = parent.and_then(|x| x.parent());
10928                    log::info!("Grandparent: {grandparent:?}");
10929                }
10930
10931                selected_larger_node |= new_range != old_range;
10932                Selection {
10933                    id: selection.id,
10934                    start: new_range.start,
10935                    end: new_range.end,
10936                    goal: SelectionGoal::None,
10937                    reversed: selection.reversed,
10938                }
10939            })
10940            .collect::<Vec<_>>();
10941
10942        if selected_larger_node {
10943            stack.push(old_selections);
10944            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10945                s.select(new_selections);
10946            });
10947        }
10948        self.select_larger_syntax_node_stack = stack;
10949    }
10950
10951    pub fn select_smaller_syntax_node(
10952        &mut self,
10953        _: &SelectSmallerSyntaxNode,
10954        window: &mut Window,
10955        cx: &mut Context<Self>,
10956    ) {
10957        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10958        if let Some(selections) = stack.pop() {
10959            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10960                s.select(selections.to_vec());
10961            });
10962        }
10963        self.select_larger_syntax_node_stack = stack;
10964    }
10965
10966    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10967        if !EditorSettings::get_global(cx).gutter.runnables {
10968            self.clear_tasks();
10969            return Task::ready(());
10970        }
10971        let project = self.project.as_ref().map(Entity::downgrade);
10972        cx.spawn_in(window, |this, mut cx| async move {
10973            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10974            let Some(project) = project.and_then(|p| p.upgrade()) else {
10975                return;
10976            };
10977            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10978                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10979            }) else {
10980                return;
10981            };
10982
10983            let hide_runnables = project
10984                .update(&mut cx, |project, cx| {
10985                    // Do not display any test indicators in non-dev server remote projects.
10986                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10987                })
10988                .unwrap_or(true);
10989            if hide_runnables {
10990                return;
10991            }
10992            let new_rows =
10993                cx.background_spawn({
10994                    let snapshot = display_snapshot.clone();
10995                    async move {
10996                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10997                    }
10998                })
10999                    .await;
11000
11001            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
11002            this.update(&mut cx, |this, _| {
11003                this.clear_tasks();
11004                for (key, value) in rows {
11005                    this.insert_tasks(key, value);
11006                }
11007            })
11008            .ok();
11009        })
11010    }
11011    fn fetch_runnable_ranges(
11012        snapshot: &DisplaySnapshot,
11013        range: Range<Anchor>,
11014    ) -> Vec<language::RunnableRange> {
11015        snapshot.buffer_snapshot.runnable_ranges(range).collect()
11016    }
11017
11018    fn runnable_rows(
11019        project: Entity<Project>,
11020        snapshot: DisplaySnapshot,
11021        runnable_ranges: Vec<RunnableRange>,
11022        mut cx: AsyncWindowContext,
11023    ) -> Vec<((BufferId, u32), RunnableTasks)> {
11024        runnable_ranges
11025            .into_iter()
11026            .filter_map(|mut runnable| {
11027                let tasks = cx
11028                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11029                    .ok()?;
11030                if tasks.is_empty() {
11031                    return None;
11032                }
11033
11034                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11035
11036                let row = snapshot
11037                    .buffer_snapshot
11038                    .buffer_line_for_row(MultiBufferRow(point.row))?
11039                    .1
11040                    .start
11041                    .row;
11042
11043                let context_range =
11044                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11045                Some((
11046                    (runnable.buffer_id, row),
11047                    RunnableTasks {
11048                        templates: tasks,
11049                        offset: snapshot
11050                            .buffer_snapshot
11051                            .anchor_before(runnable.run_range.start),
11052                        context_range,
11053                        column: point.column,
11054                        extra_variables: runnable.extra_captures,
11055                    },
11056                ))
11057            })
11058            .collect()
11059    }
11060
11061    fn templates_with_tags(
11062        project: &Entity<Project>,
11063        runnable: &mut Runnable,
11064        cx: &mut App,
11065    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11066        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11067            let (worktree_id, file) = project
11068                .buffer_for_id(runnable.buffer, cx)
11069                .and_then(|buffer| buffer.read(cx).file())
11070                .map(|file| (file.worktree_id(cx), file.clone()))
11071                .unzip();
11072
11073            (
11074                project.task_store().read(cx).task_inventory().cloned(),
11075                worktree_id,
11076                file,
11077            )
11078        });
11079
11080        let tags = mem::take(&mut runnable.tags);
11081        let mut tags: Vec<_> = tags
11082            .into_iter()
11083            .flat_map(|tag| {
11084                let tag = tag.0.clone();
11085                inventory
11086                    .as_ref()
11087                    .into_iter()
11088                    .flat_map(|inventory| {
11089                        inventory.read(cx).list_tasks(
11090                            file.clone(),
11091                            Some(runnable.language.clone()),
11092                            worktree_id,
11093                            cx,
11094                        )
11095                    })
11096                    .filter(move |(_, template)| {
11097                        template.tags.iter().any(|source_tag| source_tag == &tag)
11098                    })
11099            })
11100            .sorted_by_key(|(kind, _)| kind.to_owned())
11101            .collect();
11102        if let Some((leading_tag_source, _)) = tags.first() {
11103            // Strongest source wins; if we have worktree tag binding, prefer that to
11104            // global and language bindings;
11105            // if we have a global binding, prefer that to language binding.
11106            let first_mismatch = tags
11107                .iter()
11108                .position(|(tag_source, _)| tag_source != leading_tag_source);
11109            if let Some(index) = first_mismatch {
11110                tags.truncate(index);
11111            }
11112        }
11113
11114        tags
11115    }
11116
11117    pub fn move_to_enclosing_bracket(
11118        &mut self,
11119        _: &MoveToEnclosingBracket,
11120        window: &mut Window,
11121        cx: &mut Context<Self>,
11122    ) {
11123        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11124            s.move_offsets_with(|snapshot, selection| {
11125                let Some(enclosing_bracket_ranges) =
11126                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11127                else {
11128                    return;
11129                };
11130
11131                let mut best_length = usize::MAX;
11132                let mut best_inside = false;
11133                let mut best_in_bracket_range = false;
11134                let mut best_destination = None;
11135                for (open, close) in enclosing_bracket_ranges {
11136                    let close = close.to_inclusive();
11137                    let length = close.end() - open.start;
11138                    let inside = selection.start >= open.end && selection.end <= *close.start();
11139                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
11140                        || close.contains(&selection.head());
11141
11142                    // If best is next to a bracket and current isn't, skip
11143                    if !in_bracket_range && best_in_bracket_range {
11144                        continue;
11145                    }
11146
11147                    // Prefer smaller lengths unless best is inside and current isn't
11148                    if length > best_length && (best_inside || !inside) {
11149                        continue;
11150                    }
11151
11152                    best_length = length;
11153                    best_inside = inside;
11154                    best_in_bracket_range = in_bracket_range;
11155                    best_destination = Some(
11156                        if close.contains(&selection.start) && close.contains(&selection.end) {
11157                            if inside {
11158                                open.end
11159                            } else {
11160                                open.start
11161                            }
11162                        } else if inside {
11163                            *close.start()
11164                        } else {
11165                            *close.end()
11166                        },
11167                    );
11168                }
11169
11170                if let Some(destination) = best_destination {
11171                    selection.collapse_to(destination, SelectionGoal::None);
11172                }
11173            })
11174        });
11175    }
11176
11177    pub fn undo_selection(
11178        &mut self,
11179        _: &UndoSelection,
11180        window: &mut Window,
11181        cx: &mut Context<Self>,
11182    ) {
11183        self.end_selection(window, cx);
11184        self.selection_history.mode = SelectionHistoryMode::Undoing;
11185        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11186            self.change_selections(None, window, cx, |s| {
11187                s.select_anchors(entry.selections.to_vec())
11188            });
11189            self.select_next_state = entry.select_next_state;
11190            self.select_prev_state = entry.select_prev_state;
11191            self.add_selections_state = entry.add_selections_state;
11192            self.request_autoscroll(Autoscroll::newest(), cx);
11193        }
11194        self.selection_history.mode = SelectionHistoryMode::Normal;
11195    }
11196
11197    pub fn redo_selection(
11198        &mut self,
11199        _: &RedoSelection,
11200        window: &mut Window,
11201        cx: &mut Context<Self>,
11202    ) {
11203        self.end_selection(window, cx);
11204        self.selection_history.mode = SelectionHistoryMode::Redoing;
11205        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11206            self.change_selections(None, window, cx, |s| {
11207                s.select_anchors(entry.selections.to_vec())
11208            });
11209            self.select_next_state = entry.select_next_state;
11210            self.select_prev_state = entry.select_prev_state;
11211            self.add_selections_state = entry.add_selections_state;
11212            self.request_autoscroll(Autoscroll::newest(), cx);
11213        }
11214        self.selection_history.mode = SelectionHistoryMode::Normal;
11215    }
11216
11217    pub fn expand_excerpts(
11218        &mut self,
11219        action: &ExpandExcerpts,
11220        _: &mut Window,
11221        cx: &mut Context<Self>,
11222    ) {
11223        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11224    }
11225
11226    pub fn expand_excerpts_down(
11227        &mut self,
11228        action: &ExpandExcerptsDown,
11229        _: &mut Window,
11230        cx: &mut Context<Self>,
11231    ) {
11232        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11233    }
11234
11235    pub fn expand_excerpts_up(
11236        &mut self,
11237        action: &ExpandExcerptsUp,
11238        _: &mut Window,
11239        cx: &mut Context<Self>,
11240    ) {
11241        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11242    }
11243
11244    pub fn expand_excerpts_for_direction(
11245        &mut self,
11246        lines: u32,
11247        direction: ExpandExcerptDirection,
11248
11249        cx: &mut Context<Self>,
11250    ) {
11251        let selections = self.selections.disjoint_anchors();
11252
11253        let lines = if lines == 0 {
11254            EditorSettings::get_global(cx).expand_excerpt_lines
11255        } else {
11256            lines
11257        };
11258
11259        self.buffer.update(cx, |buffer, cx| {
11260            let snapshot = buffer.snapshot(cx);
11261            let mut excerpt_ids = selections
11262                .iter()
11263                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11264                .collect::<Vec<_>>();
11265            excerpt_ids.sort();
11266            excerpt_ids.dedup();
11267            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11268        })
11269    }
11270
11271    pub fn expand_excerpt(
11272        &mut self,
11273        excerpt: ExcerptId,
11274        direction: ExpandExcerptDirection,
11275        cx: &mut Context<Self>,
11276    ) {
11277        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11278        self.buffer.update(cx, |buffer, cx| {
11279            buffer.expand_excerpts([excerpt], lines, direction, cx)
11280        })
11281    }
11282
11283    pub fn go_to_singleton_buffer_point(
11284        &mut self,
11285        point: Point,
11286        window: &mut Window,
11287        cx: &mut Context<Self>,
11288    ) {
11289        self.go_to_singleton_buffer_range(point..point, window, cx);
11290    }
11291
11292    pub fn go_to_singleton_buffer_range(
11293        &mut self,
11294        range: Range<Point>,
11295        window: &mut Window,
11296        cx: &mut Context<Self>,
11297    ) {
11298        let multibuffer = self.buffer().read(cx);
11299        let Some(buffer) = multibuffer.as_singleton() else {
11300            return;
11301        };
11302        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11303            return;
11304        };
11305        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11306            return;
11307        };
11308        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11309            s.select_anchor_ranges([start..end])
11310        });
11311    }
11312
11313    fn go_to_diagnostic(
11314        &mut self,
11315        _: &GoToDiagnostic,
11316        window: &mut Window,
11317        cx: &mut Context<Self>,
11318    ) {
11319        self.go_to_diagnostic_impl(Direction::Next, window, cx)
11320    }
11321
11322    fn go_to_prev_diagnostic(
11323        &mut self,
11324        _: &GoToPreviousDiagnostic,
11325        window: &mut Window,
11326        cx: &mut Context<Self>,
11327    ) {
11328        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11329    }
11330
11331    pub fn go_to_diagnostic_impl(
11332        &mut self,
11333        direction: Direction,
11334        window: &mut Window,
11335        cx: &mut Context<Self>,
11336    ) {
11337        let buffer = self.buffer.read(cx).snapshot(cx);
11338        let selection = self.selections.newest::<usize>(cx);
11339
11340        // If there is an active Diagnostic Popover jump to its diagnostic instead.
11341        if direction == Direction::Next {
11342            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11343                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11344                    return;
11345                };
11346                self.activate_diagnostics(
11347                    buffer_id,
11348                    popover.local_diagnostic.diagnostic.group_id,
11349                    window,
11350                    cx,
11351                );
11352                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11353                    let primary_range_start = active_diagnostics.primary_range.start;
11354                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11355                        let mut new_selection = s.newest_anchor().clone();
11356                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11357                        s.select_anchors(vec![new_selection.clone()]);
11358                    });
11359                    self.refresh_inline_completion(false, true, window, cx);
11360                }
11361                return;
11362            }
11363        }
11364
11365        let active_group_id = self
11366            .active_diagnostics
11367            .as_ref()
11368            .map(|active_group| active_group.group_id);
11369        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11370            active_diagnostics
11371                .primary_range
11372                .to_offset(&buffer)
11373                .to_inclusive()
11374        });
11375        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11376            if active_primary_range.contains(&selection.head()) {
11377                *active_primary_range.start()
11378            } else {
11379                selection.head()
11380            }
11381        } else {
11382            selection.head()
11383        };
11384
11385        let snapshot = self.snapshot(window, cx);
11386        let primary_diagnostics_before = buffer
11387            .diagnostics_in_range::<usize>(0..search_start)
11388            .filter(|entry| entry.diagnostic.is_primary)
11389            .filter(|entry| entry.range.start != entry.range.end)
11390            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11391            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11392            .collect::<Vec<_>>();
11393        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11394            primary_diagnostics_before
11395                .iter()
11396                .position(|entry| entry.diagnostic.group_id == active_group_id)
11397        });
11398
11399        let primary_diagnostics_after = buffer
11400            .diagnostics_in_range::<usize>(search_start..buffer.len())
11401            .filter(|entry| entry.diagnostic.is_primary)
11402            .filter(|entry| entry.range.start != entry.range.end)
11403            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11404            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11405            .collect::<Vec<_>>();
11406        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11407            primary_diagnostics_after
11408                .iter()
11409                .enumerate()
11410                .rev()
11411                .find_map(|(i, entry)| {
11412                    if entry.diagnostic.group_id == active_group_id {
11413                        Some(i)
11414                    } else {
11415                        None
11416                    }
11417                })
11418        });
11419
11420        let next_primary_diagnostic = match direction {
11421            Direction::Prev => primary_diagnostics_before
11422                .iter()
11423                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11424                .rev()
11425                .next(),
11426            Direction::Next => primary_diagnostics_after
11427                .iter()
11428                .skip(
11429                    last_same_group_diagnostic_after
11430                        .map(|index| index + 1)
11431                        .unwrap_or(0),
11432                )
11433                .next(),
11434        };
11435
11436        // Cycle around to the start of the buffer, potentially moving back to the start of
11437        // the currently active diagnostic.
11438        let cycle_around = || match direction {
11439            Direction::Prev => primary_diagnostics_after
11440                .iter()
11441                .rev()
11442                .chain(primary_diagnostics_before.iter().rev())
11443                .next(),
11444            Direction::Next => primary_diagnostics_before
11445                .iter()
11446                .chain(primary_diagnostics_after.iter())
11447                .next(),
11448        };
11449
11450        if let Some((primary_range, group_id)) = next_primary_diagnostic
11451            .or_else(cycle_around)
11452            .map(|entry| (&entry.range, entry.diagnostic.group_id))
11453        {
11454            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11455                return;
11456            };
11457            self.activate_diagnostics(buffer_id, group_id, window, cx);
11458            if self.active_diagnostics.is_some() {
11459                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11460                    s.select(vec![Selection {
11461                        id: selection.id,
11462                        start: primary_range.start,
11463                        end: primary_range.start,
11464                        reversed: false,
11465                        goal: SelectionGoal::None,
11466                    }]);
11467                });
11468                self.refresh_inline_completion(false, true, window, cx);
11469            }
11470        }
11471    }
11472
11473    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11474        let snapshot = self.snapshot(window, cx);
11475        let selection = self.selections.newest::<Point>(cx);
11476        self.go_to_hunk_before_or_after_position(
11477            &snapshot,
11478            selection.head(),
11479            Direction::Next,
11480            window,
11481            cx,
11482        );
11483    }
11484
11485    fn go_to_hunk_before_or_after_position(
11486        &mut self,
11487        snapshot: &EditorSnapshot,
11488        position: Point,
11489        direction: Direction,
11490        window: &mut Window,
11491        cx: &mut Context<Editor>,
11492    ) {
11493        let row = if direction == Direction::Next {
11494            self.hunk_after_position(snapshot, position)
11495                .map(|hunk| hunk.row_range.start)
11496        } else {
11497            self.hunk_before_position(snapshot, position)
11498        };
11499
11500        if let Some(row) = row {
11501            let destination = Point::new(row.0, 0);
11502            let autoscroll = Autoscroll::center();
11503
11504            self.unfold_ranges(&[destination..destination], false, false, cx);
11505            self.change_selections(Some(autoscroll), window, cx, |s| {
11506                s.select_ranges([destination..destination]);
11507            });
11508        }
11509    }
11510
11511    fn hunk_after_position(
11512        &mut self,
11513        snapshot: &EditorSnapshot,
11514        position: Point,
11515    ) -> Option<MultiBufferDiffHunk> {
11516        snapshot
11517            .buffer_snapshot
11518            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11519            .find(|hunk| hunk.row_range.start.0 > position.row)
11520            .or_else(|| {
11521                snapshot
11522                    .buffer_snapshot
11523                    .diff_hunks_in_range(Point::zero()..position)
11524                    .find(|hunk| hunk.row_range.end.0 < position.row)
11525            })
11526    }
11527
11528    fn go_to_prev_hunk(
11529        &mut self,
11530        _: &GoToPreviousHunk,
11531        window: &mut Window,
11532        cx: &mut Context<Self>,
11533    ) {
11534        let snapshot = self.snapshot(window, cx);
11535        let selection = self.selections.newest::<Point>(cx);
11536        self.go_to_hunk_before_or_after_position(
11537            &snapshot,
11538            selection.head(),
11539            Direction::Prev,
11540            window,
11541            cx,
11542        );
11543    }
11544
11545    fn hunk_before_position(
11546        &mut self,
11547        snapshot: &EditorSnapshot,
11548        position: Point,
11549    ) -> Option<MultiBufferRow> {
11550        snapshot
11551            .buffer_snapshot
11552            .diff_hunk_before(position)
11553            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11554    }
11555
11556    pub fn go_to_definition(
11557        &mut self,
11558        _: &GoToDefinition,
11559        window: &mut Window,
11560        cx: &mut Context<Self>,
11561    ) -> Task<Result<Navigated>> {
11562        let definition =
11563            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11564        cx.spawn_in(window, |editor, mut cx| async move {
11565            if definition.await? == Navigated::Yes {
11566                return Ok(Navigated::Yes);
11567            }
11568            match editor.update_in(&mut cx, |editor, window, cx| {
11569                editor.find_all_references(&FindAllReferences, window, cx)
11570            })? {
11571                Some(references) => references.await,
11572                None => Ok(Navigated::No),
11573            }
11574        })
11575    }
11576
11577    pub fn go_to_declaration(
11578        &mut self,
11579        _: &GoToDeclaration,
11580        window: &mut Window,
11581        cx: &mut Context<Self>,
11582    ) -> Task<Result<Navigated>> {
11583        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11584    }
11585
11586    pub fn go_to_declaration_split(
11587        &mut self,
11588        _: &GoToDeclaration,
11589        window: &mut Window,
11590        cx: &mut Context<Self>,
11591    ) -> Task<Result<Navigated>> {
11592        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11593    }
11594
11595    pub fn go_to_implementation(
11596        &mut self,
11597        _: &GoToImplementation,
11598        window: &mut Window,
11599        cx: &mut Context<Self>,
11600    ) -> Task<Result<Navigated>> {
11601        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11602    }
11603
11604    pub fn go_to_implementation_split(
11605        &mut self,
11606        _: &GoToImplementationSplit,
11607        window: &mut Window,
11608        cx: &mut Context<Self>,
11609    ) -> Task<Result<Navigated>> {
11610        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11611    }
11612
11613    pub fn go_to_type_definition(
11614        &mut self,
11615        _: &GoToTypeDefinition,
11616        window: &mut Window,
11617        cx: &mut Context<Self>,
11618    ) -> Task<Result<Navigated>> {
11619        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11620    }
11621
11622    pub fn go_to_definition_split(
11623        &mut self,
11624        _: &GoToDefinitionSplit,
11625        window: &mut Window,
11626        cx: &mut Context<Self>,
11627    ) -> Task<Result<Navigated>> {
11628        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11629    }
11630
11631    pub fn go_to_type_definition_split(
11632        &mut self,
11633        _: &GoToTypeDefinitionSplit,
11634        window: &mut Window,
11635        cx: &mut Context<Self>,
11636    ) -> Task<Result<Navigated>> {
11637        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11638    }
11639
11640    fn go_to_definition_of_kind(
11641        &mut self,
11642        kind: GotoDefinitionKind,
11643        split: bool,
11644        window: &mut Window,
11645        cx: &mut Context<Self>,
11646    ) -> Task<Result<Navigated>> {
11647        let Some(provider) = self.semantics_provider.clone() else {
11648            return Task::ready(Ok(Navigated::No));
11649        };
11650        let head = self.selections.newest::<usize>(cx).head();
11651        let buffer = self.buffer.read(cx);
11652        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11653            text_anchor
11654        } else {
11655            return Task::ready(Ok(Navigated::No));
11656        };
11657
11658        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11659            return Task::ready(Ok(Navigated::No));
11660        };
11661
11662        cx.spawn_in(window, |editor, mut cx| async move {
11663            let definitions = definitions.await?;
11664            let navigated = editor
11665                .update_in(&mut cx, |editor, window, cx| {
11666                    editor.navigate_to_hover_links(
11667                        Some(kind),
11668                        definitions
11669                            .into_iter()
11670                            .filter(|location| {
11671                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11672                            })
11673                            .map(HoverLink::Text)
11674                            .collect::<Vec<_>>(),
11675                        split,
11676                        window,
11677                        cx,
11678                    )
11679                })?
11680                .await?;
11681            anyhow::Ok(navigated)
11682        })
11683    }
11684
11685    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11686        let selection = self.selections.newest_anchor();
11687        let head = selection.head();
11688        let tail = selection.tail();
11689
11690        let Some((buffer, start_position)) =
11691            self.buffer.read(cx).text_anchor_for_position(head, cx)
11692        else {
11693            return;
11694        };
11695
11696        let end_position = if head != tail {
11697            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11698                return;
11699            };
11700            Some(pos)
11701        } else {
11702            None
11703        };
11704
11705        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11706            let url = if let Some(end_pos) = end_position {
11707                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11708            } else {
11709                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11710            };
11711
11712            if let Some(url) = url {
11713                editor.update(&mut cx, |_, cx| {
11714                    cx.open_url(&url);
11715                })
11716            } else {
11717                Ok(())
11718            }
11719        });
11720
11721        url_finder.detach();
11722    }
11723
11724    pub fn open_selected_filename(
11725        &mut self,
11726        _: &OpenSelectedFilename,
11727        window: &mut Window,
11728        cx: &mut Context<Self>,
11729    ) {
11730        let Some(workspace) = self.workspace() else {
11731            return;
11732        };
11733
11734        let position = self.selections.newest_anchor().head();
11735
11736        let Some((buffer, buffer_position)) =
11737            self.buffer.read(cx).text_anchor_for_position(position, cx)
11738        else {
11739            return;
11740        };
11741
11742        let project = self.project.clone();
11743
11744        cx.spawn_in(window, |_, mut cx| async move {
11745            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11746
11747            if let Some((_, path)) = result {
11748                workspace
11749                    .update_in(&mut cx, |workspace, window, cx| {
11750                        workspace.open_resolved_path(path, window, cx)
11751                    })?
11752                    .await?;
11753            }
11754            anyhow::Ok(())
11755        })
11756        .detach();
11757    }
11758
11759    pub(crate) fn navigate_to_hover_links(
11760        &mut self,
11761        kind: Option<GotoDefinitionKind>,
11762        mut definitions: Vec<HoverLink>,
11763        split: bool,
11764        window: &mut Window,
11765        cx: &mut Context<Editor>,
11766    ) -> Task<Result<Navigated>> {
11767        // If there is one definition, just open it directly
11768        if definitions.len() == 1 {
11769            let definition = definitions.pop().unwrap();
11770
11771            enum TargetTaskResult {
11772                Location(Option<Location>),
11773                AlreadyNavigated,
11774            }
11775
11776            let target_task = match definition {
11777                HoverLink::Text(link) => {
11778                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11779                }
11780                HoverLink::InlayHint(lsp_location, server_id) => {
11781                    let computation =
11782                        self.compute_target_location(lsp_location, server_id, window, cx);
11783                    cx.background_spawn(async move {
11784                        let location = computation.await?;
11785                        Ok(TargetTaskResult::Location(location))
11786                    })
11787                }
11788                HoverLink::Url(url) => {
11789                    cx.open_url(&url);
11790                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11791                }
11792                HoverLink::File(path) => {
11793                    if let Some(workspace) = self.workspace() {
11794                        cx.spawn_in(window, |_, mut cx| async move {
11795                            workspace
11796                                .update_in(&mut cx, |workspace, window, cx| {
11797                                    workspace.open_resolved_path(path, window, cx)
11798                                })?
11799                                .await
11800                                .map(|_| TargetTaskResult::AlreadyNavigated)
11801                        })
11802                    } else {
11803                        Task::ready(Ok(TargetTaskResult::Location(None)))
11804                    }
11805                }
11806            };
11807            cx.spawn_in(window, |editor, mut cx| async move {
11808                let target = match target_task.await.context("target resolution task")? {
11809                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11810                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11811                    TargetTaskResult::Location(Some(target)) => target,
11812                };
11813
11814                editor.update_in(&mut cx, |editor, window, cx| {
11815                    let Some(workspace) = editor.workspace() else {
11816                        return Navigated::No;
11817                    };
11818                    let pane = workspace.read(cx).active_pane().clone();
11819
11820                    let range = target.range.to_point(target.buffer.read(cx));
11821                    let range = editor.range_for_match(&range);
11822                    let range = collapse_multiline_range(range);
11823
11824                    if !split
11825                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11826                    {
11827                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11828                    } else {
11829                        window.defer(cx, move |window, cx| {
11830                            let target_editor: Entity<Self> =
11831                                workspace.update(cx, |workspace, cx| {
11832                                    let pane = if split {
11833                                        workspace.adjacent_pane(window, cx)
11834                                    } else {
11835                                        workspace.active_pane().clone()
11836                                    };
11837
11838                                    workspace.open_project_item(
11839                                        pane,
11840                                        target.buffer.clone(),
11841                                        true,
11842                                        true,
11843                                        window,
11844                                        cx,
11845                                    )
11846                                });
11847                            target_editor.update(cx, |target_editor, cx| {
11848                                // When selecting a definition in a different buffer, disable the nav history
11849                                // to avoid creating a history entry at the previous cursor location.
11850                                pane.update(cx, |pane, _| pane.disable_history());
11851                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11852                                pane.update(cx, |pane, _| pane.enable_history());
11853                            });
11854                        });
11855                    }
11856                    Navigated::Yes
11857                })
11858            })
11859        } else if !definitions.is_empty() {
11860            cx.spawn_in(window, |editor, mut cx| async move {
11861                let (title, location_tasks, workspace) = editor
11862                    .update_in(&mut cx, |editor, window, cx| {
11863                        let tab_kind = match kind {
11864                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11865                            _ => "Definitions",
11866                        };
11867                        let title = definitions
11868                            .iter()
11869                            .find_map(|definition| match definition {
11870                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11871                                    let buffer = origin.buffer.read(cx);
11872                                    format!(
11873                                        "{} for {}",
11874                                        tab_kind,
11875                                        buffer
11876                                            .text_for_range(origin.range.clone())
11877                                            .collect::<String>()
11878                                    )
11879                                }),
11880                                HoverLink::InlayHint(_, _) => None,
11881                                HoverLink::Url(_) => None,
11882                                HoverLink::File(_) => None,
11883                            })
11884                            .unwrap_or(tab_kind.to_string());
11885                        let location_tasks = definitions
11886                            .into_iter()
11887                            .map(|definition| match definition {
11888                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11889                                HoverLink::InlayHint(lsp_location, server_id) => editor
11890                                    .compute_target_location(lsp_location, server_id, window, cx),
11891                                HoverLink::Url(_) => Task::ready(Ok(None)),
11892                                HoverLink::File(_) => Task::ready(Ok(None)),
11893                            })
11894                            .collect::<Vec<_>>();
11895                        (title, location_tasks, editor.workspace().clone())
11896                    })
11897                    .context("location tasks preparation")?;
11898
11899                let locations = future::join_all(location_tasks)
11900                    .await
11901                    .into_iter()
11902                    .filter_map(|location| location.transpose())
11903                    .collect::<Result<_>>()
11904                    .context("location tasks")?;
11905
11906                let Some(workspace) = workspace else {
11907                    return Ok(Navigated::No);
11908                };
11909                let opened = workspace
11910                    .update_in(&mut cx, |workspace, window, cx| {
11911                        Self::open_locations_in_multibuffer(
11912                            workspace,
11913                            locations,
11914                            title,
11915                            split,
11916                            MultibufferSelectionMode::First,
11917                            window,
11918                            cx,
11919                        )
11920                    })
11921                    .ok();
11922
11923                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11924            })
11925        } else {
11926            Task::ready(Ok(Navigated::No))
11927        }
11928    }
11929
11930    fn compute_target_location(
11931        &self,
11932        lsp_location: lsp::Location,
11933        server_id: LanguageServerId,
11934        window: &mut Window,
11935        cx: &mut Context<Self>,
11936    ) -> Task<anyhow::Result<Option<Location>>> {
11937        let Some(project) = self.project.clone() else {
11938            return Task::ready(Ok(None));
11939        };
11940
11941        cx.spawn_in(window, move |editor, mut cx| async move {
11942            let location_task = editor.update(&mut cx, |_, cx| {
11943                project.update(cx, |project, cx| {
11944                    let language_server_name = project
11945                        .language_server_statuses(cx)
11946                        .find(|(id, _)| server_id == *id)
11947                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11948                    language_server_name.map(|language_server_name| {
11949                        project.open_local_buffer_via_lsp(
11950                            lsp_location.uri.clone(),
11951                            server_id,
11952                            language_server_name,
11953                            cx,
11954                        )
11955                    })
11956                })
11957            })?;
11958            let location = match location_task {
11959                Some(task) => Some({
11960                    let target_buffer_handle = task.await.context("open local buffer")?;
11961                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11962                        let target_start = target_buffer
11963                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11964                        let target_end = target_buffer
11965                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11966                        target_buffer.anchor_after(target_start)
11967                            ..target_buffer.anchor_before(target_end)
11968                    })?;
11969                    Location {
11970                        buffer: target_buffer_handle,
11971                        range,
11972                    }
11973                }),
11974                None => None,
11975            };
11976            Ok(location)
11977        })
11978    }
11979
11980    pub fn find_all_references(
11981        &mut self,
11982        _: &FindAllReferences,
11983        window: &mut Window,
11984        cx: &mut Context<Self>,
11985    ) -> Option<Task<Result<Navigated>>> {
11986        let selection = self.selections.newest::<usize>(cx);
11987        let multi_buffer = self.buffer.read(cx);
11988        let head = selection.head();
11989
11990        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11991        let head_anchor = multi_buffer_snapshot.anchor_at(
11992            head,
11993            if head < selection.tail() {
11994                Bias::Right
11995            } else {
11996                Bias::Left
11997            },
11998        );
11999
12000        match self
12001            .find_all_references_task_sources
12002            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12003        {
12004            Ok(_) => {
12005                log::info!(
12006                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
12007                );
12008                return None;
12009            }
12010            Err(i) => {
12011                self.find_all_references_task_sources.insert(i, head_anchor);
12012            }
12013        }
12014
12015        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12016        let workspace = self.workspace()?;
12017        let project = workspace.read(cx).project().clone();
12018        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12019        Some(cx.spawn_in(window, |editor, mut cx| async move {
12020            let _cleanup = defer({
12021                let mut cx = cx.clone();
12022                move || {
12023                    let _ = editor.update(&mut cx, |editor, _| {
12024                        if let Ok(i) =
12025                            editor
12026                                .find_all_references_task_sources
12027                                .binary_search_by(|anchor| {
12028                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
12029                                })
12030                        {
12031                            editor.find_all_references_task_sources.remove(i);
12032                        }
12033                    });
12034                }
12035            });
12036
12037            let locations = references.await?;
12038            if locations.is_empty() {
12039                return anyhow::Ok(Navigated::No);
12040            }
12041
12042            workspace.update_in(&mut cx, |workspace, window, cx| {
12043                let title = locations
12044                    .first()
12045                    .as_ref()
12046                    .map(|location| {
12047                        let buffer = location.buffer.read(cx);
12048                        format!(
12049                            "References to `{}`",
12050                            buffer
12051                                .text_for_range(location.range.clone())
12052                                .collect::<String>()
12053                        )
12054                    })
12055                    .unwrap();
12056                Self::open_locations_in_multibuffer(
12057                    workspace,
12058                    locations,
12059                    title,
12060                    false,
12061                    MultibufferSelectionMode::First,
12062                    window,
12063                    cx,
12064                );
12065                Navigated::Yes
12066            })
12067        }))
12068    }
12069
12070    /// Opens a multibuffer with the given project locations in it
12071    pub fn open_locations_in_multibuffer(
12072        workspace: &mut Workspace,
12073        mut locations: Vec<Location>,
12074        title: String,
12075        split: bool,
12076        multibuffer_selection_mode: MultibufferSelectionMode,
12077        window: &mut Window,
12078        cx: &mut Context<Workspace>,
12079    ) {
12080        // If there are multiple definitions, open them in a multibuffer
12081        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12082        let mut locations = locations.into_iter().peekable();
12083        let mut ranges = Vec::new();
12084        let capability = workspace.project().read(cx).capability();
12085
12086        let excerpt_buffer = cx.new(|cx| {
12087            let mut multibuffer = MultiBuffer::new(capability);
12088            while let Some(location) = locations.next() {
12089                let buffer = location.buffer.read(cx);
12090                let mut ranges_for_buffer = Vec::new();
12091                let range = location.range.to_offset(buffer);
12092                ranges_for_buffer.push(range.clone());
12093
12094                while let Some(next_location) = locations.peek() {
12095                    if next_location.buffer == location.buffer {
12096                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
12097                        locations.next();
12098                    } else {
12099                        break;
12100                    }
12101                }
12102
12103                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12104                ranges.extend(multibuffer.push_excerpts_with_context_lines(
12105                    location.buffer.clone(),
12106                    ranges_for_buffer,
12107                    DEFAULT_MULTIBUFFER_CONTEXT,
12108                    cx,
12109                ))
12110            }
12111
12112            multibuffer.with_title(title)
12113        });
12114
12115        let editor = cx.new(|cx| {
12116            Editor::for_multibuffer(
12117                excerpt_buffer,
12118                Some(workspace.project().clone()),
12119                true,
12120                window,
12121                cx,
12122            )
12123        });
12124        editor.update(cx, |editor, cx| {
12125            match multibuffer_selection_mode {
12126                MultibufferSelectionMode::First => {
12127                    if let Some(first_range) = ranges.first() {
12128                        editor.change_selections(None, window, cx, |selections| {
12129                            selections.clear_disjoint();
12130                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12131                        });
12132                    }
12133                    editor.highlight_background::<Self>(
12134                        &ranges,
12135                        |theme| theme.editor_highlighted_line_background,
12136                        cx,
12137                    );
12138                }
12139                MultibufferSelectionMode::All => {
12140                    editor.change_selections(None, window, cx, |selections| {
12141                        selections.clear_disjoint();
12142                        selections.select_anchor_ranges(ranges);
12143                    });
12144                }
12145            }
12146            editor.register_buffers_with_language_servers(cx);
12147        });
12148
12149        let item = Box::new(editor);
12150        let item_id = item.item_id();
12151
12152        if split {
12153            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12154        } else {
12155            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12156                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12157                    pane.close_current_preview_item(window, cx)
12158                } else {
12159                    None
12160                }
12161            });
12162            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12163        }
12164        workspace.active_pane().update(cx, |pane, cx| {
12165            pane.set_preview_item_id(Some(item_id), cx);
12166        });
12167    }
12168
12169    pub fn rename(
12170        &mut self,
12171        _: &Rename,
12172        window: &mut Window,
12173        cx: &mut Context<Self>,
12174    ) -> Option<Task<Result<()>>> {
12175        use language::ToOffset as _;
12176
12177        let provider = self.semantics_provider.clone()?;
12178        let selection = self.selections.newest_anchor().clone();
12179        let (cursor_buffer, cursor_buffer_position) = self
12180            .buffer
12181            .read(cx)
12182            .text_anchor_for_position(selection.head(), cx)?;
12183        let (tail_buffer, cursor_buffer_position_end) = self
12184            .buffer
12185            .read(cx)
12186            .text_anchor_for_position(selection.tail(), cx)?;
12187        if tail_buffer != cursor_buffer {
12188            return None;
12189        }
12190
12191        let snapshot = cursor_buffer.read(cx).snapshot();
12192        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12193        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12194        let prepare_rename = provider
12195            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12196            .unwrap_or_else(|| Task::ready(Ok(None)));
12197        drop(snapshot);
12198
12199        Some(cx.spawn_in(window, |this, mut cx| async move {
12200            let rename_range = if let Some(range) = prepare_rename.await? {
12201                Some(range)
12202            } else {
12203                this.update(&mut cx, |this, cx| {
12204                    let buffer = this.buffer.read(cx).snapshot(cx);
12205                    let mut buffer_highlights = this
12206                        .document_highlights_for_position(selection.head(), &buffer)
12207                        .filter(|highlight| {
12208                            highlight.start.excerpt_id == selection.head().excerpt_id
12209                                && highlight.end.excerpt_id == selection.head().excerpt_id
12210                        });
12211                    buffer_highlights
12212                        .next()
12213                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12214                })?
12215            };
12216            if let Some(rename_range) = rename_range {
12217                this.update_in(&mut cx, |this, window, cx| {
12218                    let snapshot = cursor_buffer.read(cx).snapshot();
12219                    let rename_buffer_range = rename_range.to_offset(&snapshot);
12220                    let cursor_offset_in_rename_range =
12221                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12222                    let cursor_offset_in_rename_range_end =
12223                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12224
12225                    this.take_rename(false, window, cx);
12226                    let buffer = this.buffer.read(cx).read(cx);
12227                    let cursor_offset = selection.head().to_offset(&buffer);
12228                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12229                    let rename_end = rename_start + rename_buffer_range.len();
12230                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12231                    let mut old_highlight_id = None;
12232                    let old_name: Arc<str> = buffer
12233                        .chunks(rename_start..rename_end, true)
12234                        .map(|chunk| {
12235                            if old_highlight_id.is_none() {
12236                                old_highlight_id = chunk.syntax_highlight_id;
12237                            }
12238                            chunk.text
12239                        })
12240                        .collect::<String>()
12241                        .into();
12242
12243                    drop(buffer);
12244
12245                    // Position the selection in the rename editor so that it matches the current selection.
12246                    this.show_local_selections = false;
12247                    let rename_editor = cx.new(|cx| {
12248                        let mut editor = Editor::single_line(window, cx);
12249                        editor.buffer.update(cx, |buffer, cx| {
12250                            buffer.edit([(0..0, old_name.clone())], None, cx)
12251                        });
12252                        let rename_selection_range = match cursor_offset_in_rename_range
12253                            .cmp(&cursor_offset_in_rename_range_end)
12254                        {
12255                            Ordering::Equal => {
12256                                editor.select_all(&SelectAll, window, cx);
12257                                return editor;
12258                            }
12259                            Ordering::Less => {
12260                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12261                            }
12262                            Ordering::Greater => {
12263                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12264                            }
12265                        };
12266                        if rename_selection_range.end > old_name.len() {
12267                            editor.select_all(&SelectAll, window, cx);
12268                        } else {
12269                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12270                                s.select_ranges([rename_selection_range]);
12271                            });
12272                        }
12273                        editor
12274                    });
12275                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12276                        if e == &EditorEvent::Focused {
12277                            cx.emit(EditorEvent::FocusedIn)
12278                        }
12279                    })
12280                    .detach();
12281
12282                    let write_highlights =
12283                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12284                    let read_highlights =
12285                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
12286                    let ranges = write_highlights
12287                        .iter()
12288                        .flat_map(|(_, ranges)| ranges.iter())
12289                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12290                        .cloned()
12291                        .collect();
12292
12293                    this.highlight_text::<Rename>(
12294                        ranges,
12295                        HighlightStyle {
12296                            fade_out: Some(0.6),
12297                            ..Default::default()
12298                        },
12299                        cx,
12300                    );
12301                    let rename_focus_handle = rename_editor.focus_handle(cx);
12302                    window.focus(&rename_focus_handle);
12303                    let block_id = this.insert_blocks(
12304                        [BlockProperties {
12305                            style: BlockStyle::Flex,
12306                            placement: BlockPlacement::Below(range.start),
12307                            height: 1,
12308                            render: Arc::new({
12309                                let rename_editor = rename_editor.clone();
12310                                move |cx: &mut BlockContext| {
12311                                    let mut text_style = cx.editor_style.text.clone();
12312                                    if let Some(highlight_style) = old_highlight_id
12313                                        .and_then(|h| h.style(&cx.editor_style.syntax))
12314                                    {
12315                                        text_style = text_style.highlight(highlight_style);
12316                                    }
12317                                    div()
12318                                        .block_mouse_down()
12319                                        .pl(cx.anchor_x)
12320                                        .child(EditorElement::new(
12321                                            &rename_editor,
12322                                            EditorStyle {
12323                                                background: cx.theme().system().transparent,
12324                                                local_player: cx.editor_style.local_player,
12325                                                text: text_style,
12326                                                scrollbar_width: cx.editor_style.scrollbar_width,
12327                                                syntax: cx.editor_style.syntax.clone(),
12328                                                status: cx.editor_style.status.clone(),
12329                                                inlay_hints_style: HighlightStyle {
12330                                                    font_weight: Some(FontWeight::BOLD),
12331                                                    ..make_inlay_hints_style(cx.app)
12332                                                },
12333                                                inline_completion_styles: make_suggestion_styles(
12334                                                    cx.app,
12335                                                ),
12336                                                ..EditorStyle::default()
12337                                            },
12338                                        ))
12339                                        .into_any_element()
12340                                }
12341                            }),
12342                            priority: 0,
12343                        }],
12344                        Some(Autoscroll::fit()),
12345                        cx,
12346                    )[0];
12347                    this.pending_rename = Some(RenameState {
12348                        range,
12349                        old_name,
12350                        editor: rename_editor,
12351                        block_id,
12352                    });
12353                })?;
12354            }
12355
12356            Ok(())
12357        }))
12358    }
12359
12360    pub fn confirm_rename(
12361        &mut self,
12362        _: &ConfirmRename,
12363        window: &mut Window,
12364        cx: &mut Context<Self>,
12365    ) -> Option<Task<Result<()>>> {
12366        let rename = self.take_rename(false, window, cx)?;
12367        let workspace = self.workspace()?.downgrade();
12368        let (buffer, start) = self
12369            .buffer
12370            .read(cx)
12371            .text_anchor_for_position(rename.range.start, cx)?;
12372        let (end_buffer, _) = self
12373            .buffer
12374            .read(cx)
12375            .text_anchor_for_position(rename.range.end, cx)?;
12376        if buffer != end_buffer {
12377            return None;
12378        }
12379
12380        let old_name = rename.old_name;
12381        let new_name = rename.editor.read(cx).text(cx);
12382
12383        let rename = self.semantics_provider.as_ref()?.perform_rename(
12384            &buffer,
12385            start,
12386            new_name.clone(),
12387            cx,
12388        )?;
12389
12390        Some(cx.spawn_in(window, |editor, mut cx| async move {
12391            let project_transaction = rename.await?;
12392            Self::open_project_transaction(
12393                &editor,
12394                workspace,
12395                project_transaction,
12396                format!("Rename: {}{}", old_name, new_name),
12397                cx.clone(),
12398            )
12399            .await?;
12400
12401            editor.update(&mut cx, |editor, cx| {
12402                editor.refresh_document_highlights(cx);
12403            })?;
12404            Ok(())
12405        }))
12406    }
12407
12408    fn take_rename(
12409        &mut self,
12410        moving_cursor: bool,
12411        window: &mut Window,
12412        cx: &mut Context<Self>,
12413    ) -> Option<RenameState> {
12414        let rename = self.pending_rename.take()?;
12415        if rename.editor.focus_handle(cx).is_focused(window) {
12416            window.focus(&self.focus_handle);
12417        }
12418
12419        self.remove_blocks(
12420            [rename.block_id].into_iter().collect(),
12421            Some(Autoscroll::fit()),
12422            cx,
12423        );
12424        self.clear_highlights::<Rename>(cx);
12425        self.show_local_selections = true;
12426
12427        if moving_cursor {
12428            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12429                editor.selections.newest::<usize>(cx).head()
12430            });
12431
12432            // Update the selection to match the position of the selection inside
12433            // the rename editor.
12434            let snapshot = self.buffer.read(cx).read(cx);
12435            let rename_range = rename.range.to_offset(&snapshot);
12436            let cursor_in_editor = snapshot
12437                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12438                .min(rename_range.end);
12439            drop(snapshot);
12440
12441            self.change_selections(None, window, cx, |s| {
12442                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12443            });
12444        } else {
12445            self.refresh_document_highlights(cx);
12446        }
12447
12448        Some(rename)
12449    }
12450
12451    pub fn pending_rename(&self) -> Option<&RenameState> {
12452        self.pending_rename.as_ref()
12453    }
12454
12455    fn format(
12456        &mut self,
12457        _: &Format,
12458        window: &mut Window,
12459        cx: &mut Context<Self>,
12460    ) -> Option<Task<Result<()>>> {
12461        let project = match &self.project {
12462            Some(project) => project.clone(),
12463            None => return None,
12464        };
12465
12466        Some(self.perform_format(
12467            project,
12468            FormatTrigger::Manual,
12469            FormatTarget::Buffers,
12470            window,
12471            cx,
12472        ))
12473    }
12474
12475    fn format_selections(
12476        &mut self,
12477        _: &FormatSelections,
12478        window: &mut Window,
12479        cx: &mut Context<Self>,
12480    ) -> Option<Task<Result<()>>> {
12481        let project = match &self.project {
12482            Some(project) => project.clone(),
12483            None => return None,
12484        };
12485
12486        let ranges = self
12487            .selections
12488            .all_adjusted(cx)
12489            .into_iter()
12490            .map(|selection| selection.range())
12491            .collect_vec();
12492
12493        Some(self.perform_format(
12494            project,
12495            FormatTrigger::Manual,
12496            FormatTarget::Ranges(ranges),
12497            window,
12498            cx,
12499        ))
12500    }
12501
12502    fn perform_format(
12503        &mut self,
12504        project: Entity<Project>,
12505        trigger: FormatTrigger,
12506        target: FormatTarget,
12507        window: &mut Window,
12508        cx: &mut Context<Self>,
12509    ) -> Task<Result<()>> {
12510        let buffer = self.buffer.clone();
12511        let (buffers, target) = match target {
12512            FormatTarget::Buffers => {
12513                let mut buffers = buffer.read(cx).all_buffers();
12514                if trigger == FormatTrigger::Save {
12515                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
12516                }
12517                (buffers, LspFormatTarget::Buffers)
12518            }
12519            FormatTarget::Ranges(selection_ranges) => {
12520                let multi_buffer = buffer.read(cx);
12521                let snapshot = multi_buffer.read(cx);
12522                let mut buffers = HashSet::default();
12523                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12524                    BTreeMap::new();
12525                for selection_range in selection_ranges {
12526                    for (buffer, buffer_range, _) in
12527                        snapshot.range_to_buffer_ranges(selection_range)
12528                    {
12529                        let buffer_id = buffer.remote_id();
12530                        let start = buffer.anchor_before(buffer_range.start);
12531                        let end = buffer.anchor_after(buffer_range.end);
12532                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12533                        buffer_id_to_ranges
12534                            .entry(buffer_id)
12535                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12536                            .or_insert_with(|| vec![start..end]);
12537                    }
12538                }
12539                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12540            }
12541        };
12542
12543        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12544        let format = project.update(cx, |project, cx| {
12545            project.format(buffers, target, true, trigger, cx)
12546        });
12547
12548        cx.spawn_in(window, |_, mut cx| async move {
12549            let transaction = futures::select_biased! {
12550                () = timeout => {
12551                    log::warn!("timed out waiting for formatting");
12552                    None
12553                }
12554                transaction = format.log_err().fuse() => transaction,
12555            };
12556
12557            buffer
12558                .update(&mut cx, |buffer, cx| {
12559                    if let Some(transaction) = transaction {
12560                        if !buffer.is_singleton() {
12561                            buffer.push_transaction(&transaction.0, cx);
12562                        }
12563                    }
12564                    cx.notify();
12565                })
12566                .ok();
12567
12568            Ok(())
12569        })
12570    }
12571
12572    fn organize_imports(
12573        &mut self,
12574        _: &OrganizeImports,
12575        window: &mut Window,
12576        cx: &mut Context<Self>,
12577    ) -> Option<Task<Result<()>>> {
12578        let project = match &self.project {
12579            Some(project) => project.clone(),
12580            None => return None,
12581        };
12582        Some(self.perform_code_action_kind(
12583            project,
12584            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12585            window,
12586            cx,
12587        ))
12588    }
12589
12590    fn perform_code_action_kind(
12591        &mut self,
12592        project: Entity<Project>,
12593        kind: CodeActionKind,
12594        window: &mut Window,
12595        cx: &mut Context<Self>,
12596    ) -> Task<Result<()>> {
12597        let buffer = self.buffer.clone();
12598        let buffers = buffer.read(cx).all_buffers();
12599        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12600        let apply_action = project.update(cx, |project, cx| {
12601            project.apply_code_action_kind(buffers, kind, true, cx)
12602        });
12603        cx.spawn_in(window, |_, mut cx| async move {
12604            let transaction = futures::select_biased! {
12605                () = timeout => {
12606                    log::warn!("timed out waiting for executing code action");
12607                    None
12608                }
12609                transaction = apply_action.log_err().fuse() => transaction,
12610            };
12611            buffer
12612                .update(&mut cx, |buffer, cx| {
12613                    // check if we need this
12614                    if let Some(transaction) = transaction {
12615                        if !buffer.is_singleton() {
12616                            buffer.push_transaction(&transaction.0, cx);
12617                        }
12618                    }
12619                    cx.notify();
12620                })
12621                .ok();
12622            Ok(())
12623        })
12624    }
12625
12626    fn restart_language_server(
12627        &mut self,
12628        _: &RestartLanguageServer,
12629        _: &mut Window,
12630        cx: &mut Context<Self>,
12631    ) {
12632        if let Some(project) = self.project.clone() {
12633            self.buffer.update(cx, |multi_buffer, cx| {
12634                project.update(cx, |project, cx| {
12635                    project.restart_language_servers_for_buffers(
12636                        multi_buffer.all_buffers().into_iter().collect(),
12637                        cx,
12638                    );
12639                });
12640            })
12641        }
12642    }
12643
12644    fn cancel_language_server_work(
12645        workspace: &mut Workspace,
12646        _: &actions::CancelLanguageServerWork,
12647        _: &mut Window,
12648        cx: &mut Context<Workspace>,
12649    ) {
12650        let project = workspace.project();
12651        let buffers = workspace
12652            .active_item(cx)
12653            .and_then(|item| item.act_as::<Editor>(cx))
12654            .map_or(HashSet::default(), |editor| {
12655                editor.read(cx).buffer.read(cx).all_buffers()
12656            });
12657        project.update(cx, |project, cx| {
12658            project.cancel_language_server_work_for_buffers(buffers, cx);
12659        });
12660    }
12661
12662    fn show_character_palette(
12663        &mut self,
12664        _: &ShowCharacterPalette,
12665        window: &mut Window,
12666        _: &mut Context<Self>,
12667    ) {
12668        window.show_character_palette();
12669    }
12670
12671    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12672        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12673            let buffer = self.buffer.read(cx).snapshot(cx);
12674            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12675            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12676            let is_valid = buffer
12677                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12678                .any(|entry| {
12679                    entry.diagnostic.is_primary
12680                        && !entry.range.is_empty()
12681                        && entry.range.start == primary_range_start
12682                        && entry.diagnostic.message == active_diagnostics.primary_message
12683                });
12684
12685            if is_valid != active_diagnostics.is_valid {
12686                active_diagnostics.is_valid = is_valid;
12687                if is_valid {
12688                    let mut new_styles = HashMap::default();
12689                    for (block_id, diagnostic) in &active_diagnostics.blocks {
12690                        new_styles.insert(
12691                            *block_id,
12692                            diagnostic_block_renderer(diagnostic.clone(), None, true),
12693                        );
12694                    }
12695                    self.display_map.update(cx, |display_map, _cx| {
12696                        display_map.replace_blocks(new_styles);
12697                    });
12698                } else {
12699                    self.dismiss_diagnostics(cx);
12700                }
12701            }
12702        }
12703    }
12704
12705    fn activate_diagnostics(
12706        &mut self,
12707        buffer_id: BufferId,
12708        group_id: usize,
12709        window: &mut Window,
12710        cx: &mut Context<Self>,
12711    ) {
12712        self.dismiss_diagnostics(cx);
12713        let snapshot = self.snapshot(window, cx);
12714        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12715            let buffer = self.buffer.read(cx).snapshot(cx);
12716
12717            let mut primary_range = None;
12718            let mut primary_message = None;
12719            let diagnostic_group = buffer
12720                .diagnostic_group(buffer_id, group_id)
12721                .filter_map(|entry| {
12722                    let start = entry.range.start;
12723                    let end = entry.range.end;
12724                    if snapshot.is_line_folded(MultiBufferRow(start.row))
12725                        && (start.row == end.row
12726                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
12727                    {
12728                        return None;
12729                    }
12730                    if entry.diagnostic.is_primary {
12731                        primary_range = Some(entry.range.clone());
12732                        primary_message = Some(entry.diagnostic.message.clone());
12733                    }
12734                    Some(entry)
12735                })
12736                .collect::<Vec<_>>();
12737            let primary_range = primary_range?;
12738            let primary_message = primary_message?;
12739
12740            let blocks = display_map
12741                .insert_blocks(
12742                    diagnostic_group.iter().map(|entry| {
12743                        let diagnostic = entry.diagnostic.clone();
12744                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12745                        BlockProperties {
12746                            style: BlockStyle::Fixed,
12747                            placement: BlockPlacement::Below(
12748                                buffer.anchor_after(entry.range.start),
12749                            ),
12750                            height: message_height,
12751                            render: diagnostic_block_renderer(diagnostic, None, true),
12752                            priority: 0,
12753                        }
12754                    }),
12755                    cx,
12756                )
12757                .into_iter()
12758                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12759                .collect();
12760
12761            Some(ActiveDiagnosticGroup {
12762                primary_range: buffer.anchor_before(primary_range.start)
12763                    ..buffer.anchor_after(primary_range.end),
12764                primary_message,
12765                group_id,
12766                blocks,
12767                is_valid: true,
12768            })
12769        });
12770    }
12771
12772    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12773        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12774            self.display_map.update(cx, |display_map, cx| {
12775                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12776            });
12777            cx.notify();
12778        }
12779    }
12780
12781    /// Disable inline diagnostics rendering for this editor.
12782    pub fn disable_inline_diagnostics(&mut self) {
12783        self.inline_diagnostics_enabled = false;
12784        self.inline_diagnostics_update = Task::ready(());
12785        self.inline_diagnostics.clear();
12786    }
12787
12788    pub fn inline_diagnostics_enabled(&self) -> bool {
12789        self.inline_diagnostics_enabled
12790    }
12791
12792    pub fn show_inline_diagnostics(&self) -> bool {
12793        self.show_inline_diagnostics
12794    }
12795
12796    pub fn toggle_inline_diagnostics(
12797        &mut self,
12798        _: &ToggleInlineDiagnostics,
12799        window: &mut Window,
12800        cx: &mut Context<'_, Editor>,
12801    ) {
12802        self.show_inline_diagnostics = !self.show_inline_diagnostics;
12803        self.refresh_inline_diagnostics(false, window, cx);
12804    }
12805
12806    fn refresh_inline_diagnostics(
12807        &mut self,
12808        debounce: bool,
12809        window: &mut Window,
12810        cx: &mut Context<Self>,
12811    ) {
12812        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12813            self.inline_diagnostics_update = Task::ready(());
12814            self.inline_diagnostics.clear();
12815            return;
12816        }
12817
12818        let debounce_ms = ProjectSettings::get_global(cx)
12819            .diagnostics
12820            .inline
12821            .update_debounce_ms;
12822        let debounce = if debounce && debounce_ms > 0 {
12823            Some(Duration::from_millis(debounce_ms))
12824        } else {
12825            None
12826        };
12827        self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12828            if let Some(debounce) = debounce {
12829                cx.background_executor().timer(debounce).await;
12830            }
12831            let Some(snapshot) = editor
12832                .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12833                .ok()
12834            else {
12835                return;
12836            };
12837
12838            let new_inline_diagnostics = cx
12839                .background_spawn(async move {
12840                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12841                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12842                        let message = diagnostic_entry
12843                            .diagnostic
12844                            .message
12845                            .split_once('\n')
12846                            .map(|(line, _)| line)
12847                            .map(SharedString::new)
12848                            .unwrap_or_else(|| {
12849                                SharedString::from(diagnostic_entry.diagnostic.message)
12850                            });
12851                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12852                        let (Ok(i) | Err(i)) = inline_diagnostics
12853                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12854                        inline_diagnostics.insert(
12855                            i,
12856                            (
12857                                start_anchor,
12858                                InlineDiagnostic {
12859                                    message,
12860                                    group_id: diagnostic_entry.diagnostic.group_id,
12861                                    start: diagnostic_entry.range.start.to_point(&snapshot),
12862                                    is_primary: diagnostic_entry.diagnostic.is_primary,
12863                                    severity: diagnostic_entry.diagnostic.severity,
12864                                },
12865                            ),
12866                        );
12867                    }
12868                    inline_diagnostics
12869                })
12870                .await;
12871
12872            editor
12873                .update(&mut cx, |editor, cx| {
12874                    editor.inline_diagnostics = new_inline_diagnostics;
12875                    cx.notify();
12876                })
12877                .ok();
12878        });
12879    }
12880
12881    pub fn set_selections_from_remote(
12882        &mut self,
12883        selections: Vec<Selection<Anchor>>,
12884        pending_selection: Option<Selection<Anchor>>,
12885        window: &mut Window,
12886        cx: &mut Context<Self>,
12887    ) {
12888        let old_cursor_position = self.selections.newest_anchor().head();
12889        self.selections.change_with(cx, |s| {
12890            s.select_anchors(selections);
12891            if let Some(pending_selection) = pending_selection {
12892                s.set_pending(pending_selection, SelectMode::Character);
12893            } else {
12894                s.clear_pending();
12895            }
12896        });
12897        self.selections_did_change(false, &old_cursor_position, true, window, cx);
12898    }
12899
12900    fn push_to_selection_history(&mut self) {
12901        self.selection_history.push(SelectionHistoryEntry {
12902            selections: self.selections.disjoint_anchors(),
12903            select_next_state: self.select_next_state.clone(),
12904            select_prev_state: self.select_prev_state.clone(),
12905            add_selections_state: self.add_selections_state.clone(),
12906        });
12907    }
12908
12909    pub fn transact(
12910        &mut self,
12911        window: &mut Window,
12912        cx: &mut Context<Self>,
12913        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12914    ) -> Option<TransactionId> {
12915        self.start_transaction_at(Instant::now(), window, cx);
12916        update(self, window, cx);
12917        self.end_transaction_at(Instant::now(), cx)
12918    }
12919
12920    pub fn start_transaction_at(
12921        &mut self,
12922        now: Instant,
12923        window: &mut Window,
12924        cx: &mut Context<Self>,
12925    ) {
12926        self.end_selection(window, cx);
12927        if let Some(tx_id) = self
12928            .buffer
12929            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12930        {
12931            self.selection_history
12932                .insert_transaction(tx_id, self.selections.disjoint_anchors());
12933            cx.emit(EditorEvent::TransactionBegun {
12934                transaction_id: tx_id,
12935            })
12936        }
12937    }
12938
12939    pub fn end_transaction_at(
12940        &mut self,
12941        now: Instant,
12942        cx: &mut Context<Self>,
12943    ) -> Option<TransactionId> {
12944        if let Some(transaction_id) = self
12945            .buffer
12946            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12947        {
12948            if let Some((_, end_selections)) =
12949                self.selection_history.transaction_mut(transaction_id)
12950            {
12951                *end_selections = Some(self.selections.disjoint_anchors());
12952            } else {
12953                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12954            }
12955
12956            cx.emit(EditorEvent::Edited { transaction_id });
12957            Some(transaction_id)
12958        } else {
12959            None
12960        }
12961    }
12962
12963    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12964        if self.selection_mark_mode {
12965            self.change_selections(None, window, cx, |s| {
12966                s.move_with(|_, sel| {
12967                    sel.collapse_to(sel.head(), SelectionGoal::None);
12968                });
12969            })
12970        }
12971        self.selection_mark_mode = true;
12972        cx.notify();
12973    }
12974
12975    pub fn swap_selection_ends(
12976        &mut self,
12977        _: &actions::SwapSelectionEnds,
12978        window: &mut Window,
12979        cx: &mut Context<Self>,
12980    ) {
12981        self.change_selections(None, window, cx, |s| {
12982            s.move_with(|_, sel| {
12983                if sel.start != sel.end {
12984                    sel.reversed = !sel.reversed
12985                }
12986            });
12987        });
12988        self.request_autoscroll(Autoscroll::newest(), cx);
12989        cx.notify();
12990    }
12991
12992    pub fn toggle_fold(
12993        &mut self,
12994        _: &actions::ToggleFold,
12995        window: &mut Window,
12996        cx: &mut Context<Self>,
12997    ) {
12998        if self.is_singleton(cx) {
12999            let selection = self.selections.newest::<Point>(cx);
13000
13001            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13002            let range = if selection.is_empty() {
13003                let point = selection.head().to_display_point(&display_map);
13004                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13005                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13006                    .to_point(&display_map);
13007                start..end
13008            } else {
13009                selection.range()
13010            };
13011            if display_map.folds_in_range(range).next().is_some() {
13012                self.unfold_lines(&Default::default(), window, cx)
13013            } else {
13014                self.fold(&Default::default(), window, cx)
13015            }
13016        } else {
13017            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13018            let buffer_ids: HashSet<_> = self
13019                .selections
13020                .disjoint_anchor_ranges()
13021                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13022                .collect();
13023
13024            let should_unfold = buffer_ids
13025                .iter()
13026                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13027
13028            for buffer_id in buffer_ids {
13029                if should_unfold {
13030                    self.unfold_buffer(buffer_id, cx);
13031                } else {
13032                    self.fold_buffer(buffer_id, cx);
13033                }
13034            }
13035        }
13036    }
13037
13038    pub fn toggle_fold_recursive(
13039        &mut self,
13040        _: &actions::ToggleFoldRecursive,
13041        window: &mut Window,
13042        cx: &mut Context<Self>,
13043    ) {
13044        let selection = self.selections.newest::<Point>(cx);
13045
13046        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13047        let range = if selection.is_empty() {
13048            let point = selection.head().to_display_point(&display_map);
13049            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13050            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13051                .to_point(&display_map);
13052            start..end
13053        } else {
13054            selection.range()
13055        };
13056        if display_map.folds_in_range(range).next().is_some() {
13057            self.unfold_recursive(&Default::default(), window, cx)
13058        } else {
13059            self.fold_recursive(&Default::default(), window, cx)
13060        }
13061    }
13062
13063    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13064        if self.is_singleton(cx) {
13065            let mut to_fold = Vec::new();
13066            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13067            let selections = self.selections.all_adjusted(cx);
13068
13069            for selection in selections {
13070                let range = selection.range().sorted();
13071                let buffer_start_row = range.start.row;
13072
13073                if range.start.row != range.end.row {
13074                    let mut found = false;
13075                    let mut row = range.start.row;
13076                    while row <= range.end.row {
13077                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13078                        {
13079                            found = true;
13080                            row = crease.range().end.row + 1;
13081                            to_fold.push(crease);
13082                        } else {
13083                            row += 1
13084                        }
13085                    }
13086                    if found {
13087                        continue;
13088                    }
13089                }
13090
13091                for row in (0..=range.start.row).rev() {
13092                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13093                        if crease.range().end.row >= buffer_start_row {
13094                            to_fold.push(crease);
13095                            if row <= range.start.row {
13096                                break;
13097                            }
13098                        }
13099                    }
13100                }
13101            }
13102
13103            self.fold_creases(to_fold, true, window, cx);
13104        } else {
13105            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13106            let buffer_ids = self
13107                .selections
13108                .disjoint_anchor_ranges()
13109                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13110                .collect::<HashSet<_>>();
13111            for buffer_id in buffer_ids {
13112                self.fold_buffer(buffer_id, cx);
13113            }
13114        }
13115    }
13116
13117    fn fold_at_level(
13118        &mut self,
13119        fold_at: &FoldAtLevel,
13120        window: &mut Window,
13121        cx: &mut Context<Self>,
13122    ) {
13123        if !self.buffer.read(cx).is_singleton() {
13124            return;
13125        }
13126
13127        let fold_at_level = fold_at.0;
13128        let snapshot = self.buffer.read(cx).snapshot(cx);
13129        let mut to_fold = Vec::new();
13130        let mut stack = vec![(0, snapshot.max_row().0, 1)];
13131
13132        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13133            while start_row < end_row {
13134                match self
13135                    .snapshot(window, cx)
13136                    .crease_for_buffer_row(MultiBufferRow(start_row))
13137                {
13138                    Some(crease) => {
13139                        let nested_start_row = crease.range().start.row + 1;
13140                        let nested_end_row = crease.range().end.row;
13141
13142                        if current_level < fold_at_level {
13143                            stack.push((nested_start_row, nested_end_row, current_level + 1));
13144                        } else if current_level == fold_at_level {
13145                            to_fold.push(crease);
13146                        }
13147
13148                        start_row = nested_end_row + 1;
13149                    }
13150                    None => start_row += 1,
13151                }
13152            }
13153        }
13154
13155        self.fold_creases(to_fold, true, window, cx);
13156    }
13157
13158    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13159        if self.buffer.read(cx).is_singleton() {
13160            let mut fold_ranges = Vec::new();
13161            let snapshot = self.buffer.read(cx).snapshot(cx);
13162
13163            for row in 0..snapshot.max_row().0 {
13164                if let Some(foldable_range) = self
13165                    .snapshot(window, cx)
13166                    .crease_for_buffer_row(MultiBufferRow(row))
13167                {
13168                    fold_ranges.push(foldable_range);
13169                }
13170            }
13171
13172            self.fold_creases(fold_ranges, true, window, cx);
13173        } else {
13174            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13175                editor
13176                    .update_in(&mut cx, |editor, _, cx| {
13177                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13178                            editor.fold_buffer(buffer_id, cx);
13179                        }
13180                    })
13181                    .ok();
13182            });
13183        }
13184    }
13185
13186    pub fn fold_function_bodies(
13187        &mut self,
13188        _: &actions::FoldFunctionBodies,
13189        window: &mut Window,
13190        cx: &mut Context<Self>,
13191    ) {
13192        let snapshot = self.buffer.read(cx).snapshot(cx);
13193
13194        let ranges = snapshot
13195            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13196            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13197            .collect::<Vec<_>>();
13198
13199        let creases = ranges
13200            .into_iter()
13201            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13202            .collect();
13203
13204        self.fold_creases(creases, true, window, cx);
13205    }
13206
13207    pub fn fold_recursive(
13208        &mut self,
13209        _: &actions::FoldRecursive,
13210        window: &mut Window,
13211        cx: &mut Context<Self>,
13212    ) {
13213        let mut to_fold = Vec::new();
13214        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13215        let selections = self.selections.all_adjusted(cx);
13216
13217        for selection in selections {
13218            let range = selection.range().sorted();
13219            let buffer_start_row = range.start.row;
13220
13221            if range.start.row != range.end.row {
13222                let mut found = false;
13223                for row in range.start.row..=range.end.row {
13224                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13225                        found = true;
13226                        to_fold.push(crease);
13227                    }
13228                }
13229                if found {
13230                    continue;
13231                }
13232            }
13233
13234            for row in (0..=range.start.row).rev() {
13235                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13236                    if crease.range().end.row >= buffer_start_row {
13237                        to_fold.push(crease);
13238                    } else {
13239                        break;
13240                    }
13241                }
13242            }
13243        }
13244
13245        self.fold_creases(to_fold, true, window, cx);
13246    }
13247
13248    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13249        let buffer_row = fold_at.buffer_row;
13250        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13251
13252        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13253            let autoscroll = self
13254                .selections
13255                .all::<Point>(cx)
13256                .iter()
13257                .any(|selection| crease.range().overlaps(&selection.range()));
13258
13259            self.fold_creases(vec![crease], autoscroll, window, cx);
13260        }
13261    }
13262
13263    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13264        if self.is_singleton(cx) {
13265            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13266            let buffer = &display_map.buffer_snapshot;
13267            let selections = self.selections.all::<Point>(cx);
13268            let ranges = selections
13269                .iter()
13270                .map(|s| {
13271                    let range = s.display_range(&display_map).sorted();
13272                    let mut start = range.start.to_point(&display_map);
13273                    let mut end = range.end.to_point(&display_map);
13274                    start.column = 0;
13275                    end.column = buffer.line_len(MultiBufferRow(end.row));
13276                    start..end
13277                })
13278                .collect::<Vec<_>>();
13279
13280            self.unfold_ranges(&ranges, true, true, cx);
13281        } else {
13282            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13283            let buffer_ids = self
13284                .selections
13285                .disjoint_anchor_ranges()
13286                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13287                .collect::<HashSet<_>>();
13288            for buffer_id in buffer_ids {
13289                self.unfold_buffer(buffer_id, cx);
13290            }
13291        }
13292    }
13293
13294    pub fn unfold_recursive(
13295        &mut self,
13296        _: &UnfoldRecursive,
13297        _window: &mut Window,
13298        cx: &mut Context<Self>,
13299    ) {
13300        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13301        let selections = self.selections.all::<Point>(cx);
13302        let ranges = selections
13303            .iter()
13304            .map(|s| {
13305                let mut range = s.display_range(&display_map).sorted();
13306                *range.start.column_mut() = 0;
13307                *range.end.column_mut() = display_map.line_len(range.end.row());
13308                let start = range.start.to_point(&display_map);
13309                let end = range.end.to_point(&display_map);
13310                start..end
13311            })
13312            .collect::<Vec<_>>();
13313
13314        self.unfold_ranges(&ranges, true, true, cx);
13315    }
13316
13317    pub fn unfold_at(
13318        &mut self,
13319        unfold_at: &UnfoldAt,
13320        _window: &mut Window,
13321        cx: &mut Context<Self>,
13322    ) {
13323        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13324
13325        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13326            ..Point::new(
13327                unfold_at.buffer_row.0,
13328                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13329            );
13330
13331        let autoscroll = self
13332            .selections
13333            .all::<Point>(cx)
13334            .iter()
13335            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13336
13337        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13338    }
13339
13340    pub fn unfold_all(
13341        &mut self,
13342        _: &actions::UnfoldAll,
13343        _window: &mut Window,
13344        cx: &mut Context<Self>,
13345    ) {
13346        if self.buffer.read(cx).is_singleton() {
13347            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13348            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13349        } else {
13350            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13351                editor
13352                    .update(&mut cx, |editor, cx| {
13353                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13354                            editor.unfold_buffer(buffer_id, cx);
13355                        }
13356                    })
13357                    .ok();
13358            });
13359        }
13360    }
13361
13362    pub fn fold_selected_ranges(
13363        &mut self,
13364        _: &FoldSelectedRanges,
13365        window: &mut Window,
13366        cx: &mut Context<Self>,
13367    ) {
13368        let selections = self.selections.all::<Point>(cx);
13369        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13370        let line_mode = self.selections.line_mode;
13371        let ranges = selections
13372            .into_iter()
13373            .map(|s| {
13374                if line_mode {
13375                    let start = Point::new(s.start.row, 0);
13376                    let end = Point::new(
13377                        s.end.row,
13378                        display_map
13379                            .buffer_snapshot
13380                            .line_len(MultiBufferRow(s.end.row)),
13381                    );
13382                    Crease::simple(start..end, display_map.fold_placeholder.clone())
13383                } else {
13384                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13385                }
13386            })
13387            .collect::<Vec<_>>();
13388        self.fold_creases(ranges, true, window, cx);
13389    }
13390
13391    pub fn fold_ranges<T: ToOffset + Clone>(
13392        &mut self,
13393        ranges: Vec<Range<T>>,
13394        auto_scroll: bool,
13395        window: &mut Window,
13396        cx: &mut Context<Self>,
13397    ) {
13398        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13399        let ranges = ranges
13400            .into_iter()
13401            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13402            .collect::<Vec<_>>();
13403        self.fold_creases(ranges, auto_scroll, window, cx);
13404    }
13405
13406    pub fn fold_creases<T: ToOffset + Clone>(
13407        &mut self,
13408        creases: Vec<Crease<T>>,
13409        auto_scroll: bool,
13410        window: &mut Window,
13411        cx: &mut Context<Self>,
13412    ) {
13413        if creases.is_empty() {
13414            return;
13415        }
13416
13417        let mut buffers_affected = HashSet::default();
13418        let multi_buffer = self.buffer().read(cx);
13419        for crease in &creases {
13420            if let Some((_, buffer, _)) =
13421                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13422            {
13423                buffers_affected.insert(buffer.read(cx).remote_id());
13424            };
13425        }
13426
13427        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13428
13429        if auto_scroll {
13430            self.request_autoscroll(Autoscroll::fit(), cx);
13431        }
13432
13433        cx.notify();
13434
13435        if let Some(active_diagnostics) = self.active_diagnostics.take() {
13436            // Clear diagnostics block when folding a range that contains it.
13437            let snapshot = self.snapshot(window, cx);
13438            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13439                drop(snapshot);
13440                self.active_diagnostics = Some(active_diagnostics);
13441                self.dismiss_diagnostics(cx);
13442            } else {
13443                self.active_diagnostics = Some(active_diagnostics);
13444            }
13445        }
13446
13447        self.scrollbar_marker_state.dirty = true;
13448    }
13449
13450    /// Removes any folds whose ranges intersect any of the given ranges.
13451    pub fn unfold_ranges<T: ToOffset + Clone>(
13452        &mut self,
13453        ranges: &[Range<T>],
13454        inclusive: bool,
13455        auto_scroll: bool,
13456        cx: &mut Context<Self>,
13457    ) {
13458        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13459            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13460        });
13461    }
13462
13463    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13464        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13465            return;
13466        }
13467        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13468        self.display_map.update(cx, |display_map, cx| {
13469            display_map.fold_buffers([buffer_id], cx)
13470        });
13471        cx.emit(EditorEvent::BufferFoldToggled {
13472            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13473            folded: true,
13474        });
13475        cx.notify();
13476    }
13477
13478    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13479        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13480            return;
13481        }
13482        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13483        self.display_map.update(cx, |display_map, cx| {
13484            display_map.unfold_buffers([buffer_id], cx);
13485        });
13486        cx.emit(EditorEvent::BufferFoldToggled {
13487            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13488            folded: false,
13489        });
13490        cx.notify();
13491    }
13492
13493    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13494        self.display_map.read(cx).is_buffer_folded(buffer)
13495    }
13496
13497    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13498        self.display_map.read(cx).folded_buffers()
13499    }
13500
13501    /// Removes any folds with the given ranges.
13502    pub fn remove_folds_with_type<T: ToOffset + Clone>(
13503        &mut self,
13504        ranges: &[Range<T>],
13505        type_id: TypeId,
13506        auto_scroll: bool,
13507        cx: &mut Context<Self>,
13508    ) {
13509        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13510            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13511        });
13512    }
13513
13514    fn remove_folds_with<T: ToOffset + Clone>(
13515        &mut self,
13516        ranges: &[Range<T>],
13517        auto_scroll: bool,
13518        cx: &mut Context<Self>,
13519        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13520    ) {
13521        if ranges.is_empty() {
13522            return;
13523        }
13524
13525        let mut buffers_affected = HashSet::default();
13526        let multi_buffer = self.buffer().read(cx);
13527        for range in ranges {
13528            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13529                buffers_affected.insert(buffer.read(cx).remote_id());
13530            };
13531        }
13532
13533        self.display_map.update(cx, update);
13534
13535        if auto_scroll {
13536            self.request_autoscroll(Autoscroll::fit(), cx);
13537        }
13538
13539        cx.notify();
13540        self.scrollbar_marker_state.dirty = true;
13541        self.active_indent_guides_state.dirty = true;
13542    }
13543
13544    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13545        self.display_map.read(cx).fold_placeholder.clone()
13546    }
13547
13548    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13549        self.buffer.update(cx, |buffer, cx| {
13550            buffer.set_all_diff_hunks_expanded(cx);
13551        });
13552    }
13553
13554    pub fn expand_all_diff_hunks(
13555        &mut self,
13556        _: &ExpandAllDiffHunks,
13557        _window: &mut Window,
13558        cx: &mut Context<Self>,
13559    ) {
13560        self.buffer.update(cx, |buffer, cx| {
13561            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13562        });
13563    }
13564
13565    pub fn toggle_selected_diff_hunks(
13566        &mut self,
13567        _: &ToggleSelectedDiffHunks,
13568        _window: &mut Window,
13569        cx: &mut Context<Self>,
13570    ) {
13571        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13572        self.toggle_diff_hunks_in_ranges(ranges, cx);
13573    }
13574
13575    pub fn diff_hunks_in_ranges<'a>(
13576        &'a self,
13577        ranges: &'a [Range<Anchor>],
13578        buffer: &'a MultiBufferSnapshot,
13579    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13580        ranges.iter().flat_map(move |range| {
13581            let end_excerpt_id = range.end.excerpt_id;
13582            let range = range.to_point(buffer);
13583            let mut peek_end = range.end;
13584            if range.end.row < buffer.max_row().0 {
13585                peek_end = Point::new(range.end.row + 1, 0);
13586            }
13587            buffer
13588                .diff_hunks_in_range(range.start..peek_end)
13589                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13590        })
13591    }
13592
13593    pub fn has_stageable_diff_hunks_in_ranges(
13594        &self,
13595        ranges: &[Range<Anchor>],
13596        snapshot: &MultiBufferSnapshot,
13597    ) -> bool {
13598        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13599        hunks.any(|hunk| hunk.status().has_secondary_hunk())
13600    }
13601
13602    pub fn toggle_staged_selected_diff_hunks(
13603        &mut self,
13604        _: &::git::ToggleStaged,
13605        _: &mut Window,
13606        cx: &mut Context<Self>,
13607    ) {
13608        let snapshot = self.buffer.read(cx).snapshot(cx);
13609        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13610        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13611        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13612    }
13613
13614    pub fn stage_and_next(
13615        &mut self,
13616        _: &::git::StageAndNext,
13617        window: &mut Window,
13618        cx: &mut Context<Self>,
13619    ) {
13620        self.do_stage_or_unstage_and_next(true, window, cx);
13621    }
13622
13623    pub fn unstage_and_next(
13624        &mut self,
13625        _: &::git::UnstageAndNext,
13626        window: &mut Window,
13627        cx: &mut Context<Self>,
13628    ) {
13629        self.do_stage_or_unstage_and_next(false, window, cx);
13630    }
13631
13632    pub fn stage_or_unstage_diff_hunks(
13633        &mut self,
13634        stage: bool,
13635        ranges: Vec<Range<Anchor>>,
13636        cx: &mut Context<Self>,
13637    ) {
13638        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
13639        cx.spawn(|this, mut cx| async move {
13640            task.await?;
13641            this.update(&mut cx, |this, cx| {
13642                let snapshot = this.buffer.read(cx).snapshot(cx);
13643                let chunk_by = this
13644                    .diff_hunks_in_ranges(&ranges, &snapshot)
13645                    .chunk_by(|hunk| hunk.buffer_id);
13646                for (buffer_id, hunks) in &chunk_by {
13647                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
13648                }
13649            })
13650        })
13651        .detach_and_log_err(cx);
13652    }
13653
13654    fn save_buffers_for_ranges_if_needed(
13655        &mut self,
13656        ranges: &[Range<Anchor>],
13657        cx: &mut Context<'_, Editor>,
13658    ) -> Task<Result<()>> {
13659        let multibuffer = self.buffer.read(cx);
13660        let snapshot = multibuffer.read(cx);
13661        let buffer_ids: HashSet<_> = ranges
13662            .iter()
13663            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
13664            .collect();
13665        drop(snapshot);
13666
13667        let mut buffers = HashSet::default();
13668        for buffer_id in buffer_ids {
13669            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
13670                let buffer = buffer_entity.read(cx);
13671                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
13672                {
13673                    buffers.insert(buffer_entity);
13674                }
13675            }
13676        }
13677
13678        if let Some(project) = &self.project {
13679            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
13680        } else {
13681            Task::ready(Ok(()))
13682        }
13683    }
13684
13685    fn do_stage_or_unstage_and_next(
13686        &mut self,
13687        stage: bool,
13688        window: &mut Window,
13689        cx: &mut Context<Self>,
13690    ) {
13691        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13692
13693        if ranges.iter().any(|range| range.start != range.end) {
13694            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13695            return;
13696        }
13697
13698        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13699        let snapshot = self.snapshot(window, cx);
13700        let position = self.selections.newest::<Point>(cx).head();
13701        let mut row = snapshot
13702            .buffer_snapshot
13703            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13704            .find(|hunk| hunk.row_range.start.0 > position.row)
13705            .map(|hunk| hunk.row_range.start);
13706
13707        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
13708        // Outside of the project diff editor, wrap around to the beginning.
13709        if !all_diff_hunks_expanded {
13710            row = row.or_else(|| {
13711                snapshot
13712                    .buffer_snapshot
13713                    .diff_hunks_in_range(Point::zero()..position)
13714                    .find(|hunk| hunk.row_range.end.0 < position.row)
13715                    .map(|hunk| hunk.row_range.start)
13716            });
13717        }
13718
13719        if let Some(row) = row {
13720            let destination = Point::new(row.0, 0);
13721            let autoscroll = Autoscroll::center();
13722
13723            self.unfold_ranges(&[destination..destination], false, false, cx);
13724            self.change_selections(Some(autoscroll), window, cx, |s| {
13725                s.select_ranges([destination..destination]);
13726            });
13727        } else if all_diff_hunks_expanded {
13728            window.dispatch_action(::git::ExpandCommitEditor.boxed_clone(), cx);
13729        }
13730    }
13731
13732    fn do_stage_or_unstage(
13733        &self,
13734        stage: bool,
13735        buffer_id: BufferId,
13736        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13737        cx: &mut App,
13738    ) -> Option<()> {
13739        let project = self.project.as_ref()?;
13740        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
13741        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
13742        let buffer_snapshot = buffer.read(cx).snapshot();
13743        let file_exists = buffer_snapshot
13744            .file()
13745            .is_some_and(|file| file.disk_state().exists());
13746        diff.update(cx, |diff, cx| {
13747            diff.stage_or_unstage_hunks(
13748                stage,
13749                &hunks
13750                    .map(|hunk| buffer_diff::DiffHunk {
13751                        buffer_range: hunk.buffer_range,
13752                        diff_base_byte_range: hunk.diff_base_byte_range,
13753                        secondary_status: hunk.secondary_status,
13754                        range: Point::zero()..Point::zero(), // unused
13755                    })
13756                    .collect::<Vec<_>>(),
13757                &buffer_snapshot,
13758                file_exists,
13759                cx,
13760            )
13761        });
13762        None
13763    }
13764
13765    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13766        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13767        self.buffer
13768            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13769    }
13770
13771    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13772        self.buffer.update(cx, |buffer, cx| {
13773            let ranges = vec![Anchor::min()..Anchor::max()];
13774            if !buffer.all_diff_hunks_expanded()
13775                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13776            {
13777                buffer.collapse_diff_hunks(ranges, cx);
13778                true
13779            } else {
13780                false
13781            }
13782        })
13783    }
13784
13785    fn toggle_diff_hunks_in_ranges(
13786        &mut self,
13787        ranges: Vec<Range<Anchor>>,
13788        cx: &mut Context<'_, Editor>,
13789    ) {
13790        self.buffer.update(cx, |buffer, cx| {
13791            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13792            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13793        })
13794    }
13795
13796    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13797        self.buffer.update(cx, |buffer, cx| {
13798            let snapshot = buffer.snapshot(cx);
13799            let excerpt_id = range.end.excerpt_id;
13800            let point_range = range.to_point(&snapshot);
13801            let expand = !buffer.single_hunk_is_expanded(range, cx);
13802            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13803        })
13804    }
13805
13806    pub(crate) fn apply_all_diff_hunks(
13807        &mut self,
13808        _: &ApplyAllDiffHunks,
13809        window: &mut Window,
13810        cx: &mut Context<Self>,
13811    ) {
13812        let buffers = self.buffer.read(cx).all_buffers();
13813        for branch_buffer in buffers {
13814            branch_buffer.update(cx, |branch_buffer, cx| {
13815                branch_buffer.merge_into_base(Vec::new(), cx);
13816            });
13817        }
13818
13819        if let Some(project) = self.project.clone() {
13820            self.save(true, project, window, cx).detach_and_log_err(cx);
13821        }
13822    }
13823
13824    pub(crate) fn apply_selected_diff_hunks(
13825        &mut self,
13826        _: &ApplyDiffHunk,
13827        window: &mut Window,
13828        cx: &mut Context<Self>,
13829    ) {
13830        let snapshot = self.snapshot(window, cx);
13831        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
13832        let mut ranges_by_buffer = HashMap::default();
13833        self.transact(window, cx, |editor, _window, cx| {
13834            for hunk in hunks {
13835                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13836                    ranges_by_buffer
13837                        .entry(buffer.clone())
13838                        .or_insert_with(Vec::new)
13839                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13840                }
13841            }
13842
13843            for (buffer, ranges) in ranges_by_buffer {
13844                buffer.update(cx, |buffer, cx| {
13845                    buffer.merge_into_base(ranges, cx);
13846                });
13847            }
13848        });
13849
13850        if let Some(project) = self.project.clone() {
13851            self.save(true, project, window, cx).detach_and_log_err(cx);
13852        }
13853    }
13854
13855    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13856        if hovered != self.gutter_hovered {
13857            self.gutter_hovered = hovered;
13858            cx.notify();
13859        }
13860    }
13861
13862    pub fn insert_blocks(
13863        &mut self,
13864        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13865        autoscroll: Option<Autoscroll>,
13866        cx: &mut Context<Self>,
13867    ) -> Vec<CustomBlockId> {
13868        let blocks = self
13869            .display_map
13870            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13871        if let Some(autoscroll) = autoscroll {
13872            self.request_autoscroll(autoscroll, cx);
13873        }
13874        cx.notify();
13875        blocks
13876    }
13877
13878    pub fn resize_blocks(
13879        &mut self,
13880        heights: HashMap<CustomBlockId, u32>,
13881        autoscroll: Option<Autoscroll>,
13882        cx: &mut Context<Self>,
13883    ) {
13884        self.display_map
13885            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13886        if let Some(autoscroll) = autoscroll {
13887            self.request_autoscroll(autoscroll, cx);
13888        }
13889        cx.notify();
13890    }
13891
13892    pub fn replace_blocks(
13893        &mut self,
13894        renderers: HashMap<CustomBlockId, RenderBlock>,
13895        autoscroll: Option<Autoscroll>,
13896        cx: &mut Context<Self>,
13897    ) {
13898        self.display_map
13899            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13900        if let Some(autoscroll) = autoscroll {
13901            self.request_autoscroll(autoscroll, cx);
13902        }
13903        cx.notify();
13904    }
13905
13906    pub fn remove_blocks(
13907        &mut self,
13908        block_ids: HashSet<CustomBlockId>,
13909        autoscroll: Option<Autoscroll>,
13910        cx: &mut Context<Self>,
13911    ) {
13912        self.display_map.update(cx, |display_map, cx| {
13913            display_map.remove_blocks(block_ids, cx)
13914        });
13915        if let Some(autoscroll) = autoscroll {
13916            self.request_autoscroll(autoscroll, cx);
13917        }
13918        cx.notify();
13919    }
13920
13921    pub fn row_for_block(
13922        &self,
13923        block_id: CustomBlockId,
13924        cx: &mut Context<Self>,
13925    ) -> Option<DisplayRow> {
13926        self.display_map
13927            .update(cx, |map, cx| map.row_for_block(block_id, cx))
13928    }
13929
13930    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13931        self.focused_block = Some(focused_block);
13932    }
13933
13934    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13935        self.focused_block.take()
13936    }
13937
13938    pub fn insert_creases(
13939        &mut self,
13940        creases: impl IntoIterator<Item = Crease<Anchor>>,
13941        cx: &mut Context<Self>,
13942    ) -> Vec<CreaseId> {
13943        self.display_map
13944            .update(cx, |map, cx| map.insert_creases(creases, cx))
13945    }
13946
13947    pub fn remove_creases(
13948        &mut self,
13949        ids: impl IntoIterator<Item = CreaseId>,
13950        cx: &mut Context<Self>,
13951    ) {
13952        self.display_map
13953            .update(cx, |map, cx| map.remove_creases(ids, cx));
13954    }
13955
13956    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13957        self.display_map
13958            .update(cx, |map, cx| map.snapshot(cx))
13959            .longest_row()
13960    }
13961
13962    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13963        self.display_map
13964            .update(cx, |map, cx| map.snapshot(cx))
13965            .max_point()
13966    }
13967
13968    pub fn text(&self, cx: &App) -> String {
13969        self.buffer.read(cx).read(cx).text()
13970    }
13971
13972    pub fn is_empty(&self, cx: &App) -> bool {
13973        self.buffer.read(cx).read(cx).is_empty()
13974    }
13975
13976    pub fn text_option(&self, cx: &App) -> Option<String> {
13977        let text = self.text(cx);
13978        let text = text.trim();
13979
13980        if text.is_empty() {
13981            return None;
13982        }
13983
13984        Some(text.to_string())
13985    }
13986
13987    pub fn set_text(
13988        &mut self,
13989        text: impl Into<Arc<str>>,
13990        window: &mut Window,
13991        cx: &mut Context<Self>,
13992    ) {
13993        self.transact(window, cx, |this, _, cx| {
13994            this.buffer
13995                .read(cx)
13996                .as_singleton()
13997                .expect("you can only call set_text on editors for singleton buffers")
13998                .update(cx, |buffer, cx| buffer.set_text(text, cx));
13999        });
14000    }
14001
14002    pub fn display_text(&self, cx: &mut App) -> String {
14003        self.display_map
14004            .update(cx, |map, cx| map.snapshot(cx))
14005            .text()
14006    }
14007
14008    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
14009        let mut wrap_guides = smallvec::smallvec![];
14010
14011        if self.show_wrap_guides == Some(false) {
14012            return wrap_guides;
14013        }
14014
14015        let settings = self.buffer.read(cx).language_settings(cx);
14016        if settings.show_wrap_guides {
14017            match self.soft_wrap_mode(cx) {
14018                SoftWrap::Column(soft_wrap) => {
14019                    wrap_guides.push((soft_wrap as usize, true));
14020                }
14021                SoftWrap::Bounded(soft_wrap) => {
14022                    wrap_guides.push((soft_wrap as usize, true));
14023                }
14024                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
14025            }
14026            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14027        }
14028
14029        wrap_guides
14030    }
14031
14032    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14033        let settings = self.buffer.read(cx).language_settings(cx);
14034        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14035        match mode {
14036            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14037                SoftWrap::None
14038            }
14039            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14040            language_settings::SoftWrap::PreferredLineLength => {
14041                SoftWrap::Column(settings.preferred_line_length)
14042            }
14043            language_settings::SoftWrap::Bounded => {
14044                SoftWrap::Bounded(settings.preferred_line_length)
14045            }
14046        }
14047    }
14048
14049    pub fn set_soft_wrap_mode(
14050        &mut self,
14051        mode: language_settings::SoftWrap,
14052
14053        cx: &mut Context<Self>,
14054    ) {
14055        self.soft_wrap_mode_override = Some(mode);
14056        cx.notify();
14057    }
14058
14059    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
14060        self.hard_wrap = hard_wrap;
14061        cx.notify();
14062    }
14063
14064    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14065        self.text_style_refinement = Some(style);
14066    }
14067
14068    /// called by the Element so we know what style we were most recently rendered with.
14069    pub(crate) fn set_style(
14070        &mut self,
14071        style: EditorStyle,
14072        window: &mut Window,
14073        cx: &mut Context<Self>,
14074    ) {
14075        let rem_size = window.rem_size();
14076        self.display_map.update(cx, |map, cx| {
14077            map.set_font(
14078                style.text.font(),
14079                style.text.font_size.to_pixels(rem_size),
14080                cx,
14081            )
14082        });
14083        self.style = Some(style);
14084    }
14085
14086    pub fn style(&self) -> Option<&EditorStyle> {
14087        self.style.as_ref()
14088    }
14089
14090    // Called by the element. This method is not designed to be called outside of the editor
14091    // element's layout code because it does not notify when rewrapping is computed synchronously.
14092    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14093        self.display_map
14094            .update(cx, |map, cx| map.set_wrap_width(width, cx))
14095    }
14096
14097    pub fn set_soft_wrap(&mut self) {
14098        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14099    }
14100
14101    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14102        if self.soft_wrap_mode_override.is_some() {
14103            self.soft_wrap_mode_override.take();
14104        } else {
14105            let soft_wrap = match self.soft_wrap_mode(cx) {
14106                SoftWrap::GitDiff => return,
14107                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14108                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14109                    language_settings::SoftWrap::None
14110                }
14111            };
14112            self.soft_wrap_mode_override = Some(soft_wrap);
14113        }
14114        cx.notify();
14115    }
14116
14117    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14118        let Some(workspace) = self.workspace() else {
14119            return;
14120        };
14121        let fs = workspace.read(cx).app_state().fs.clone();
14122        let current_show = TabBarSettings::get_global(cx).show;
14123        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14124            setting.show = Some(!current_show);
14125        });
14126    }
14127
14128    pub fn toggle_indent_guides(
14129        &mut self,
14130        _: &ToggleIndentGuides,
14131        _: &mut Window,
14132        cx: &mut Context<Self>,
14133    ) {
14134        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14135            self.buffer
14136                .read(cx)
14137                .language_settings(cx)
14138                .indent_guides
14139                .enabled
14140        });
14141        self.show_indent_guides = Some(!currently_enabled);
14142        cx.notify();
14143    }
14144
14145    fn should_show_indent_guides(&self) -> Option<bool> {
14146        self.show_indent_guides
14147    }
14148
14149    pub fn toggle_line_numbers(
14150        &mut self,
14151        _: &ToggleLineNumbers,
14152        _: &mut Window,
14153        cx: &mut Context<Self>,
14154    ) {
14155        let mut editor_settings = EditorSettings::get_global(cx).clone();
14156        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14157        EditorSettings::override_global(editor_settings, cx);
14158    }
14159
14160    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14161        self.use_relative_line_numbers
14162            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14163    }
14164
14165    pub fn toggle_relative_line_numbers(
14166        &mut self,
14167        _: &ToggleRelativeLineNumbers,
14168        _: &mut Window,
14169        cx: &mut Context<Self>,
14170    ) {
14171        let is_relative = self.should_use_relative_line_numbers(cx);
14172        self.set_relative_line_number(Some(!is_relative), cx)
14173    }
14174
14175    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14176        self.use_relative_line_numbers = is_relative;
14177        cx.notify();
14178    }
14179
14180    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14181        self.show_gutter = show_gutter;
14182        cx.notify();
14183    }
14184
14185    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14186        self.show_scrollbars = show_scrollbars;
14187        cx.notify();
14188    }
14189
14190    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14191        self.show_line_numbers = Some(show_line_numbers);
14192        cx.notify();
14193    }
14194
14195    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14196        self.show_git_diff_gutter = Some(show_git_diff_gutter);
14197        cx.notify();
14198    }
14199
14200    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14201        self.show_code_actions = Some(show_code_actions);
14202        cx.notify();
14203    }
14204
14205    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14206        self.show_runnables = Some(show_runnables);
14207        cx.notify();
14208    }
14209
14210    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14211        if self.display_map.read(cx).masked != masked {
14212            self.display_map.update(cx, |map, _| map.masked = masked);
14213        }
14214        cx.notify()
14215    }
14216
14217    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14218        self.show_wrap_guides = Some(show_wrap_guides);
14219        cx.notify();
14220    }
14221
14222    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14223        self.show_indent_guides = Some(show_indent_guides);
14224        cx.notify();
14225    }
14226
14227    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14228        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14229            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14230                if let Some(dir) = file.abs_path(cx).parent() {
14231                    return Some(dir.to_owned());
14232                }
14233            }
14234
14235            if let Some(project_path) = buffer.read(cx).project_path(cx) {
14236                return Some(project_path.path.to_path_buf());
14237            }
14238        }
14239
14240        None
14241    }
14242
14243    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14244        self.active_excerpt(cx)?
14245            .1
14246            .read(cx)
14247            .file()
14248            .and_then(|f| f.as_local())
14249    }
14250
14251    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14252        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14253            let buffer = buffer.read(cx);
14254            if let Some(project_path) = buffer.project_path(cx) {
14255                let project = self.project.as_ref()?.read(cx);
14256                project.absolute_path(&project_path, cx)
14257            } else {
14258                buffer
14259                    .file()
14260                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14261            }
14262        })
14263    }
14264
14265    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14266        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14267            let project_path = buffer.read(cx).project_path(cx)?;
14268            let project = self.project.as_ref()?.read(cx);
14269            let entry = project.entry_for_path(&project_path, cx)?;
14270            let path = entry.path.to_path_buf();
14271            Some(path)
14272        })
14273    }
14274
14275    pub fn reveal_in_finder(
14276        &mut self,
14277        _: &RevealInFileManager,
14278        _window: &mut Window,
14279        cx: &mut Context<Self>,
14280    ) {
14281        if let Some(target) = self.target_file(cx) {
14282            cx.reveal_path(&target.abs_path(cx));
14283        }
14284    }
14285
14286    pub fn copy_path(
14287        &mut self,
14288        _: &zed_actions::workspace::CopyPath,
14289        _window: &mut Window,
14290        cx: &mut Context<Self>,
14291    ) {
14292        if let Some(path) = self.target_file_abs_path(cx) {
14293            if let Some(path) = path.to_str() {
14294                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14295            }
14296        }
14297    }
14298
14299    pub fn copy_relative_path(
14300        &mut self,
14301        _: &zed_actions::workspace::CopyRelativePath,
14302        _window: &mut Window,
14303        cx: &mut Context<Self>,
14304    ) {
14305        if let Some(path) = self.target_file_path(cx) {
14306            if let Some(path) = path.to_str() {
14307                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14308            }
14309        }
14310    }
14311
14312    pub fn copy_file_name_without_extension(
14313        &mut self,
14314        _: &CopyFileNameWithoutExtension,
14315        _: &mut Window,
14316        cx: &mut Context<Self>,
14317    ) {
14318        if let Some(file) = self.target_file(cx) {
14319            if let Some(file_stem) = file.path().file_stem() {
14320                if let Some(name) = file_stem.to_str() {
14321                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14322                }
14323            }
14324        }
14325    }
14326
14327    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14328        if let Some(file) = self.target_file(cx) {
14329            if let Some(file_name) = file.path().file_name() {
14330                if let Some(name) = file_name.to_str() {
14331                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14332                }
14333            }
14334        }
14335    }
14336
14337    pub fn toggle_git_blame(
14338        &mut self,
14339        _: &::git::Blame,
14340        window: &mut Window,
14341        cx: &mut Context<Self>,
14342    ) {
14343        self.show_git_blame_gutter = !self.show_git_blame_gutter;
14344
14345        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14346            self.start_git_blame(true, window, cx);
14347        }
14348
14349        cx.notify();
14350    }
14351
14352    pub fn toggle_git_blame_inline(
14353        &mut self,
14354        _: &ToggleGitBlameInline,
14355        window: &mut Window,
14356        cx: &mut Context<Self>,
14357    ) {
14358        self.toggle_git_blame_inline_internal(true, window, cx);
14359        cx.notify();
14360    }
14361
14362    pub fn git_blame_inline_enabled(&self) -> bool {
14363        self.git_blame_inline_enabled
14364    }
14365
14366    pub fn toggle_selection_menu(
14367        &mut self,
14368        _: &ToggleSelectionMenu,
14369        _: &mut Window,
14370        cx: &mut Context<Self>,
14371    ) {
14372        self.show_selection_menu = self
14373            .show_selection_menu
14374            .map(|show_selections_menu| !show_selections_menu)
14375            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14376
14377        cx.notify();
14378    }
14379
14380    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14381        self.show_selection_menu
14382            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14383    }
14384
14385    fn start_git_blame(
14386        &mut self,
14387        user_triggered: bool,
14388        window: &mut Window,
14389        cx: &mut Context<Self>,
14390    ) {
14391        if let Some(project) = self.project.as_ref() {
14392            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14393                return;
14394            };
14395
14396            if buffer.read(cx).file().is_none() {
14397                return;
14398            }
14399
14400            let focused = self.focus_handle(cx).contains_focused(window, cx);
14401
14402            let project = project.clone();
14403            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14404            self.blame_subscription =
14405                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14406            self.blame = Some(blame);
14407        }
14408    }
14409
14410    fn toggle_git_blame_inline_internal(
14411        &mut self,
14412        user_triggered: bool,
14413        window: &mut Window,
14414        cx: &mut Context<Self>,
14415    ) {
14416        if self.git_blame_inline_enabled {
14417            self.git_blame_inline_enabled = false;
14418            self.show_git_blame_inline = false;
14419            self.show_git_blame_inline_delay_task.take();
14420        } else {
14421            self.git_blame_inline_enabled = true;
14422            self.start_git_blame_inline(user_triggered, window, cx);
14423        }
14424
14425        cx.notify();
14426    }
14427
14428    fn start_git_blame_inline(
14429        &mut self,
14430        user_triggered: bool,
14431        window: &mut Window,
14432        cx: &mut Context<Self>,
14433    ) {
14434        self.start_git_blame(user_triggered, window, cx);
14435
14436        if ProjectSettings::get_global(cx)
14437            .git
14438            .inline_blame_delay()
14439            .is_some()
14440        {
14441            self.start_inline_blame_timer(window, cx);
14442        } else {
14443            self.show_git_blame_inline = true
14444        }
14445    }
14446
14447    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14448        self.blame.as_ref()
14449    }
14450
14451    pub fn show_git_blame_gutter(&self) -> bool {
14452        self.show_git_blame_gutter
14453    }
14454
14455    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14456        self.show_git_blame_gutter && self.has_blame_entries(cx)
14457    }
14458
14459    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14460        self.show_git_blame_inline
14461            && (self.focus_handle.is_focused(window)
14462                || self
14463                    .git_blame_inline_tooltip
14464                    .as_ref()
14465                    .and_then(|t| t.upgrade())
14466                    .is_some())
14467            && !self.newest_selection_head_on_empty_line(cx)
14468            && self.has_blame_entries(cx)
14469    }
14470
14471    fn has_blame_entries(&self, cx: &App) -> bool {
14472        self.blame()
14473            .map_or(false, |blame| blame.read(cx).has_generated_entries())
14474    }
14475
14476    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14477        let cursor_anchor = self.selections.newest_anchor().head();
14478
14479        let snapshot = self.buffer.read(cx).snapshot(cx);
14480        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14481
14482        snapshot.line_len(buffer_row) == 0
14483    }
14484
14485    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14486        let buffer_and_selection = maybe!({
14487            let selection = self.selections.newest::<Point>(cx);
14488            let selection_range = selection.range();
14489
14490            let multi_buffer = self.buffer().read(cx);
14491            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14492            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14493
14494            let (buffer, range, _) = if selection.reversed {
14495                buffer_ranges.first()
14496            } else {
14497                buffer_ranges.last()
14498            }?;
14499
14500            let selection = text::ToPoint::to_point(&range.start, &buffer).row
14501                ..text::ToPoint::to_point(&range.end, &buffer).row;
14502            Some((
14503                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14504                selection,
14505            ))
14506        });
14507
14508        let Some((buffer, selection)) = buffer_and_selection else {
14509            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14510        };
14511
14512        let Some(project) = self.project.as_ref() else {
14513            return Task::ready(Err(anyhow!("editor does not have project")));
14514        };
14515
14516        project.update(cx, |project, cx| {
14517            project.get_permalink_to_line(&buffer, selection, cx)
14518        })
14519    }
14520
14521    pub fn copy_permalink_to_line(
14522        &mut self,
14523        _: &CopyPermalinkToLine,
14524        window: &mut Window,
14525        cx: &mut Context<Self>,
14526    ) {
14527        let permalink_task = self.get_permalink_to_line(cx);
14528        let workspace = self.workspace();
14529
14530        cx.spawn_in(window, |_, mut cx| async move {
14531            match permalink_task.await {
14532                Ok(permalink) => {
14533                    cx.update(|_, cx| {
14534                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14535                    })
14536                    .ok();
14537                }
14538                Err(err) => {
14539                    let message = format!("Failed to copy permalink: {err}");
14540
14541                    Err::<(), anyhow::Error>(err).log_err();
14542
14543                    if let Some(workspace) = workspace {
14544                        workspace
14545                            .update_in(&mut cx, |workspace, _, cx| {
14546                                struct CopyPermalinkToLine;
14547
14548                                workspace.show_toast(
14549                                    Toast::new(
14550                                        NotificationId::unique::<CopyPermalinkToLine>(),
14551                                        message,
14552                                    ),
14553                                    cx,
14554                                )
14555                            })
14556                            .ok();
14557                    }
14558                }
14559            }
14560        })
14561        .detach();
14562    }
14563
14564    pub fn copy_file_location(
14565        &mut self,
14566        _: &CopyFileLocation,
14567        _: &mut Window,
14568        cx: &mut Context<Self>,
14569    ) {
14570        let selection = self.selections.newest::<Point>(cx).start.row + 1;
14571        if let Some(file) = self.target_file(cx) {
14572            if let Some(path) = file.path().to_str() {
14573                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14574            }
14575        }
14576    }
14577
14578    pub fn open_permalink_to_line(
14579        &mut self,
14580        _: &OpenPermalinkToLine,
14581        window: &mut Window,
14582        cx: &mut Context<Self>,
14583    ) {
14584        let permalink_task = self.get_permalink_to_line(cx);
14585        let workspace = self.workspace();
14586
14587        cx.spawn_in(window, |_, mut cx| async move {
14588            match permalink_task.await {
14589                Ok(permalink) => {
14590                    cx.update(|_, cx| {
14591                        cx.open_url(permalink.as_ref());
14592                    })
14593                    .ok();
14594                }
14595                Err(err) => {
14596                    let message = format!("Failed to open permalink: {err}");
14597
14598                    Err::<(), anyhow::Error>(err).log_err();
14599
14600                    if let Some(workspace) = workspace {
14601                        workspace
14602                            .update(&mut cx, |workspace, cx| {
14603                                struct OpenPermalinkToLine;
14604
14605                                workspace.show_toast(
14606                                    Toast::new(
14607                                        NotificationId::unique::<OpenPermalinkToLine>(),
14608                                        message,
14609                                    ),
14610                                    cx,
14611                                )
14612                            })
14613                            .ok();
14614                    }
14615                }
14616            }
14617        })
14618        .detach();
14619    }
14620
14621    pub fn insert_uuid_v4(
14622        &mut self,
14623        _: &InsertUuidV4,
14624        window: &mut Window,
14625        cx: &mut Context<Self>,
14626    ) {
14627        self.insert_uuid(UuidVersion::V4, window, cx);
14628    }
14629
14630    pub fn insert_uuid_v7(
14631        &mut self,
14632        _: &InsertUuidV7,
14633        window: &mut Window,
14634        cx: &mut Context<Self>,
14635    ) {
14636        self.insert_uuid(UuidVersion::V7, window, cx);
14637    }
14638
14639    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14640        self.transact(window, cx, |this, window, cx| {
14641            let edits = this
14642                .selections
14643                .all::<Point>(cx)
14644                .into_iter()
14645                .map(|selection| {
14646                    let uuid = match version {
14647                        UuidVersion::V4 => uuid::Uuid::new_v4(),
14648                        UuidVersion::V7 => uuid::Uuid::now_v7(),
14649                    };
14650
14651                    (selection.range(), uuid.to_string())
14652                });
14653            this.edit(edits, cx);
14654            this.refresh_inline_completion(true, false, window, cx);
14655        });
14656    }
14657
14658    pub fn open_selections_in_multibuffer(
14659        &mut self,
14660        _: &OpenSelectionsInMultibuffer,
14661        window: &mut Window,
14662        cx: &mut Context<Self>,
14663    ) {
14664        let multibuffer = self.buffer.read(cx);
14665
14666        let Some(buffer) = multibuffer.as_singleton() else {
14667            return;
14668        };
14669
14670        let Some(workspace) = self.workspace() else {
14671            return;
14672        };
14673
14674        let locations = self
14675            .selections
14676            .disjoint_anchors()
14677            .iter()
14678            .map(|range| Location {
14679                buffer: buffer.clone(),
14680                range: range.start.text_anchor..range.end.text_anchor,
14681            })
14682            .collect::<Vec<_>>();
14683
14684        let title = multibuffer.title(cx).to_string();
14685
14686        cx.spawn_in(window, |_, mut cx| async move {
14687            workspace.update_in(&mut cx, |workspace, window, cx| {
14688                Self::open_locations_in_multibuffer(
14689                    workspace,
14690                    locations,
14691                    format!("Selections for '{title}'"),
14692                    false,
14693                    MultibufferSelectionMode::All,
14694                    window,
14695                    cx,
14696                );
14697            })
14698        })
14699        .detach();
14700    }
14701
14702    /// Adds a row highlight for the given range. If a row has multiple highlights, the
14703    /// last highlight added will be used.
14704    ///
14705    /// If the range ends at the beginning of a line, then that line will not be highlighted.
14706    pub fn highlight_rows<T: 'static>(
14707        &mut self,
14708        range: Range<Anchor>,
14709        color: Hsla,
14710        should_autoscroll: bool,
14711        cx: &mut Context<Self>,
14712    ) {
14713        let snapshot = self.buffer().read(cx).snapshot(cx);
14714        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14715        let ix = row_highlights.binary_search_by(|highlight| {
14716            Ordering::Equal
14717                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14718                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14719        });
14720
14721        if let Err(mut ix) = ix {
14722            let index = post_inc(&mut self.highlight_order);
14723
14724            // If this range intersects with the preceding highlight, then merge it with
14725            // the preceding highlight. Otherwise insert a new highlight.
14726            let mut merged = false;
14727            if ix > 0 {
14728                let prev_highlight = &mut row_highlights[ix - 1];
14729                if prev_highlight
14730                    .range
14731                    .end
14732                    .cmp(&range.start, &snapshot)
14733                    .is_ge()
14734                {
14735                    ix -= 1;
14736                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14737                        prev_highlight.range.end = range.end;
14738                    }
14739                    merged = true;
14740                    prev_highlight.index = index;
14741                    prev_highlight.color = color;
14742                    prev_highlight.should_autoscroll = should_autoscroll;
14743                }
14744            }
14745
14746            if !merged {
14747                row_highlights.insert(
14748                    ix,
14749                    RowHighlight {
14750                        range: range.clone(),
14751                        index,
14752                        color,
14753                        should_autoscroll,
14754                    },
14755                );
14756            }
14757
14758            // If any of the following highlights intersect with this one, merge them.
14759            while let Some(next_highlight) = row_highlights.get(ix + 1) {
14760                let highlight = &row_highlights[ix];
14761                if next_highlight
14762                    .range
14763                    .start
14764                    .cmp(&highlight.range.end, &snapshot)
14765                    .is_le()
14766                {
14767                    if next_highlight
14768                        .range
14769                        .end
14770                        .cmp(&highlight.range.end, &snapshot)
14771                        .is_gt()
14772                    {
14773                        row_highlights[ix].range.end = next_highlight.range.end;
14774                    }
14775                    row_highlights.remove(ix + 1);
14776                } else {
14777                    break;
14778                }
14779            }
14780        }
14781    }
14782
14783    /// Remove any highlighted row ranges of the given type that intersect the
14784    /// given ranges.
14785    pub fn remove_highlighted_rows<T: 'static>(
14786        &mut self,
14787        ranges_to_remove: Vec<Range<Anchor>>,
14788        cx: &mut Context<Self>,
14789    ) {
14790        let snapshot = self.buffer().read(cx).snapshot(cx);
14791        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14792        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14793        row_highlights.retain(|highlight| {
14794            while let Some(range_to_remove) = ranges_to_remove.peek() {
14795                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14796                    Ordering::Less | Ordering::Equal => {
14797                        ranges_to_remove.next();
14798                    }
14799                    Ordering::Greater => {
14800                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14801                            Ordering::Less | Ordering::Equal => {
14802                                return false;
14803                            }
14804                            Ordering::Greater => break,
14805                        }
14806                    }
14807                }
14808            }
14809
14810            true
14811        })
14812    }
14813
14814    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14815    pub fn clear_row_highlights<T: 'static>(&mut self) {
14816        self.highlighted_rows.remove(&TypeId::of::<T>());
14817    }
14818
14819    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14820    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14821        self.highlighted_rows
14822            .get(&TypeId::of::<T>())
14823            .map_or(&[] as &[_], |vec| vec.as_slice())
14824            .iter()
14825            .map(|highlight| (highlight.range.clone(), highlight.color))
14826    }
14827
14828    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14829    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14830    /// Allows to ignore certain kinds of highlights.
14831    pub fn highlighted_display_rows(
14832        &self,
14833        window: &mut Window,
14834        cx: &mut App,
14835    ) -> BTreeMap<DisplayRow, LineHighlight> {
14836        let snapshot = self.snapshot(window, cx);
14837        let mut used_highlight_orders = HashMap::default();
14838        self.highlighted_rows
14839            .iter()
14840            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14841            .fold(
14842                BTreeMap::<DisplayRow, LineHighlight>::new(),
14843                |mut unique_rows, highlight| {
14844                    let start = highlight.range.start.to_display_point(&snapshot);
14845                    let end = highlight.range.end.to_display_point(&snapshot);
14846                    let start_row = start.row().0;
14847                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14848                        && end.column() == 0
14849                    {
14850                        end.row().0.saturating_sub(1)
14851                    } else {
14852                        end.row().0
14853                    };
14854                    for row in start_row..=end_row {
14855                        let used_index =
14856                            used_highlight_orders.entry(row).or_insert(highlight.index);
14857                        if highlight.index >= *used_index {
14858                            *used_index = highlight.index;
14859                            unique_rows.insert(DisplayRow(row), highlight.color.into());
14860                        }
14861                    }
14862                    unique_rows
14863                },
14864            )
14865    }
14866
14867    pub fn highlighted_display_row_for_autoscroll(
14868        &self,
14869        snapshot: &DisplaySnapshot,
14870    ) -> Option<DisplayRow> {
14871        self.highlighted_rows
14872            .values()
14873            .flat_map(|highlighted_rows| highlighted_rows.iter())
14874            .filter_map(|highlight| {
14875                if highlight.should_autoscroll {
14876                    Some(highlight.range.start.to_display_point(snapshot).row())
14877                } else {
14878                    None
14879                }
14880            })
14881            .min()
14882    }
14883
14884    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14885        self.highlight_background::<SearchWithinRange>(
14886            ranges,
14887            |colors| colors.editor_document_highlight_read_background,
14888            cx,
14889        )
14890    }
14891
14892    pub fn set_breadcrumb_header(&mut self, new_header: String) {
14893        self.breadcrumb_header = Some(new_header);
14894    }
14895
14896    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14897        self.clear_background_highlights::<SearchWithinRange>(cx);
14898    }
14899
14900    pub fn highlight_background<T: 'static>(
14901        &mut self,
14902        ranges: &[Range<Anchor>],
14903        color_fetcher: fn(&ThemeColors) -> Hsla,
14904        cx: &mut Context<Self>,
14905    ) {
14906        self.background_highlights
14907            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14908        self.scrollbar_marker_state.dirty = true;
14909        cx.notify();
14910    }
14911
14912    pub fn clear_background_highlights<T: 'static>(
14913        &mut self,
14914        cx: &mut Context<Self>,
14915    ) -> Option<BackgroundHighlight> {
14916        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14917        if !text_highlights.1.is_empty() {
14918            self.scrollbar_marker_state.dirty = true;
14919            cx.notify();
14920        }
14921        Some(text_highlights)
14922    }
14923
14924    pub fn highlight_gutter<T: 'static>(
14925        &mut self,
14926        ranges: &[Range<Anchor>],
14927        color_fetcher: fn(&App) -> Hsla,
14928        cx: &mut Context<Self>,
14929    ) {
14930        self.gutter_highlights
14931            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14932        cx.notify();
14933    }
14934
14935    pub fn clear_gutter_highlights<T: 'static>(
14936        &mut self,
14937        cx: &mut Context<Self>,
14938    ) -> Option<GutterHighlight> {
14939        cx.notify();
14940        self.gutter_highlights.remove(&TypeId::of::<T>())
14941    }
14942
14943    #[cfg(feature = "test-support")]
14944    pub fn all_text_background_highlights(
14945        &self,
14946        window: &mut Window,
14947        cx: &mut Context<Self>,
14948    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14949        let snapshot = self.snapshot(window, cx);
14950        let buffer = &snapshot.buffer_snapshot;
14951        let start = buffer.anchor_before(0);
14952        let end = buffer.anchor_after(buffer.len());
14953        let theme = cx.theme().colors();
14954        self.background_highlights_in_range(start..end, &snapshot, theme)
14955    }
14956
14957    #[cfg(feature = "test-support")]
14958    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14959        let snapshot = self.buffer().read(cx).snapshot(cx);
14960
14961        let highlights = self
14962            .background_highlights
14963            .get(&TypeId::of::<items::BufferSearchHighlights>());
14964
14965        if let Some((_color, ranges)) = highlights {
14966            ranges
14967                .iter()
14968                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14969                .collect_vec()
14970        } else {
14971            vec![]
14972        }
14973    }
14974
14975    fn document_highlights_for_position<'a>(
14976        &'a self,
14977        position: Anchor,
14978        buffer: &'a MultiBufferSnapshot,
14979    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
14980        let read_highlights = self
14981            .background_highlights
14982            .get(&TypeId::of::<DocumentHighlightRead>())
14983            .map(|h| &h.1);
14984        let write_highlights = self
14985            .background_highlights
14986            .get(&TypeId::of::<DocumentHighlightWrite>())
14987            .map(|h| &h.1);
14988        let left_position = position.bias_left(buffer);
14989        let right_position = position.bias_right(buffer);
14990        read_highlights
14991            .into_iter()
14992            .chain(write_highlights)
14993            .flat_map(move |ranges| {
14994                let start_ix = match ranges.binary_search_by(|probe| {
14995                    let cmp = probe.end.cmp(&left_position, buffer);
14996                    if cmp.is_ge() {
14997                        Ordering::Greater
14998                    } else {
14999                        Ordering::Less
15000                    }
15001                }) {
15002                    Ok(i) | Err(i) => i,
15003                };
15004
15005                ranges[start_ix..]
15006                    .iter()
15007                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
15008            })
15009    }
15010
15011    pub fn has_background_highlights<T: 'static>(&self) -> bool {
15012        self.background_highlights
15013            .get(&TypeId::of::<T>())
15014            .map_or(false, |(_, highlights)| !highlights.is_empty())
15015    }
15016
15017    pub fn background_highlights_in_range(
15018        &self,
15019        search_range: Range<Anchor>,
15020        display_snapshot: &DisplaySnapshot,
15021        theme: &ThemeColors,
15022    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15023        let mut results = Vec::new();
15024        for (color_fetcher, ranges) in self.background_highlights.values() {
15025            let color = color_fetcher(theme);
15026            let start_ix = match ranges.binary_search_by(|probe| {
15027                let cmp = probe
15028                    .end
15029                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15030                if cmp.is_gt() {
15031                    Ordering::Greater
15032                } else {
15033                    Ordering::Less
15034                }
15035            }) {
15036                Ok(i) | Err(i) => i,
15037            };
15038            for range in &ranges[start_ix..] {
15039                if range
15040                    .start
15041                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15042                    .is_ge()
15043                {
15044                    break;
15045                }
15046
15047                let start = range.start.to_display_point(display_snapshot);
15048                let end = range.end.to_display_point(display_snapshot);
15049                results.push((start..end, color))
15050            }
15051        }
15052        results
15053    }
15054
15055    pub fn background_highlight_row_ranges<T: 'static>(
15056        &self,
15057        search_range: Range<Anchor>,
15058        display_snapshot: &DisplaySnapshot,
15059        count: usize,
15060    ) -> Vec<RangeInclusive<DisplayPoint>> {
15061        let mut results = Vec::new();
15062        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15063            return vec![];
15064        };
15065
15066        let start_ix = match ranges.binary_search_by(|probe| {
15067            let cmp = probe
15068                .end
15069                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15070            if cmp.is_gt() {
15071                Ordering::Greater
15072            } else {
15073                Ordering::Less
15074            }
15075        }) {
15076            Ok(i) | Err(i) => i,
15077        };
15078        let mut push_region = |start: Option<Point>, end: Option<Point>| {
15079            if let (Some(start_display), Some(end_display)) = (start, end) {
15080                results.push(
15081                    start_display.to_display_point(display_snapshot)
15082                        ..=end_display.to_display_point(display_snapshot),
15083                );
15084            }
15085        };
15086        let mut start_row: Option<Point> = None;
15087        let mut end_row: Option<Point> = None;
15088        if ranges.len() > count {
15089            return Vec::new();
15090        }
15091        for range in &ranges[start_ix..] {
15092            if range
15093                .start
15094                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15095                .is_ge()
15096            {
15097                break;
15098            }
15099            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15100            if let Some(current_row) = &end_row {
15101                if end.row == current_row.row {
15102                    continue;
15103                }
15104            }
15105            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15106            if start_row.is_none() {
15107                assert_eq!(end_row, None);
15108                start_row = Some(start);
15109                end_row = Some(end);
15110                continue;
15111            }
15112            if let Some(current_end) = end_row.as_mut() {
15113                if start.row > current_end.row + 1 {
15114                    push_region(start_row, end_row);
15115                    start_row = Some(start);
15116                    end_row = Some(end);
15117                } else {
15118                    // Merge two hunks.
15119                    *current_end = end;
15120                }
15121            } else {
15122                unreachable!();
15123            }
15124        }
15125        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15126        push_region(start_row, end_row);
15127        results
15128    }
15129
15130    pub fn gutter_highlights_in_range(
15131        &self,
15132        search_range: Range<Anchor>,
15133        display_snapshot: &DisplaySnapshot,
15134        cx: &App,
15135    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15136        let mut results = Vec::new();
15137        for (color_fetcher, ranges) in self.gutter_highlights.values() {
15138            let color = color_fetcher(cx);
15139            let start_ix = match ranges.binary_search_by(|probe| {
15140                let cmp = probe
15141                    .end
15142                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15143                if cmp.is_gt() {
15144                    Ordering::Greater
15145                } else {
15146                    Ordering::Less
15147                }
15148            }) {
15149                Ok(i) | Err(i) => i,
15150            };
15151            for range in &ranges[start_ix..] {
15152                if range
15153                    .start
15154                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15155                    .is_ge()
15156                {
15157                    break;
15158                }
15159
15160                let start = range.start.to_display_point(display_snapshot);
15161                let end = range.end.to_display_point(display_snapshot);
15162                results.push((start..end, color))
15163            }
15164        }
15165        results
15166    }
15167
15168    /// Get the text ranges corresponding to the redaction query
15169    pub fn redacted_ranges(
15170        &self,
15171        search_range: Range<Anchor>,
15172        display_snapshot: &DisplaySnapshot,
15173        cx: &App,
15174    ) -> Vec<Range<DisplayPoint>> {
15175        display_snapshot
15176            .buffer_snapshot
15177            .redacted_ranges(search_range, |file| {
15178                if let Some(file) = file {
15179                    file.is_private()
15180                        && EditorSettings::get(
15181                            Some(SettingsLocation {
15182                                worktree_id: file.worktree_id(cx),
15183                                path: file.path().as_ref(),
15184                            }),
15185                            cx,
15186                        )
15187                        .redact_private_values
15188                } else {
15189                    false
15190                }
15191            })
15192            .map(|range| {
15193                range.start.to_display_point(display_snapshot)
15194                    ..range.end.to_display_point(display_snapshot)
15195            })
15196            .collect()
15197    }
15198
15199    pub fn highlight_text<T: 'static>(
15200        &mut self,
15201        ranges: Vec<Range<Anchor>>,
15202        style: HighlightStyle,
15203        cx: &mut Context<Self>,
15204    ) {
15205        self.display_map.update(cx, |map, _| {
15206            map.highlight_text(TypeId::of::<T>(), ranges, style)
15207        });
15208        cx.notify();
15209    }
15210
15211    pub(crate) fn highlight_inlays<T: 'static>(
15212        &mut self,
15213        highlights: Vec<InlayHighlight>,
15214        style: HighlightStyle,
15215        cx: &mut Context<Self>,
15216    ) {
15217        self.display_map.update(cx, |map, _| {
15218            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15219        });
15220        cx.notify();
15221    }
15222
15223    pub fn text_highlights<'a, T: 'static>(
15224        &'a self,
15225        cx: &'a App,
15226    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15227        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15228    }
15229
15230    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15231        let cleared = self
15232            .display_map
15233            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15234        if cleared {
15235            cx.notify();
15236        }
15237    }
15238
15239    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15240        (self.read_only(cx) || self.blink_manager.read(cx).visible())
15241            && self.focus_handle.is_focused(window)
15242    }
15243
15244    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15245        self.show_cursor_when_unfocused = is_enabled;
15246        cx.notify();
15247    }
15248
15249    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15250        cx.notify();
15251    }
15252
15253    fn on_buffer_event(
15254        &mut self,
15255        multibuffer: &Entity<MultiBuffer>,
15256        event: &multi_buffer::Event,
15257        window: &mut Window,
15258        cx: &mut Context<Self>,
15259    ) {
15260        match event {
15261            multi_buffer::Event::Edited {
15262                singleton_buffer_edited,
15263                edited_buffer: buffer_edited,
15264            } => {
15265                self.scrollbar_marker_state.dirty = true;
15266                self.active_indent_guides_state.dirty = true;
15267                self.refresh_active_diagnostics(cx);
15268                self.refresh_code_actions(window, cx);
15269                if self.has_active_inline_completion() {
15270                    self.update_visible_inline_completion(window, cx);
15271                }
15272                if let Some(buffer) = buffer_edited {
15273                    let buffer_id = buffer.read(cx).remote_id();
15274                    if !self.registered_buffers.contains_key(&buffer_id) {
15275                        if let Some(project) = self.project.as_ref() {
15276                            project.update(cx, |project, cx| {
15277                                self.registered_buffers.insert(
15278                                    buffer_id,
15279                                    project.register_buffer_with_language_servers(&buffer, cx),
15280                                );
15281                            })
15282                        }
15283                    }
15284                }
15285                cx.emit(EditorEvent::BufferEdited);
15286                cx.emit(SearchEvent::MatchesInvalidated);
15287                if *singleton_buffer_edited {
15288                    if let Some(project) = &self.project {
15289                        #[allow(clippy::mutable_key_type)]
15290                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15291                            multibuffer
15292                                .all_buffers()
15293                                .into_iter()
15294                                .filter_map(|buffer| {
15295                                    buffer.update(cx, |buffer, cx| {
15296                                        let language = buffer.language()?;
15297                                        let should_discard = project.update(cx, |project, cx| {
15298                                            project.is_local()
15299                                                && !project.has_language_servers_for(buffer, cx)
15300                                        });
15301                                        should_discard.not().then_some(language.clone())
15302                                    })
15303                                })
15304                                .collect::<HashSet<_>>()
15305                        });
15306                        if !languages_affected.is_empty() {
15307                            self.refresh_inlay_hints(
15308                                InlayHintRefreshReason::BufferEdited(languages_affected),
15309                                cx,
15310                            );
15311                        }
15312                    }
15313                }
15314
15315                let Some(project) = &self.project else { return };
15316                let (telemetry, is_via_ssh) = {
15317                    let project = project.read(cx);
15318                    let telemetry = project.client().telemetry().clone();
15319                    let is_via_ssh = project.is_via_ssh();
15320                    (telemetry, is_via_ssh)
15321                };
15322                refresh_linked_ranges(self, window, cx);
15323                telemetry.log_edit_event("editor", is_via_ssh);
15324            }
15325            multi_buffer::Event::ExcerptsAdded {
15326                buffer,
15327                predecessor,
15328                excerpts,
15329            } => {
15330                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15331                let buffer_id = buffer.read(cx).remote_id();
15332                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15333                    if let Some(project) = &self.project {
15334                        get_uncommitted_diff_for_buffer(
15335                            project,
15336                            [buffer.clone()],
15337                            self.buffer.clone(),
15338                            cx,
15339                        )
15340                        .detach();
15341                    }
15342                }
15343                cx.emit(EditorEvent::ExcerptsAdded {
15344                    buffer: buffer.clone(),
15345                    predecessor: *predecessor,
15346                    excerpts: excerpts.clone(),
15347                });
15348                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15349            }
15350            multi_buffer::Event::ExcerptsRemoved { ids } => {
15351                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15352                let buffer = self.buffer.read(cx);
15353                self.registered_buffers
15354                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15355                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15356            }
15357            multi_buffer::Event::ExcerptsEdited {
15358                excerpt_ids,
15359                buffer_ids,
15360            } => {
15361                self.display_map.update(cx, |map, cx| {
15362                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
15363                });
15364                cx.emit(EditorEvent::ExcerptsEdited {
15365                    ids: excerpt_ids.clone(),
15366                })
15367            }
15368            multi_buffer::Event::ExcerptsExpanded { ids } => {
15369                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15370                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15371            }
15372            multi_buffer::Event::Reparsed(buffer_id) => {
15373                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15374
15375                cx.emit(EditorEvent::Reparsed(*buffer_id));
15376            }
15377            multi_buffer::Event::DiffHunksToggled => {
15378                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15379            }
15380            multi_buffer::Event::LanguageChanged(buffer_id) => {
15381                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15382                cx.emit(EditorEvent::Reparsed(*buffer_id));
15383                cx.notify();
15384            }
15385            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15386            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15387            multi_buffer::Event::FileHandleChanged
15388            | multi_buffer::Event::Reloaded
15389            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
15390            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15391            multi_buffer::Event::DiagnosticsUpdated => {
15392                self.refresh_active_diagnostics(cx);
15393                self.refresh_inline_diagnostics(true, window, cx);
15394                self.scrollbar_marker_state.dirty = true;
15395                cx.notify();
15396            }
15397            _ => {}
15398        };
15399    }
15400
15401    fn on_display_map_changed(
15402        &mut self,
15403        _: Entity<DisplayMap>,
15404        _: &mut Window,
15405        cx: &mut Context<Self>,
15406    ) {
15407        cx.notify();
15408    }
15409
15410    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15411        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15412        self.update_edit_prediction_settings(cx);
15413        self.refresh_inline_completion(true, false, window, cx);
15414        self.refresh_inlay_hints(
15415            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15416                self.selections.newest_anchor().head(),
15417                &self.buffer.read(cx).snapshot(cx),
15418                cx,
15419            )),
15420            cx,
15421        );
15422
15423        let old_cursor_shape = self.cursor_shape;
15424
15425        {
15426            let editor_settings = EditorSettings::get_global(cx);
15427            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15428            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15429            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15430        }
15431
15432        if old_cursor_shape != self.cursor_shape {
15433            cx.emit(EditorEvent::CursorShapeChanged);
15434        }
15435
15436        let project_settings = ProjectSettings::get_global(cx);
15437        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15438
15439        if self.mode == EditorMode::Full {
15440            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15441            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15442            if self.show_inline_diagnostics != show_inline_diagnostics {
15443                self.show_inline_diagnostics = show_inline_diagnostics;
15444                self.refresh_inline_diagnostics(false, window, cx);
15445            }
15446
15447            if self.git_blame_inline_enabled != inline_blame_enabled {
15448                self.toggle_git_blame_inline_internal(false, window, cx);
15449            }
15450        }
15451
15452        cx.notify();
15453    }
15454
15455    pub fn set_searchable(&mut self, searchable: bool) {
15456        self.searchable = searchable;
15457    }
15458
15459    pub fn searchable(&self) -> bool {
15460        self.searchable
15461    }
15462
15463    fn open_proposed_changes_editor(
15464        &mut self,
15465        _: &OpenProposedChangesEditor,
15466        window: &mut Window,
15467        cx: &mut Context<Self>,
15468    ) {
15469        let Some(workspace) = self.workspace() else {
15470            cx.propagate();
15471            return;
15472        };
15473
15474        let selections = self.selections.all::<usize>(cx);
15475        let multi_buffer = self.buffer.read(cx);
15476        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15477        let mut new_selections_by_buffer = HashMap::default();
15478        for selection in selections {
15479            for (buffer, range, _) in
15480                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15481            {
15482                let mut range = range.to_point(buffer);
15483                range.start.column = 0;
15484                range.end.column = buffer.line_len(range.end.row);
15485                new_selections_by_buffer
15486                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15487                    .or_insert(Vec::new())
15488                    .push(range)
15489            }
15490        }
15491
15492        let proposed_changes_buffers = new_selections_by_buffer
15493            .into_iter()
15494            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15495            .collect::<Vec<_>>();
15496        let proposed_changes_editor = cx.new(|cx| {
15497            ProposedChangesEditor::new(
15498                "Proposed changes",
15499                proposed_changes_buffers,
15500                self.project.clone(),
15501                window,
15502                cx,
15503            )
15504        });
15505
15506        window.defer(cx, move |window, cx| {
15507            workspace.update(cx, |workspace, cx| {
15508                workspace.active_pane().update(cx, |pane, cx| {
15509                    pane.add_item(
15510                        Box::new(proposed_changes_editor),
15511                        true,
15512                        true,
15513                        None,
15514                        window,
15515                        cx,
15516                    );
15517                });
15518            });
15519        });
15520    }
15521
15522    pub fn open_excerpts_in_split(
15523        &mut self,
15524        _: &OpenExcerptsSplit,
15525        window: &mut Window,
15526        cx: &mut Context<Self>,
15527    ) {
15528        self.open_excerpts_common(None, true, window, cx)
15529    }
15530
15531    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15532        self.open_excerpts_common(None, false, window, cx)
15533    }
15534
15535    fn open_excerpts_common(
15536        &mut self,
15537        jump_data: Option<JumpData>,
15538        split: bool,
15539        window: &mut Window,
15540        cx: &mut Context<Self>,
15541    ) {
15542        let Some(workspace) = self.workspace() else {
15543            cx.propagate();
15544            return;
15545        };
15546
15547        if self.buffer.read(cx).is_singleton() {
15548            cx.propagate();
15549            return;
15550        }
15551
15552        let mut new_selections_by_buffer = HashMap::default();
15553        match &jump_data {
15554            Some(JumpData::MultiBufferPoint {
15555                excerpt_id,
15556                position,
15557                anchor,
15558                line_offset_from_top,
15559            }) => {
15560                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15561                if let Some(buffer) = multi_buffer_snapshot
15562                    .buffer_id_for_excerpt(*excerpt_id)
15563                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15564                {
15565                    let buffer_snapshot = buffer.read(cx).snapshot();
15566                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15567                        language::ToPoint::to_point(anchor, &buffer_snapshot)
15568                    } else {
15569                        buffer_snapshot.clip_point(*position, Bias::Left)
15570                    };
15571                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15572                    new_selections_by_buffer.insert(
15573                        buffer,
15574                        (
15575                            vec![jump_to_offset..jump_to_offset],
15576                            Some(*line_offset_from_top),
15577                        ),
15578                    );
15579                }
15580            }
15581            Some(JumpData::MultiBufferRow {
15582                row,
15583                line_offset_from_top,
15584            }) => {
15585                let point = MultiBufferPoint::new(row.0, 0);
15586                if let Some((buffer, buffer_point, _)) =
15587                    self.buffer.read(cx).point_to_buffer_point(point, cx)
15588                {
15589                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15590                    new_selections_by_buffer
15591                        .entry(buffer)
15592                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
15593                        .0
15594                        .push(buffer_offset..buffer_offset)
15595                }
15596            }
15597            None => {
15598                let selections = self.selections.all::<usize>(cx);
15599                let multi_buffer = self.buffer.read(cx);
15600                for selection in selections {
15601                    for (snapshot, range, _, anchor) in multi_buffer
15602                        .snapshot(cx)
15603                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15604                    {
15605                        if let Some(anchor) = anchor {
15606                            // selection is in a deleted hunk
15607                            let Some(buffer_id) = anchor.buffer_id else {
15608                                continue;
15609                            };
15610                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15611                                continue;
15612                            };
15613                            let offset = text::ToOffset::to_offset(
15614                                &anchor.text_anchor,
15615                                &buffer_handle.read(cx).snapshot(),
15616                            );
15617                            let range = offset..offset;
15618                            new_selections_by_buffer
15619                                .entry(buffer_handle)
15620                                .or_insert((Vec::new(), None))
15621                                .0
15622                                .push(range)
15623                        } else {
15624                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15625                            else {
15626                                continue;
15627                            };
15628                            new_selections_by_buffer
15629                                .entry(buffer_handle)
15630                                .or_insert((Vec::new(), None))
15631                                .0
15632                                .push(range)
15633                        }
15634                    }
15635                }
15636            }
15637        }
15638
15639        if new_selections_by_buffer.is_empty() {
15640            return;
15641        }
15642
15643        // We defer the pane interaction because we ourselves are a workspace item
15644        // and activating a new item causes the pane to call a method on us reentrantly,
15645        // which panics if we're on the stack.
15646        window.defer(cx, move |window, cx| {
15647            workspace.update(cx, |workspace, cx| {
15648                let pane = if split {
15649                    workspace.adjacent_pane(window, cx)
15650                } else {
15651                    workspace.active_pane().clone()
15652                };
15653
15654                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15655                    let editor = buffer
15656                        .read(cx)
15657                        .file()
15658                        .is_none()
15659                        .then(|| {
15660                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15661                            // so `workspace.open_project_item` will never find them, always opening a new editor.
15662                            // Instead, we try to activate the existing editor in the pane first.
15663                            let (editor, pane_item_index) =
15664                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
15665                                    let editor = item.downcast::<Editor>()?;
15666                                    let singleton_buffer =
15667                                        editor.read(cx).buffer().read(cx).as_singleton()?;
15668                                    if singleton_buffer == buffer {
15669                                        Some((editor, i))
15670                                    } else {
15671                                        None
15672                                    }
15673                                })?;
15674                            pane.update(cx, |pane, cx| {
15675                                pane.activate_item(pane_item_index, true, true, window, cx)
15676                            });
15677                            Some(editor)
15678                        })
15679                        .flatten()
15680                        .unwrap_or_else(|| {
15681                            workspace.open_project_item::<Self>(
15682                                pane.clone(),
15683                                buffer,
15684                                true,
15685                                true,
15686                                window,
15687                                cx,
15688                            )
15689                        });
15690
15691                    editor.update(cx, |editor, cx| {
15692                        let autoscroll = match scroll_offset {
15693                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15694                            None => Autoscroll::newest(),
15695                        };
15696                        let nav_history = editor.nav_history.take();
15697                        editor.change_selections(Some(autoscroll), window, cx, |s| {
15698                            s.select_ranges(ranges);
15699                        });
15700                        editor.nav_history = nav_history;
15701                    });
15702                }
15703            })
15704        });
15705    }
15706
15707    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15708        let snapshot = self.buffer.read(cx).read(cx);
15709        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15710        Some(
15711            ranges
15712                .iter()
15713                .map(move |range| {
15714                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15715                })
15716                .collect(),
15717        )
15718    }
15719
15720    fn selection_replacement_ranges(
15721        &self,
15722        range: Range<OffsetUtf16>,
15723        cx: &mut App,
15724    ) -> Vec<Range<OffsetUtf16>> {
15725        let selections = self.selections.all::<OffsetUtf16>(cx);
15726        let newest_selection = selections
15727            .iter()
15728            .max_by_key(|selection| selection.id)
15729            .unwrap();
15730        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15731        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15732        let snapshot = self.buffer.read(cx).read(cx);
15733        selections
15734            .into_iter()
15735            .map(|mut selection| {
15736                selection.start.0 =
15737                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
15738                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15739                snapshot.clip_offset_utf16(selection.start, Bias::Left)
15740                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15741            })
15742            .collect()
15743    }
15744
15745    fn report_editor_event(
15746        &self,
15747        event_type: &'static str,
15748        file_extension: Option<String>,
15749        cx: &App,
15750    ) {
15751        if cfg!(any(test, feature = "test-support")) {
15752            return;
15753        }
15754
15755        let Some(project) = &self.project else { return };
15756
15757        // If None, we are in a file without an extension
15758        let file = self
15759            .buffer
15760            .read(cx)
15761            .as_singleton()
15762            .and_then(|b| b.read(cx).file());
15763        let file_extension = file_extension.or(file
15764            .as_ref()
15765            .and_then(|file| Path::new(file.file_name(cx)).extension())
15766            .and_then(|e| e.to_str())
15767            .map(|a| a.to_string()));
15768
15769        let vim_mode = cx
15770            .global::<SettingsStore>()
15771            .raw_user_settings()
15772            .get("vim_mode")
15773            == Some(&serde_json::Value::Bool(true));
15774
15775        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15776        let copilot_enabled = edit_predictions_provider
15777            == language::language_settings::EditPredictionProvider::Copilot;
15778        let copilot_enabled_for_language = self
15779            .buffer
15780            .read(cx)
15781            .language_settings(cx)
15782            .show_edit_predictions;
15783
15784        let project = project.read(cx);
15785        telemetry::event!(
15786            event_type,
15787            file_extension,
15788            vim_mode,
15789            copilot_enabled,
15790            copilot_enabled_for_language,
15791            edit_predictions_provider,
15792            is_via_ssh = project.is_via_ssh(),
15793        );
15794    }
15795
15796    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15797    /// with each line being an array of {text, highlight} objects.
15798    fn copy_highlight_json(
15799        &mut self,
15800        _: &CopyHighlightJson,
15801        window: &mut Window,
15802        cx: &mut Context<Self>,
15803    ) {
15804        #[derive(Serialize)]
15805        struct Chunk<'a> {
15806            text: String,
15807            highlight: Option<&'a str>,
15808        }
15809
15810        let snapshot = self.buffer.read(cx).snapshot(cx);
15811        let range = self
15812            .selected_text_range(false, window, cx)
15813            .and_then(|selection| {
15814                if selection.range.is_empty() {
15815                    None
15816                } else {
15817                    Some(selection.range)
15818                }
15819            })
15820            .unwrap_or_else(|| 0..snapshot.len());
15821
15822        let chunks = snapshot.chunks(range, true);
15823        let mut lines = Vec::new();
15824        let mut line: VecDeque<Chunk> = VecDeque::new();
15825
15826        let Some(style) = self.style.as_ref() else {
15827            return;
15828        };
15829
15830        for chunk in chunks {
15831            let highlight = chunk
15832                .syntax_highlight_id
15833                .and_then(|id| id.name(&style.syntax));
15834            let mut chunk_lines = chunk.text.split('\n').peekable();
15835            while let Some(text) = chunk_lines.next() {
15836                let mut merged_with_last_token = false;
15837                if let Some(last_token) = line.back_mut() {
15838                    if last_token.highlight == highlight {
15839                        last_token.text.push_str(text);
15840                        merged_with_last_token = true;
15841                    }
15842                }
15843
15844                if !merged_with_last_token {
15845                    line.push_back(Chunk {
15846                        text: text.into(),
15847                        highlight,
15848                    });
15849                }
15850
15851                if chunk_lines.peek().is_some() {
15852                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
15853                        line.pop_front();
15854                    }
15855                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
15856                        line.pop_back();
15857                    }
15858
15859                    lines.push(mem::take(&mut line));
15860                }
15861            }
15862        }
15863
15864        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15865            return;
15866        };
15867        cx.write_to_clipboard(ClipboardItem::new_string(lines));
15868    }
15869
15870    pub fn open_context_menu(
15871        &mut self,
15872        _: &OpenContextMenu,
15873        window: &mut Window,
15874        cx: &mut Context<Self>,
15875    ) {
15876        self.request_autoscroll(Autoscroll::newest(), cx);
15877        let position = self.selections.newest_display(cx).start;
15878        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15879    }
15880
15881    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15882        &self.inlay_hint_cache
15883    }
15884
15885    pub fn replay_insert_event(
15886        &mut self,
15887        text: &str,
15888        relative_utf16_range: Option<Range<isize>>,
15889        window: &mut Window,
15890        cx: &mut Context<Self>,
15891    ) {
15892        if !self.input_enabled {
15893            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15894            return;
15895        }
15896        if let Some(relative_utf16_range) = relative_utf16_range {
15897            let selections = self.selections.all::<OffsetUtf16>(cx);
15898            self.change_selections(None, window, cx, |s| {
15899                let new_ranges = selections.into_iter().map(|range| {
15900                    let start = OffsetUtf16(
15901                        range
15902                            .head()
15903                            .0
15904                            .saturating_add_signed(relative_utf16_range.start),
15905                    );
15906                    let end = OffsetUtf16(
15907                        range
15908                            .head()
15909                            .0
15910                            .saturating_add_signed(relative_utf16_range.end),
15911                    );
15912                    start..end
15913                });
15914                s.select_ranges(new_ranges);
15915            });
15916        }
15917
15918        self.handle_input(text, window, cx);
15919    }
15920
15921    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15922        let Some(provider) = self.semantics_provider.as_ref() else {
15923            return false;
15924        };
15925
15926        let mut supports = false;
15927        self.buffer().update(cx, |this, cx| {
15928            this.for_each_buffer(|buffer| {
15929                supports |= provider.supports_inlay_hints(buffer, cx);
15930            });
15931        });
15932
15933        supports
15934    }
15935
15936    pub fn is_focused(&self, window: &Window) -> bool {
15937        self.focus_handle.is_focused(window)
15938    }
15939
15940    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15941        cx.emit(EditorEvent::Focused);
15942
15943        if let Some(descendant) = self
15944            .last_focused_descendant
15945            .take()
15946            .and_then(|descendant| descendant.upgrade())
15947        {
15948            window.focus(&descendant);
15949        } else {
15950            if let Some(blame) = self.blame.as_ref() {
15951                blame.update(cx, GitBlame::focus)
15952            }
15953
15954            self.blink_manager.update(cx, BlinkManager::enable);
15955            self.show_cursor_names(window, cx);
15956            self.buffer.update(cx, |buffer, cx| {
15957                buffer.finalize_last_transaction(cx);
15958                if self.leader_peer_id.is_none() {
15959                    buffer.set_active_selections(
15960                        &self.selections.disjoint_anchors(),
15961                        self.selections.line_mode,
15962                        self.cursor_shape,
15963                        cx,
15964                    );
15965                }
15966            });
15967        }
15968    }
15969
15970    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15971        cx.emit(EditorEvent::FocusedIn)
15972    }
15973
15974    fn handle_focus_out(
15975        &mut self,
15976        event: FocusOutEvent,
15977        _window: &mut Window,
15978        cx: &mut Context<Self>,
15979    ) {
15980        if event.blurred != self.focus_handle {
15981            self.last_focused_descendant = Some(event.blurred);
15982        }
15983        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
15984    }
15985
15986    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15987        self.blink_manager.update(cx, BlinkManager::disable);
15988        self.buffer
15989            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
15990
15991        if let Some(blame) = self.blame.as_ref() {
15992            blame.update(cx, GitBlame::blur)
15993        }
15994        if !self.hover_state.focused(window, cx) {
15995            hide_hover(self, cx);
15996        }
15997        if !self
15998            .context_menu
15999            .borrow()
16000            .as_ref()
16001            .is_some_and(|context_menu| context_menu.focused(window, cx))
16002        {
16003            self.hide_context_menu(window, cx);
16004        }
16005        self.discard_inline_completion(false, cx);
16006        cx.emit(EditorEvent::Blurred);
16007        cx.notify();
16008    }
16009
16010    pub fn register_action<A: Action>(
16011        &mut self,
16012        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
16013    ) -> Subscription {
16014        let id = self.next_editor_action_id.post_inc();
16015        let listener = Arc::new(listener);
16016        self.editor_actions.borrow_mut().insert(
16017            id,
16018            Box::new(move |window, _| {
16019                let listener = listener.clone();
16020                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
16021                    let action = action.downcast_ref().unwrap();
16022                    if phase == DispatchPhase::Bubble {
16023                        listener(action, window, cx)
16024                    }
16025                })
16026            }),
16027        );
16028
16029        let editor_actions = self.editor_actions.clone();
16030        Subscription::new(move || {
16031            editor_actions.borrow_mut().remove(&id);
16032        })
16033    }
16034
16035    pub fn file_header_size(&self) -> u32 {
16036        FILE_HEADER_HEIGHT
16037    }
16038
16039    pub fn restore(
16040        &mut self,
16041        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16042        window: &mut Window,
16043        cx: &mut Context<Self>,
16044    ) {
16045        let workspace = self.workspace();
16046        let project = self.project.as_ref();
16047        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16048            let mut tasks = Vec::new();
16049            for (buffer_id, changes) in revert_changes {
16050                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16051                    buffer.update(cx, |buffer, cx| {
16052                        buffer.edit(
16053                            changes
16054                                .into_iter()
16055                                .map(|(range, text)| (range, text.to_string())),
16056                            None,
16057                            cx,
16058                        );
16059                    });
16060
16061                    if let Some(project) =
16062                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16063                    {
16064                        project.update(cx, |project, cx| {
16065                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16066                        })
16067                    }
16068                }
16069            }
16070            tasks
16071        });
16072        cx.spawn_in(window, |_, mut cx| async move {
16073            for (buffer, task) in save_tasks {
16074                let result = task.await;
16075                if result.is_err() {
16076                    let Some(path) = buffer
16077                        .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16078                        .ok()
16079                    else {
16080                        continue;
16081                    };
16082                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16083                        let Some(task) = cx
16084                            .update_window_entity(&workspace, |workspace, window, cx| {
16085                                workspace
16086                                    .open_path_preview(path, None, false, false, false, window, cx)
16087                            })
16088                            .ok()
16089                        else {
16090                            continue;
16091                        };
16092                        task.await.log_err();
16093                    }
16094                }
16095            }
16096        })
16097        .detach();
16098        self.change_selections(None, window, cx, |selections| selections.refresh());
16099    }
16100
16101    pub fn to_pixel_point(
16102        &self,
16103        source: multi_buffer::Anchor,
16104        editor_snapshot: &EditorSnapshot,
16105        window: &mut Window,
16106    ) -> Option<gpui::Point<Pixels>> {
16107        let source_point = source.to_display_point(editor_snapshot);
16108        self.display_to_pixel_point(source_point, editor_snapshot, window)
16109    }
16110
16111    pub fn display_to_pixel_point(
16112        &self,
16113        source: DisplayPoint,
16114        editor_snapshot: &EditorSnapshot,
16115        window: &mut Window,
16116    ) -> Option<gpui::Point<Pixels>> {
16117        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16118        let text_layout_details = self.text_layout_details(window);
16119        let scroll_top = text_layout_details
16120            .scroll_anchor
16121            .scroll_position(editor_snapshot)
16122            .y;
16123
16124        if source.row().as_f32() < scroll_top.floor() {
16125            return None;
16126        }
16127        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16128        let source_y = line_height * (source.row().as_f32() - scroll_top);
16129        Some(gpui::Point::new(source_x, source_y))
16130    }
16131
16132    pub fn has_visible_completions_menu(&self) -> bool {
16133        !self.edit_prediction_preview_is_active()
16134            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16135                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16136            })
16137    }
16138
16139    pub fn register_addon<T: Addon>(&mut self, instance: T) {
16140        self.addons
16141            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16142    }
16143
16144    pub fn unregister_addon<T: Addon>(&mut self) {
16145        self.addons.remove(&std::any::TypeId::of::<T>());
16146    }
16147
16148    pub fn addon<T: Addon>(&self) -> Option<&T> {
16149        let type_id = std::any::TypeId::of::<T>();
16150        self.addons
16151            .get(&type_id)
16152            .and_then(|item| item.to_any().downcast_ref::<T>())
16153    }
16154
16155    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16156        let text_layout_details = self.text_layout_details(window);
16157        let style = &text_layout_details.editor_style;
16158        let font_id = window.text_system().resolve_font(&style.text.font());
16159        let font_size = style.text.font_size.to_pixels(window.rem_size());
16160        let line_height = style.text.line_height_in_pixels(window.rem_size());
16161        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16162
16163        gpui::Size::new(em_width, line_height)
16164    }
16165
16166    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16167        self.load_diff_task.clone()
16168    }
16169
16170    fn read_selections_from_db(
16171        &mut self,
16172        item_id: u64,
16173        workspace_id: WorkspaceId,
16174        window: &mut Window,
16175        cx: &mut Context<Editor>,
16176    ) {
16177        if !self.is_singleton(cx)
16178            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16179        {
16180            return;
16181        }
16182        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16183            return;
16184        };
16185        if selections.is_empty() {
16186            return;
16187        }
16188
16189        let snapshot = self.buffer.read(cx).snapshot(cx);
16190        self.change_selections(None, window, cx, |s| {
16191            s.select_ranges(selections.into_iter().map(|(start, end)| {
16192                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16193            }));
16194        });
16195    }
16196}
16197
16198fn insert_extra_newline_brackets(
16199    buffer: &MultiBufferSnapshot,
16200    range: Range<usize>,
16201    language: &language::LanguageScope,
16202) -> bool {
16203    let leading_whitespace_len = buffer
16204        .reversed_chars_at(range.start)
16205        .take_while(|c| c.is_whitespace() && *c != '\n')
16206        .map(|c| c.len_utf8())
16207        .sum::<usize>();
16208    let trailing_whitespace_len = buffer
16209        .chars_at(range.end)
16210        .take_while(|c| c.is_whitespace() && *c != '\n')
16211        .map(|c| c.len_utf8())
16212        .sum::<usize>();
16213    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16214
16215    language.brackets().any(|(pair, enabled)| {
16216        let pair_start = pair.start.trim_end();
16217        let pair_end = pair.end.trim_start();
16218
16219        enabled
16220            && pair.newline
16221            && buffer.contains_str_at(range.end, pair_end)
16222            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16223    })
16224}
16225
16226fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16227    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16228        [(buffer, range, _)] => (*buffer, range.clone()),
16229        _ => return false,
16230    };
16231    let pair = {
16232        let mut result: Option<BracketMatch> = None;
16233
16234        for pair in buffer
16235            .all_bracket_ranges(range.clone())
16236            .filter(move |pair| {
16237                pair.open_range.start <= range.start && pair.close_range.end >= range.end
16238            })
16239        {
16240            let len = pair.close_range.end - pair.open_range.start;
16241
16242            if let Some(existing) = &result {
16243                let existing_len = existing.close_range.end - existing.open_range.start;
16244                if len > existing_len {
16245                    continue;
16246                }
16247            }
16248
16249            result = Some(pair);
16250        }
16251
16252        result
16253    };
16254    let Some(pair) = pair else {
16255        return false;
16256    };
16257    pair.newline_only
16258        && buffer
16259            .chars_for_range(pair.open_range.end..range.start)
16260            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16261            .all(|c| c.is_whitespace() && c != '\n')
16262}
16263
16264fn get_uncommitted_diff_for_buffer(
16265    project: &Entity<Project>,
16266    buffers: impl IntoIterator<Item = Entity<Buffer>>,
16267    buffer: Entity<MultiBuffer>,
16268    cx: &mut App,
16269) -> Task<()> {
16270    let mut tasks = Vec::new();
16271    project.update(cx, |project, cx| {
16272        for buffer in buffers {
16273            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16274        }
16275    });
16276    cx.spawn(|mut cx| async move {
16277        let diffs = future::join_all(tasks).await;
16278        buffer
16279            .update(&mut cx, |buffer, cx| {
16280                for diff in diffs.into_iter().flatten() {
16281                    buffer.add_diff(diff, cx);
16282                }
16283            })
16284            .ok();
16285    })
16286}
16287
16288fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16289    let tab_size = tab_size.get() as usize;
16290    let mut width = offset;
16291
16292    for ch in text.chars() {
16293        width += if ch == '\t' {
16294            tab_size - (width % tab_size)
16295        } else {
16296            1
16297        };
16298    }
16299
16300    width - offset
16301}
16302
16303#[cfg(test)]
16304mod tests {
16305    use super::*;
16306
16307    #[test]
16308    fn test_string_size_with_expanded_tabs() {
16309        let nz = |val| NonZeroU32::new(val).unwrap();
16310        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16311        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16312        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16313        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16314        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16315        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16316        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16317        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16318    }
16319}
16320
16321/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16322struct WordBreakingTokenizer<'a> {
16323    input: &'a str,
16324}
16325
16326impl<'a> WordBreakingTokenizer<'a> {
16327    fn new(input: &'a str) -> Self {
16328        Self { input }
16329    }
16330}
16331
16332fn is_char_ideographic(ch: char) -> bool {
16333    use unicode_script::Script::*;
16334    use unicode_script::UnicodeScript;
16335    matches!(ch.script(), Han | Tangut | Yi)
16336}
16337
16338fn is_grapheme_ideographic(text: &str) -> bool {
16339    text.chars().any(is_char_ideographic)
16340}
16341
16342fn is_grapheme_whitespace(text: &str) -> bool {
16343    text.chars().any(|x| x.is_whitespace())
16344}
16345
16346fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16347    text.chars().next().map_or(false, |ch| {
16348        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16349    })
16350}
16351
16352#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16353struct WordBreakToken<'a> {
16354    token: &'a str,
16355    grapheme_len: usize,
16356    is_whitespace: bool,
16357}
16358
16359impl<'a> Iterator for WordBreakingTokenizer<'a> {
16360    /// Yields a span, the count of graphemes in the token, and whether it was
16361    /// whitespace. Note that it also breaks at word boundaries.
16362    type Item = WordBreakToken<'a>;
16363
16364    fn next(&mut self) -> Option<Self::Item> {
16365        use unicode_segmentation::UnicodeSegmentation;
16366        if self.input.is_empty() {
16367            return None;
16368        }
16369
16370        let mut iter = self.input.graphemes(true).peekable();
16371        let mut offset = 0;
16372        let mut graphemes = 0;
16373        if let Some(first_grapheme) = iter.next() {
16374            let is_whitespace = is_grapheme_whitespace(first_grapheme);
16375            offset += first_grapheme.len();
16376            graphemes += 1;
16377            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16378                if let Some(grapheme) = iter.peek().copied() {
16379                    if should_stay_with_preceding_ideograph(grapheme) {
16380                        offset += grapheme.len();
16381                        graphemes += 1;
16382                    }
16383                }
16384            } else {
16385                let mut words = self.input[offset..].split_word_bound_indices().peekable();
16386                let mut next_word_bound = words.peek().copied();
16387                if next_word_bound.map_or(false, |(i, _)| i == 0) {
16388                    next_word_bound = words.next();
16389                }
16390                while let Some(grapheme) = iter.peek().copied() {
16391                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
16392                        break;
16393                    };
16394                    if is_grapheme_whitespace(grapheme) != is_whitespace {
16395                        break;
16396                    };
16397                    offset += grapheme.len();
16398                    graphemes += 1;
16399                    iter.next();
16400                }
16401            }
16402            let token = &self.input[..offset];
16403            self.input = &self.input[offset..];
16404            if is_whitespace {
16405                Some(WordBreakToken {
16406                    token: " ",
16407                    grapheme_len: 1,
16408                    is_whitespace: true,
16409                })
16410            } else {
16411                Some(WordBreakToken {
16412                    token,
16413                    grapheme_len: graphemes,
16414                    is_whitespace: false,
16415                })
16416            }
16417        } else {
16418            None
16419        }
16420    }
16421}
16422
16423#[test]
16424fn test_word_breaking_tokenizer() {
16425    let tests: &[(&str, &[(&str, usize, bool)])] = &[
16426        ("", &[]),
16427        ("  ", &[(" ", 1, true)]),
16428        ("Ʒ", &[("Ʒ", 1, false)]),
16429        ("Ǽ", &[("Ǽ", 1, false)]),
16430        ("", &[("", 1, false)]),
16431        ("⋑⋑", &[("⋑⋑", 2, false)]),
16432        (
16433            "原理,进而",
16434            &[
16435                ("", 1, false),
16436                ("理,", 2, false),
16437                ("", 1, false),
16438                ("", 1, false),
16439            ],
16440        ),
16441        (
16442            "hello world",
16443            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16444        ),
16445        (
16446            "hello, world",
16447            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16448        ),
16449        (
16450            "  hello world",
16451            &[
16452                (" ", 1, true),
16453                ("hello", 5, false),
16454                (" ", 1, true),
16455                ("world", 5, false),
16456            ],
16457        ),
16458        (
16459            "这是什么 \n 钢笔",
16460            &[
16461                ("", 1, false),
16462                ("", 1, false),
16463                ("", 1, false),
16464                ("", 1, false),
16465                (" ", 1, true),
16466                ("", 1, false),
16467                ("", 1, false),
16468            ],
16469        ),
16470        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16471    ];
16472
16473    for (input, result) in tests {
16474        assert_eq!(
16475            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16476            result
16477                .iter()
16478                .copied()
16479                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16480                    token,
16481                    grapheme_len,
16482                    is_whitespace,
16483                })
16484                .collect::<Vec<_>>()
16485        );
16486    }
16487}
16488
16489fn wrap_with_prefix(
16490    line_prefix: String,
16491    unwrapped_text: String,
16492    wrap_column: usize,
16493    tab_size: NonZeroU32,
16494) -> String {
16495    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16496    let mut wrapped_text = String::new();
16497    let mut current_line = line_prefix.clone();
16498
16499    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16500    let mut current_line_len = line_prefix_len;
16501    for WordBreakToken {
16502        token,
16503        grapheme_len,
16504        is_whitespace,
16505    } in tokenizer
16506    {
16507        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16508            wrapped_text.push_str(current_line.trim_end());
16509            wrapped_text.push('\n');
16510            current_line.truncate(line_prefix.len());
16511            current_line_len = line_prefix_len;
16512            if !is_whitespace {
16513                current_line.push_str(token);
16514                current_line_len += grapheme_len;
16515            }
16516        } else if !is_whitespace {
16517            current_line.push_str(token);
16518            current_line_len += grapheme_len;
16519        } else if current_line_len != line_prefix_len {
16520            current_line.push(' ');
16521            current_line_len += 1;
16522        }
16523    }
16524
16525    if !current_line.is_empty() {
16526        wrapped_text.push_str(&current_line);
16527    }
16528    wrapped_text
16529}
16530
16531#[test]
16532fn test_wrap_with_prefix() {
16533    assert_eq!(
16534        wrap_with_prefix(
16535            "# ".to_string(),
16536            "abcdefg".to_string(),
16537            4,
16538            NonZeroU32::new(4).unwrap()
16539        ),
16540        "# abcdefg"
16541    );
16542    assert_eq!(
16543        wrap_with_prefix(
16544            "".to_string(),
16545            "\thello world".to_string(),
16546            8,
16547            NonZeroU32::new(4).unwrap()
16548        ),
16549        "hello\nworld"
16550    );
16551    assert_eq!(
16552        wrap_with_prefix(
16553            "// ".to_string(),
16554            "xx \nyy zz aa bb cc".to_string(),
16555            12,
16556            NonZeroU32::new(4).unwrap()
16557        ),
16558        "// xx yy zz\n// aa bb cc"
16559    );
16560    assert_eq!(
16561        wrap_with_prefix(
16562            String::new(),
16563            "这是什么 \n 钢笔".to_string(),
16564            3,
16565            NonZeroU32::new(4).unwrap()
16566        ),
16567        "这是什\n么 钢\n"
16568    );
16569}
16570
16571pub trait CollaborationHub {
16572    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16573    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16574    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16575}
16576
16577impl CollaborationHub for Entity<Project> {
16578    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16579        self.read(cx).collaborators()
16580    }
16581
16582    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16583        self.read(cx).user_store().read(cx).participant_indices()
16584    }
16585
16586    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16587        let this = self.read(cx);
16588        let user_ids = this.collaborators().values().map(|c| c.user_id);
16589        this.user_store().read_with(cx, |user_store, cx| {
16590            user_store.participant_names(user_ids, cx)
16591        })
16592    }
16593}
16594
16595pub trait SemanticsProvider {
16596    fn hover(
16597        &self,
16598        buffer: &Entity<Buffer>,
16599        position: text::Anchor,
16600        cx: &mut App,
16601    ) -> Option<Task<Vec<project::Hover>>>;
16602
16603    fn inlay_hints(
16604        &self,
16605        buffer_handle: Entity<Buffer>,
16606        range: Range<text::Anchor>,
16607        cx: &mut App,
16608    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16609
16610    fn resolve_inlay_hint(
16611        &self,
16612        hint: InlayHint,
16613        buffer_handle: Entity<Buffer>,
16614        server_id: LanguageServerId,
16615        cx: &mut App,
16616    ) -> Option<Task<anyhow::Result<InlayHint>>>;
16617
16618    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16619
16620    fn document_highlights(
16621        &self,
16622        buffer: &Entity<Buffer>,
16623        position: text::Anchor,
16624        cx: &mut App,
16625    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16626
16627    fn definitions(
16628        &self,
16629        buffer: &Entity<Buffer>,
16630        position: text::Anchor,
16631        kind: GotoDefinitionKind,
16632        cx: &mut App,
16633    ) -> Option<Task<Result<Vec<LocationLink>>>>;
16634
16635    fn range_for_rename(
16636        &self,
16637        buffer: &Entity<Buffer>,
16638        position: text::Anchor,
16639        cx: &mut App,
16640    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16641
16642    fn perform_rename(
16643        &self,
16644        buffer: &Entity<Buffer>,
16645        position: text::Anchor,
16646        new_name: String,
16647        cx: &mut App,
16648    ) -> Option<Task<Result<ProjectTransaction>>>;
16649}
16650
16651pub trait CompletionProvider {
16652    fn completions(
16653        &self,
16654        buffer: &Entity<Buffer>,
16655        buffer_position: text::Anchor,
16656        trigger: CompletionContext,
16657        window: &mut Window,
16658        cx: &mut Context<Editor>,
16659    ) -> Task<Result<Vec<Completion>>>;
16660
16661    fn resolve_completions(
16662        &self,
16663        buffer: Entity<Buffer>,
16664        completion_indices: Vec<usize>,
16665        completions: Rc<RefCell<Box<[Completion]>>>,
16666        cx: &mut Context<Editor>,
16667    ) -> Task<Result<bool>>;
16668
16669    fn apply_additional_edits_for_completion(
16670        &self,
16671        _buffer: Entity<Buffer>,
16672        _completions: Rc<RefCell<Box<[Completion]>>>,
16673        _completion_index: usize,
16674        _push_to_history: bool,
16675        _cx: &mut Context<Editor>,
16676    ) -> Task<Result<Option<language::Transaction>>> {
16677        Task::ready(Ok(None))
16678    }
16679
16680    fn is_completion_trigger(
16681        &self,
16682        buffer: &Entity<Buffer>,
16683        position: language::Anchor,
16684        text: &str,
16685        trigger_in_words: bool,
16686        cx: &mut Context<Editor>,
16687    ) -> bool;
16688
16689    fn sort_completions(&self) -> bool {
16690        true
16691    }
16692}
16693
16694pub trait CodeActionProvider {
16695    fn id(&self) -> Arc<str>;
16696
16697    fn code_actions(
16698        &self,
16699        buffer: &Entity<Buffer>,
16700        range: Range<text::Anchor>,
16701        window: &mut Window,
16702        cx: &mut App,
16703    ) -> Task<Result<Vec<CodeAction>>>;
16704
16705    fn apply_code_action(
16706        &self,
16707        buffer_handle: Entity<Buffer>,
16708        action: CodeAction,
16709        excerpt_id: ExcerptId,
16710        push_to_history: bool,
16711        window: &mut Window,
16712        cx: &mut App,
16713    ) -> Task<Result<ProjectTransaction>>;
16714}
16715
16716impl CodeActionProvider for Entity<Project> {
16717    fn id(&self) -> Arc<str> {
16718        "project".into()
16719    }
16720
16721    fn code_actions(
16722        &self,
16723        buffer: &Entity<Buffer>,
16724        range: Range<text::Anchor>,
16725        _window: &mut Window,
16726        cx: &mut App,
16727    ) -> Task<Result<Vec<CodeAction>>> {
16728        self.update(cx, |project, cx| {
16729            project.code_actions(buffer, range, None, cx)
16730        })
16731    }
16732
16733    fn apply_code_action(
16734        &self,
16735        buffer_handle: Entity<Buffer>,
16736        action: CodeAction,
16737        _excerpt_id: ExcerptId,
16738        push_to_history: bool,
16739        _window: &mut Window,
16740        cx: &mut App,
16741    ) -> Task<Result<ProjectTransaction>> {
16742        self.update(cx, |project, cx| {
16743            project.apply_code_action(buffer_handle, action, push_to_history, cx)
16744        })
16745    }
16746}
16747
16748fn snippet_completions(
16749    project: &Project,
16750    buffer: &Entity<Buffer>,
16751    buffer_position: text::Anchor,
16752    cx: &mut App,
16753) -> Task<Result<Vec<Completion>>> {
16754    let language = buffer.read(cx).language_at(buffer_position);
16755    let language_name = language.as_ref().map(|language| language.lsp_id());
16756    let snippet_store = project.snippets().read(cx);
16757    let snippets = snippet_store.snippets_for(language_name, cx);
16758
16759    if snippets.is_empty() {
16760        return Task::ready(Ok(vec![]));
16761    }
16762    let snapshot = buffer.read(cx).text_snapshot();
16763    let chars: String = snapshot
16764        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16765        .collect();
16766
16767    let scope = language.map(|language| language.default_scope());
16768    let executor = cx.background_executor().clone();
16769
16770    cx.background_spawn(async move {
16771        let classifier = CharClassifier::new(scope).for_completion(true);
16772        let mut last_word = chars
16773            .chars()
16774            .take_while(|c| classifier.is_word(*c))
16775            .collect::<String>();
16776        last_word = last_word.chars().rev().collect();
16777
16778        if last_word.is_empty() {
16779            return Ok(vec![]);
16780        }
16781
16782        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16783        let to_lsp = |point: &text::Anchor| {
16784            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16785            point_to_lsp(end)
16786        };
16787        let lsp_end = to_lsp(&buffer_position);
16788
16789        let candidates = snippets
16790            .iter()
16791            .enumerate()
16792            .flat_map(|(ix, snippet)| {
16793                snippet
16794                    .prefix
16795                    .iter()
16796                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16797            })
16798            .collect::<Vec<StringMatchCandidate>>();
16799
16800        let mut matches = fuzzy::match_strings(
16801            &candidates,
16802            &last_word,
16803            last_word.chars().any(|c| c.is_uppercase()),
16804            100,
16805            &Default::default(),
16806            executor,
16807        )
16808        .await;
16809
16810        // Remove all candidates where the query's start does not match the start of any word in the candidate
16811        if let Some(query_start) = last_word.chars().next() {
16812            matches.retain(|string_match| {
16813                split_words(&string_match.string).any(|word| {
16814                    // Check that the first codepoint of the word as lowercase matches the first
16815                    // codepoint of the query as lowercase
16816                    word.chars()
16817                        .flat_map(|codepoint| codepoint.to_lowercase())
16818                        .zip(query_start.to_lowercase())
16819                        .all(|(word_cp, query_cp)| word_cp == query_cp)
16820                })
16821            });
16822        }
16823
16824        let matched_strings = matches
16825            .into_iter()
16826            .map(|m| m.string)
16827            .collect::<HashSet<_>>();
16828
16829        let result: Vec<Completion> = snippets
16830            .into_iter()
16831            .filter_map(|snippet| {
16832                let matching_prefix = snippet
16833                    .prefix
16834                    .iter()
16835                    .find(|prefix| matched_strings.contains(*prefix))?;
16836                let start = as_offset - last_word.len();
16837                let start = snapshot.anchor_before(start);
16838                let range = start..buffer_position;
16839                let lsp_start = to_lsp(&start);
16840                let lsp_range = lsp::Range {
16841                    start: lsp_start,
16842                    end: lsp_end,
16843                };
16844                Some(Completion {
16845                    old_range: range,
16846                    new_text: snippet.body.clone(),
16847                    resolved: false,
16848                    label: CodeLabel {
16849                        text: matching_prefix.clone(),
16850                        runs: vec![],
16851                        filter_range: 0..matching_prefix.len(),
16852                    },
16853                    server_id: LanguageServerId(usize::MAX),
16854                    documentation: snippet
16855                        .description
16856                        .clone()
16857                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
16858                    lsp_completion: lsp::CompletionItem {
16859                        label: snippet.prefix.first().unwrap().clone(),
16860                        kind: Some(CompletionItemKind::SNIPPET),
16861                        label_details: snippet.description.as_ref().map(|description| {
16862                            lsp::CompletionItemLabelDetails {
16863                                detail: Some(description.clone()),
16864                                description: None,
16865                            }
16866                        }),
16867                        insert_text_format: Some(InsertTextFormat::SNIPPET),
16868                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16869                            lsp::InsertReplaceEdit {
16870                                new_text: snippet.body.clone(),
16871                                insert: lsp_range,
16872                                replace: lsp_range,
16873                            },
16874                        )),
16875                        filter_text: Some(snippet.body.clone()),
16876                        sort_text: Some(char::MAX.to_string()),
16877                        ..Default::default()
16878                    },
16879                    confirm: None,
16880                })
16881            })
16882            .collect();
16883
16884        Ok(result)
16885    })
16886}
16887
16888impl CompletionProvider for Entity<Project> {
16889    fn completions(
16890        &self,
16891        buffer: &Entity<Buffer>,
16892        buffer_position: text::Anchor,
16893        options: CompletionContext,
16894        _window: &mut Window,
16895        cx: &mut Context<Editor>,
16896    ) -> Task<Result<Vec<Completion>>> {
16897        self.update(cx, |project, cx| {
16898            let snippets = snippet_completions(project, buffer, buffer_position, cx);
16899            let project_completions = project.completions(buffer, buffer_position, options, cx);
16900            cx.background_spawn(async move {
16901                let mut completions = project_completions.await?;
16902                let snippets_completions = snippets.await?;
16903                completions.extend(snippets_completions);
16904                Ok(completions)
16905            })
16906        })
16907    }
16908
16909    fn resolve_completions(
16910        &self,
16911        buffer: Entity<Buffer>,
16912        completion_indices: Vec<usize>,
16913        completions: Rc<RefCell<Box<[Completion]>>>,
16914        cx: &mut Context<Editor>,
16915    ) -> Task<Result<bool>> {
16916        self.update(cx, |project, cx| {
16917            project.lsp_store().update(cx, |lsp_store, cx| {
16918                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16919            })
16920        })
16921    }
16922
16923    fn apply_additional_edits_for_completion(
16924        &self,
16925        buffer: Entity<Buffer>,
16926        completions: Rc<RefCell<Box<[Completion]>>>,
16927        completion_index: usize,
16928        push_to_history: bool,
16929        cx: &mut Context<Editor>,
16930    ) -> Task<Result<Option<language::Transaction>>> {
16931        self.update(cx, |project, cx| {
16932            project.lsp_store().update(cx, |lsp_store, cx| {
16933                lsp_store.apply_additional_edits_for_completion(
16934                    buffer,
16935                    completions,
16936                    completion_index,
16937                    push_to_history,
16938                    cx,
16939                )
16940            })
16941        })
16942    }
16943
16944    fn is_completion_trigger(
16945        &self,
16946        buffer: &Entity<Buffer>,
16947        position: language::Anchor,
16948        text: &str,
16949        trigger_in_words: bool,
16950        cx: &mut Context<Editor>,
16951    ) -> bool {
16952        let mut chars = text.chars();
16953        let char = if let Some(char) = chars.next() {
16954            char
16955        } else {
16956            return false;
16957        };
16958        if chars.next().is_some() {
16959            return false;
16960        }
16961
16962        let buffer = buffer.read(cx);
16963        let snapshot = buffer.snapshot();
16964        if !snapshot.settings_at(position, cx).show_completions_on_input {
16965            return false;
16966        }
16967        let classifier = snapshot.char_classifier_at(position).for_completion(true);
16968        if trigger_in_words && classifier.is_word(char) {
16969            return true;
16970        }
16971
16972        buffer.completion_triggers().contains(text)
16973    }
16974}
16975
16976impl SemanticsProvider for Entity<Project> {
16977    fn hover(
16978        &self,
16979        buffer: &Entity<Buffer>,
16980        position: text::Anchor,
16981        cx: &mut App,
16982    ) -> Option<Task<Vec<project::Hover>>> {
16983        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
16984    }
16985
16986    fn document_highlights(
16987        &self,
16988        buffer: &Entity<Buffer>,
16989        position: text::Anchor,
16990        cx: &mut App,
16991    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
16992        Some(self.update(cx, |project, cx| {
16993            project.document_highlights(buffer, position, cx)
16994        }))
16995    }
16996
16997    fn definitions(
16998        &self,
16999        buffer: &Entity<Buffer>,
17000        position: text::Anchor,
17001        kind: GotoDefinitionKind,
17002        cx: &mut App,
17003    ) -> Option<Task<Result<Vec<LocationLink>>>> {
17004        Some(self.update(cx, |project, cx| match kind {
17005            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
17006            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
17007            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
17008            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
17009        }))
17010    }
17011
17012    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
17013        // TODO: make this work for remote projects
17014        self.update(cx, |this, cx| {
17015            buffer.update(cx, |buffer, cx| {
17016                this.any_language_server_supports_inlay_hints(buffer, cx)
17017            })
17018        })
17019    }
17020
17021    fn inlay_hints(
17022        &self,
17023        buffer_handle: Entity<Buffer>,
17024        range: Range<text::Anchor>,
17025        cx: &mut App,
17026    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
17027        Some(self.update(cx, |project, cx| {
17028            project.inlay_hints(buffer_handle, range, cx)
17029        }))
17030    }
17031
17032    fn resolve_inlay_hint(
17033        &self,
17034        hint: InlayHint,
17035        buffer_handle: Entity<Buffer>,
17036        server_id: LanguageServerId,
17037        cx: &mut App,
17038    ) -> Option<Task<anyhow::Result<InlayHint>>> {
17039        Some(self.update(cx, |project, cx| {
17040            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
17041        }))
17042    }
17043
17044    fn range_for_rename(
17045        &self,
17046        buffer: &Entity<Buffer>,
17047        position: text::Anchor,
17048        cx: &mut App,
17049    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17050        Some(self.update(cx, |project, cx| {
17051            let buffer = buffer.clone();
17052            let task = project.prepare_rename(buffer.clone(), position, cx);
17053            cx.spawn(|_, mut cx| async move {
17054                Ok(match task.await? {
17055                    PrepareRenameResponse::Success(range) => Some(range),
17056                    PrepareRenameResponse::InvalidPosition => None,
17057                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17058                        // Fallback on using TreeSitter info to determine identifier range
17059                        buffer.update(&mut cx, |buffer, _| {
17060                            let snapshot = buffer.snapshot();
17061                            let (range, kind) = snapshot.surrounding_word(position);
17062                            if kind != Some(CharKind::Word) {
17063                                return None;
17064                            }
17065                            Some(
17066                                snapshot.anchor_before(range.start)
17067                                    ..snapshot.anchor_after(range.end),
17068                            )
17069                        })?
17070                    }
17071                })
17072            })
17073        }))
17074    }
17075
17076    fn perform_rename(
17077        &self,
17078        buffer: &Entity<Buffer>,
17079        position: text::Anchor,
17080        new_name: String,
17081        cx: &mut App,
17082    ) -> Option<Task<Result<ProjectTransaction>>> {
17083        Some(self.update(cx, |project, cx| {
17084            project.perform_rename(buffer.clone(), position, new_name, cx)
17085        }))
17086    }
17087}
17088
17089fn inlay_hint_settings(
17090    location: Anchor,
17091    snapshot: &MultiBufferSnapshot,
17092    cx: &mut Context<Editor>,
17093) -> InlayHintSettings {
17094    let file = snapshot.file_at(location);
17095    let language = snapshot.language_at(location).map(|l| l.name());
17096    language_settings(language, file, cx).inlay_hints
17097}
17098
17099fn consume_contiguous_rows(
17100    contiguous_row_selections: &mut Vec<Selection<Point>>,
17101    selection: &Selection<Point>,
17102    display_map: &DisplaySnapshot,
17103    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17104) -> (MultiBufferRow, MultiBufferRow) {
17105    contiguous_row_selections.push(selection.clone());
17106    let start_row = MultiBufferRow(selection.start.row);
17107    let mut end_row = ending_row(selection, display_map);
17108
17109    while let Some(next_selection) = selections.peek() {
17110        if next_selection.start.row <= end_row.0 {
17111            end_row = ending_row(next_selection, display_map);
17112            contiguous_row_selections.push(selections.next().unwrap().clone());
17113        } else {
17114            break;
17115        }
17116    }
17117    (start_row, end_row)
17118}
17119
17120fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17121    if next_selection.end.column > 0 || next_selection.is_empty() {
17122        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17123    } else {
17124        MultiBufferRow(next_selection.end.row)
17125    }
17126}
17127
17128impl EditorSnapshot {
17129    pub fn remote_selections_in_range<'a>(
17130        &'a self,
17131        range: &'a Range<Anchor>,
17132        collaboration_hub: &dyn CollaborationHub,
17133        cx: &'a App,
17134    ) -> impl 'a + Iterator<Item = RemoteSelection> {
17135        let participant_names = collaboration_hub.user_names(cx);
17136        let participant_indices = collaboration_hub.user_participant_indices(cx);
17137        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17138        let collaborators_by_replica_id = collaborators_by_peer_id
17139            .iter()
17140            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17141            .collect::<HashMap<_, _>>();
17142        self.buffer_snapshot
17143            .selections_in_range(range, false)
17144            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17145                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17146                let participant_index = participant_indices.get(&collaborator.user_id).copied();
17147                let user_name = participant_names.get(&collaborator.user_id).cloned();
17148                Some(RemoteSelection {
17149                    replica_id,
17150                    selection,
17151                    cursor_shape,
17152                    line_mode,
17153                    participant_index,
17154                    peer_id: collaborator.peer_id,
17155                    user_name,
17156                })
17157            })
17158    }
17159
17160    pub fn hunks_for_ranges(
17161        &self,
17162        ranges: impl IntoIterator<Item = Range<Point>>,
17163    ) -> Vec<MultiBufferDiffHunk> {
17164        let mut hunks = Vec::new();
17165        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17166            HashMap::default();
17167        for query_range in ranges {
17168            let query_rows =
17169                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17170            for hunk in self.buffer_snapshot.diff_hunks_in_range(
17171                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17172            ) {
17173                // Include deleted hunks that are adjacent to the query range, because
17174                // otherwise they would be missed.
17175                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
17176                if hunk.status().is_deleted() {
17177                    intersects_range |= hunk.row_range.start == query_rows.end;
17178                    intersects_range |= hunk.row_range.end == query_rows.start;
17179                }
17180                if intersects_range {
17181                    if !processed_buffer_rows
17182                        .entry(hunk.buffer_id)
17183                        .or_default()
17184                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17185                    {
17186                        continue;
17187                    }
17188                    hunks.push(hunk);
17189                }
17190            }
17191        }
17192
17193        hunks
17194    }
17195
17196    fn display_diff_hunks_for_rows<'a>(
17197        &'a self,
17198        display_rows: Range<DisplayRow>,
17199        folded_buffers: &'a HashSet<BufferId>,
17200    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17201        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17202        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17203
17204        self.buffer_snapshot
17205            .diff_hunks_in_range(buffer_start..buffer_end)
17206            .filter_map(|hunk| {
17207                if folded_buffers.contains(&hunk.buffer_id) {
17208                    return None;
17209                }
17210
17211                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17212                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17213
17214                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17215                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17216
17217                let display_hunk = if hunk_display_start.column() != 0 {
17218                    DisplayDiffHunk::Folded {
17219                        display_row: hunk_display_start.row(),
17220                    }
17221                } else {
17222                    let mut end_row = hunk_display_end.row();
17223                    if hunk_display_end.column() > 0 {
17224                        end_row.0 += 1;
17225                    }
17226                    let is_created_file = hunk.is_created_file();
17227                    DisplayDiffHunk::Unfolded {
17228                        status: hunk.status(),
17229                        diff_base_byte_range: hunk.diff_base_byte_range,
17230                        display_row_range: hunk_display_start.row()..end_row,
17231                        multi_buffer_range: Anchor::range_in_buffer(
17232                            hunk.excerpt_id,
17233                            hunk.buffer_id,
17234                            hunk.buffer_range,
17235                        ),
17236                        is_created_file,
17237                    }
17238                };
17239
17240                Some(display_hunk)
17241            })
17242    }
17243
17244    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17245        self.display_snapshot.buffer_snapshot.language_at(position)
17246    }
17247
17248    pub fn is_focused(&self) -> bool {
17249        self.is_focused
17250    }
17251
17252    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17253        self.placeholder_text.as_ref()
17254    }
17255
17256    pub fn scroll_position(&self) -> gpui::Point<f32> {
17257        self.scroll_anchor.scroll_position(&self.display_snapshot)
17258    }
17259
17260    fn gutter_dimensions(
17261        &self,
17262        font_id: FontId,
17263        font_size: Pixels,
17264        max_line_number_width: Pixels,
17265        cx: &App,
17266    ) -> Option<GutterDimensions> {
17267        if !self.show_gutter {
17268            return None;
17269        }
17270
17271        let descent = cx.text_system().descent(font_id, font_size);
17272        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17273        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17274
17275        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17276            matches!(
17277                ProjectSettings::get_global(cx).git.git_gutter,
17278                Some(GitGutterSetting::TrackedFiles)
17279            )
17280        });
17281        let gutter_settings = EditorSettings::get_global(cx).gutter;
17282        let show_line_numbers = self
17283            .show_line_numbers
17284            .unwrap_or(gutter_settings.line_numbers);
17285        let line_gutter_width = if show_line_numbers {
17286            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17287            let min_width_for_number_on_gutter = em_advance * 4.0;
17288            max_line_number_width.max(min_width_for_number_on_gutter)
17289        } else {
17290            0.0.into()
17291        };
17292
17293        let show_code_actions = self
17294            .show_code_actions
17295            .unwrap_or(gutter_settings.code_actions);
17296
17297        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17298
17299        let git_blame_entries_width =
17300            self.git_blame_gutter_max_author_length
17301                .map(|max_author_length| {
17302                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17303
17304                    /// The number of characters to dedicate to gaps and margins.
17305                    const SPACING_WIDTH: usize = 4;
17306
17307                    let max_char_count = max_author_length
17308                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17309                        + ::git::SHORT_SHA_LENGTH
17310                        + MAX_RELATIVE_TIMESTAMP.len()
17311                        + SPACING_WIDTH;
17312
17313                    em_advance * max_char_count
17314                });
17315
17316        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17317        left_padding += if show_code_actions || show_runnables {
17318            em_width * 3.0
17319        } else if show_git_gutter && show_line_numbers {
17320            em_width * 2.0
17321        } else if show_git_gutter || show_line_numbers {
17322            em_width
17323        } else {
17324            px(0.)
17325        };
17326
17327        let right_padding = if gutter_settings.folds && show_line_numbers {
17328            em_width * 4.0
17329        } else if gutter_settings.folds {
17330            em_width * 3.0
17331        } else if show_line_numbers {
17332            em_width
17333        } else {
17334            px(0.)
17335        };
17336
17337        Some(GutterDimensions {
17338            left_padding,
17339            right_padding,
17340            width: line_gutter_width + left_padding + right_padding,
17341            margin: -descent,
17342            git_blame_entries_width,
17343        })
17344    }
17345
17346    pub fn render_crease_toggle(
17347        &self,
17348        buffer_row: MultiBufferRow,
17349        row_contains_cursor: bool,
17350        editor: Entity<Editor>,
17351        window: &mut Window,
17352        cx: &mut App,
17353    ) -> Option<AnyElement> {
17354        let folded = self.is_line_folded(buffer_row);
17355        let mut is_foldable = false;
17356
17357        if let Some(crease) = self
17358            .crease_snapshot
17359            .query_row(buffer_row, &self.buffer_snapshot)
17360        {
17361            is_foldable = true;
17362            match crease {
17363                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17364                    if let Some(render_toggle) = render_toggle {
17365                        let toggle_callback =
17366                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17367                                if folded {
17368                                    editor.update(cx, |editor, cx| {
17369                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17370                                    });
17371                                } else {
17372                                    editor.update(cx, |editor, cx| {
17373                                        editor.unfold_at(
17374                                            &crate::UnfoldAt { buffer_row },
17375                                            window,
17376                                            cx,
17377                                        )
17378                                    });
17379                                }
17380                            });
17381                        return Some((render_toggle)(
17382                            buffer_row,
17383                            folded,
17384                            toggle_callback,
17385                            window,
17386                            cx,
17387                        ));
17388                    }
17389                }
17390            }
17391        }
17392
17393        is_foldable |= self.starts_indent(buffer_row);
17394
17395        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17396            Some(
17397                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17398                    .toggle_state(folded)
17399                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17400                        if folded {
17401                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17402                        } else {
17403                            this.fold_at(&FoldAt { buffer_row }, window, cx);
17404                        }
17405                    }))
17406                    .into_any_element(),
17407            )
17408        } else {
17409            None
17410        }
17411    }
17412
17413    pub fn render_crease_trailer(
17414        &self,
17415        buffer_row: MultiBufferRow,
17416        window: &mut Window,
17417        cx: &mut App,
17418    ) -> Option<AnyElement> {
17419        let folded = self.is_line_folded(buffer_row);
17420        if let Crease::Inline { render_trailer, .. } = self
17421            .crease_snapshot
17422            .query_row(buffer_row, &self.buffer_snapshot)?
17423        {
17424            let render_trailer = render_trailer.as_ref()?;
17425            Some(render_trailer(buffer_row, folded, window, cx))
17426        } else {
17427            None
17428        }
17429    }
17430}
17431
17432impl Deref for EditorSnapshot {
17433    type Target = DisplaySnapshot;
17434
17435    fn deref(&self) -> &Self::Target {
17436        &self.display_snapshot
17437    }
17438}
17439
17440#[derive(Clone, Debug, PartialEq, Eq)]
17441pub enum EditorEvent {
17442    InputIgnored {
17443        text: Arc<str>,
17444    },
17445    InputHandled {
17446        utf16_range_to_replace: Option<Range<isize>>,
17447        text: Arc<str>,
17448    },
17449    ExcerptsAdded {
17450        buffer: Entity<Buffer>,
17451        predecessor: ExcerptId,
17452        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17453    },
17454    ExcerptsRemoved {
17455        ids: Vec<ExcerptId>,
17456    },
17457    BufferFoldToggled {
17458        ids: Vec<ExcerptId>,
17459        folded: bool,
17460    },
17461    ExcerptsEdited {
17462        ids: Vec<ExcerptId>,
17463    },
17464    ExcerptsExpanded {
17465        ids: Vec<ExcerptId>,
17466    },
17467    BufferEdited,
17468    Edited {
17469        transaction_id: clock::Lamport,
17470    },
17471    Reparsed(BufferId),
17472    Focused,
17473    FocusedIn,
17474    Blurred,
17475    DirtyChanged,
17476    Saved,
17477    TitleChanged,
17478    DiffBaseChanged,
17479    SelectionsChanged {
17480        local: bool,
17481    },
17482    ScrollPositionChanged {
17483        local: bool,
17484        autoscroll: bool,
17485    },
17486    Closed,
17487    TransactionUndone {
17488        transaction_id: clock::Lamport,
17489    },
17490    TransactionBegun {
17491        transaction_id: clock::Lamport,
17492    },
17493    Reloaded,
17494    CursorShapeChanged,
17495}
17496
17497impl EventEmitter<EditorEvent> for Editor {}
17498
17499impl Focusable for Editor {
17500    fn focus_handle(&self, _cx: &App) -> FocusHandle {
17501        self.focus_handle.clone()
17502    }
17503}
17504
17505impl Render for Editor {
17506    fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17507        let settings = ThemeSettings::get_global(cx);
17508
17509        let mut text_style = match self.mode {
17510            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17511                color: cx.theme().colors().editor_foreground,
17512                font_family: settings.ui_font.family.clone(),
17513                font_features: settings.ui_font.features.clone(),
17514                font_fallbacks: settings.ui_font.fallbacks.clone(),
17515                font_size: rems(0.875).into(),
17516                font_weight: settings.ui_font.weight,
17517                line_height: relative(settings.buffer_line_height.value()),
17518                ..Default::default()
17519            },
17520            EditorMode::Full => TextStyle {
17521                color: cx.theme().colors().editor_foreground,
17522                font_family: settings.buffer_font.family.clone(),
17523                font_features: settings.buffer_font.features.clone(),
17524                font_fallbacks: settings.buffer_font.fallbacks.clone(),
17525                font_size: settings.buffer_font_size(cx).into(),
17526                font_weight: settings.buffer_font.weight,
17527                line_height: relative(settings.buffer_line_height.value()),
17528                ..Default::default()
17529            },
17530        };
17531        if let Some(text_style_refinement) = &self.text_style_refinement {
17532            text_style.refine(text_style_refinement)
17533        }
17534
17535        let background = match self.mode {
17536            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17537            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17538            EditorMode::Full => cx.theme().colors().editor_background,
17539        };
17540
17541        EditorElement::new(
17542            &cx.entity(),
17543            EditorStyle {
17544                background,
17545                local_player: cx.theme().players().local(),
17546                text: text_style,
17547                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17548                syntax: cx.theme().syntax().clone(),
17549                status: cx.theme().status().clone(),
17550                inlay_hints_style: make_inlay_hints_style(cx),
17551                inline_completion_styles: make_suggestion_styles(cx),
17552                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17553            },
17554        )
17555    }
17556}
17557
17558impl EntityInputHandler for Editor {
17559    fn text_for_range(
17560        &mut self,
17561        range_utf16: Range<usize>,
17562        adjusted_range: &mut Option<Range<usize>>,
17563        _: &mut Window,
17564        cx: &mut Context<Self>,
17565    ) -> Option<String> {
17566        let snapshot = self.buffer.read(cx).read(cx);
17567        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17568        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17569        if (start.0..end.0) != range_utf16 {
17570            adjusted_range.replace(start.0..end.0);
17571        }
17572        Some(snapshot.text_for_range(start..end).collect())
17573    }
17574
17575    fn selected_text_range(
17576        &mut self,
17577        ignore_disabled_input: bool,
17578        _: &mut Window,
17579        cx: &mut Context<Self>,
17580    ) -> Option<UTF16Selection> {
17581        // Prevent the IME menu from appearing when holding down an alphabetic key
17582        // while input is disabled.
17583        if !ignore_disabled_input && !self.input_enabled {
17584            return None;
17585        }
17586
17587        let selection = self.selections.newest::<OffsetUtf16>(cx);
17588        let range = selection.range();
17589
17590        Some(UTF16Selection {
17591            range: range.start.0..range.end.0,
17592            reversed: selection.reversed,
17593        })
17594    }
17595
17596    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17597        let snapshot = self.buffer.read(cx).read(cx);
17598        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17599        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17600    }
17601
17602    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17603        self.clear_highlights::<InputComposition>(cx);
17604        self.ime_transaction.take();
17605    }
17606
17607    fn replace_text_in_range(
17608        &mut self,
17609        range_utf16: Option<Range<usize>>,
17610        text: &str,
17611        window: &mut Window,
17612        cx: &mut Context<Self>,
17613    ) {
17614        if !self.input_enabled {
17615            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17616            return;
17617        }
17618
17619        self.transact(window, cx, |this, window, cx| {
17620            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17621                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17622                Some(this.selection_replacement_ranges(range_utf16, cx))
17623            } else {
17624                this.marked_text_ranges(cx)
17625            };
17626
17627            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17628                let newest_selection_id = this.selections.newest_anchor().id;
17629                this.selections
17630                    .all::<OffsetUtf16>(cx)
17631                    .iter()
17632                    .zip(ranges_to_replace.iter())
17633                    .find_map(|(selection, range)| {
17634                        if selection.id == newest_selection_id {
17635                            Some(
17636                                (range.start.0 as isize - selection.head().0 as isize)
17637                                    ..(range.end.0 as isize - selection.head().0 as isize),
17638                            )
17639                        } else {
17640                            None
17641                        }
17642                    })
17643            });
17644
17645            cx.emit(EditorEvent::InputHandled {
17646                utf16_range_to_replace: range_to_replace,
17647                text: text.into(),
17648            });
17649
17650            if let Some(new_selected_ranges) = new_selected_ranges {
17651                this.change_selections(None, window, cx, |selections| {
17652                    selections.select_ranges(new_selected_ranges)
17653                });
17654                this.backspace(&Default::default(), window, cx);
17655            }
17656
17657            this.handle_input(text, window, cx);
17658        });
17659
17660        if let Some(transaction) = self.ime_transaction {
17661            self.buffer.update(cx, |buffer, cx| {
17662                buffer.group_until_transaction(transaction, cx);
17663            });
17664        }
17665
17666        self.unmark_text(window, cx);
17667    }
17668
17669    fn replace_and_mark_text_in_range(
17670        &mut self,
17671        range_utf16: Option<Range<usize>>,
17672        text: &str,
17673        new_selected_range_utf16: Option<Range<usize>>,
17674        window: &mut Window,
17675        cx: &mut Context<Self>,
17676    ) {
17677        if !self.input_enabled {
17678            return;
17679        }
17680
17681        let transaction = self.transact(window, cx, |this, window, cx| {
17682            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17683                let snapshot = this.buffer.read(cx).read(cx);
17684                if let Some(relative_range_utf16) = range_utf16.as_ref() {
17685                    for marked_range in &mut marked_ranges {
17686                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17687                        marked_range.start.0 += relative_range_utf16.start;
17688                        marked_range.start =
17689                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17690                        marked_range.end =
17691                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17692                    }
17693                }
17694                Some(marked_ranges)
17695            } else if let Some(range_utf16) = range_utf16 {
17696                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17697                Some(this.selection_replacement_ranges(range_utf16, cx))
17698            } else {
17699                None
17700            };
17701
17702            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17703                let newest_selection_id = this.selections.newest_anchor().id;
17704                this.selections
17705                    .all::<OffsetUtf16>(cx)
17706                    .iter()
17707                    .zip(ranges_to_replace.iter())
17708                    .find_map(|(selection, range)| {
17709                        if selection.id == newest_selection_id {
17710                            Some(
17711                                (range.start.0 as isize - selection.head().0 as isize)
17712                                    ..(range.end.0 as isize - selection.head().0 as isize),
17713                            )
17714                        } else {
17715                            None
17716                        }
17717                    })
17718            });
17719
17720            cx.emit(EditorEvent::InputHandled {
17721                utf16_range_to_replace: range_to_replace,
17722                text: text.into(),
17723            });
17724
17725            if let Some(ranges) = ranges_to_replace {
17726                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17727            }
17728
17729            let marked_ranges = {
17730                let snapshot = this.buffer.read(cx).read(cx);
17731                this.selections
17732                    .disjoint_anchors()
17733                    .iter()
17734                    .map(|selection| {
17735                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17736                    })
17737                    .collect::<Vec<_>>()
17738            };
17739
17740            if text.is_empty() {
17741                this.unmark_text(window, cx);
17742            } else {
17743                this.highlight_text::<InputComposition>(
17744                    marked_ranges.clone(),
17745                    HighlightStyle {
17746                        underline: Some(UnderlineStyle {
17747                            thickness: px(1.),
17748                            color: None,
17749                            wavy: false,
17750                        }),
17751                        ..Default::default()
17752                    },
17753                    cx,
17754                );
17755            }
17756
17757            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17758            let use_autoclose = this.use_autoclose;
17759            let use_auto_surround = this.use_auto_surround;
17760            this.set_use_autoclose(false);
17761            this.set_use_auto_surround(false);
17762            this.handle_input(text, window, cx);
17763            this.set_use_autoclose(use_autoclose);
17764            this.set_use_auto_surround(use_auto_surround);
17765
17766            if let Some(new_selected_range) = new_selected_range_utf16 {
17767                let snapshot = this.buffer.read(cx).read(cx);
17768                let new_selected_ranges = marked_ranges
17769                    .into_iter()
17770                    .map(|marked_range| {
17771                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17772                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17773                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17774                        snapshot.clip_offset_utf16(new_start, Bias::Left)
17775                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17776                    })
17777                    .collect::<Vec<_>>();
17778
17779                drop(snapshot);
17780                this.change_selections(None, window, cx, |selections| {
17781                    selections.select_ranges(new_selected_ranges)
17782                });
17783            }
17784        });
17785
17786        self.ime_transaction = self.ime_transaction.or(transaction);
17787        if let Some(transaction) = self.ime_transaction {
17788            self.buffer.update(cx, |buffer, cx| {
17789                buffer.group_until_transaction(transaction, cx);
17790            });
17791        }
17792
17793        if self.text_highlights::<InputComposition>(cx).is_none() {
17794            self.ime_transaction.take();
17795        }
17796    }
17797
17798    fn bounds_for_range(
17799        &mut self,
17800        range_utf16: Range<usize>,
17801        element_bounds: gpui::Bounds<Pixels>,
17802        window: &mut Window,
17803        cx: &mut Context<Self>,
17804    ) -> Option<gpui::Bounds<Pixels>> {
17805        let text_layout_details = self.text_layout_details(window);
17806        let gpui::Size {
17807            width: em_width,
17808            height: line_height,
17809        } = self.character_size(window);
17810
17811        let snapshot = self.snapshot(window, cx);
17812        let scroll_position = snapshot.scroll_position();
17813        let scroll_left = scroll_position.x * em_width;
17814
17815        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17816        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17817            + self.gutter_dimensions.width
17818            + self.gutter_dimensions.margin;
17819        let y = line_height * (start.row().as_f32() - scroll_position.y);
17820
17821        Some(Bounds {
17822            origin: element_bounds.origin + point(x, y),
17823            size: size(em_width, line_height),
17824        })
17825    }
17826
17827    fn character_index_for_point(
17828        &mut self,
17829        point: gpui::Point<Pixels>,
17830        _window: &mut Window,
17831        _cx: &mut Context<Self>,
17832    ) -> Option<usize> {
17833        let position_map = self.last_position_map.as_ref()?;
17834        if !position_map.text_hitbox.contains(&point) {
17835            return None;
17836        }
17837        let display_point = position_map.point_for_position(point).previous_valid;
17838        let anchor = position_map
17839            .snapshot
17840            .display_point_to_anchor(display_point, Bias::Left);
17841        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17842        Some(utf16_offset.0)
17843    }
17844}
17845
17846trait SelectionExt {
17847    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17848    fn spanned_rows(
17849        &self,
17850        include_end_if_at_line_start: bool,
17851        map: &DisplaySnapshot,
17852    ) -> Range<MultiBufferRow>;
17853}
17854
17855impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17856    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17857        let start = self
17858            .start
17859            .to_point(&map.buffer_snapshot)
17860            .to_display_point(map);
17861        let end = self
17862            .end
17863            .to_point(&map.buffer_snapshot)
17864            .to_display_point(map);
17865        if self.reversed {
17866            end..start
17867        } else {
17868            start..end
17869        }
17870    }
17871
17872    fn spanned_rows(
17873        &self,
17874        include_end_if_at_line_start: bool,
17875        map: &DisplaySnapshot,
17876    ) -> Range<MultiBufferRow> {
17877        let start = self.start.to_point(&map.buffer_snapshot);
17878        let mut end = self.end.to_point(&map.buffer_snapshot);
17879        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17880            end.row -= 1;
17881        }
17882
17883        let buffer_start = map.prev_line_boundary(start).0;
17884        let buffer_end = map.next_line_boundary(end).0;
17885        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17886    }
17887}
17888
17889impl<T: InvalidationRegion> InvalidationStack<T> {
17890    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17891    where
17892        S: Clone + ToOffset,
17893    {
17894        while let Some(region) = self.last() {
17895            let all_selections_inside_invalidation_ranges =
17896                if selections.len() == region.ranges().len() {
17897                    selections
17898                        .iter()
17899                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17900                        .all(|(selection, invalidation_range)| {
17901                            let head = selection.head().to_offset(buffer);
17902                            invalidation_range.start <= head && invalidation_range.end >= head
17903                        })
17904                } else {
17905                    false
17906                };
17907
17908            if all_selections_inside_invalidation_ranges {
17909                break;
17910            } else {
17911                self.pop();
17912            }
17913        }
17914    }
17915}
17916
17917impl<T> Default for InvalidationStack<T> {
17918    fn default() -> Self {
17919        Self(Default::default())
17920    }
17921}
17922
17923impl<T> Deref for InvalidationStack<T> {
17924    type Target = Vec<T>;
17925
17926    fn deref(&self) -> &Self::Target {
17927        &self.0
17928    }
17929}
17930
17931impl<T> DerefMut for InvalidationStack<T> {
17932    fn deref_mut(&mut self) -> &mut Self::Target {
17933        &mut self.0
17934    }
17935}
17936
17937impl InvalidationRegion for SnippetState {
17938    fn ranges(&self) -> &[Range<Anchor>] {
17939        &self.ranges[self.active_index]
17940    }
17941}
17942
17943pub fn diagnostic_block_renderer(
17944    diagnostic: Diagnostic,
17945    max_message_rows: Option<u8>,
17946    allow_closing: bool,
17947) -> RenderBlock {
17948    let (text_without_backticks, code_ranges) =
17949        highlight_diagnostic_message(&diagnostic, max_message_rows);
17950
17951    Arc::new(move |cx: &mut BlockContext| {
17952        let group_id: SharedString = cx.block_id.to_string().into();
17953
17954        let mut text_style = cx.window.text_style().clone();
17955        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17956        let theme_settings = ThemeSettings::get_global(cx);
17957        text_style.font_family = theme_settings.buffer_font.family.clone();
17958        text_style.font_style = theme_settings.buffer_font.style;
17959        text_style.font_features = theme_settings.buffer_font.features.clone();
17960        text_style.font_weight = theme_settings.buffer_font.weight;
17961
17962        let multi_line_diagnostic = diagnostic.message.contains('\n');
17963
17964        let buttons = |diagnostic: &Diagnostic| {
17965            if multi_line_diagnostic {
17966                v_flex()
17967            } else {
17968                h_flex()
17969            }
17970            .when(allow_closing, |div| {
17971                div.children(diagnostic.is_primary.then(|| {
17972                    IconButton::new("close-block", IconName::XCircle)
17973                        .icon_color(Color::Muted)
17974                        .size(ButtonSize::Compact)
17975                        .style(ButtonStyle::Transparent)
17976                        .visible_on_hover(group_id.clone())
17977                        .on_click(move |_click, window, cx| {
17978                            window.dispatch_action(Box::new(Cancel), cx)
17979                        })
17980                        .tooltip(|window, cx| {
17981                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
17982                        })
17983                }))
17984            })
17985            .child(
17986                IconButton::new("copy-block", IconName::Copy)
17987                    .icon_color(Color::Muted)
17988                    .size(ButtonSize::Compact)
17989                    .style(ButtonStyle::Transparent)
17990                    .visible_on_hover(group_id.clone())
17991                    .on_click({
17992                        let message = diagnostic.message.clone();
17993                        move |_click, _, cx| {
17994                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
17995                        }
17996                    })
17997                    .tooltip(Tooltip::text("Copy diagnostic message")),
17998            )
17999        };
18000
18001        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
18002            AvailableSpace::min_size(),
18003            cx.window,
18004            cx.app,
18005        );
18006
18007        h_flex()
18008            .id(cx.block_id)
18009            .group(group_id.clone())
18010            .relative()
18011            .size_full()
18012            .block_mouse_down()
18013            .pl(cx.gutter_dimensions.width)
18014            .w(cx.max_width - cx.gutter_dimensions.full_width())
18015            .child(
18016                div()
18017                    .flex()
18018                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
18019                    .flex_shrink(),
18020            )
18021            .child(buttons(&diagnostic))
18022            .child(div().flex().flex_shrink_0().child(
18023                StyledText::new(text_without_backticks.clone()).with_default_highlights(
18024                    &text_style,
18025                    code_ranges.iter().map(|range| {
18026                        (
18027                            range.clone(),
18028                            HighlightStyle {
18029                                font_weight: Some(FontWeight::BOLD),
18030                                ..Default::default()
18031                            },
18032                        )
18033                    }),
18034                ),
18035            ))
18036            .into_any_element()
18037    })
18038}
18039
18040fn inline_completion_edit_text(
18041    current_snapshot: &BufferSnapshot,
18042    edits: &[(Range<Anchor>, String)],
18043    edit_preview: &EditPreview,
18044    include_deletions: bool,
18045    cx: &App,
18046) -> HighlightedText {
18047    let edits = edits
18048        .iter()
18049        .map(|(anchor, text)| {
18050            (
18051                anchor.start.text_anchor..anchor.end.text_anchor,
18052                text.clone(),
18053            )
18054        })
18055        .collect::<Vec<_>>();
18056
18057    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18058}
18059
18060pub fn highlight_diagnostic_message(
18061    diagnostic: &Diagnostic,
18062    mut max_message_rows: Option<u8>,
18063) -> (SharedString, Vec<Range<usize>>) {
18064    let mut text_without_backticks = String::new();
18065    let mut code_ranges = Vec::new();
18066
18067    if let Some(source) = &diagnostic.source {
18068        text_without_backticks.push_str(source);
18069        code_ranges.push(0..source.len());
18070        text_without_backticks.push_str(": ");
18071    }
18072
18073    let mut prev_offset = 0;
18074    let mut in_code_block = false;
18075    let has_row_limit = max_message_rows.is_some();
18076    let mut newline_indices = diagnostic
18077        .message
18078        .match_indices('\n')
18079        .filter(|_| has_row_limit)
18080        .map(|(ix, _)| ix)
18081        .fuse()
18082        .peekable();
18083
18084    for (quote_ix, _) in diagnostic
18085        .message
18086        .match_indices('`')
18087        .chain([(diagnostic.message.len(), "")])
18088    {
18089        let mut first_newline_ix = None;
18090        let mut last_newline_ix = None;
18091        while let Some(newline_ix) = newline_indices.peek() {
18092            if *newline_ix < quote_ix {
18093                if first_newline_ix.is_none() {
18094                    first_newline_ix = Some(*newline_ix);
18095                }
18096                last_newline_ix = Some(*newline_ix);
18097
18098                if let Some(rows_left) = &mut max_message_rows {
18099                    if *rows_left == 0 {
18100                        break;
18101                    } else {
18102                        *rows_left -= 1;
18103                    }
18104                }
18105                let _ = newline_indices.next();
18106            } else {
18107                break;
18108            }
18109        }
18110        let prev_len = text_without_backticks.len();
18111        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18112        text_without_backticks.push_str(new_text);
18113        if in_code_block {
18114            code_ranges.push(prev_len..text_without_backticks.len());
18115        }
18116        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18117        in_code_block = !in_code_block;
18118        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18119            text_without_backticks.push_str("...");
18120            break;
18121        }
18122    }
18123
18124    (text_without_backticks.into(), code_ranges)
18125}
18126
18127fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18128    match severity {
18129        DiagnosticSeverity::ERROR => colors.error,
18130        DiagnosticSeverity::WARNING => colors.warning,
18131        DiagnosticSeverity::INFORMATION => colors.info,
18132        DiagnosticSeverity::HINT => colors.info,
18133        _ => colors.ignored,
18134    }
18135}
18136
18137pub fn styled_runs_for_code_label<'a>(
18138    label: &'a CodeLabel,
18139    syntax_theme: &'a theme::SyntaxTheme,
18140) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18141    let fade_out = HighlightStyle {
18142        fade_out: Some(0.35),
18143        ..Default::default()
18144    };
18145
18146    let mut prev_end = label.filter_range.end;
18147    label
18148        .runs
18149        .iter()
18150        .enumerate()
18151        .flat_map(move |(ix, (range, highlight_id))| {
18152            let style = if let Some(style) = highlight_id.style(syntax_theme) {
18153                style
18154            } else {
18155                return Default::default();
18156            };
18157            let mut muted_style = style;
18158            muted_style.highlight(fade_out);
18159
18160            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18161            if range.start >= label.filter_range.end {
18162                if range.start > prev_end {
18163                    runs.push((prev_end..range.start, fade_out));
18164                }
18165                runs.push((range.clone(), muted_style));
18166            } else if range.end <= label.filter_range.end {
18167                runs.push((range.clone(), style));
18168            } else {
18169                runs.push((range.start..label.filter_range.end, style));
18170                runs.push((label.filter_range.end..range.end, muted_style));
18171            }
18172            prev_end = cmp::max(prev_end, range.end);
18173
18174            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18175                runs.push((prev_end..label.text.len(), fade_out));
18176            }
18177
18178            runs
18179        })
18180}
18181
18182pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18183    let mut prev_index = 0;
18184    let mut prev_codepoint: Option<char> = None;
18185    text.char_indices()
18186        .chain([(text.len(), '\0')])
18187        .filter_map(move |(index, codepoint)| {
18188            let prev_codepoint = prev_codepoint.replace(codepoint)?;
18189            let is_boundary = index == text.len()
18190                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18191                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18192            if is_boundary {
18193                let chunk = &text[prev_index..index];
18194                prev_index = index;
18195                Some(chunk)
18196            } else {
18197                None
18198            }
18199        })
18200}
18201
18202pub trait RangeToAnchorExt: Sized {
18203    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18204
18205    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18206        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18207        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18208    }
18209}
18210
18211impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18212    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18213        let start_offset = self.start.to_offset(snapshot);
18214        let end_offset = self.end.to_offset(snapshot);
18215        if start_offset == end_offset {
18216            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18217        } else {
18218            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18219        }
18220    }
18221}
18222
18223pub trait RowExt {
18224    fn as_f32(&self) -> f32;
18225
18226    fn next_row(&self) -> Self;
18227
18228    fn previous_row(&self) -> Self;
18229
18230    fn minus(&self, other: Self) -> u32;
18231}
18232
18233impl RowExt for DisplayRow {
18234    fn as_f32(&self) -> f32 {
18235        self.0 as f32
18236    }
18237
18238    fn next_row(&self) -> Self {
18239        Self(self.0 + 1)
18240    }
18241
18242    fn previous_row(&self) -> Self {
18243        Self(self.0.saturating_sub(1))
18244    }
18245
18246    fn minus(&self, other: Self) -> u32 {
18247        self.0 - other.0
18248    }
18249}
18250
18251impl RowExt for MultiBufferRow {
18252    fn as_f32(&self) -> f32 {
18253        self.0 as f32
18254    }
18255
18256    fn next_row(&self) -> Self {
18257        Self(self.0 + 1)
18258    }
18259
18260    fn previous_row(&self) -> Self {
18261        Self(self.0.saturating_sub(1))
18262    }
18263
18264    fn minus(&self, other: Self) -> u32 {
18265        self.0 - other.0
18266    }
18267}
18268
18269trait RowRangeExt {
18270    type Row;
18271
18272    fn len(&self) -> usize;
18273
18274    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18275}
18276
18277impl RowRangeExt for Range<MultiBufferRow> {
18278    type Row = MultiBufferRow;
18279
18280    fn len(&self) -> usize {
18281        (self.end.0 - self.start.0) as usize
18282    }
18283
18284    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18285        (self.start.0..self.end.0).map(MultiBufferRow)
18286    }
18287}
18288
18289impl RowRangeExt for Range<DisplayRow> {
18290    type Row = DisplayRow;
18291
18292    fn len(&self) -> usize {
18293        (self.end.0 - self.start.0) as usize
18294    }
18295
18296    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18297        (self.start.0..self.end.0).map(DisplayRow)
18298    }
18299}
18300
18301/// If select range has more than one line, we
18302/// just point the cursor to range.start.
18303fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18304    if range.start.row == range.end.row {
18305        range
18306    } else {
18307        range.start..range.start
18308    }
18309}
18310pub struct KillRing(ClipboardItem);
18311impl Global for KillRing {}
18312
18313const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18314
18315fn all_edits_insertions_or_deletions(
18316    edits: &Vec<(Range<Anchor>, String)>,
18317    snapshot: &MultiBufferSnapshot,
18318) -> bool {
18319    let mut all_insertions = true;
18320    let mut all_deletions = true;
18321
18322    for (range, new_text) in edits.iter() {
18323        let range_is_empty = range.to_offset(&snapshot).is_empty();
18324        let text_is_empty = new_text.is_empty();
18325
18326        if range_is_empty != text_is_empty {
18327            if range_is_empty {
18328                all_deletions = false;
18329            } else {
18330                all_insertions = false;
18331            }
18332        } else {
18333            return false;
18334        }
18335
18336        if !all_insertions && !all_deletions {
18337            return false;
18338        }
18339    }
18340    all_insertions || all_deletions
18341}
18342
18343#[derive(Debug, Clone, Copy, PartialEq)]
18344pub struct LineHighlight {
18345    pub background: Background,
18346    pub border: Option<gpui::Hsla>,
18347}
18348
18349impl From<Hsla> for LineHighlight {
18350    fn from(hsla: Hsla) -> Self {
18351        Self {
18352            background: hsla.into(),
18353            border: None,
18354        }
18355    }
18356}
18357
18358impl From<Background> for LineHighlight {
18359    fn from(background: Background) -> Self {
18360        Self {
18361            background,
18362            border: None,
18363        }
18364    }
18365}