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#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  609pub enum IsVimMode {
  610    Yes,
  611    No,
  612}
  613
  614/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  615///
  616/// See the [module level documentation](self) for more information.
  617pub struct Editor {
  618    focus_handle: FocusHandle,
  619    last_focused_descendant: Option<WeakFocusHandle>,
  620    /// The text buffer being edited
  621    buffer: Entity<MultiBuffer>,
  622    /// Map of how text in the buffer should be displayed.
  623    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  624    pub display_map: Entity<DisplayMap>,
  625    pub selections: SelectionsCollection,
  626    pub scroll_manager: ScrollManager,
  627    /// When inline assist editors are linked, they all render cursors because
  628    /// typing enters text into each of them, even the ones that aren't focused.
  629    pub(crate) show_cursor_when_unfocused: bool,
  630    columnar_selection_tail: Option<Anchor>,
  631    add_selections_state: Option<AddSelectionsState>,
  632    select_next_state: Option<SelectNextState>,
  633    select_prev_state: Option<SelectNextState>,
  634    selection_history: SelectionHistory,
  635    autoclose_regions: Vec<AutocloseRegion>,
  636    snippet_stack: InvalidationStack<SnippetState>,
  637    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  638    ime_transaction: Option<TransactionId>,
  639    active_diagnostics: Option<ActiveDiagnosticGroup>,
  640    show_inline_diagnostics: bool,
  641    inline_diagnostics_update: Task<()>,
  642    inline_diagnostics_enabled: bool,
  643    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  644    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  645
  646    // TODO: make this a access method
  647    pub project: Option<Entity<Project>>,
  648    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  649    completion_provider: Option<Box<dyn CompletionProvider>>,
  650    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  651    blink_manager: Entity<BlinkManager>,
  652    show_cursor_names: bool,
  653    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  654    pub show_local_selections: bool,
  655    mode: EditorMode,
  656    show_breadcrumbs: bool,
  657    show_gutter: bool,
  658    show_scrollbars: bool,
  659    show_line_numbers: Option<bool>,
  660    use_relative_line_numbers: Option<bool>,
  661    show_git_diff_gutter: Option<bool>,
  662    show_code_actions: Option<bool>,
  663    show_runnables: Option<bool>,
  664    show_wrap_guides: Option<bool>,
  665    show_indent_guides: Option<bool>,
  666    placeholder_text: Option<Arc<str>>,
  667    highlight_order: usize,
  668    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  669    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  670    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  671    scrollbar_marker_state: ScrollbarMarkerState,
  672    active_indent_guides_state: ActiveIndentGuidesState,
  673    nav_history: Option<ItemNavHistory>,
  674    context_menu: RefCell<Option<CodeContextMenu>>,
  675    mouse_context_menu: Option<MouseContextMenu>,
  676    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  677    signature_help_state: SignatureHelpState,
  678    auto_signature_help: Option<bool>,
  679    find_all_references_task_sources: Vec<Anchor>,
  680    next_completion_id: CompletionId,
  681    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  682    code_actions_task: Option<Task<Result<()>>>,
  683    selection_highlight_task: Option<Task<()>>,
  684    document_highlights_task: Option<Task<()>>,
  685    linked_editing_range_task: Option<Task<Option<()>>>,
  686    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  687    pending_rename: Option<RenameState>,
  688    searchable: bool,
  689    cursor_shape: CursorShape,
  690    current_line_highlight: Option<CurrentLineHighlight>,
  691    collapse_matches: bool,
  692    autoindent_mode: Option<AutoindentMode>,
  693    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  694    input_enabled: bool,
  695    use_modal_editing: bool,
  696    read_only: bool,
  697    leader_peer_id: Option<PeerId>,
  698    remote_id: Option<ViewId>,
  699    hover_state: HoverState,
  700    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  701    gutter_hovered: bool,
  702    hovered_link_state: Option<HoveredLinkState>,
  703    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  704    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  705    active_inline_completion: Option<InlineCompletionState>,
  706    /// Used to prevent flickering as the user types while the menu is open
  707    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  708    edit_prediction_settings: EditPredictionSettings,
  709    inline_completions_hidden_for_vim_mode: bool,
  710    show_inline_completions_override: Option<bool>,
  711    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  712    edit_prediction_preview: EditPredictionPreview,
  713    edit_prediction_indent_conflict: bool,
  714    edit_prediction_requires_modifier_in_indent_conflict: bool,
  715    inlay_hint_cache: InlayHintCache,
  716    next_inlay_id: usize,
  717    _subscriptions: Vec<Subscription>,
  718    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  719    gutter_dimensions: GutterDimensions,
  720    style: Option<EditorStyle>,
  721    text_style_refinement: Option<TextStyleRefinement>,
  722    next_editor_action_id: EditorActionId,
  723    editor_actions:
  724        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  725    use_autoclose: bool,
  726    use_auto_surround: bool,
  727    auto_replace_emoji_shortcode: bool,
  728    show_git_blame_gutter: bool,
  729    show_git_blame_inline: bool,
  730    show_git_blame_inline_delay_task: Option<Task<()>>,
  731    git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
  732    git_blame_inline_enabled: bool,
  733    serialize_dirty_buffers: bool,
  734    show_selection_menu: Option<bool>,
  735    blame: Option<Entity<GitBlame>>,
  736    blame_subscription: Option<Subscription>,
  737    custom_context_menu: Option<
  738        Box<
  739            dyn 'static
  740                + Fn(
  741                    &mut Self,
  742                    DisplayPoint,
  743                    &mut Window,
  744                    &mut Context<Self>,
  745                ) -> Option<Entity<ui::ContextMenu>>,
  746        >,
  747    >,
  748    last_bounds: Option<Bounds<Pixels>>,
  749    last_position_map: Option<Rc<PositionMap>>,
  750    expect_bounds_change: Option<Bounds<Pixels>>,
  751    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  752    tasks_update_task: Option<Task<()>>,
  753    in_project_search: bool,
  754    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  755    breadcrumb_header: Option<String>,
  756    focused_block: Option<FocusedBlock>,
  757    next_scroll_position: NextScrollCursorCenterTopBottom,
  758    addons: HashMap<TypeId, Box<dyn Addon>>,
  759    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  760    load_diff_task: Option<Shared<Task<()>>>,
  761    selection_mark_mode: bool,
  762    toggle_fold_multiple_buffers: Task<()>,
  763    _scroll_cursor_center_top_bottom_task: Task<()>,
  764    serialize_selections: Task<()>,
  765}
  766
  767#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  768enum NextScrollCursorCenterTopBottom {
  769    #[default]
  770    Center,
  771    Top,
  772    Bottom,
  773}
  774
  775impl NextScrollCursorCenterTopBottom {
  776    fn next(&self) -> Self {
  777        match self {
  778            Self::Center => Self::Top,
  779            Self::Top => Self::Bottom,
  780            Self::Bottom => Self::Center,
  781        }
  782    }
  783}
  784
  785#[derive(Clone)]
  786pub struct EditorSnapshot {
  787    pub mode: EditorMode,
  788    show_gutter: bool,
  789    show_line_numbers: Option<bool>,
  790    show_git_diff_gutter: Option<bool>,
  791    show_code_actions: Option<bool>,
  792    show_runnables: Option<bool>,
  793    git_blame_gutter_max_author_length: Option<usize>,
  794    pub display_snapshot: DisplaySnapshot,
  795    pub placeholder_text: Option<Arc<str>>,
  796    is_focused: bool,
  797    scroll_anchor: ScrollAnchor,
  798    ongoing_scroll: OngoingScroll,
  799    current_line_highlight: CurrentLineHighlight,
  800    gutter_hovered: bool,
  801}
  802
  803const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  804
  805#[derive(Default, Debug, Clone, Copy)]
  806pub struct GutterDimensions {
  807    pub left_padding: Pixels,
  808    pub right_padding: Pixels,
  809    pub width: Pixels,
  810    pub margin: Pixels,
  811    pub git_blame_entries_width: Option<Pixels>,
  812}
  813
  814impl GutterDimensions {
  815    /// The full width of the space taken up by the gutter.
  816    pub fn full_width(&self) -> Pixels {
  817        self.margin + self.width
  818    }
  819
  820    /// The width of the space reserved for the fold indicators,
  821    /// use alongside 'justify_end' and `gutter_width` to
  822    /// right align content with the line numbers
  823    pub fn fold_area_width(&self) -> Pixels {
  824        self.margin + self.right_padding
  825    }
  826}
  827
  828#[derive(Debug)]
  829pub struct RemoteSelection {
  830    pub replica_id: ReplicaId,
  831    pub selection: Selection<Anchor>,
  832    pub cursor_shape: CursorShape,
  833    pub peer_id: PeerId,
  834    pub line_mode: bool,
  835    pub participant_index: Option<ParticipantIndex>,
  836    pub user_name: Option<SharedString>,
  837}
  838
  839#[derive(Clone, Debug)]
  840struct SelectionHistoryEntry {
  841    selections: Arc<[Selection<Anchor>]>,
  842    select_next_state: Option<SelectNextState>,
  843    select_prev_state: Option<SelectNextState>,
  844    add_selections_state: Option<AddSelectionsState>,
  845}
  846
  847enum SelectionHistoryMode {
  848    Normal,
  849    Undoing,
  850    Redoing,
  851}
  852
  853#[derive(Clone, PartialEq, Eq, Hash)]
  854struct HoveredCursor {
  855    replica_id: u16,
  856    selection_id: usize,
  857}
  858
  859impl Default for SelectionHistoryMode {
  860    fn default() -> Self {
  861        Self::Normal
  862    }
  863}
  864
  865#[derive(Default)]
  866struct SelectionHistory {
  867    #[allow(clippy::type_complexity)]
  868    selections_by_transaction:
  869        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  870    mode: SelectionHistoryMode,
  871    undo_stack: VecDeque<SelectionHistoryEntry>,
  872    redo_stack: VecDeque<SelectionHistoryEntry>,
  873}
  874
  875impl SelectionHistory {
  876    fn insert_transaction(
  877        &mut self,
  878        transaction_id: TransactionId,
  879        selections: Arc<[Selection<Anchor>]>,
  880    ) {
  881        self.selections_by_transaction
  882            .insert(transaction_id, (selections, None));
  883    }
  884
  885    #[allow(clippy::type_complexity)]
  886    fn transaction(
  887        &self,
  888        transaction_id: TransactionId,
  889    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  890        self.selections_by_transaction.get(&transaction_id)
  891    }
  892
  893    #[allow(clippy::type_complexity)]
  894    fn transaction_mut(
  895        &mut self,
  896        transaction_id: TransactionId,
  897    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  898        self.selections_by_transaction.get_mut(&transaction_id)
  899    }
  900
  901    fn push(&mut self, entry: SelectionHistoryEntry) {
  902        if !entry.selections.is_empty() {
  903            match self.mode {
  904                SelectionHistoryMode::Normal => {
  905                    self.push_undo(entry);
  906                    self.redo_stack.clear();
  907                }
  908                SelectionHistoryMode::Undoing => self.push_redo(entry),
  909                SelectionHistoryMode::Redoing => self.push_undo(entry),
  910            }
  911        }
  912    }
  913
  914    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  915        if self
  916            .undo_stack
  917            .back()
  918            .map_or(true, |e| e.selections != entry.selections)
  919        {
  920            self.undo_stack.push_back(entry);
  921            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  922                self.undo_stack.pop_front();
  923            }
  924        }
  925    }
  926
  927    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  928        if self
  929            .redo_stack
  930            .back()
  931            .map_or(true, |e| e.selections != entry.selections)
  932        {
  933            self.redo_stack.push_back(entry);
  934            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  935                self.redo_stack.pop_front();
  936            }
  937        }
  938    }
  939}
  940
  941struct RowHighlight {
  942    index: usize,
  943    range: Range<Anchor>,
  944    color: Hsla,
  945    should_autoscroll: bool,
  946}
  947
  948#[derive(Clone, Debug)]
  949struct AddSelectionsState {
  950    above: bool,
  951    stack: Vec<usize>,
  952}
  953
  954#[derive(Clone)]
  955struct SelectNextState {
  956    query: AhoCorasick,
  957    wordwise: bool,
  958    done: bool,
  959}
  960
  961impl std::fmt::Debug for SelectNextState {
  962    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  963        f.debug_struct(std::any::type_name::<Self>())
  964            .field("wordwise", &self.wordwise)
  965            .field("done", &self.done)
  966            .finish()
  967    }
  968}
  969
  970#[derive(Debug)]
  971struct AutocloseRegion {
  972    selection_id: usize,
  973    range: Range<Anchor>,
  974    pair: BracketPair,
  975}
  976
  977#[derive(Debug)]
  978struct SnippetState {
  979    ranges: Vec<Vec<Range<Anchor>>>,
  980    active_index: usize,
  981    choices: Vec<Option<Vec<String>>>,
  982}
  983
  984#[doc(hidden)]
  985pub struct RenameState {
  986    pub range: Range<Anchor>,
  987    pub old_name: Arc<str>,
  988    pub editor: Entity<Editor>,
  989    block_id: CustomBlockId,
  990}
  991
  992struct InvalidationStack<T>(Vec<T>);
  993
  994struct RegisteredInlineCompletionProvider {
  995    provider: Arc<dyn InlineCompletionProviderHandle>,
  996    _subscription: Subscription,
  997}
  998
  999#[derive(Debug, PartialEq, Eq)]
 1000struct ActiveDiagnosticGroup {
 1001    primary_range: Range<Anchor>,
 1002    primary_message: String,
 1003    group_id: usize,
 1004    blocks: HashMap<CustomBlockId, Diagnostic>,
 1005    is_valid: bool,
 1006}
 1007
 1008#[derive(Serialize, Deserialize, Clone, Debug)]
 1009pub struct ClipboardSelection {
 1010    /// The number of bytes in this selection.
 1011    pub len: usize,
 1012    /// Whether this was a full-line selection.
 1013    pub is_entire_line: bool,
 1014    /// The column where this selection originally started.
 1015    pub start_column: u32,
 1016}
 1017
 1018#[derive(Debug)]
 1019pub(crate) struct NavigationData {
 1020    cursor_anchor: Anchor,
 1021    cursor_position: Point,
 1022    scroll_anchor: ScrollAnchor,
 1023    scroll_top_row: u32,
 1024}
 1025
 1026#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1027pub enum GotoDefinitionKind {
 1028    Symbol,
 1029    Declaration,
 1030    Type,
 1031    Implementation,
 1032}
 1033
 1034#[derive(Debug, Clone)]
 1035enum InlayHintRefreshReason {
 1036    ModifiersChanged(bool),
 1037    Toggle(bool),
 1038    SettingsChange(InlayHintSettings),
 1039    NewLinesShown,
 1040    BufferEdited(HashSet<Arc<Language>>),
 1041    RefreshRequested,
 1042    ExcerptsRemoved(Vec<ExcerptId>),
 1043}
 1044
 1045impl InlayHintRefreshReason {
 1046    fn description(&self) -> &'static str {
 1047        match self {
 1048            Self::ModifiersChanged(_) => "modifiers changed",
 1049            Self::Toggle(_) => "toggle",
 1050            Self::SettingsChange(_) => "settings change",
 1051            Self::NewLinesShown => "new lines shown",
 1052            Self::BufferEdited(_) => "buffer edited",
 1053            Self::RefreshRequested => "refresh requested",
 1054            Self::ExcerptsRemoved(_) => "excerpts removed",
 1055        }
 1056    }
 1057}
 1058
 1059pub enum FormatTarget {
 1060    Buffers,
 1061    Ranges(Vec<Range<MultiBufferPoint>>),
 1062}
 1063
 1064pub(crate) struct FocusedBlock {
 1065    id: BlockId,
 1066    focus_handle: WeakFocusHandle,
 1067}
 1068
 1069#[derive(Clone)]
 1070enum JumpData {
 1071    MultiBufferRow {
 1072        row: MultiBufferRow,
 1073        line_offset_from_top: u32,
 1074    },
 1075    MultiBufferPoint {
 1076        excerpt_id: ExcerptId,
 1077        position: Point,
 1078        anchor: text::Anchor,
 1079        line_offset_from_top: u32,
 1080    },
 1081}
 1082
 1083pub enum MultibufferSelectionMode {
 1084    First,
 1085    All,
 1086}
 1087
 1088impl Editor {
 1089    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1090        let buffer = cx.new(|cx| Buffer::local("", cx));
 1091        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1092        Self::new(
 1093            EditorMode::SingleLine { auto_width: false },
 1094            buffer,
 1095            None,
 1096            false,
 1097            window,
 1098            cx,
 1099        )
 1100    }
 1101
 1102    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1103        let buffer = cx.new(|cx| Buffer::local("", cx));
 1104        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1105        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1106    }
 1107
 1108    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1109        let buffer = cx.new(|cx| Buffer::local("", cx));
 1110        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1111        Self::new(
 1112            EditorMode::SingleLine { auto_width: true },
 1113            buffer,
 1114            None,
 1115            false,
 1116            window,
 1117            cx,
 1118        )
 1119    }
 1120
 1121    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1122        let buffer = cx.new(|cx| Buffer::local("", cx));
 1123        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1124        Self::new(
 1125            EditorMode::AutoHeight { max_lines },
 1126            buffer,
 1127            None,
 1128            false,
 1129            window,
 1130            cx,
 1131        )
 1132    }
 1133
 1134    pub fn for_buffer(
 1135        buffer: Entity<Buffer>,
 1136        project: Option<Entity<Project>>,
 1137        window: &mut Window,
 1138        cx: &mut Context<Self>,
 1139    ) -> Self {
 1140        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1141        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1142    }
 1143
 1144    pub fn for_multibuffer(
 1145        buffer: Entity<MultiBuffer>,
 1146        project: Option<Entity<Project>>,
 1147        show_excerpt_controls: bool,
 1148        window: &mut Window,
 1149        cx: &mut Context<Self>,
 1150    ) -> Self {
 1151        Self::new(
 1152            EditorMode::Full,
 1153            buffer,
 1154            project,
 1155            show_excerpt_controls,
 1156            window,
 1157            cx,
 1158        )
 1159    }
 1160
 1161    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1162        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1163        let mut clone = Self::new(
 1164            self.mode,
 1165            self.buffer.clone(),
 1166            self.project.clone(),
 1167            show_excerpt_controls,
 1168            window,
 1169            cx,
 1170        );
 1171        self.display_map.update(cx, |display_map, cx| {
 1172            let snapshot = display_map.snapshot(cx);
 1173            clone.display_map.update(cx, |display_map, cx| {
 1174                display_map.set_state(&snapshot, cx);
 1175            });
 1176        });
 1177        clone.selections.clone_state(&self.selections);
 1178        clone.scroll_manager.clone_state(&self.scroll_manager);
 1179        clone.searchable = self.searchable;
 1180        clone
 1181    }
 1182
 1183    pub fn new(
 1184        mode: EditorMode,
 1185        buffer: Entity<MultiBuffer>,
 1186        project: Option<Entity<Project>>,
 1187        show_excerpt_controls: bool,
 1188        window: &mut Window,
 1189        cx: &mut Context<Self>,
 1190    ) -> Self {
 1191        let style = window.text_style();
 1192        let font_size = style.font_size.to_pixels(window.rem_size());
 1193        let editor = cx.entity().downgrade();
 1194        let fold_placeholder = FoldPlaceholder {
 1195            constrain_width: true,
 1196            render: Arc::new(move |fold_id, fold_range, cx| {
 1197                let editor = editor.clone();
 1198                div()
 1199                    .id(fold_id)
 1200                    .bg(cx.theme().colors().ghost_element_background)
 1201                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1202                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1203                    .rounded_sm()
 1204                    .size_full()
 1205                    .cursor_pointer()
 1206                    .child("")
 1207                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1208                    .on_click(move |_, _window, cx| {
 1209                        editor
 1210                            .update(cx, |editor, cx| {
 1211                                editor.unfold_ranges(
 1212                                    &[fold_range.start..fold_range.end],
 1213                                    true,
 1214                                    false,
 1215                                    cx,
 1216                                );
 1217                                cx.stop_propagation();
 1218                            })
 1219                            .ok();
 1220                    })
 1221                    .into_any()
 1222            }),
 1223            merge_adjacent: true,
 1224            ..Default::default()
 1225        };
 1226        let display_map = cx.new(|cx| {
 1227            DisplayMap::new(
 1228                buffer.clone(),
 1229                style.font(),
 1230                font_size,
 1231                None,
 1232                show_excerpt_controls,
 1233                FILE_HEADER_HEIGHT,
 1234                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1235                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1236                fold_placeholder,
 1237                cx,
 1238            )
 1239        });
 1240
 1241        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1242
 1243        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1244
 1245        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1246            .then(|| language_settings::SoftWrap::None);
 1247
 1248        let mut project_subscriptions = Vec::new();
 1249        if mode == EditorMode::Full {
 1250            if let Some(project) = project.as_ref() {
 1251                if buffer.read(cx).is_singleton() {
 1252                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1253                        cx.emit(EditorEvent::TitleChanged);
 1254                    }));
 1255                }
 1256                project_subscriptions.push(cx.subscribe_in(
 1257                    project,
 1258                    window,
 1259                    |editor, _, event, window, cx| {
 1260                        if let project::Event::RefreshInlayHints = event {
 1261                            editor
 1262                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1263                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1264                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1265                                let focus_handle = editor.focus_handle(cx);
 1266                                if focus_handle.is_focused(window) {
 1267                                    let snapshot = buffer.read(cx).snapshot();
 1268                                    for (range, snippet) in snippet_edits {
 1269                                        let editor_range =
 1270                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1271                                        editor
 1272                                            .insert_snippet(
 1273                                                &[editor_range],
 1274                                                snippet.clone(),
 1275                                                window,
 1276                                                cx,
 1277                                            )
 1278                                            .ok();
 1279                                    }
 1280                                }
 1281                            }
 1282                        }
 1283                    },
 1284                ));
 1285                if let Some(task_inventory) = project
 1286                    .read(cx)
 1287                    .task_store()
 1288                    .read(cx)
 1289                    .task_inventory()
 1290                    .cloned()
 1291                {
 1292                    project_subscriptions.push(cx.observe_in(
 1293                        &task_inventory,
 1294                        window,
 1295                        |editor, _, window, cx| {
 1296                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1297                        },
 1298                    ));
 1299                }
 1300            }
 1301        }
 1302
 1303        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1304
 1305        let inlay_hint_settings =
 1306            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1307        let focus_handle = cx.focus_handle();
 1308        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1309            .detach();
 1310        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1311            .detach();
 1312        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1313            .detach();
 1314        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1315            .detach();
 1316
 1317        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1318            Some(false)
 1319        } else {
 1320            None
 1321        };
 1322
 1323        let mut code_action_providers = Vec::new();
 1324        let mut load_uncommitted_diff = None;
 1325        if let Some(project) = project.clone() {
 1326            load_uncommitted_diff = Some(
 1327                get_uncommitted_diff_for_buffer(
 1328                    &project,
 1329                    buffer.read(cx).all_buffers(),
 1330                    buffer.clone(),
 1331                    cx,
 1332                )
 1333                .shared(),
 1334            );
 1335            code_action_providers.push(Rc::new(project) as Rc<_>);
 1336        }
 1337
 1338        let mut this = Self {
 1339            focus_handle,
 1340            show_cursor_when_unfocused: false,
 1341            last_focused_descendant: None,
 1342            buffer: buffer.clone(),
 1343            display_map: display_map.clone(),
 1344            selections,
 1345            scroll_manager: ScrollManager::new(cx),
 1346            columnar_selection_tail: None,
 1347            add_selections_state: None,
 1348            select_next_state: None,
 1349            select_prev_state: None,
 1350            selection_history: Default::default(),
 1351            autoclose_regions: Default::default(),
 1352            snippet_stack: Default::default(),
 1353            select_larger_syntax_node_stack: Vec::new(),
 1354            ime_transaction: Default::default(),
 1355            active_diagnostics: None,
 1356            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1357            inline_diagnostics_update: Task::ready(()),
 1358            inline_diagnostics: Vec::new(),
 1359            soft_wrap_mode_override,
 1360            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1361            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1362            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1363            project,
 1364            blink_manager: blink_manager.clone(),
 1365            show_local_selections: true,
 1366            show_scrollbars: true,
 1367            mode,
 1368            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1369            show_gutter: mode == EditorMode::Full,
 1370            show_line_numbers: None,
 1371            use_relative_line_numbers: None,
 1372            show_git_diff_gutter: None,
 1373            show_code_actions: None,
 1374            show_runnables: None,
 1375            show_wrap_guides: None,
 1376            show_indent_guides,
 1377            placeholder_text: None,
 1378            highlight_order: 0,
 1379            highlighted_rows: HashMap::default(),
 1380            background_highlights: Default::default(),
 1381            gutter_highlights: TreeMap::default(),
 1382            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1383            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1384            nav_history: None,
 1385            context_menu: RefCell::new(None),
 1386            mouse_context_menu: None,
 1387            completion_tasks: Default::default(),
 1388            signature_help_state: SignatureHelpState::default(),
 1389            auto_signature_help: None,
 1390            find_all_references_task_sources: Vec::new(),
 1391            next_completion_id: 0,
 1392            next_inlay_id: 0,
 1393            code_action_providers,
 1394            available_code_actions: Default::default(),
 1395            code_actions_task: Default::default(),
 1396            selection_highlight_task: Default::default(),
 1397            document_highlights_task: Default::default(),
 1398            linked_editing_range_task: Default::default(),
 1399            pending_rename: Default::default(),
 1400            searchable: true,
 1401            cursor_shape: EditorSettings::get_global(cx)
 1402                .cursor_shape
 1403                .unwrap_or_default(),
 1404            current_line_highlight: None,
 1405            autoindent_mode: Some(AutoindentMode::EachLine),
 1406            collapse_matches: false,
 1407            workspace: None,
 1408            input_enabled: true,
 1409            use_modal_editing: mode == EditorMode::Full,
 1410            read_only: false,
 1411            use_autoclose: true,
 1412            use_auto_surround: true,
 1413            auto_replace_emoji_shortcode: false,
 1414            leader_peer_id: None,
 1415            remote_id: None,
 1416            hover_state: Default::default(),
 1417            pending_mouse_down: None,
 1418            hovered_link_state: Default::default(),
 1419            edit_prediction_provider: None,
 1420            active_inline_completion: None,
 1421            stale_inline_completion_in_menu: None,
 1422            edit_prediction_preview: EditPredictionPreview::Inactive {
 1423                released_too_fast: false,
 1424            },
 1425            inline_diagnostics_enabled: mode == EditorMode::Full,
 1426            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1427
 1428            gutter_hovered: false,
 1429            pixel_position_of_newest_cursor: None,
 1430            last_bounds: None,
 1431            last_position_map: None,
 1432            expect_bounds_change: None,
 1433            gutter_dimensions: GutterDimensions::default(),
 1434            style: None,
 1435            show_cursor_names: false,
 1436            hovered_cursors: Default::default(),
 1437            next_editor_action_id: EditorActionId::default(),
 1438            editor_actions: Rc::default(),
 1439            inline_completions_hidden_for_vim_mode: false,
 1440            show_inline_completions_override: None,
 1441            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1442            edit_prediction_settings: EditPredictionSettings::Disabled,
 1443            edit_prediction_indent_conflict: false,
 1444            edit_prediction_requires_modifier_in_indent_conflict: true,
 1445            custom_context_menu: None,
 1446            show_git_blame_gutter: false,
 1447            show_git_blame_inline: false,
 1448            show_selection_menu: None,
 1449            show_git_blame_inline_delay_task: None,
 1450            git_blame_inline_tooltip: None,
 1451            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1452            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1453                .session
 1454                .restore_unsaved_buffers,
 1455            blame: None,
 1456            blame_subscription: None,
 1457            tasks: Default::default(),
 1458            _subscriptions: vec![
 1459                cx.observe(&buffer, Self::on_buffer_changed),
 1460                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1461                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1462                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1463                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1464                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1465                cx.observe_window_activation(window, |editor, window, cx| {
 1466                    let active = window.is_window_active();
 1467                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1468                        if active {
 1469                            blink_manager.enable(cx);
 1470                        } else {
 1471                            blink_manager.disable(cx);
 1472                        }
 1473                    });
 1474                }),
 1475            ],
 1476            tasks_update_task: None,
 1477            linked_edit_ranges: Default::default(),
 1478            in_project_search: false,
 1479            previous_search_ranges: None,
 1480            breadcrumb_header: None,
 1481            focused_block: None,
 1482            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1483            addons: HashMap::default(),
 1484            registered_buffers: HashMap::default(),
 1485            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1486            selection_mark_mode: false,
 1487            toggle_fold_multiple_buffers: Task::ready(()),
 1488            serialize_selections: Task::ready(()),
 1489            text_style_refinement: None,
 1490            load_diff_task: load_uncommitted_diff,
 1491        };
 1492        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1493        this._subscriptions.extend(project_subscriptions);
 1494
 1495        this.end_selection(window, cx);
 1496        this.scroll_manager.show_scrollbar(window, cx);
 1497
 1498        if mode == EditorMode::Full {
 1499            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1500            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1501
 1502            if this.git_blame_inline_enabled {
 1503                this.git_blame_inline_enabled = true;
 1504                this.start_git_blame_inline(false, window, cx);
 1505            }
 1506
 1507            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1508                if let Some(project) = this.project.as_ref() {
 1509                    let handle = project.update(cx, |project, cx| {
 1510                        project.register_buffer_with_language_servers(&buffer, cx)
 1511                    });
 1512                    this.registered_buffers
 1513                        .insert(buffer.read(cx).remote_id(), handle);
 1514                }
 1515            }
 1516        }
 1517
 1518        this.report_editor_event("Editor Opened", None, cx);
 1519        this
 1520    }
 1521
 1522    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1523        self.mouse_context_menu
 1524            .as_ref()
 1525            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1526    }
 1527
 1528    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1529        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1530    }
 1531
 1532    fn key_context_internal(
 1533        &self,
 1534        has_active_edit_prediction: bool,
 1535        window: &Window,
 1536        cx: &App,
 1537    ) -> KeyContext {
 1538        let mut key_context = KeyContext::new_with_defaults();
 1539        key_context.add("Editor");
 1540        let mode = match self.mode {
 1541            EditorMode::SingleLine { .. } => "single_line",
 1542            EditorMode::AutoHeight { .. } => "auto_height",
 1543            EditorMode::Full => "full",
 1544        };
 1545
 1546        if EditorSettings::jupyter_enabled(cx) {
 1547            key_context.add("jupyter");
 1548        }
 1549
 1550        key_context.set("mode", mode);
 1551        if self.pending_rename.is_some() {
 1552            key_context.add("renaming");
 1553        }
 1554
 1555        match self.context_menu.borrow().as_ref() {
 1556            Some(CodeContextMenu::Completions(_)) => {
 1557                key_context.add("menu");
 1558                key_context.add("showing_completions");
 1559            }
 1560            Some(CodeContextMenu::CodeActions(_)) => {
 1561                key_context.add("menu");
 1562                key_context.add("showing_code_actions")
 1563            }
 1564            None => {}
 1565        }
 1566
 1567        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1568        if !self.focus_handle(cx).contains_focused(window, cx)
 1569            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1570        {
 1571            for addon in self.addons.values() {
 1572                addon.extend_key_context(&mut key_context, cx)
 1573            }
 1574        }
 1575
 1576        if let Some(extension) = self
 1577            .buffer
 1578            .read(cx)
 1579            .as_singleton()
 1580            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1581        {
 1582            key_context.set("extension", extension.to_string());
 1583        }
 1584
 1585        if has_active_edit_prediction {
 1586            if self.edit_prediction_in_conflict() {
 1587                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1588            } else {
 1589                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1590                key_context.add("copilot_suggestion");
 1591            }
 1592        }
 1593
 1594        if self.selection_mark_mode {
 1595            key_context.add("selection_mode");
 1596        }
 1597
 1598        key_context
 1599    }
 1600
 1601    pub fn edit_prediction_in_conflict(&self) -> bool {
 1602        if !self.show_edit_predictions_in_menu() {
 1603            return false;
 1604        }
 1605
 1606        let showing_completions = self
 1607            .context_menu
 1608            .borrow()
 1609            .as_ref()
 1610            .map_or(false, |context| {
 1611                matches!(context, CodeContextMenu::Completions(_))
 1612            });
 1613
 1614        showing_completions
 1615            || self.edit_prediction_requires_modifier()
 1616            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1617            // bindings to insert tab characters.
 1618            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1619    }
 1620
 1621    pub fn accept_edit_prediction_keybind(
 1622        &self,
 1623        window: &Window,
 1624        cx: &App,
 1625    ) -> AcceptEditPredictionBinding {
 1626        let key_context = self.key_context_internal(true, window, cx);
 1627        let in_conflict = self.edit_prediction_in_conflict();
 1628
 1629        AcceptEditPredictionBinding(
 1630            window
 1631                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1632                .into_iter()
 1633                .filter(|binding| {
 1634                    !in_conflict
 1635                        || binding
 1636                            .keystrokes()
 1637                            .first()
 1638                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1639                })
 1640                .rev()
 1641                .min_by_key(|binding| {
 1642                    binding
 1643                        .keystrokes()
 1644                        .first()
 1645                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1646                }),
 1647        )
 1648    }
 1649
 1650    pub fn new_file(
 1651        workspace: &mut Workspace,
 1652        _: &workspace::NewFile,
 1653        window: &mut Window,
 1654        cx: &mut Context<Workspace>,
 1655    ) {
 1656        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1657            "Failed to create buffer",
 1658            window,
 1659            cx,
 1660            |e, _, _| match e.error_code() {
 1661                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1662                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1663                e.error_tag("required").unwrap_or("the latest version")
 1664            )),
 1665                _ => None,
 1666            },
 1667        );
 1668    }
 1669
 1670    pub fn new_in_workspace(
 1671        workspace: &mut Workspace,
 1672        window: &mut Window,
 1673        cx: &mut Context<Workspace>,
 1674    ) -> Task<Result<Entity<Editor>>> {
 1675        let project = workspace.project().clone();
 1676        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1677
 1678        cx.spawn_in(window, |workspace, mut cx| async move {
 1679            let buffer = create.await?;
 1680            workspace.update_in(&mut cx, |workspace, window, cx| {
 1681                let editor =
 1682                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1683                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1684                editor
 1685            })
 1686        })
 1687    }
 1688
 1689    fn new_file_vertical(
 1690        workspace: &mut Workspace,
 1691        _: &workspace::NewFileSplitVertical,
 1692        window: &mut Window,
 1693        cx: &mut Context<Workspace>,
 1694    ) {
 1695        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1696    }
 1697
 1698    fn new_file_horizontal(
 1699        workspace: &mut Workspace,
 1700        _: &workspace::NewFileSplitHorizontal,
 1701        window: &mut Window,
 1702        cx: &mut Context<Workspace>,
 1703    ) {
 1704        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1705    }
 1706
 1707    fn new_file_in_direction(
 1708        workspace: &mut Workspace,
 1709        direction: SplitDirection,
 1710        window: &mut Window,
 1711        cx: &mut Context<Workspace>,
 1712    ) {
 1713        let project = workspace.project().clone();
 1714        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1715
 1716        cx.spawn_in(window, |workspace, mut cx| async move {
 1717            let buffer = create.await?;
 1718            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1719                workspace.split_item(
 1720                    direction,
 1721                    Box::new(
 1722                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1723                    ),
 1724                    window,
 1725                    cx,
 1726                )
 1727            })?;
 1728            anyhow::Ok(())
 1729        })
 1730        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1731            match e.error_code() {
 1732                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1733                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1734                e.error_tag("required").unwrap_or("the latest version")
 1735            )),
 1736                _ => None,
 1737            }
 1738        });
 1739    }
 1740
 1741    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1742        self.leader_peer_id
 1743    }
 1744
 1745    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1746        &self.buffer
 1747    }
 1748
 1749    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1750        self.workspace.as_ref()?.0.upgrade()
 1751    }
 1752
 1753    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1754        self.buffer().read(cx).title(cx)
 1755    }
 1756
 1757    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1758        let git_blame_gutter_max_author_length = self
 1759            .render_git_blame_gutter(cx)
 1760            .then(|| {
 1761                if let Some(blame) = self.blame.as_ref() {
 1762                    let max_author_length =
 1763                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1764                    Some(max_author_length)
 1765                } else {
 1766                    None
 1767                }
 1768            })
 1769            .flatten();
 1770
 1771        EditorSnapshot {
 1772            mode: self.mode,
 1773            show_gutter: self.show_gutter,
 1774            show_line_numbers: self.show_line_numbers,
 1775            show_git_diff_gutter: self.show_git_diff_gutter,
 1776            show_code_actions: self.show_code_actions,
 1777            show_runnables: self.show_runnables,
 1778            git_blame_gutter_max_author_length,
 1779            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1780            scroll_anchor: self.scroll_manager.anchor(),
 1781            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1782            placeholder_text: self.placeholder_text.clone(),
 1783            is_focused: self.focus_handle.is_focused(window),
 1784            current_line_highlight: self
 1785                .current_line_highlight
 1786                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1787            gutter_hovered: self.gutter_hovered,
 1788        }
 1789    }
 1790
 1791    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1792        self.buffer.read(cx).language_at(point, cx)
 1793    }
 1794
 1795    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1796        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1797    }
 1798
 1799    pub fn active_excerpt(
 1800        &self,
 1801        cx: &App,
 1802    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1803        self.buffer
 1804            .read(cx)
 1805            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1806    }
 1807
 1808    pub fn mode(&self) -> EditorMode {
 1809        self.mode
 1810    }
 1811
 1812    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1813        self.collaboration_hub.as_deref()
 1814    }
 1815
 1816    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1817        self.collaboration_hub = Some(hub);
 1818    }
 1819
 1820    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1821        self.in_project_search = in_project_search;
 1822    }
 1823
 1824    pub fn set_custom_context_menu(
 1825        &mut self,
 1826        f: impl 'static
 1827            + Fn(
 1828                &mut Self,
 1829                DisplayPoint,
 1830                &mut Window,
 1831                &mut Context<Self>,
 1832            ) -> Option<Entity<ui::ContextMenu>>,
 1833    ) {
 1834        self.custom_context_menu = Some(Box::new(f))
 1835    }
 1836
 1837    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1838        self.completion_provider = provider;
 1839    }
 1840
 1841    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1842        self.semantics_provider.clone()
 1843    }
 1844
 1845    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1846        self.semantics_provider = provider;
 1847    }
 1848
 1849    pub fn set_edit_prediction_provider<T>(
 1850        &mut self,
 1851        provider: Option<Entity<T>>,
 1852        window: &mut Window,
 1853        cx: &mut Context<Self>,
 1854    ) where
 1855        T: EditPredictionProvider,
 1856    {
 1857        self.edit_prediction_provider =
 1858            provider.map(|provider| RegisteredInlineCompletionProvider {
 1859                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1860                    if this.focus_handle.is_focused(window) {
 1861                        this.update_visible_inline_completion(window, cx);
 1862                    }
 1863                }),
 1864                provider: Arc::new(provider),
 1865            });
 1866        self.update_edit_prediction_settings(cx);
 1867        self.refresh_inline_completion(false, false, window, cx);
 1868    }
 1869
 1870    pub fn placeholder_text(&self) -> Option<&str> {
 1871        self.placeholder_text.as_deref()
 1872    }
 1873
 1874    pub fn set_placeholder_text(
 1875        &mut self,
 1876        placeholder_text: impl Into<Arc<str>>,
 1877        cx: &mut Context<Self>,
 1878    ) {
 1879        let placeholder_text = Some(placeholder_text.into());
 1880        if self.placeholder_text != placeholder_text {
 1881            self.placeholder_text = placeholder_text;
 1882            cx.notify();
 1883        }
 1884    }
 1885
 1886    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1887        self.cursor_shape = cursor_shape;
 1888
 1889        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1890        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1891
 1892        cx.notify();
 1893    }
 1894
 1895    pub fn set_current_line_highlight(
 1896        &mut self,
 1897        current_line_highlight: Option<CurrentLineHighlight>,
 1898    ) {
 1899        self.current_line_highlight = current_line_highlight;
 1900    }
 1901
 1902    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1903        self.collapse_matches = collapse_matches;
 1904    }
 1905
 1906    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1907        let buffers = self.buffer.read(cx).all_buffers();
 1908        let Some(project) = self.project.as_ref() else {
 1909            return;
 1910        };
 1911        project.update(cx, |project, cx| {
 1912            for buffer in buffers {
 1913                self.registered_buffers
 1914                    .entry(buffer.read(cx).remote_id())
 1915                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1916            }
 1917        })
 1918    }
 1919
 1920    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1921        if self.collapse_matches {
 1922            return range.start..range.start;
 1923        }
 1924        range.clone()
 1925    }
 1926
 1927    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1928        if self.display_map.read(cx).clip_at_line_ends != clip {
 1929            self.display_map
 1930                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1931        }
 1932    }
 1933
 1934    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1935        self.input_enabled = input_enabled;
 1936    }
 1937
 1938    pub fn set_inline_completions_hidden_for_vim_mode(
 1939        &mut self,
 1940        hidden: bool,
 1941        window: &mut Window,
 1942        cx: &mut Context<Self>,
 1943    ) {
 1944        if hidden != self.inline_completions_hidden_for_vim_mode {
 1945            self.inline_completions_hidden_for_vim_mode = hidden;
 1946            if hidden {
 1947                self.update_visible_inline_completion(window, cx);
 1948            } else {
 1949                self.refresh_inline_completion(true, false, window, cx);
 1950            }
 1951        }
 1952    }
 1953
 1954    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1955        self.menu_inline_completions_policy = value;
 1956    }
 1957
 1958    pub fn set_autoindent(&mut self, autoindent: bool) {
 1959        if autoindent {
 1960            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1961        } else {
 1962            self.autoindent_mode = None;
 1963        }
 1964    }
 1965
 1966    pub fn read_only(&self, cx: &App) -> bool {
 1967        self.read_only || self.buffer.read(cx).read_only()
 1968    }
 1969
 1970    pub fn set_read_only(&mut self, read_only: bool) {
 1971        self.read_only = read_only;
 1972    }
 1973
 1974    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1975        self.use_autoclose = autoclose;
 1976    }
 1977
 1978    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1979        self.use_auto_surround = auto_surround;
 1980    }
 1981
 1982    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1983        self.auto_replace_emoji_shortcode = auto_replace;
 1984    }
 1985
 1986    pub fn toggle_edit_predictions(
 1987        &mut self,
 1988        _: &ToggleEditPrediction,
 1989        window: &mut Window,
 1990        cx: &mut Context<Self>,
 1991    ) {
 1992        if self.show_inline_completions_override.is_some() {
 1993            self.set_show_edit_predictions(None, window, cx);
 1994        } else {
 1995            let show_edit_predictions = !self.edit_predictions_enabled();
 1996            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1997        }
 1998    }
 1999
 2000    pub fn set_show_edit_predictions(
 2001        &mut self,
 2002        show_edit_predictions: Option<bool>,
 2003        window: &mut Window,
 2004        cx: &mut Context<Self>,
 2005    ) {
 2006        self.show_inline_completions_override = show_edit_predictions;
 2007        self.update_edit_prediction_settings(cx);
 2008
 2009        if let Some(false) = show_edit_predictions {
 2010            self.discard_inline_completion(false, cx);
 2011        } else {
 2012            self.refresh_inline_completion(false, true, window, cx);
 2013        }
 2014    }
 2015
 2016    fn inline_completions_disabled_in_scope(
 2017        &self,
 2018        buffer: &Entity<Buffer>,
 2019        buffer_position: language::Anchor,
 2020        cx: &App,
 2021    ) -> bool {
 2022        let snapshot = buffer.read(cx).snapshot();
 2023        let settings = snapshot.settings_at(buffer_position, cx);
 2024
 2025        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2026            return false;
 2027        };
 2028
 2029        scope.override_name().map_or(false, |scope_name| {
 2030            settings
 2031                .edit_predictions_disabled_in
 2032                .iter()
 2033                .any(|s| s == scope_name)
 2034        })
 2035    }
 2036
 2037    pub fn set_use_modal_editing(&mut self, to: bool) {
 2038        self.use_modal_editing = to;
 2039    }
 2040
 2041    pub fn use_modal_editing(&self) -> bool {
 2042        self.use_modal_editing
 2043    }
 2044
 2045    fn selections_did_change(
 2046        &mut self,
 2047        local: bool,
 2048        old_cursor_position: &Anchor,
 2049        show_completions: bool,
 2050        window: &mut Window,
 2051        cx: &mut Context<Self>,
 2052    ) {
 2053        window.invalidate_character_coordinates();
 2054
 2055        // Copy selections to primary selection buffer
 2056        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2057        if local {
 2058            let selections = self.selections.all::<usize>(cx);
 2059            let buffer_handle = self.buffer.read(cx).read(cx);
 2060
 2061            let mut text = String::new();
 2062            for (index, selection) in selections.iter().enumerate() {
 2063                let text_for_selection = buffer_handle
 2064                    .text_for_range(selection.start..selection.end)
 2065                    .collect::<String>();
 2066
 2067                text.push_str(&text_for_selection);
 2068                if index != selections.len() - 1 {
 2069                    text.push('\n');
 2070                }
 2071            }
 2072
 2073            if !text.is_empty() {
 2074                cx.write_to_primary(ClipboardItem::new_string(text));
 2075            }
 2076        }
 2077
 2078        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2079            self.buffer.update(cx, |buffer, cx| {
 2080                buffer.set_active_selections(
 2081                    &self.selections.disjoint_anchors(),
 2082                    self.selections.line_mode,
 2083                    self.cursor_shape,
 2084                    cx,
 2085                )
 2086            });
 2087        }
 2088        let display_map = self
 2089            .display_map
 2090            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2091        let buffer = &display_map.buffer_snapshot;
 2092        self.add_selections_state = None;
 2093        self.select_next_state = None;
 2094        self.select_prev_state = None;
 2095        self.select_larger_syntax_node_stack.clear();
 2096        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2097        self.snippet_stack
 2098            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2099        self.take_rename(false, window, cx);
 2100
 2101        let new_cursor_position = self.selections.newest_anchor().head();
 2102
 2103        self.push_to_nav_history(
 2104            *old_cursor_position,
 2105            Some(new_cursor_position.to_point(buffer)),
 2106            cx,
 2107        );
 2108
 2109        if local {
 2110            let new_cursor_position = self.selections.newest_anchor().head();
 2111            let mut context_menu = self.context_menu.borrow_mut();
 2112            let completion_menu = match context_menu.as_ref() {
 2113                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2114                _ => {
 2115                    *context_menu = None;
 2116                    None
 2117                }
 2118            };
 2119            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2120                if !self.registered_buffers.contains_key(&buffer_id) {
 2121                    if let Some(project) = self.project.as_ref() {
 2122                        project.update(cx, |project, cx| {
 2123                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2124                                return;
 2125                            };
 2126                            self.registered_buffers.insert(
 2127                                buffer_id,
 2128                                project.register_buffer_with_language_servers(&buffer, cx),
 2129                            );
 2130                        })
 2131                    }
 2132                }
 2133            }
 2134
 2135            if let Some(completion_menu) = completion_menu {
 2136                let cursor_position = new_cursor_position.to_offset(buffer);
 2137                let (word_range, kind) =
 2138                    buffer.surrounding_word(completion_menu.initial_position, true);
 2139                if kind == Some(CharKind::Word)
 2140                    && word_range.to_inclusive().contains(&cursor_position)
 2141                {
 2142                    let mut completion_menu = completion_menu.clone();
 2143                    drop(context_menu);
 2144
 2145                    let query = Self::completion_query(buffer, cursor_position);
 2146                    cx.spawn(move |this, mut cx| async move {
 2147                        completion_menu
 2148                            .filter(query.as_deref(), cx.background_executor().clone())
 2149                            .await;
 2150
 2151                        this.update(&mut cx, |this, cx| {
 2152                            let mut context_menu = this.context_menu.borrow_mut();
 2153                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2154                            else {
 2155                                return;
 2156                            };
 2157
 2158                            if menu.id > completion_menu.id {
 2159                                return;
 2160                            }
 2161
 2162                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2163                            drop(context_menu);
 2164                            cx.notify();
 2165                        })
 2166                    })
 2167                    .detach();
 2168
 2169                    if show_completions {
 2170                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2171                    }
 2172                } else {
 2173                    drop(context_menu);
 2174                    self.hide_context_menu(window, cx);
 2175                }
 2176            } else {
 2177                drop(context_menu);
 2178            }
 2179
 2180            hide_hover(self, cx);
 2181
 2182            if old_cursor_position.to_display_point(&display_map).row()
 2183                != new_cursor_position.to_display_point(&display_map).row()
 2184            {
 2185                self.available_code_actions.take();
 2186            }
 2187            self.refresh_code_actions(window, cx);
 2188            self.refresh_document_highlights(cx);
 2189            self.refresh_selected_text_highlights(window, cx);
 2190            refresh_matching_bracket_highlights(self, window, cx);
 2191            self.update_visible_inline_completion(window, cx);
 2192            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2193            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2194            if self.git_blame_inline_enabled {
 2195                self.start_inline_blame_timer(window, cx);
 2196            }
 2197        }
 2198
 2199        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2200        cx.emit(EditorEvent::SelectionsChanged { local });
 2201
 2202        let selections = &self.selections.disjoint;
 2203        if selections.len() == 1 {
 2204            cx.emit(SearchEvent::ActiveMatchChanged)
 2205        }
 2206        if local
 2207            && self.is_singleton(cx)
 2208            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2209        {
 2210            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2211                let background_executor = cx.background_executor().clone();
 2212                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2213                let snapshot = self.buffer().read(cx).snapshot(cx);
 2214                let selections = selections.clone();
 2215                self.serialize_selections = cx.background_spawn(async move {
 2216                    background_executor.timer(Duration::from_millis(100)).await;
 2217                    let selections = selections
 2218                        .iter()
 2219                        .map(|selection| {
 2220                            (
 2221                                selection.start.to_offset(&snapshot),
 2222                                selection.end.to_offset(&snapshot),
 2223                            )
 2224                        })
 2225                        .collect();
 2226                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2227                        .await
 2228                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2229                        .log_err();
 2230                });
 2231            }
 2232        }
 2233
 2234        cx.notify();
 2235    }
 2236
 2237    pub fn sync_selections(
 2238        &mut self,
 2239        other: Entity<Editor>,
 2240        cx: &mut Context<Self>,
 2241    ) -> gpui::Subscription {
 2242        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2243        self.selections.change_with(cx, |selections| {
 2244            selections.select_anchors(other_selections);
 2245        });
 2246
 2247        let other_subscription =
 2248            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2249                EditorEvent::SelectionsChanged { local: true } => {
 2250                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2251                    if other_selections.is_empty() {
 2252                        return;
 2253                    }
 2254                    this.selections.change_with(cx, |selections| {
 2255                        selections.select_anchors(other_selections);
 2256                    });
 2257                }
 2258                _ => {}
 2259            });
 2260
 2261        let this_subscription =
 2262            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2263                EditorEvent::SelectionsChanged { local: true } => {
 2264                    let these_selections = this.selections.disjoint.to_vec();
 2265                    if these_selections.is_empty() {
 2266                        return;
 2267                    }
 2268                    other.update(cx, |other_editor, cx| {
 2269                        other_editor.selections.change_with(cx, |selections| {
 2270                            selections.select_anchors(these_selections);
 2271                        })
 2272                    });
 2273                }
 2274                _ => {}
 2275            });
 2276
 2277        Subscription::join(other_subscription, this_subscription)
 2278    }
 2279
 2280    pub fn change_selections<R>(
 2281        &mut self,
 2282        autoscroll: Option<Autoscroll>,
 2283        window: &mut Window,
 2284        cx: &mut Context<Self>,
 2285        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2286    ) -> R {
 2287        self.change_selections_inner(autoscroll, true, window, cx, change)
 2288    }
 2289
 2290    fn change_selections_inner<R>(
 2291        &mut self,
 2292        autoscroll: Option<Autoscroll>,
 2293        request_completions: bool,
 2294        window: &mut Window,
 2295        cx: &mut Context<Self>,
 2296        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2297    ) -> R {
 2298        let old_cursor_position = self.selections.newest_anchor().head();
 2299        self.push_to_selection_history();
 2300
 2301        let (changed, result) = self.selections.change_with(cx, change);
 2302
 2303        if changed {
 2304            if let Some(autoscroll) = autoscroll {
 2305                self.request_autoscroll(autoscroll, cx);
 2306            }
 2307            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2308
 2309            if self.should_open_signature_help_automatically(
 2310                &old_cursor_position,
 2311                self.signature_help_state.backspace_pressed(),
 2312                cx,
 2313            ) {
 2314                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2315            }
 2316            self.signature_help_state.set_backspace_pressed(false);
 2317        }
 2318
 2319        result
 2320    }
 2321
 2322    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2323    where
 2324        I: IntoIterator<Item = (Range<S>, T)>,
 2325        S: ToOffset,
 2326        T: Into<Arc<str>>,
 2327    {
 2328        if self.read_only(cx) {
 2329            return;
 2330        }
 2331
 2332        self.buffer
 2333            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2334    }
 2335
 2336    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2337    where
 2338        I: IntoIterator<Item = (Range<S>, T)>,
 2339        S: ToOffset,
 2340        T: Into<Arc<str>>,
 2341    {
 2342        if self.read_only(cx) {
 2343            return;
 2344        }
 2345
 2346        self.buffer.update(cx, |buffer, cx| {
 2347            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2348        });
 2349    }
 2350
 2351    pub fn edit_with_block_indent<I, S, T>(
 2352        &mut self,
 2353        edits: I,
 2354        original_start_columns: Vec<u32>,
 2355        cx: &mut Context<Self>,
 2356    ) where
 2357        I: IntoIterator<Item = (Range<S>, T)>,
 2358        S: ToOffset,
 2359        T: Into<Arc<str>>,
 2360    {
 2361        if self.read_only(cx) {
 2362            return;
 2363        }
 2364
 2365        self.buffer.update(cx, |buffer, cx| {
 2366            buffer.edit(
 2367                edits,
 2368                Some(AutoindentMode::Block {
 2369                    original_start_columns,
 2370                }),
 2371                cx,
 2372            )
 2373        });
 2374    }
 2375
 2376    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2377        self.hide_context_menu(window, cx);
 2378
 2379        match phase {
 2380            SelectPhase::Begin {
 2381                position,
 2382                add,
 2383                click_count,
 2384            } => self.begin_selection(position, add, click_count, window, cx),
 2385            SelectPhase::BeginColumnar {
 2386                position,
 2387                goal_column,
 2388                reset,
 2389            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2390            SelectPhase::Extend {
 2391                position,
 2392                click_count,
 2393            } => self.extend_selection(position, click_count, window, cx),
 2394            SelectPhase::Update {
 2395                position,
 2396                goal_column,
 2397                scroll_delta,
 2398            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2399            SelectPhase::End => self.end_selection(window, cx),
 2400        }
 2401    }
 2402
 2403    fn extend_selection(
 2404        &mut self,
 2405        position: DisplayPoint,
 2406        click_count: usize,
 2407        window: &mut Window,
 2408        cx: &mut Context<Self>,
 2409    ) {
 2410        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2411        let tail = self.selections.newest::<usize>(cx).tail();
 2412        self.begin_selection(position, false, click_count, window, cx);
 2413
 2414        let position = position.to_offset(&display_map, Bias::Left);
 2415        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2416
 2417        let mut pending_selection = self
 2418            .selections
 2419            .pending_anchor()
 2420            .expect("extend_selection not called with pending selection");
 2421        if position >= tail {
 2422            pending_selection.start = tail_anchor;
 2423        } else {
 2424            pending_selection.end = tail_anchor;
 2425            pending_selection.reversed = true;
 2426        }
 2427
 2428        let mut pending_mode = self.selections.pending_mode().unwrap();
 2429        match &mut pending_mode {
 2430            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2431            _ => {}
 2432        }
 2433
 2434        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2435            s.set_pending(pending_selection, pending_mode)
 2436        });
 2437    }
 2438
 2439    fn begin_selection(
 2440        &mut self,
 2441        position: DisplayPoint,
 2442        add: bool,
 2443        click_count: usize,
 2444        window: &mut Window,
 2445        cx: &mut Context<Self>,
 2446    ) {
 2447        if !self.focus_handle.is_focused(window) {
 2448            self.last_focused_descendant = None;
 2449            window.focus(&self.focus_handle);
 2450        }
 2451
 2452        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2453        let buffer = &display_map.buffer_snapshot;
 2454        let newest_selection = self.selections.newest_anchor().clone();
 2455        let position = display_map.clip_point(position, Bias::Left);
 2456
 2457        let start;
 2458        let end;
 2459        let mode;
 2460        let mut auto_scroll;
 2461        match click_count {
 2462            1 => {
 2463                start = buffer.anchor_before(position.to_point(&display_map));
 2464                end = start;
 2465                mode = SelectMode::Character;
 2466                auto_scroll = true;
 2467            }
 2468            2 => {
 2469                let range = movement::surrounding_word(&display_map, position);
 2470                start = buffer.anchor_before(range.start.to_point(&display_map));
 2471                end = buffer.anchor_before(range.end.to_point(&display_map));
 2472                mode = SelectMode::Word(start..end);
 2473                auto_scroll = true;
 2474            }
 2475            3 => {
 2476                let position = display_map
 2477                    .clip_point(position, Bias::Left)
 2478                    .to_point(&display_map);
 2479                let line_start = display_map.prev_line_boundary(position).0;
 2480                let next_line_start = buffer.clip_point(
 2481                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2482                    Bias::Left,
 2483                );
 2484                start = buffer.anchor_before(line_start);
 2485                end = buffer.anchor_before(next_line_start);
 2486                mode = SelectMode::Line(start..end);
 2487                auto_scroll = true;
 2488            }
 2489            _ => {
 2490                start = buffer.anchor_before(0);
 2491                end = buffer.anchor_before(buffer.len());
 2492                mode = SelectMode::All;
 2493                auto_scroll = false;
 2494            }
 2495        }
 2496        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2497
 2498        let point_to_delete: Option<usize> = {
 2499            let selected_points: Vec<Selection<Point>> =
 2500                self.selections.disjoint_in_range(start..end, cx);
 2501
 2502            if !add || click_count > 1 {
 2503                None
 2504            } else if !selected_points.is_empty() {
 2505                Some(selected_points[0].id)
 2506            } else {
 2507                let clicked_point_already_selected =
 2508                    self.selections.disjoint.iter().find(|selection| {
 2509                        selection.start.to_point(buffer) == start.to_point(buffer)
 2510                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2511                    });
 2512
 2513                clicked_point_already_selected.map(|selection| selection.id)
 2514            }
 2515        };
 2516
 2517        let selections_count = self.selections.count();
 2518
 2519        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2520            if let Some(point_to_delete) = point_to_delete {
 2521                s.delete(point_to_delete);
 2522
 2523                if selections_count == 1 {
 2524                    s.set_pending_anchor_range(start..end, mode);
 2525                }
 2526            } else {
 2527                if !add {
 2528                    s.clear_disjoint();
 2529                } else if click_count > 1 {
 2530                    s.delete(newest_selection.id)
 2531                }
 2532
 2533                s.set_pending_anchor_range(start..end, mode);
 2534            }
 2535        });
 2536    }
 2537
 2538    fn begin_columnar_selection(
 2539        &mut self,
 2540        position: DisplayPoint,
 2541        goal_column: u32,
 2542        reset: bool,
 2543        window: &mut Window,
 2544        cx: &mut Context<Self>,
 2545    ) {
 2546        if !self.focus_handle.is_focused(window) {
 2547            self.last_focused_descendant = None;
 2548            window.focus(&self.focus_handle);
 2549        }
 2550
 2551        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2552
 2553        if reset {
 2554            let pointer_position = display_map
 2555                .buffer_snapshot
 2556                .anchor_before(position.to_point(&display_map));
 2557
 2558            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2559                s.clear_disjoint();
 2560                s.set_pending_anchor_range(
 2561                    pointer_position..pointer_position,
 2562                    SelectMode::Character,
 2563                );
 2564            });
 2565        }
 2566
 2567        let tail = self.selections.newest::<Point>(cx).tail();
 2568        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2569
 2570        if !reset {
 2571            self.select_columns(
 2572                tail.to_display_point(&display_map),
 2573                position,
 2574                goal_column,
 2575                &display_map,
 2576                window,
 2577                cx,
 2578            );
 2579        }
 2580    }
 2581
 2582    fn update_selection(
 2583        &mut self,
 2584        position: DisplayPoint,
 2585        goal_column: u32,
 2586        scroll_delta: gpui::Point<f32>,
 2587        window: &mut Window,
 2588        cx: &mut Context<Self>,
 2589    ) {
 2590        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2591
 2592        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2593            let tail = tail.to_display_point(&display_map);
 2594            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2595        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2596            let buffer = self.buffer.read(cx).snapshot(cx);
 2597            let head;
 2598            let tail;
 2599            let mode = self.selections.pending_mode().unwrap();
 2600            match &mode {
 2601                SelectMode::Character => {
 2602                    head = position.to_point(&display_map);
 2603                    tail = pending.tail().to_point(&buffer);
 2604                }
 2605                SelectMode::Word(original_range) => {
 2606                    let original_display_range = original_range.start.to_display_point(&display_map)
 2607                        ..original_range.end.to_display_point(&display_map);
 2608                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2609                        ..original_display_range.end.to_point(&display_map);
 2610                    if movement::is_inside_word(&display_map, position)
 2611                        || original_display_range.contains(&position)
 2612                    {
 2613                        let word_range = movement::surrounding_word(&display_map, position);
 2614                        if word_range.start < original_display_range.start {
 2615                            head = word_range.start.to_point(&display_map);
 2616                        } else {
 2617                            head = word_range.end.to_point(&display_map);
 2618                        }
 2619                    } else {
 2620                        head = position.to_point(&display_map);
 2621                    }
 2622
 2623                    if head <= original_buffer_range.start {
 2624                        tail = original_buffer_range.end;
 2625                    } else {
 2626                        tail = original_buffer_range.start;
 2627                    }
 2628                }
 2629                SelectMode::Line(original_range) => {
 2630                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2631
 2632                    let position = display_map
 2633                        .clip_point(position, Bias::Left)
 2634                        .to_point(&display_map);
 2635                    let line_start = display_map.prev_line_boundary(position).0;
 2636                    let next_line_start = buffer.clip_point(
 2637                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2638                        Bias::Left,
 2639                    );
 2640
 2641                    if line_start < original_range.start {
 2642                        head = line_start
 2643                    } else {
 2644                        head = next_line_start
 2645                    }
 2646
 2647                    if head <= original_range.start {
 2648                        tail = original_range.end;
 2649                    } else {
 2650                        tail = original_range.start;
 2651                    }
 2652                }
 2653                SelectMode::All => {
 2654                    return;
 2655                }
 2656            };
 2657
 2658            if head < tail {
 2659                pending.start = buffer.anchor_before(head);
 2660                pending.end = buffer.anchor_before(tail);
 2661                pending.reversed = true;
 2662            } else {
 2663                pending.start = buffer.anchor_before(tail);
 2664                pending.end = buffer.anchor_before(head);
 2665                pending.reversed = false;
 2666            }
 2667
 2668            self.change_selections(None, window, cx, |s| {
 2669                s.set_pending(pending, mode);
 2670            });
 2671        } else {
 2672            log::error!("update_selection dispatched with no pending selection");
 2673            return;
 2674        }
 2675
 2676        self.apply_scroll_delta(scroll_delta, window, cx);
 2677        cx.notify();
 2678    }
 2679
 2680    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2681        self.columnar_selection_tail.take();
 2682        if self.selections.pending_anchor().is_some() {
 2683            let selections = self.selections.all::<usize>(cx);
 2684            self.change_selections(None, window, cx, |s| {
 2685                s.select(selections);
 2686                s.clear_pending();
 2687            });
 2688        }
 2689    }
 2690
 2691    fn select_columns(
 2692        &mut self,
 2693        tail: DisplayPoint,
 2694        head: DisplayPoint,
 2695        goal_column: u32,
 2696        display_map: &DisplaySnapshot,
 2697        window: &mut Window,
 2698        cx: &mut Context<Self>,
 2699    ) {
 2700        let start_row = cmp::min(tail.row(), head.row());
 2701        let end_row = cmp::max(tail.row(), head.row());
 2702        let start_column = cmp::min(tail.column(), goal_column);
 2703        let end_column = cmp::max(tail.column(), goal_column);
 2704        let reversed = start_column < tail.column();
 2705
 2706        let selection_ranges = (start_row.0..=end_row.0)
 2707            .map(DisplayRow)
 2708            .filter_map(|row| {
 2709                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2710                    let start = display_map
 2711                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2712                        .to_point(display_map);
 2713                    let end = display_map
 2714                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2715                        .to_point(display_map);
 2716                    if reversed {
 2717                        Some(end..start)
 2718                    } else {
 2719                        Some(start..end)
 2720                    }
 2721                } else {
 2722                    None
 2723                }
 2724            })
 2725            .collect::<Vec<_>>();
 2726
 2727        self.change_selections(None, window, cx, |s| {
 2728            s.select_ranges(selection_ranges);
 2729        });
 2730        cx.notify();
 2731    }
 2732
 2733    pub fn has_pending_nonempty_selection(&self) -> bool {
 2734        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2735            Some(Selection { start, end, .. }) => start != end,
 2736            None => false,
 2737        };
 2738
 2739        pending_nonempty_selection
 2740            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2741    }
 2742
 2743    pub fn has_pending_selection(&self) -> bool {
 2744        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2745    }
 2746
 2747    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2748        self.selection_mark_mode = false;
 2749
 2750        if self.clear_expanded_diff_hunks(cx) {
 2751            cx.notify();
 2752            return;
 2753        }
 2754        if self.dismiss_menus_and_popups(true, window, cx) {
 2755            return;
 2756        }
 2757
 2758        if self.mode == EditorMode::Full
 2759            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2760        {
 2761            return;
 2762        }
 2763
 2764        cx.propagate();
 2765    }
 2766
 2767    pub fn dismiss_menus_and_popups(
 2768        &mut self,
 2769        is_user_requested: bool,
 2770        window: &mut Window,
 2771        cx: &mut Context<Self>,
 2772    ) -> bool {
 2773        if self.take_rename(false, window, cx).is_some() {
 2774            return true;
 2775        }
 2776
 2777        if hide_hover(self, cx) {
 2778            return true;
 2779        }
 2780
 2781        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2782            return true;
 2783        }
 2784
 2785        if self.hide_context_menu(window, cx).is_some() {
 2786            return true;
 2787        }
 2788
 2789        if self.mouse_context_menu.take().is_some() {
 2790            return true;
 2791        }
 2792
 2793        if is_user_requested && self.discard_inline_completion(true, cx) {
 2794            return true;
 2795        }
 2796
 2797        if self.snippet_stack.pop().is_some() {
 2798            return true;
 2799        }
 2800
 2801        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2802            self.dismiss_diagnostics(cx);
 2803            return true;
 2804        }
 2805
 2806        false
 2807    }
 2808
 2809    fn linked_editing_ranges_for(
 2810        &self,
 2811        selection: Range<text::Anchor>,
 2812        cx: &App,
 2813    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2814        if self.linked_edit_ranges.is_empty() {
 2815            return None;
 2816        }
 2817        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2818            selection.end.buffer_id.and_then(|end_buffer_id| {
 2819                if selection.start.buffer_id != Some(end_buffer_id) {
 2820                    return None;
 2821                }
 2822                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2823                let snapshot = buffer.read(cx).snapshot();
 2824                self.linked_edit_ranges
 2825                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2826                    .map(|ranges| (ranges, snapshot, buffer))
 2827            })?;
 2828        use text::ToOffset as TO;
 2829        // find offset from the start of current range to current cursor position
 2830        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2831
 2832        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2833        let start_difference = start_offset - start_byte_offset;
 2834        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2835        let end_difference = end_offset - start_byte_offset;
 2836        // Current range has associated linked ranges.
 2837        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2838        for range in linked_ranges.iter() {
 2839            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2840            let end_offset = start_offset + end_difference;
 2841            let start_offset = start_offset + start_difference;
 2842            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2843                continue;
 2844            }
 2845            if self.selections.disjoint_anchor_ranges().any(|s| {
 2846                if s.start.buffer_id != selection.start.buffer_id
 2847                    || s.end.buffer_id != selection.end.buffer_id
 2848                {
 2849                    return false;
 2850                }
 2851                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2852                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2853            }) {
 2854                continue;
 2855            }
 2856            let start = buffer_snapshot.anchor_after(start_offset);
 2857            let end = buffer_snapshot.anchor_after(end_offset);
 2858            linked_edits
 2859                .entry(buffer.clone())
 2860                .or_default()
 2861                .push(start..end);
 2862        }
 2863        Some(linked_edits)
 2864    }
 2865
 2866    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2867        let text: Arc<str> = text.into();
 2868
 2869        if self.read_only(cx) {
 2870            return;
 2871        }
 2872
 2873        let selections = self.selections.all_adjusted(cx);
 2874        let mut bracket_inserted = false;
 2875        let mut edits = Vec::new();
 2876        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2877        let mut new_selections = Vec::with_capacity(selections.len());
 2878        let mut new_autoclose_regions = Vec::new();
 2879        let snapshot = self.buffer.read(cx).read(cx);
 2880
 2881        for (selection, autoclose_region) in
 2882            self.selections_with_autoclose_regions(selections, &snapshot)
 2883        {
 2884            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2885                // Determine if the inserted text matches the opening or closing
 2886                // bracket of any of this language's bracket pairs.
 2887                let mut bracket_pair = None;
 2888                let mut is_bracket_pair_start = false;
 2889                let mut is_bracket_pair_end = false;
 2890                if !text.is_empty() {
 2891                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2892                    //  and they are removing the character that triggered IME popup.
 2893                    for (pair, enabled) in scope.brackets() {
 2894                        if !pair.close && !pair.surround {
 2895                            continue;
 2896                        }
 2897
 2898                        if enabled && pair.start.ends_with(text.as_ref()) {
 2899                            let prefix_len = pair.start.len() - text.len();
 2900                            let preceding_text_matches_prefix = prefix_len == 0
 2901                                || (selection.start.column >= (prefix_len as u32)
 2902                                    && snapshot.contains_str_at(
 2903                                        Point::new(
 2904                                            selection.start.row,
 2905                                            selection.start.column - (prefix_len as u32),
 2906                                        ),
 2907                                        &pair.start[..prefix_len],
 2908                                    ));
 2909                            if preceding_text_matches_prefix {
 2910                                bracket_pair = Some(pair.clone());
 2911                                is_bracket_pair_start = true;
 2912                                break;
 2913                            }
 2914                        }
 2915                        if pair.end.as_str() == text.as_ref() {
 2916                            bracket_pair = Some(pair.clone());
 2917                            is_bracket_pair_end = true;
 2918                            break;
 2919                        }
 2920                    }
 2921                }
 2922
 2923                if let Some(bracket_pair) = bracket_pair {
 2924                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2925                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2926                    let auto_surround =
 2927                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2928                    if selection.is_empty() {
 2929                        if is_bracket_pair_start {
 2930                            // If the inserted text is a suffix of an opening bracket and the
 2931                            // selection is preceded by the rest of the opening bracket, then
 2932                            // insert the closing bracket.
 2933                            let following_text_allows_autoclose = snapshot
 2934                                .chars_at(selection.start)
 2935                                .next()
 2936                                .map_or(true, |c| scope.should_autoclose_before(c));
 2937
 2938                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2939                                && bracket_pair.start.len() == 1
 2940                            {
 2941                                let target = bracket_pair.start.chars().next().unwrap();
 2942                                let current_line_count = snapshot
 2943                                    .reversed_chars_at(selection.start)
 2944                                    .take_while(|&c| c != '\n')
 2945                                    .filter(|&c| c == target)
 2946                                    .count();
 2947                                current_line_count % 2 == 1
 2948                            } else {
 2949                                false
 2950                            };
 2951
 2952                            if autoclose
 2953                                && bracket_pair.close
 2954                                && following_text_allows_autoclose
 2955                                && !is_closing_quote
 2956                            {
 2957                                let anchor = snapshot.anchor_before(selection.end);
 2958                                new_selections.push((selection.map(|_| anchor), text.len()));
 2959                                new_autoclose_regions.push((
 2960                                    anchor,
 2961                                    text.len(),
 2962                                    selection.id,
 2963                                    bracket_pair.clone(),
 2964                                ));
 2965                                edits.push((
 2966                                    selection.range(),
 2967                                    format!("{}{}", text, bracket_pair.end).into(),
 2968                                ));
 2969                                bracket_inserted = true;
 2970                                continue;
 2971                            }
 2972                        }
 2973
 2974                        if let Some(region) = autoclose_region {
 2975                            // If the selection is followed by an auto-inserted closing bracket,
 2976                            // then don't insert that closing bracket again; just move the selection
 2977                            // past the closing bracket.
 2978                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2979                                && text.as_ref() == region.pair.end.as_str();
 2980                            if should_skip {
 2981                                let anchor = snapshot.anchor_after(selection.end);
 2982                                new_selections
 2983                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2984                                continue;
 2985                            }
 2986                        }
 2987
 2988                        let always_treat_brackets_as_autoclosed = snapshot
 2989                            .settings_at(selection.start, cx)
 2990                            .always_treat_brackets_as_autoclosed;
 2991                        if always_treat_brackets_as_autoclosed
 2992                            && is_bracket_pair_end
 2993                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2994                        {
 2995                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2996                            // and the inserted text is a closing bracket and the selection is followed
 2997                            // by the closing bracket then move the selection past the closing bracket.
 2998                            let anchor = snapshot.anchor_after(selection.end);
 2999                            new_selections.push((selection.map(|_| anchor), text.len()));
 3000                            continue;
 3001                        }
 3002                    }
 3003                    // If an opening bracket is 1 character long and is typed while
 3004                    // text is selected, then surround that text with the bracket pair.
 3005                    else if auto_surround
 3006                        && bracket_pair.surround
 3007                        && is_bracket_pair_start
 3008                        && bracket_pair.start.chars().count() == 1
 3009                    {
 3010                        edits.push((selection.start..selection.start, text.clone()));
 3011                        edits.push((
 3012                            selection.end..selection.end,
 3013                            bracket_pair.end.as_str().into(),
 3014                        ));
 3015                        bracket_inserted = true;
 3016                        new_selections.push((
 3017                            Selection {
 3018                                id: selection.id,
 3019                                start: snapshot.anchor_after(selection.start),
 3020                                end: snapshot.anchor_before(selection.end),
 3021                                reversed: selection.reversed,
 3022                                goal: selection.goal,
 3023                            },
 3024                            0,
 3025                        ));
 3026                        continue;
 3027                    }
 3028                }
 3029            }
 3030
 3031            if self.auto_replace_emoji_shortcode
 3032                && selection.is_empty()
 3033                && text.as_ref().ends_with(':')
 3034            {
 3035                if let Some(possible_emoji_short_code) =
 3036                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3037                {
 3038                    if !possible_emoji_short_code.is_empty() {
 3039                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3040                            let emoji_shortcode_start = Point::new(
 3041                                selection.start.row,
 3042                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3043                            );
 3044
 3045                            // Remove shortcode from buffer
 3046                            edits.push((
 3047                                emoji_shortcode_start..selection.start,
 3048                                "".to_string().into(),
 3049                            ));
 3050                            new_selections.push((
 3051                                Selection {
 3052                                    id: selection.id,
 3053                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3054                                    end: snapshot.anchor_before(selection.start),
 3055                                    reversed: selection.reversed,
 3056                                    goal: selection.goal,
 3057                                },
 3058                                0,
 3059                            ));
 3060
 3061                            // Insert emoji
 3062                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3063                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3064                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3065
 3066                            continue;
 3067                        }
 3068                    }
 3069                }
 3070            }
 3071
 3072            // If not handling any auto-close operation, then just replace the selected
 3073            // text with the given input and move the selection to the end of the
 3074            // newly inserted text.
 3075            let anchor = snapshot.anchor_after(selection.end);
 3076            if !self.linked_edit_ranges.is_empty() {
 3077                let start_anchor = snapshot.anchor_before(selection.start);
 3078
 3079                let is_word_char = text.chars().next().map_or(true, |char| {
 3080                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3081                    classifier.is_word(char)
 3082                });
 3083
 3084                if is_word_char {
 3085                    if let Some(ranges) = self
 3086                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3087                    {
 3088                        for (buffer, edits) in ranges {
 3089                            linked_edits
 3090                                .entry(buffer.clone())
 3091                                .or_default()
 3092                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3093                        }
 3094                    }
 3095                }
 3096            }
 3097
 3098            new_selections.push((selection.map(|_| anchor), 0));
 3099            edits.push((selection.start..selection.end, text.clone()));
 3100        }
 3101
 3102        drop(snapshot);
 3103
 3104        self.transact(window, cx, |this, window, cx| {
 3105            this.buffer.update(cx, |buffer, cx| {
 3106                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3107            });
 3108            for (buffer, edits) in linked_edits {
 3109                buffer.update(cx, |buffer, cx| {
 3110                    let snapshot = buffer.snapshot();
 3111                    let edits = edits
 3112                        .into_iter()
 3113                        .map(|(range, text)| {
 3114                            use text::ToPoint as TP;
 3115                            let end_point = TP::to_point(&range.end, &snapshot);
 3116                            let start_point = TP::to_point(&range.start, &snapshot);
 3117                            (start_point..end_point, text)
 3118                        })
 3119                        .sorted_by_key(|(range, _)| range.start)
 3120                        .collect::<Vec<_>>();
 3121                    buffer.edit(edits, None, cx);
 3122                })
 3123            }
 3124            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3125            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3126            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3127            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3128                .zip(new_selection_deltas)
 3129                .map(|(selection, delta)| Selection {
 3130                    id: selection.id,
 3131                    start: selection.start + delta,
 3132                    end: selection.end + delta,
 3133                    reversed: selection.reversed,
 3134                    goal: SelectionGoal::None,
 3135                })
 3136                .collect::<Vec<_>>();
 3137
 3138            let mut i = 0;
 3139            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3140                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3141                let start = map.buffer_snapshot.anchor_before(position);
 3142                let end = map.buffer_snapshot.anchor_after(position);
 3143                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3144                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3145                        Ordering::Less => i += 1,
 3146                        Ordering::Greater => break,
 3147                        Ordering::Equal => {
 3148                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3149                                Ordering::Less => i += 1,
 3150                                Ordering::Equal => break,
 3151                                Ordering::Greater => break,
 3152                            }
 3153                        }
 3154                    }
 3155                }
 3156                this.autoclose_regions.insert(
 3157                    i,
 3158                    AutocloseRegion {
 3159                        selection_id,
 3160                        range: start..end,
 3161                        pair,
 3162                    },
 3163                );
 3164            }
 3165
 3166            let had_active_inline_completion = this.has_active_inline_completion();
 3167            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3168                s.select(new_selections)
 3169            });
 3170
 3171            if !bracket_inserted {
 3172                if let Some(on_type_format_task) =
 3173                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3174                {
 3175                    on_type_format_task.detach_and_log_err(cx);
 3176                }
 3177            }
 3178
 3179            let editor_settings = EditorSettings::get_global(cx);
 3180            if bracket_inserted
 3181                && (editor_settings.auto_signature_help
 3182                    || editor_settings.show_signature_help_after_edits)
 3183            {
 3184                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3185            }
 3186
 3187            let trigger_in_words =
 3188                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3189            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3190            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3191            this.refresh_inline_completion(true, false, window, cx);
 3192        });
 3193    }
 3194
 3195    fn find_possible_emoji_shortcode_at_position(
 3196        snapshot: &MultiBufferSnapshot,
 3197        position: Point,
 3198    ) -> Option<String> {
 3199        let mut chars = Vec::new();
 3200        let mut found_colon = false;
 3201        for char in snapshot.reversed_chars_at(position).take(100) {
 3202            // Found a possible emoji shortcode in the middle of the buffer
 3203            if found_colon {
 3204                if char.is_whitespace() {
 3205                    chars.reverse();
 3206                    return Some(chars.iter().collect());
 3207                }
 3208                // If the previous character is not a whitespace, we are in the middle of a word
 3209                // and we only want to complete the shortcode if the word is made up of other emojis
 3210                let mut containing_word = String::new();
 3211                for ch in snapshot
 3212                    .reversed_chars_at(position)
 3213                    .skip(chars.len() + 1)
 3214                    .take(100)
 3215                {
 3216                    if ch.is_whitespace() {
 3217                        break;
 3218                    }
 3219                    containing_word.push(ch);
 3220                }
 3221                let containing_word = containing_word.chars().rev().collect::<String>();
 3222                if util::word_consists_of_emojis(containing_word.as_str()) {
 3223                    chars.reverse();
 3224                    return Some(chars.iter().collect());
 3225                }
 3226            }
 3227
 3228            if char.is_whitespace() || !char.is_ascii() {
 3229                return None;
 3230            }
 3231            if char == ':' {
 3232                found_colon = true;
 3233            } else {
 3234                chars.push(char);
 3235            }
 3236        }
 3237        // Found a possible emoji shortcode at the beginning of the buffer
 3238        chars.reverse();
 3239        Some(chars.iter().collect())
 3240    }
 3241
 3242    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3243        self.transact(window, cx, |this, window, cx| {
 3244            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3245                let selections = this.selections.all::<usize>(cx);
 3246                let multi_buffer = this.buffer.read(cx);
 3247                let buffer = multi_buffer.snapshot(cx);
 3248                selections
 3249                    .iter()
 3250                    .map(|selection| {
 3251                        let start_point = selection.start.to_point(&buffer);
 3252                        let mut indent =
 3253                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3254                        indent.len = cmp::min(indent.len, start_point.column);
 3255                        let start = selection.start;
 3256                        let end = selection.end;
 3257                        let selection_is_empty = start == end;
 3258                        let language_scope = buffer.language_scope_at(start);
 3259                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3260                            &language_scope
 3261                        {
 3262                            let insert_extra_newline =
 3263                                insert_extra_newline_brackets(&buffer, start..end, language)
 3264                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3265
 3266                            // Comment extension on newline is allowed only for cursor selections
 3267                            let comment_delimiter = maybe!({
 3268                                if !selection_is_empty {
 3269                                    return None;
 3270                                }
 3271
 3272                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3273                                    return None;
 3274                                }
 3275
 3276                                let delimiters = language.line_comment_prefixes();
 3277                                let max_len_of_delimiter =
 3278                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3279                                let (snapshot, range) =
 3280                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3281
 3282                                let mut index_of_first_non_whitespace = 0;
 3283                                let comment_candidate = snapshot
 3284                                    .chars_for_range(range)
 3285                                    .skip_while(|c| {
 3286                                        let should_skip = c.is_whitespace();
 3287                                        if should_skip {
 3288                                            index_of_first_non_whitespace += 1;
 3289                                        }
 3290                                        should_skip
 3291                                    })
 3292                                    .take(max_len_of_delimiter)
 3293                                    .collect::<String>();
 3294                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3295                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3296                                })?;
 3297                                let cursor_is_placed_after_comment_marker =
 3298                                    index_of_first_non_whitespace + comment_prefix.len()
 3299                                        <= start_point.column as usize;
 3300                                if cursor_is_placed_after_comment_marker {
 3301                                    Some(comment_prefix.clone())
 3302                                } else {
 3303                                    None
 3304                                }
 3305                            });
 3306                            (comment_delimiter, insert_extra_newline)
 3307                        } else {
 3308                            (None, false)
 3309                        };
 3310
 3311                        let capacity_for_delimiter = comment_delimiter
 3312                            .as_deref()
 3313                            .map(str::len)
 3314                            .unwrap_or_default();
 3315                        let mut new_text =
 3316                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3317                        new_text.push('\n');
 3318                        new_text.extend(indent.chars());
 3319                        if let Some(delimiter) = &comment_delimiter {
 3320                            new_text.push_str(delimiter);
 3321                        }
 3322                        if insert_extra_newline {
 3323                            new_text = new_text.repeat(2);
 3324                        }
 3325
 3326                        let anchor = buffer.anchor_after(end);
 3327                        let new_selection = selection.map(|_| anchor);
 3328                        (
 3329                            (start..end, new_text),
 3330                            (insert_extra_newline, new_selection),
 3331                        )
 3332                    })
 3333                    .unzip()
 3334            };
 3335
 3336            this.edit_with_autoindent(edits, cx);
 3337            let buffer = this.buffer.read(cx).snapshot(cx);
 3338            let new_selections = selection_fixup_info
 3339                .into_iter()
 3340                .map(|(extra_newline_inserted, new_selection)| {
 3341                    let mut cursor = new_selection.end.to_point(&buffer);
 3342                    if extra_newline_inserted {
 3343                        cursor.row -= 1;
 3344                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3345                    }
 3346                    new_selection.map(|_| cursor)
 3347                })
 3348                .collect();
 3349
 3350            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3351                s.select(new_selections)
 3352            });
 3353            this.refresh_inline_completion(true, false, window, cx);
 3354        });
 3355    }
 3356
 3357    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3358        let buffer = self.buffer.read(cx);
 3359        let snapshot = buffer.snapshot(cx);
 3360
 3361        let mut edits = Vec::new();
 3362        let mut rows = Vec::new();
 3363
 3364        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3365            let cursor = selection.head();
 3366            let row = cursor.row;
 3367
 3368            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3369
 3370            let newline = "\n".to_string();
 3371            edits.push((start_of_line..start_of_line, newline));
 3372
 3373            rows.push(row + rows_inserted as u32);
 3374        }
 3375
 3376        self.transact(window, cx, |editor, window, cx| {
 3377            editor.edit(edits, cx);
 3378
 3379            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3380                let mut index = 0;
 3381                s.move_cursors_with(|map, _, _| {
 3382                    let row = rows[index];
 3383                    index += 1;
 3384
 3385                    let point = Point::new(row, 0);
 3386                    let boundary = map.next_line_boundary(point).1;
 3387                    let clipped = map.clip_point(boundary, Bias::Left);
 3388
 3389                    (clipped, SelectionGoal::None)
 3390                });
 3391            });
 3392
 3393            let mut indent_edits = Vec::new();
 3394            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3395            for row in rows {
 3396                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3397                for (row, indent) in indents {
 3398                    if indent.len == 0 {
 3399                        continue;
 3400                    }
 3401
 3402                    let text = match indent.kind {
 3403                        IndentKind::Space => " ".repeat(indent.len as usize),
 3404                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3405                    };
 3406                    let point = Point::new(row.0, 0);
 3407                    indent_edits.push((point..point, text));
 3408                }
 3409            }
 3410            editor.edit(indent_edits, cx);
 3411        });
 3412    }
 3413
 3414    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3415        let buffer = self.buffer.read(cx);
 3416        let snapshot = buffer.snapshot(cx);
 3417
 3418        let mut edits = Vec::new();
 3419        let mut rows = Vec::new();
 3420        let mut rows_inserted = 0;
 3421
 3422        for selection in self.selections.all_adjusted(cx) {
 3423            let cursor = selection.head();
 3424            let row = cursor.row;
 3425
 3426            let point = Point::new(row + 1, 0);
 3427            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3428
 3429            let newline = "\n".to_string();
 3430            edits.push((start_of_line..start_of_line, newline));
 3431
 3432            rows_inserted += 1;
 3433            rows.push(row + rows_inserted);
 3434        }
 3435
 3436        self.transact(window, cx, |editor, window, cx| {
 3437            editor.edit(edits, cx);
 3438
 3439            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3440                let mut index = 0;
 3441                s.move_cursors_with(|map, _, _| {
 3442                    let row = rows[index];
 3443                    index += 1;
 3444
 3445                    let point = Point::new(row, 0);
 3446                    let boundary = map.next_line_boundary(point).1;
 3447                    let clipped = map.clip_point(boundary, Bias::Left);
 3448
 3449                    (clipped, SelectionGoal::None)
 3450                });
 3451            });
 3452
 3453            let mut indent_edits = Vec::new();
 3454            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3455            for row in rows {
 3456                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3457                for (row, indent) in indents {
 3458                    if indent.len == 0 {
 3459                        continue;
 3460                    }
 3461
 3462                    let text = match indent.kind {
 3463                        IndentKind::Space => " ".repeat(indent.len as usize),
 3464                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3465                    };
 3466                    let point = Point::new(row.0, 0);
 3467                    indent_edits.push((point..point, text));
 3468                }
 3469            }
 3470            editor.edit(indent_edits, cx);
 3471        });
 3472    }
 3473
 3474    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3475        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3476            original_start_columns: Vec::new(),
 3477        });
 3478        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3479    }
 3480
 3481    fn insert_with_autoindent_mode(
 3482        &mut self,
 3483        text: &str,
 3484        autoindent_mode: Option<AutoindentMode>,
 3485        window: &mut Window,
 3486        cx: &mut Context<Self>,
 3487    ) {
 3488        if self.read_only(cx) {
 3489            return;
 3490        }
 3491
 3492        let text: Arc<str> = text.into();
 3493        self.transact(window, cx, |this, window, cx| {
 3494            let old_selections = this.selections.all_adjusted(cx);
 3495            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3496                let anchors = {
 3497                    let snapshot = buffer.read(cx);
 3498                    old_selections
 3499                        .iter()
 3500                        .map(|s| {
 3501                            let anchor = snapshot.anchor_after(s.head());
 3502                            s.map(|_| anchor)
 3503                        })
 3504                        .collect::<Vec<_>>()
 3505                };
 3506                buffer.edit(
 3507                    old_selections
 3508                        .iter()
 3509                        .map(|s| (s.start..s.end, text.clone())),
 3510                    autoindent_mode,
 3511                    cx,
 3512                );
 3513                anchors
 3514            });
 3515
 3516            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3517                s.select_anchors(selection_anchors);
 3518            });
 3519
 3520            cx.notify();
 3521        });
 3522    }
 3523
 3524    fn trigger_completion_on_input(
 3525        &mut self,
 3526        text: &str,
 3527        trigger_in_words: bool,
 3528        window: &mut Window,
 3529        cx: &mut Context<Self>,
 3530    ) {
 3531        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3532            self.show_completions(
 3533                &ShowCompletions {
 3534                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3535                },
 3536                window,
 3537                cx,
 3538            );
 3539        } else {
 3540            self.hide_context_menu(window, cx);
 3541        }
 3542    }
 3543
 3544    fn is_completion_trigger(
 3545        &self,
 3546        text: &str,
 3547        trigger_in_words: bool,
 3548        cx: &mut Context<Self>,
 3549    ) -> bool {
 3550        let position = self.selections.newest_anchor().head();
 3551        let multibuffer = self.buffer.read(cx);
 3552        let Some(buffer) = position
 3553            .buffer_id
 3554            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3555        else {
 3556            return false;
 3557        };
 3558
 3559        if let Some(completion_provider) = &self.completion_provider {
 3560            completion_provider.is_completion_trigger(
 3561                &buffer,
 3562                position.text_anchor,
 3563                text,
 3564                trigger_in_words,
 3565                cx,
 3566            )
 3567        } else {
 3568            false
 3569        }
 3570    }
 3571
 3572    /// If any empty selections is touching the start of its innermost containing autoclose
 3573    /// region, expand it to select the brackets.
 3574    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3575        let selections = self.selections.all::<usize>(cx);
 3576        let buffer = self.buffer.read(cx).read(cx);
 3577        let new_selections = self
 3578            .selections_with_autoclose_regions(selections, &buffer)
 3579            .map(|(mut selection, region)| {
 3580                if !selection.is_empty() {
 3581                    return selection;
 3582                }
 3583
 3584                if let Some(region) = region {
 3585                    let mut range = region.range.to_offset(&buffer);
 3586                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3587                        range.start -= region.pair.start.len();
 3588                        if buffer.contains_str_at(range.start, &region.pair.start)
 3589                            && buffer.contains_str_at(range.end, &region.pair.end)
 3590                        {
 3591                            range.end += region.pair.end.len();
 3592                            selection.start = range.start;
 3593                            selection.end = range.end;
 3594
 3595                            return selection;
 3596                        }
 3597                    }
 3598                }
 3599
 3600                let always_treat_brackets_as_autoclosed = buffer
 3601                    .settings_at(selection.start, cx)
 3602                    .always_treat_brackets_as_autoclosed;
 3603
 3604                if !always_treat_brackets_as_autoclosed {
 3605                    return selection;
 3606                }
 3607
 3608                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3609                    for (pair, enabled) in scope.brackets() {
 3610                        if !enabled || !pair.close {
 3611                            continue;
 3612                        }
 3613
 3614                        if buffer.contains_str_at(selection.start, &pair.end) {
 3615                            let pair_start_len = pair.start.len();
 3616                            if buffer.contains_str_at(
 3617                                selection.start.saturating_sub(pair_start_len),
 3618                                &pair.start,
 3619                            ) {
 3620                                selection.start -= pair_start_len;
 3621                                selection.end += pair.end.len();
 3622
 3623                                return selection;
 3624                            }
 3625                        }
 3626                    }
 3627                }
 3628
 3629                selection
 3630            })
 3631            .collect();
 3632
 3633        drop(buffer);
 3634        self.change_selections(None, window, cx, |selections| {
 3635            selections.select(new_selections)
 3636        });
 3637    }
 3638
 3639    /// Iterate the given selections, and for each one, find the smallest surrounding
 3640    /// autoclose region. This uses the ordering of the selections and the autoclose
 3641    /// regions to avoid repeated comparisons.
 3642    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3643        &'a self,
 3644        selections: impl IntoIterator<Item = Selection<D>>,
 3645        buffer: &'a MultiBufferSnapshot,
 3646    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3647        let mut i = 0;
 3648        let mut regions = self.autoclose_regions.as_slice();
 3649        selections.into_iter().map(move |selection| {
 3650            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3651
 3652            let mut enclosing = None;
 3653            while let Some(pair_state) = regions.get(i) {
 3654                if pair_state.range.end.to_offset(buffer) < range.start {
 3655                    regions = &regions[i + 1..];
 3656                    i = 0;
 3657                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3658                    break;
 3659                } else {
 3660                    if pair_state.selection_id == selection.id {
 3661                        enclosing = Some(pair_state);
 3662                    }
 3663                    i += 1;
 3664                }
 3665            }
 3666
 3667            (selection, enclosing)
 3668        })
 3669    }
 3670
 3671    /// Remove any autoclose regions that no longer contain their selection.
 3672    fn invalidate_autoclose_regions(
 3673        &mut self,
 3674        mut selections: &[Selection<Anchor>],
 3675        buffer: &MultiBufferSnapshot,
 3676    ) {
 3677        self.autoclose_regions.retain(|state| {
 3678            let mut i = 0;
 3679            while let Some(selection) = selections.get(i) {
 3680                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3681                    selections = &selections[1..];
 3682                    continue;
 3683                }
 3684                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3685                    break;
 3686                }
 3687                if selection.id == state.selection_id {
 3688                    return true;
 3689                } else {
 3690                    i += 1;
 3691                }
 3692            }
 3693            false
 3694        });
 3695    }
 3696
 3697    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3698        let offset = position.to_offset(buffer);
 3699        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3700        if offset > word_range.start && kind == Some(CharKind::Word) {
 3701            Some(
 3702                buffer
 3703                    .text_for_range(word_range.start..offset)
 3704                    .collect::<String>(),
 3705            )
 3706        } else {
 3707            None
 3708        }
 3709    }
 3710
 3711    pub fn toggle_inlay_hints(
 3712        &mut self,
 3713        _: &ToggleInlayHints,
 3714        _: &mut Window,
 3715        cx: &mut Context<Self>,
 3716    ) {
 3717        self.refresh_inlay_hints(
 3718            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 3719            cx,
 3720        );
 3721    }
 3722
 3723    pub fn inlay_hints_enabled(&self) -> bool {
 3724        self.inlay_hint_cache.enabled
 3725    }
 3726
 3727    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3728        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3729            return;
 3730        }
 3731
 3732        let reason_description = reason.description();
 3733        let ignore_debounce = matches!(
 3734            reason,
 3735            InlayHintRefreshReason::SettingsChange(_)
 3736                | InlayHintRefreshReason::Toggle(_)
 3737                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3738                | InlayHintRefreshReason::ModifiersChanged(_)
 3739        );
 3740        let (invalidate_cache, required_languages) = match reason {
 3741            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 3742                match self.inlay_hint_cache.modifiers_override(enabled) {
 3743                    Some(enabled) => {
 3744                        if enabled {
 3745                            (InvalidationStrategy::RefreshRequested, None)
 3746                        } else {
 3747                            self.splice_inlays(
 3748                                &self
 3749                                    .visible_inlay_hints(cx)
 3750                                    .iter()
 3751                                    .map(|inlay| inlay.id)
 3752                                    .collect::<Vec<InlayId>>(),
 3753                                Vec::new(),
 3754                                cx,
 3755                            );
 3756                            return;
 3757                        }
 3758                    }
 3759                    None => return,
 3760                }
 3761            }
 3762            InlayHintRefreshReason::Toggle(enabled) => {
 3763                if self.inlay_hint_cache.toggle(enabled) {
 3764                    if enabled {
 3765                        (InvalidationStrategy::RefreshRequested, None)
 3766                    } else {
 3767                        self.splice_inlays(
 3768                            &self
 3769                                .visible_inlay_hints(cx)
 3770                                .iter()
 3771                                .map(|inlay| inlay.id)
 3772                                .collect::<Vec<InlayId>>(),
 3773                            Vec::new(),
 3774                            cx,
 3775                        );
 3776                        return;
 3777                    }
 3778                } else {
 3779                    return;
 3780                }
 3781            }
 3782            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3783                match self.inlay_hint_cache.update_settings(
 3784                    &self.buffer,
 3785                    new_settings,
 3786                    self.visible_inlay_hints(cx),
 3787                    cx,
 3788                ) {
 3789                    ControlFlow::Break(Some(InlaySplice {
 3790                        to_remove,
 3791                        to_insert,
 3792                    })) => {
 3793                        self.splice_inlays(&to_remove, to_insert, cx);
 3794                        return;
 3795                    }
 3796                    ControlFlow::Break(None) => return,
 3797                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3798                }
 3799            }
 3800            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3801                if let Some(InlaySplice {
 3802                    to_remove,
 3803                    to_insert,
 3804                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3805                {
 3806                    self.splice_inlays(&to_remove, to_insert, cx);
 3807                }
 3808                return;
 3809            }
 3810            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3811            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3812                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3813            }
 3814            InlayHintRefreshReason::RefreshRequested => {
 3815                (InvalidationStrategy::RefreshRequested, None)
 3816            }
 3817        };
 3818
 3819        if let Some(InlaySplice {
 3820            to_remove,
 3821            to_insert,
 3822        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3823            reason_description,
 3824            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3825            invalidate_cache,
 3826            ignore_debounce,
 3827            cx,
 3828        ) {
 3829            self.splice_inlays(&to_remove, to_insert, cx);
 3830        }
 3831    }
 3832
 3833    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3834        self.display_map
 3835            .read(cx)
 3836            .current_inlays()
 3837            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3838            .cloned()
 3839            .collect()
 3840    }
 3841
 3842    pub fn excerpts_for_inlay_hints_query(
 3843        &self,
 3844        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3845        cx: &mut Context<Editor>,
 3846    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3847        let Some(project) = self.project.as_ref() else {
 3848            return HashMap::default();
 3849        };
 3850        let project = project.read(cx);
 3851        let multi_buffer = self.buffer().read(cx);
 3852        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3853        let multi_buffer_visible_start = self
 3854            .scroll_manager
 3855            .anchor()
 3856            .anchor
 3857            .to_point(&multi_buffer_snapshot);
 3858        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3859            multi_buffer_visible_start
 3860                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3861            Bias::Left,
 3862        );
 3863        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3864        multi_buffer_snapshot
 3865            .range_to_buffer_ranges(multi_buffer_visible_range)
 3866            .into_iter()
 3867            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3868            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3869                let buffer_file = project::File::from_dyn(buffer.file())?;
 3870                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3871                let worktree_entry = buffer_worktree
 3872                    .read(cx)
 3873                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3874                if worktree_entry.is_ignored {
 3875                    return None;
 3876                }
 3877
 3878                let language = buffer.language()?;
 3879                if let Some(restrict_to_languages) = restrict_to_languages {
 3880                    if !restrict_to_languages.contains(language) {
 3881                        return None;
 3882                    }
 3883                }
 3884                Some((
 3885                    excerpt_id,
 3886                    (
 3887                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3888                        buffer.version().clone(),
 3889                        excerpt_visible_range,
 3890                    ),
 3891                ))
 3892            })
 3893            .collect()
 3894    }
 3895
 3896    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3897        TextLayoutDetails {
 3898            text_system: window.text_system().clone(),
 3899            editor_style: self.style.clone().unwrap(),
 3900            rem_size: window.rem_size(),
 3901            scroll_anchor: self.scroll_manager.anchor(),
 3902            visible_rows: self.visible_line_count(),
 3903            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3904        }
 3905    }
 3906
 3907    pub fn splice_inlays(
 3908        &self,
 3909        to_remove: &[InlayId],
 3910        to_insert: Vec<Inlay>,
 3911        cx: &mut Context<Self>,
 3912    ) {
 3913        self.display_map.update(cx, |display_map, cx| {
 3914            display_map.splice_inlays(to_remove, to_insert, cx)
 3915        });
 3916        cx.notify();
 3917    }
 3918
 3919    fn trigger_on_type_formatting(
 3920        &self,
 3921        input: String,
 3922        window: &mut Window,
 3923        cx: &mut Context<Self>,
 3924    ) -> Option<Task<Result<()>>> {
 3925        if input.len() != 1 {
 3926            return None;
 3927        }
 3928
 3929        let project = self.project.as_ref()?;
 3930        let position = self.selections.newest_anchor().head();
 3931        let (buffer, buffer_position) = self
 3932            .buffer
 3933            .read(cx)
 3934            .text_anchor_for_position(position, cx)?;
 3935
 3936        let settings = language_settings::language_settings(
 3937            buffer
 3938                .read(cx)
 3939                .language_at(buffer_position)
 3940                .map(|l| l.name()),
 3941            buffer.read(cx).file(),
 3942            cx,
 3943        );
 3944        if !settings.use_on_type_format {
 3945            return None;
 3946        }
 3947
 3948        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3949        // hence we do LSP request & edit on host side only — add formats to host's history.
 3950        let push_to_lsp_host_history = true;
 3951        // If this is not the host, append its history with new edits.
 3952        let push_to_client_history = project.read(cx).is_via_collab();
 3953
 3954        let on_type_formatting = project.update(cx, |project, cx| {
 3955            project.on_type_format(
 3956                buffer.clone(),
 3957                buffer_position,
 3958                input,
 3959                push_to_lsp_host_history,
 3960                cx,
 3961            )
 3962        });
 3963        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3964            if let Some(transaction) = on_type_formatting.await? {
 3965                if push_to_client_history {
 3966                    buffer
 3967                        .update(&mut cx, |buffer, _| {
 3968                            buffer.push_transaction(transaction, Instant::now());
 3969                        })
 3970                        .ok();
 3971                }
 3972                editor.update(&mut cx, |editor, cx| {
 3973                    editor.refresh_document_highlights(cx);
 3974                })?;
 3975            }
 3976            Ok(())
 3977        }))
 3978    }
 3979
 3980    pub fn show_completions(
 3981        &mut self,
 3982        options: &ShowCompletions,
 3983        window: &mut Window,
 3984        cx: &mut Context<Self>,
 3985    ) {
 3986        if self.pending_rename.is_some() {
 3987            return;
 3988        }
 3989
 3990        let Some(provider) = self.completion_provider.as_ref() else {
 3991            return;
 3992        };
 3993
 3994        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3995            return;
 3996        }
 3997
 3998        let position = self.selections.newest_anchor().head();
 3999        if position.diff_base_anchor.is_some() {
 4000            return;
 4001        }
 4002        let (buffer, buffer_position) =
 4003            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4004                output
 4005            } else {
 4006                return;
 4007            };
 4008        let show_completion_documentation = buffer
 4009            .read(cx)
 4010            .snapshot()
 4011            .settings_at(buffer_position, cx)
 4012            .show_completion_documentation;
 4013
 4014        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4015
 4016        let trigger_kind = match &options.trigger {
 4017            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4018                CompletionTriggerKind::TRIGGER_CHARACTER
 4019            }
 4020            _ => CompletionTriggerKind::INVOKED,
 4021        };
 4022        let completion_context = CompletionContext {
 4023            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4024                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4025                    Some(String::from(trigger))
 4026                } else {
 4027                    None
 4028                }
 4029            }),
 4030            trigger_kind,
 4031        };
 4032        let completions =
 4033            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 4034        let sort_completions = provider.sort_completions();
 4035
 4036        let id = post_inc(&mut self.next_completion_id);
 4037        let task = cx.spawn_in(window, |editor, mut cx| {
 4038            async move {
 4039                editor.update(&mut cx, |this, _| {
 4040                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4041                })?;
 4042                let completions = completions.await.log_err();
 4043                let menu = if let Some(completions) = completions {
 4044                    let mut menu = CompletionsMenu::new(
 4045                        id,
 4046                        sort_completions,
 4047                        show_completion_documentation,
 4048                        position,
 4049                        buffer.clone(),
 4050                        completions.into(),
 4051                    );
 4052
 4053                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4054                        .await;
 4055
 4056                    menu.visible().then_some(menu)
 4057                } else {
 4058                    None
 4059                };
 4060
 4061                editor.update_in(&mut cx, |editor, window, cx| {
 4062                    match editor.context_menu.borrow().as_ref() {
 4063                        None => {}
 4064                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4065                            if prev_menu.id > id {
 4066                                return;
 4067                            }
 4068                        }
 4069                        _ => return,
 4070                    }
 4071
 4072                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4073                        let mut menu = menu.unwrap();
 4074                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4075
 4076                        *editor.context_menu.borrow_mut() =
 4077                            Some(CodeContextMenu::Completions(menu));
 4078
 4079                        if editor.show_edit_predictions_in_menu() {
 4080                            editor.update_visible_inline_completion(window, cx);
 4081                        } else {
 4082                            editor.discard_inline_completion(false, cx);
 4083                        }
 4084
 4085                        cx.notify();
 4086                    } else if editor.completion_tasks.len() <= 1 {
 4087                        // If there are no more completion tasks and the last menu was
 4088                        // empty, we should hide it.
 4089                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4090                        // If it was already hidden and we don't show inline
 4091                        // completions in the menu, we should also show the
 4092                        // inline-completion when available.
 4093                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4094                            editor.update_visible_inline_completion(window, cx);
 4095                        }
 4096                    }
 4097                })?;
 4098
 4099                Ok::<_, anyhow::Error>(())
 4100            }
 4101            .log_err()
 4102        });
 4103
 4104        self.completion_tasks.push((id, task));
 4105    }
 4106
 4107    pub fn confirm_completion(
 4108        &mut self,
 4109        action: &ConfirmCompletion,
 4110        window: &mut Window,
 4111        cx: &mut Context<Self>,
 4112    ) -> Option<Task<Result<()>>> {
 4113        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4114    }
 4115
 4116    pub fn compose_completion(
 4117        &mut self,
 4118        action: &ComposeCompletion,
 4119        window: &mut Window,
 4120        cx: &mut Context<Self>,
 4121    ) -> Option<Task<Result<()>>> {
 4122        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4123    }
 4124
 4125    fn do_completion(
 4126        &mut self,
 4127        item_ix: Option<usize>,
 4128        intent: CompletionIntent,
 4129        window: &mut Window,
 4130        cx: &mut Context<Editor>,
 4131    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4132        use language::ToOffset as _;
 4133
 4134        let completions_menu =
 4135            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4136                menu
 4137            } else {
 4138                return None;
 4139            };
 4140
 4141        let entries = completions_menu.entries.borrow();
 4142        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4143        if self.show_edit_predictions_in_menu() {
 4144            self.discard_inline_completion(true, cx);
 4145        }
 4146        let candidate_id = mat.candidate_id;
 4147        drop(entries);
 4148
 4149        let buffer_handle = completions_menu.buffer;
 4150        let completion = completions_menu
 4151            .completions
 4152            .borrow()
 4153            .get(candidate_id)?
 4154            .clone();
 4155        cx.stop_propagation();
 4156
 4157        let snippet;
 4158        let text;
 4159
 4160        if completion.is_snippet() {
 4161            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4162            text = snippet.as_ref().unwrap().text.clone();
 4163        } else {
 4164            snippet = None;
 4165            text = completion.new_text.clone();
 4166        };
 4167        let selections = self.selections.all::<usize>(cx);
 4168        let buffer = buffer_handle.read(cx);
 4169        let old_range = completion.old_range.to_offset(buffer);
 4170        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4171
 4172        let newest_selection = self.selections.newest_anchor();
 4173        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4174            return None;
 4175        }
 4176
 4177        let lookbehind = newest_selection
 4178            .start
 4179            .text_anchor
 4180            .to_offset(buffer)
 4181            .saturating_sub(old_range.start);
 4182        let lookahead = old_range
 4183            .end
 4184            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4185        let mut common_prefix_len = old_text
 4186            .bytes()
 4187            .zip(text.bytes())
 4188            .take_while(|(a, b)| a == b)
 4189            .count();
 4190
 4191        let snapshot = self.buffer.read(cx).snapshot(cx);
 4192        let mut range_to_replace: Option<Range<isize>> = None;
 4193        let mut ranges = Vec::new();
 4194        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4195        for selection in &selections {
 4196            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4197                let start = selection.start.saturating_sub(lookbehind);
 4198                let end = selection.end + lookahead;
 4199                if selection.id == newest_selection.id {
 4200                    range_to_replace = Some(
 4201                        ((start + common_prefix_len) as isize - selection.start as isize)
 4202                            ..(end as isize - selection.start as isize),
 4203                    );
 4204                }
 4205                ranges.push(start + common_prefix_len..end);
 4206            } else {
 4207                common_prefix_len = 0;
 4208                ranges.clear();
 4209                ranges.extend(selections.iter().map(|s| {
 4210                    if s.id == newest_selection.id {
 4211                        range_to_replace = Some(
 4212                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4213                                - selection.start as isize
 4214                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4215                                    - selection.start as isize,
 4216                        );
 4217                        old_range.clone()
 4218                    } else {
 4219                        s.start..s.end
 4220                    }
 4221                }));
 4222                break;
 4223            }
 4224            if !self.linked_edit_ranges.is_empty() {
 4225                let start_anchor = snapshot.anchor_before(selection.head());
 4226                let end_anchor = snapshot.anchor_after(selection.tail());
 4227                if let Some(ranges) = self
 4228                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4229                {
 4230                    for (buffer, edits) in ranges {
 4231                        linked_edits.entry(buffer.clone()).or_default().extend(
 4232                            edits
 4233                                .into_iter()
 4234                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4235                        );
 4236                    }
 4237                }
 4238            }
 4239        }
 4240        let text = &text[common_prefix_len..];
 4241
 4242        cx.emit(EditorEvent::InputHandled {
 4243            utf16_range_to_replace: range_to_replace,
 4244            text: text.into(),
 4245        });
 4246
 4247        self.transact(window, cx, |this, window, cx| {
 4248            if let Some(mut snippet) = snippet {
 4249                snippet.text = text.to_string();
 4250                for tabstop in snippet
 4251                    .tabstops
 4252                    .iter_mut()
 4253                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4254                {
 4255                    tabstop.start -= common_prefix_len as isize;
 4256                    tabstop.end -= common_prefix_len as isize;
 4257                }
 4258
 4259                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4260            } else {
 4261                this.buffer.update(cx, |buffer, cx| {
 4262                    buffer.edit(
 4263                        ranges.iter().map(|range| (range.clone(), text)),
 4264                        this.autoindent_mode.clone(),
 4265                        cx,
 4266                    );
 4267                });
 4268            }
 4269            for (buffer, edits) in linked_edits {
 4270                buffer.update(cx, |buffer, cx| {
 4271                    let snapshot = buffer.snapshot();
 4272                    let edits = edits
 4273                        .into_iter()
 4274                        .map(|(range, text)| {
 4275                            use text::ToPoint as TP;
 4276                            let end_point = TP::to_point(&range.end, &snapshot);
 4277                            let start_point = TP::to_point(&range.start, &snapshot);
 4278                            (start_point..end_point, text)
 4279                        })
 4280                        .sorted_by_key(|(range, _)| range.start)
 4281                        .collect::<Vec<_>>();
 4282                    buffer.edit(edits, None, cx);
 4283                })
 4284            }
 4285
 4286            this.refresh_inline_completion(true, false, window, cx);
 4287        });
 4288
 4289        let show_new_completions_on_confirm = completion
 4290            .confirm
 4291            .as_ref()
 4292            .map_or(false, |confirm| confirm(intent, window, cx));
 4293        if show_new_completions_on_confirm {
 4294            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4295        }
 4296
 4297        let provider = self.completion_provider.as_ref()?;
 4298        drop(completion);
 4299        let apply_edits = provider.apply_additional_edits_for_completion(
 4300            buffer_handle,
 4301            completions_menu.completions.clone(),
 4302            candidate_id,
 4303            true,
 4304            cx,
 4305        );
 4306
 4307        let editor_settings = EditorSettings::get_global(cx);
 4308        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4309            // After the code completion is finished, users often want to know what signatures are needed.
 4310            // so we should automatically call signature_help
 4311            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4312        }
 4313
 4314        Some(cx.foreground_executor().spawn(async move {
 4315            apply_edits.await?;
 4316            Ok(())
 4317        }))
 4318    }
 4319
 4320    pub fn toggle_code_actions(
 4321        &mut self,
 4322        action: &ToggleCodeActions,
 4323        window: &mut Window,
 4324        cx: &mut Context<Self>,
 4325    ) {
 4326        let mut context_menu = self.context_menu.borrow_mut();
 4327        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4328            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4329                // Toggle if we're selecting the same one
 4330                *context_menu = None;
 4331                cx.notify();
 4332                return;
 4333            } else {
 4334                // Otherwise, clear it and start a new one
 4335                *context_menu = None;
 4336                cx.notify();
 4337            }
 4338        }
 4339        drop(context_menu);
 4340        let snapshot = self.snapshot(window, cx);
 4341        let deployed_from_indicator = action.deployed_from_indicator;
 4342        let mut task = self.code_actions_task.take();
 4343        let action = action.clone();
 4344        cx.spawn_in(window, |editor, mut cx| async move {
 4345            while let Some(prev_task) = task {
 4346                prev_task.await.log_err();
 4347                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4348            }
 4349
 4350            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4351                if editor.focus_handle.is_focused(window) {
 4352                    let multibuffer_point = action
 4353                        .deployed_from_indicator
 4354                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4355                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4356                    let (buffer, buffer_row) = snapshot
 4357                        .buffer_snapshot
 4358                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4359                        .and_then(|(buffer_snapshot, range)| {
 4360                            editor
 4361                                .buffer
 4362                                .read(cx)
 4363                                .buffer(buffer_snapshot.remote_id())
 4364                                .map(|buffer| (buffer, range.start.row))
 4365                        })?;
 4366                    let (_, code_actions) = editor
 4367                        .available_code_actions
 4368                        .clone()
 4369                        .and_then(|(location, code_actions)| {
 4370                            let snapshot = location.buffer.read(cx).snapshot();
 4371                            let point_range = location.range.to_point(&snapshot);
 4372                            let point_range = point_range.start.row..=point_range.end.row;
 4373                            if point_range.contains(&buffer_row) {
 4374                                Some((location, code_actions))
 4375                            } else {
 4376                                None
 4377                            }
 4378                        })
 4379                        .unzip();
 4380                    let buffer_id = buffer.read(cx).remote_id();
 4381                    let tasks = editor
 4382                        .tasks
 4383                        .get(&(buffer_id, buffer_row))
 4384                        .map(|t| Arc::new(t.to_owned()));
 4385                    if tasks.is_none() && code_actions.is_none() {
 4386                        return None;
 4387                    }
 4388
 4389                    editor.completion_tasks.clear();
 4390                    editor.discard_inline_completion(false, cx);
 4391                    let task_context =
 4392                        tasks
 4393                            .as_ref()
 4394                            .zip(editor.project.clone())
 4395                            .map(|(tasks, project)| {
 4396                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4397                            });
 4398
 4399                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4400                        let task_context = match task_context {
 4401                            Some(task_context) => task_context.await,
 4402                            None => None,
 4403                        };
 4404                        let resolved_tasks =
 4405                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4406                                Rc::new(ResolvedTasks {
 4407                                    templates: tasks.resolve(&task_context).collect(),
 4408                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4409                                        multibuffer_point.row,
 4410                                        tasks.column,
 4411                                    )),
 4412                                })
 4413                            });
 4414                        let spawn_straight_away = resolved_tasks
 4415                            .as_ref()
 4416                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4417                            && code_actions
 4418                                .as_ref()
 4419                                .map_or(true, |actions| actions.is_empty());
 4420                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4421                            *editor.context_menu.borrow_mut() =
 4422                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4423                                    buffer,
 4424                                    actions: CodeActionContents {
 4425                                        tasks: resolved_tasks,
 4426                                        actions: code_actions,
 4427                                    },
 4428                                    selected_item: Default::default(),
 4429                                    scroll_handle: UniformListScrollHandle::default(),
 4430                                    deployed_from_indicator,
 4431                                }));
 4432                            if spawn_straight_away {
 4433                                if let Some(task) = editor.confirm_code_action(
 4434                                    &ConfirmCodeAction { item_ix: Some(0) },
 4435                                    window,
 4436                                    cx,
 4437                                ) {
 4438                                    cx.notify();
 4439                                    return task;
 4440                                }
 4441                            }
 4442                            cx.notify();
 4443                            Task::ready(Ok(()))
 4444                        }) {
 4445                            task.await
 4446                        } else {
 4447                            Ok(())
 4448                        }
 4449                    }))
 4450                } else {
 4451                    Some(Task::ready(Ok(())))
 4452                }
 4453            })?;
 4454            if let Some(task) = spawned_test_task {
 4455                task.await?;
 4456            }
 4457
 4458            Ok::<_, anyhow::Error>(())
 4459        })
 4460        .detach_and_log_err(cx);
 4461    }
 4462
 4463    pub fn confirm_code_action(
 4464        &mut self,
 4465        action: &ConfirmCodeAction,
 4466        window: &mut Window,
 4467        cx: &mut Context<Self>,
 4468    ) -> Option<Task<Result<()>>> {
 4469        let actions_menu =
 4470            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4471                menu
 4472            } else {
 4473                return None;
 4474            };
 4475        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4476        let action = actions_menu.actions.get(action_ix)?;
 4477        let title = action.label();
 4478        let buffer = actions_menu.buffer;
 4479        let workspace = self.workspace()?;
 4480
 4481        match action {
 4482            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4483                workspace.update(cx, |workspace, cx| {
 4484                    workspace::tasks::schedule_resolved_task(
 4485                        workspace,
 4486                        task_source_kind,
 4487                        resolved_task,
 4488                        false,
 4489                        cx,
 4490                    );
 4491
 4492                    Some(Task::ready(Ok(())))
 4493                })
 4494            }
 4495            CodeActionsItem::CodeAction {
 4496                excerpt_id,
 4497                action,
 4498                provider,
 4499            } => {
 4500                let apply_code_action =
 4501                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4502                let workspace = workspace.downgrade();
 4503                Some(cx.spawn_in(window, |editor, cx| async move {
 4504                    let project_transaction = apply_code_action.await?;
 4505                    Self::open_project_transaction(
 4506                        &editor,
 4507                        workspace,
 4508                        project_transaction,
 4509                        title,
 4510                        cx,
 4511                    )
 4512                    .await
 4513                }))
 4514            }
 4515        }
 4516    }
 4517
 4518    pub async fn open_project_transaction(
 4519        this: &WeakEntity<Editor>,
 4520        workspace: WeakEntity<Workspace>,
 4521        transaction: ProjectTransaction,
 4522        title: String,
 4523        mut cx: AsyncWindowContext,
 4524    ) -> Result<()> {
 4525        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4526        cx.update(|_, cx| {
 4527            entries.sort_unstable_by_key(|(buffer, _)| {
 4528                buffer.read(cx).file().map(|f| f.path().clone())
 4529            });
 4530        })?;
 4531
 4532        // If the project transaction's edits are all contained within this editor, then
 4533        // avoid opening a new editor to display them.
 4534
 4535        if let Some((buffer, transaction)) = entries.first() {
 4536            if entries.len() == 1 {
 4537                let excerpt = this.update(&mut cx, |editor, cx| {
 4538                    editor
 4539                        .buffer()
 4540                        .read(cx)
 4541                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4542                })?;
 4543                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4544                    if excerpted_buffer == *buffer {
 4545                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4546                            let excerpt_range = excerpt_range.to_offset(buffer);
 4547                            buffer
 4548                                .edited_ranges_for_transaction::<usize>(transaction)
 4549                                .all(|range| {
 4550                                    excerpt_range.start <= range.start
 4551                                        && excerpt_range.end >= range.end
 4552                                })
 4553                        })?;
 4554
 4555                        if all_edits_within_excerpt {
 4556                            return Ok(());
 4557                        }
 4558                    }
 4559                }
 4560            }
 4561        } else {
 4562            return Ok(());
 4563        }
 4564
 4565        let mut ranges_to_highlight = Vec::new();
 4566        let excerpt_buffer = cx.new(|cx| {
 4567            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4568            for (buffer_handle, transaction) in &entries {
 4569                let buffer = buffer_handle.read(cx);
 4570                ranges_to_highlight.extend(
 4571                    multibuffer.push_excerpts_with_context_lines(
 4572                        buffer_handle.clone(),
 4573                        buffer
 4574                            .edited_ranges_for_transaction::<usize>(transaction)
 4575                            .collect(),
 4576                        DEFAULT_MULTIBUFFER_CONTEXT,
 4577                        cx,
 4578                    ),
 4579                );
 4580            }
 4581            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4582            multibuffer
 4583        })?;
 4584
 4585        workspace.update_in(&mut cx, |workspace, window, cx| {
 4586            let project = workspace.project().clone();
 4587            let editor = cx
 4588                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4589            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4590            editor.update(cx, |editor, cx| {
 4591                editor.highlight_background::<Self>(
 4592                    &ranges_to_highlight,
 4593                    |theme| theme.editor_highlighted_line_background,
 4594                    cx,
 4595                );
 4596            });
 4597        })?;
 4598
 4599        Ok(())
 4600    }
 4601
 4602    pub fn clear_code_action_providers(&mut self) {
 4603        self.code_action_providers.clear();
 4604        self.available_code_actions.take();
 4605    }
 4606
 4607    pub fn add_code_action_provider(
 4608        &mut self,
 4609        provider: Rc<dyn CodeActionProvider>,
 4610        window: &mut Window,
 4611        cx: &mut Context<Self>,
 4612    ) {
 4613        if self
 4614            .code_action_providers
 4615            .iter()
 4616            .any(|existing_provider| existing_provider.id() == provider.id())
 4617        {
 4618            return;
 4619        }
 4620
 4621        self.code_action_providers.push(provider);
 4622        self.refresh_code_actions(window, cx);
 4623    }
 4624
 4625    pub fn remove_code_action_provider(
 4626        &mut self,
 4627        id: Arc<str>,
 4628        window: &mut Window,
 4629        cx: &mut Context<Self>,
 4630    ) {
 4631        self.code_action_providers
 4632            .retain(|provider| provider.id() != id);
 4633        self.refresh_code_actions(window, cx);
 4634    }
 4635
 4636    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4637        let buffer = self.buffer.read(cx);
 4638        let newest_selection = self.selections.newest_anchor().clone();
 4639        if newest_selection.head().diff_base_anchor.is_some() {
 4640            return None;
 4641        }
 4642        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4643        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4644        if start_buffer != end_buffer {
 4645            return None;
 4646        }
 4647
 4648        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4649            cx.background_executor()
 4650                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4651                .await;
 4652
 4653            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4654                let providers = this.code_action_providers.clone();
 4655                let tasks = this
 4656                    .code_action_providers
 4657                    .iter()
 4658                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4659                    .collect::<Vec<_>>();
 4660                (providers, tasks)
 4661            })?;
 4662
 4663            let mut actions = Vec::new();
 4664            for (provider, provider_actions) in
 4665                providers.into_iter().zip(future::join_all(tasks).await)
 4666            {
 4667                if let Some(provider_actions) = provider_actions.log_err() {
 4668                    actions.extend(provider_actions.into_iter().map(|action| {
 4669                        AvailableCodeAction {
 4670                            excerpt_id: newest_selection.start.excerpt_id,
 4671                            action,
 4672                            provider: provider.clone(),
 4673                        }
 4674                    }));
 4675                }
 4676            }
 4677
 4678            this.update(&mut cx, |this, cx| {
 4679                this.available_code_actions = if actions.is_empty() {
 4680                    None
 4681                } else {
 4682                    Some((
 4683                        Location {
 4684                            buffer: start_buffer,
 4685                            range: start..end,
 4686                        },
 4687                        actions.into(),
 4688                    ))
 4689                };
 4690                cx.notify();
 4691            })
 4692        }));
 4693        None
 4694    }
 4695
 4696    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4697        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4698            self.show_git_blame_inline = false;
 4699
 4700            self.show_git_blame_inline_delay_task =
 4701                Some(cx.spawn_in(window, |this, mut cx| async move {
 4702                    cx.background_executor().timer(delay).await;
 4703
 4704                    this.update(&mut cx, |this, cx| {
 4705                        this.show_git_blame_inline = true;
 4706                        cx.notify();
 4707                    })
 4708                    .log_err();
 4709                }));
 4710        }
 4711    }
 4712
 4713    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4714        if self.pending_rename.is_some() {
 4715            return None;
 4716        }
 4717
 4718        let provider = self.semantics_provider.clone()?;
 4719        let buffer = self.buffer.read(cx);
 4720        let newest_selection = self.selections.newest_anchor().clone();
 4721        let cursor_position = newest_selection.head();
 4722        let (cursor_buffer, cursor_buffer_position) =
 4723            buffer.text_anchor_for_position(cursor_position, cx)?;
 4724        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4725        if cursor_buffer != tail_buffer {
 4726            return None;
 4727        }
 4728        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4729        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4730            cx.background_executor()
 4731                .timer(Duration::from_millis(debounce))
 4732                .await;
 4733
 4734            let highlights = if let Some(highlights) = cx
 4735                .update(|cx| {
 4736                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4737                })
 4738                .ok()
 4739                .flatten()
 4740            {
 4741                highlights.await.log_err()
 4742            } else {
 4743                None
 4744            };
 4745
 4746            if let Some(highlights) = highlights {
 4747                this.update(&mut cx, |this, cx| {
 4748                    if this.pending_rename.is_some() {
 4749                        return;
 4750                    }
 4751
 4752                    let buffer_id = cursor_position.buffer_id;
 4753                    let buffer = this.buffer.read(cx);
 4754                    if !buffer
 4755                        .text_anchor_for_position(cursor_position, cx)
 4756                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4757                    {
 4758                        return;
 4759                    }
 4760
 4761                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4762                    let mut write_ranges = Vec::new();
 4763                    let mut read_ranges = Vec::new();
 4764                    for highlight in highlights {
 4765                        for (excerpt_id, excerpt_range) in
 4766                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4767                        {
 4768                            let start = highlight
 4769                                .range
 4770                                .start
 4771                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4772                            let end = highlight
 4773                                .range
 4774                                .end
 4775                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4776                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4777                                continue;
 4778                            }
 4779
 4780                            let range = Anchor {
 4781                                buffer_id,
 4782                                excerpt_id,
 4783                                text_anchor: start,
 4784                                diff_base_anchor: None,
 4785                            }..Anchor {
 4786                                buffer_id,
 4787                                excerpt_id,
 4788                                text_anchor: end,
 4789                                diff_base_anchor: None,
 4790                            };
 4791                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4792                                write_ranges.push(range);
 4793                            } else {
 4794                                read_ranges.push(range);
 4795                            }
 4796                        }
 4797                    }
 4798
 4799                    this.highlight_background::<DocumentHighlightRead>(
 4800                        &read_ranges,
 4801                        |theme| theme.editor_document_highlight_read_background,
 4802                        cx,
 4803                    );
 4804                    this.highlight_background::<DocumentHighlightWrite>(
 4805                        &write_ranges,
 4806                        |theme| theme.editor_document_highlight_write_background,
 4807                        cx,
 4808                    );
 4809                    cx.notify();
 4810                })
 4811                .log_err();
 4812            }
 4813        }));
 4814        None
 4815    }
 4816
 4817    pub fn refresh_selected_text_highlights(
 4818        &mut self,
 4819        window: &mut Window,
 4820        cx: &mut Context<Editor>,
 4821    ) {
 4822        self.selection_highlight_task.take();
 4823        if !EditorSettings::get_global(cx).selection_highlight {
 4824            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4825            return;
 4826        }
 4827        if self.selections.count() != 1 || self.selections.line_mode {
 4828            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4829            return;
 4830        }
 4831        let selection = self.selections.newest::<Point>(cx);
 4832        if selection.is_empty() || selection.start.row != selection.end.row {
 4833            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4834            return;
 4835        }
 4836        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4837        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4838            cx.background_executor()
 4839                .timer(Duration::from_millis(debounce))
 4840                .await;
 4841            let Some(Some(matches_task)) = editor
 4842                .update_in(&mut cx, |editor, _, cx| {
 4843                    if editor.selections.count() != 1 || editor.selections.line_mode {
 4844                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4845                        return None;
 4846                    }
 4847                    let selection = editor.selections.newest::<Point>(cx);
 4848                    if selection.is_empty() || selection.start.row != selection.end.row {
 4849                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4850                        return None;
 4851                    }
 4852                    let buffer = editor.buffer().read(cx).snapshot(cx);
 4853                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 4854                    if query.trim().is_empty() {
 4855                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4856                        return None;
 4857                    }
 4858                    Some(cx.background_spawn(async move {
 4859                        let mut ranges = Vec::new();
 4860                        let selection_anchors = selection.range().to_anchors(&buffer);
 4861                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 4862                            for (search_buffer, search_range, excerpt_id) in
 4863                                buffer.range_to_buffer_ranges(range)
 4864                            {
 4865                                ranges.extend(
 4866                                    project::search::SearchQuery::text(
 4867                                        query.clone(),
 4868                                        false,
 4869                                        false,
 4870                                        false,
 4871                                        Default::default(),
 4872                                        Default::default(),
 4873                                        None,
 4874                                    )
 4875                                    .unwrap()
 4876                                    .search(search_buffer, Some(search_range.clone()))
 4877                                    .await
 4878                                    .into_iter()
 4879                                    .filter_map(
 4880                                        |match_range| {
 4881                                            let start = search_buffer.anchor_after(
 4882                                                search_range.start + match_range.start,
 4883                                            );
 4884                                            let end = search_buffer.anchor_before(
 4885                                                search_range.start + match_range.end,
 4886                                            );
 4887                                            let range = Anchor::range_in_buffer(
 4888                                                excerpt_id,
 4889                                                search_buffer.remote_id(),
 4890                                                start..end,
 4891                                            );
 4892                                            (range != selection_anchors).then_some(range)
 4893                                        },
 4894                                    ),
 4895                                );
 4896                            }
 4897                        }
 4898                        ranges
 4899                    }))
 4900                })
 4901                .log_err()
 4902            else {
 4903                return;
 4904            };
 4905            let matches = matches_task.await;
 4906            editor
 4907                .update_in(&mut cx, |editor, _, cx| {
 4908                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4909                    if !matches.is_empty() {
 4910                        editor.highlight_background::<SelectedTextHighlight>(
 4911                            &matches,
 4912                            |theme| theme.editor_document_highlight_bracket_background,
 4913                            cx,
 4914                        )
 4915                    }
 4916                })
 4917                .log_err();
 4918        }));
 4919    }
 4920
 4921    pub fn refresh_inline_completion(
 4922        &mut self,
 4923        debounce: bool,
 4924        user_requested: bool,
 4925        window: &mut Window,
 4926        cx: &mut Context<Self>,
 4927    ) -> Option<()> {
 4928        let provider = self.edit_prediction_provider()?;
 4929        let cursor = self.selections.newest_anchor().head();
 4930        let (buffer, cursor_buffer_position) =
 4931            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4932
 4933        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4934            self.discard_inline_completion(false, cx);
 4935            return None;
 4936        }
 4937
 4938        if !user_requested
 4939            && (!self.should_show_edit_predictions()
 4940                || !self.is_focused(window)
 4941                || buffer.read(cx).is_empty())
 4942        {
 4943            self.discard_inline_completion(false, cx);
 4944            return None;
 4945        }
 4946
 4947        self.update_visible_inline_completion(window, cx);
 4948        provider.refresh(
 4949            self.project.clone(),
 4950            buffer,
 4951            cursor_buffer_position,
 4952            debounce,
 4953            cx,
 4954        );
 4955        Some(())
 4956    }
 4957
 4958    fn show_edit_predictions_in_menu(&self) -> bool {
 4959        match self.edit_prediction_settings {
 4960            EditPredictionSettings::Disabled => false,
 4961            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4962        }
 4963    }
 4964
 4965    pub fn edit_predictions_enabled(&self) -> bool {
 4966        match self.edit_prediction_settings {
 4967            EditPredictionSettings::Disabled => false,
 4968            EditPredictionSettings::Enabled { .. } => true,
 4969        }
 4970    }
 4971
 4972    fn edit_prediction_requires_modifier(&self) -> bool {
 4973        match self.edit_prediction_settings {
 4974            EditPredictionSettings::Disabled => false,
 4975            EditPredictionSettings::Enabled {
 4976                preview_requires_modifier,
 4977                ..
 4978            } => preview_requires_modifier,
 4979        }
 4980    }
 4981
 4982    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 4983        if self.edit_prediction_provider.is_none() {
 4984            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 4985        } else {
 4986            let selection = self.selections.newest_anchor();
 4987            let cursor = selection.head();
 4988
 4989            if let Some((buffer, cursor_buffer_position)) =
 4990                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4991            {
 4992                self.edit_prediction_settings =
 4993                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 4994            }
 4995        }
 4996    }
 4997
 4998    fn edit_prediction_settings_at_position(
 4999        &self,
 5000        buffer: &Entity<Buffer>,
 5001        buffer_position: language::Anchor,
 5002        cx: &App,
 5003    ) -> EditPredictionSettings {
 5004        if self.mode != EditorMode::Full
 5005            || !self.show_inline_completions_override.unwrap_or(true)
 5006            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5007        {
 5008            return EditPredictionSettings::Disabled;
 5009        }
 5010
 5011        let buffer = buffer.read(cx);
 5012
 5013        let file = buffer.file();
 5014
 5015        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5016            return EditPredictionSettings::Disabled;
 5017        };
 5018
 5019        let by_provider = matches!(
 5020            self.menu_inline_completions_policy,
 5021            MenuInlineCompletionsPolicy::ByProvider
 5022        );
 5023
 5024        let show_in_menu = by_provider
 5025            && self
 5026                .edit_prediction_provider
 5027                .as_ref()
 5028                .map_or(false, |provider| {
 5029                    provider.provider.show_completions_in_menu()
 5030                });
 5031
 5032        let preview_requires_modifier =
 5033            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5034
 5035        EditPredictionSettings::Enabled {
 5036            show_in_menu,
 5037            preview_requires_modifier,
 5038        }
 5039    }
 5040
 5041    fn should_show_edit_predictions(&self) -> bool {
 5042        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5043    }
 5044
 5045    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5046        matches!(
 5047            self.edit_prediction_preview,
 5048            EditPredictionPreview::Active { .. }
 5049        )
 5050    }
 5051
 5052    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5053        let cursor = self.selections.newest_anchor().head();
 5054        if let Some((buffer, cursor_position)) =
 5055            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5056        {
 5057            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5058        } else {
 5059            false
 5060        }
 5061    }
 5062
 5063    fn edit_predictions_enabled_in_buffer(
 5064        &self,
 5065        buffer: &Entity<Buffer>,
 5066        buffer_position: language::Anchor,
 5067        cx: &App,
 5068    ) -> bool {
 5069        maybe!({
 5070            let provider = self.edit_prediction_provider()?;
 5071            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5072                return Some(false);
 5073            }
 5074            let buffer = buffer.read(cx);
 5075            let Some(file) = buffer.file() else {
 5076                return Some(true);
 5077            };
 5078            let settings = all_language_settings(Some(file), cx);
 5079            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5080        })
 5081        .unwrap_or(false)
 5082    }
 5083
 5084    fn cycle_inline_completion(
 5085        &mut self,
 5086        direction: Direction,
 5087        window: &mut Window,
 5088        cx: &mut Context<Self>,
 5089    ) -> Option<()> {
 5090        let provider = self.edit_prediction_provider()?;
 5091        let cursor = self.selections.newest_anchor().head();
 5092        let (buffer, cursor_buffer_position) =
 5093            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5094        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5095            return None;
 5096        }
 5097
 5098        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5099        self.update_visible_inline_completion(window, cx);
 5100
 5101        Some(())
 5102    }
 5103
 5104    pub fn show_inline_completion(
 5105        &mut self,
 5106        _: &ShowEditPrediction,
 5107        window: &mut Window,
 5108        cx: &mut Context<Self>,
 5109    ) {
 5110        if !self.has_active_inline_completion() {
 5111            self.refresh_inline_completion(false, true, window, cx);
 5112            return;
 5113        }
 5114
 5115        self.update_visible_inline_completion(window, cx);
 5116    }
 5117
 5118    pub fn display_cursor_names(
 5119        &mut self,
 5120        _: &DisplayCursorNames,
 5121        window: &mut Window,
 5122        cx: &mut Context<Self>,
 5123    ) {
 5124        self.show_cursor_names(window, cx);
 5125    }
 5126
 5127    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5128        self.show_cursor_names = true;
 5129        cx.notify();
 5130        cx.spawn_in(window, |this, mut cx| async move {
 5131            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5132            this.update(&mut cx, |this, cx| {
 5133                this.show_cursor_names = false;
 5134                cx.notify()
 5135            })
 5136            .ok()
 5137        })
 5138        .detach();
 5139    }
 5140
 5141    pub fn next_edit_prediction(
 5142        &mut self,
 5143        _: &NextEditPrediction,
 5144        window: &mut Window,
 5145        cx: &mut Context<Self>,
 5146    ) {
 5147        if self.has_active_inline_completion() {
 5148            self.cycle_inline_completion(Direction::Next, window, cx);
 5149        } else {
 5150            let is_copilot_disabled = self
 5151                .refresh_inline_completion(false, true, window, cx)
 5152                .is_none();
 5153            if is_copilot_disabled {
 5154                cx.propagate();
 5155            }
 5156        }
 5157    }
 5158
 5159    pub fn previous_edit_prediction(
 5160        &mut self,
 5161        _: &PreviousEditPrediction,
 5162        window: &mut Window,
 5163        cx: &mut Context<Self>,
 5164    ) {
 5165        if self.has_active_inline_completion() {
 5166            self.cycle_inline_completion(Direction::Prev, window, cx);
 5167        } else {
 5168            let is_copilot_disabled = self
 5169                .refresh_inline_completion(false, true, window, cx)
 5170                .is_none();
 5171            if is_copilot_disabled {
 5172                cx.propagate();
 5173            }
 5174        }
 5175    }
 5176
 5177    pub fn accept_edit_prediction(
 5178        &mut self,
 5179        _: &AcceptEditPrediction,
 5180        window: &mut Window,
 5181        cx: &mut Context<Self>,
 5182    ) {
 5183        if self.show_edit_predictions_in_menu() {
 5184            self.hide_context_menu(window, cx);
 5185        }
 5186
 5187        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5188            return;
 5189        };
 5190
 5191        self.report_inline_completion_event(
 5192            active_inline_completion.completion_id.clone(),
 5193            true,
 5194            cx,
 5195        );
 5196
 5197        match &active_inline_completion.completion {
 5198            InlineCompletion::Move { target, .. } => {
 5199                let target = *target;
 5200
 5201                if let Some(position_map) = &self.last_position_map {
 5202                    if position_map
 5203                        .visible_row_range
 5204                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5205                        || !self.edit_prediction_requires_modifier()
 5206                    {
 5207                        self.unfold_ranges(&[target..target], true, false, cx);
 5208                        // Note that this is also done in vim's handler of the Tab action.
 5209                        self.change_selections(
 5210                            Some(Autoscroll::newest()),
 5211                            window,
 5212                            cx,
 5213                            |selections| {
 5214                                selections.select_anchor_ranges([target..target]);
 5215                            },
 5216                        );
 5217                        self.clear_row_highlights::<EditPredictionPreview>();
 5218
 5219                        self.edit_prediction_preview
 5220                            .set_previous_scroll_position(None);
 5221                    } else {
 5222                        self.edit_prediction_preview
 5223                            .set_previous_scroll_position(Some(
 5224                                position_map.snapshot.scroll_anchor,
 5225                            ));
 5226
 5227                        self.highlight_rows::<EditPredictionPreview>(
 5228                            target..target,
 5229                            cx.theme().colors().editor_highlighted_line_background,
 5230                            true,
 5231                            cx,
 5232                        );
 5233                        self.request_autoscroll(Autoscroll::fit(), cx);
 5234                    }
 5235                }
 5236            }
 5237            InlineCompletion::Edit { edits, .. } => {
 5238                if let Some(provider) = self.edit_prediction_provider() {
 5239                    provider.accept(cx);
 5240                }
 5241
 5242                let snapshot = self.buffer.read(cx).snapshot(cx);
 5243                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5244
 5245                self.buffer.update(cx, |buffer, cx| {
 5246                    buffer.edit(edits.iter().cloned(), None, cx)
 5247                });
 5248
 5249                self.change_selections(None, window, cx, |s| {
 5250                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5251                });
 5252
 5253                self.update_visible_inline_completion(window, cx);
 5254                if self.active_inline_completion.is_none() {
 5255                    self.refresh_inline_completion(true, true, window, cx);
 5256                }
 5257
 5258                cx.notify();
 5259            }
 5260        }
 5261
 5262        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5263    }
 5264
 5265    pub fn accept_partial_inline_completion(
 5266        &mut self,
 5267        _: &AcceptPartialEditPrediction,
 5268        window: &mut Window,
 5269        cx: &mut Context<Self>,
 5270    ) {
 5271        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5272            return;
 5273        };
 5274        if self.selections.count() != 1 {
 5275            return;
 5276        }
 5277
 5278        self.report_inline_completion_event(
 5279            active_inline_completion.completion_id.clone(),
 5280            true,
 5281            cx,
 5282        );
 5283
 5284        match &active_inline_completion.completion {
 5285            InlineCompletion::Move { target, .. } => {
 5286                let target = *target;
 5287                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5288                    selections.select_anchor_ranges([target..target]);
 5289                });
 5290            }
 5291            InlineCompletion::Edit { edits, .. } => {
 5292                // Find an insertion that starts at the cursor position.
 5293                let snapshot = self.buffer.read(cx).snapshot(cx);
 5294                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5295                let insertion = edits.iter().find_map(|(range, text)| {
 5296                    let range = range.to_offset(&snapshot);
 5297                    if range.is_empty() && range.start == cursor_offset {
 5298                        Some(text)
 5299                    } else {
 5300                        None
 5301                    }
 5302                });
 5303
 5304                if let Some(text) = insertion {
 5305                    let mut partial_completion = text
 5306                        .chars()
 5307                        .by_ref()
 5308                        .take_while(|c| c.is_alphabetic())
 5309                        .collect::<String>();
 5310                    if partial_completion.is_empty() {
 5311                        partial_completion = text
 5312                            .chars()
 5313                            .by_ref()
 5314                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5315                            .collect::<String>();
 5316                    }
 5317
 5318                    cx.emit(EditorEvent::InputHandled {
 5319                        utf16_range_to_replace: None,
 5320                        text: partial_completion.clone().into(),
 5321                    });
 5322
 5323                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5324
 5325                    self.refresh_inline_completion(true, true, window, cx);
 5326                    cx.notify();
 5327                } else {
 5328                    self.accept_edit_prediction(&Default::default(), window, cx);
 5329                }
 5330            }
 5331        }
 5332    }
 5333
 5334    fn discard_inline_completion(
 5335        &mut self,
 5336        should_report_inline_completion_event: bool,
 5337        cx: &mut Context<Self>,
 5338    ) -> bool {
 5339        if should_report_inline_completion_event {
 5340            let completion_id = self
 5341                .active_inline_completion
 5342                .as_ref()
 5343                .and_then(|active_completion| active_completion.completion_id.clone());
 5344
 5345            self.report_inline_completion_event(completion_id, false, cx);
 5346        }
 5347
 5348        if let Some(provider) = self.edit_prediction_provider() {
 5349            provider.discard(cx);
 5350        }
 5351
 5352        self.take_active_inline_completion(cx)
 5353    }
 5354
 5355    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5356        let Some(provider) = self.edit_prediction_provider() else {
 5357            return;
 5358        };
 5359
 5360        let Some((_, buffer, _)) = self
 5361            .buffer
 5362            .read(cx)
 5363            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5364        else {
 5365            return;
 5366        };
 5367
 5368        let extension = buffer
 5369            .read(cx)
 5370            .file()
 5371            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5372
 5373        let event_type = match accepted {
 5374            true => "Edit Prediction Accepted",
 5375            false => "Edit Prediction Discarded",
 5376        };
 5377        telemetry::event!(
 5378            event_type,
 5379            provider = provider.name(),
 5380            prediction_id = id,
 5381            suggestion_accepted = accepted,
 5382            file_extension = extension,
 5383        );
 5384    }
 5385
 5386    pub fn has_active_inline_completion(&self) -> bool {
 5387        self.active_inline_completion.is_some()
 5388    }
 5389
 5390    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5391        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5392            return false;
 5393        };
 5394
 5395        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5396        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5397        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5398        true
 5399    }
 5400
 5401    /// Returns true when we're displaying the edit prediction popover below the cursor
 5402    /// like we are not previewing and the LSP autocomplete menu is visible
 5403    /// or we are in `when_holding_modifier` mode.
 5404    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5405        if self.edit_prediction_preview_is_active()
 5406            || !self.show_edit_predictions_in_menu()
 5407            || !self.edit_predictions_enabled()
 5408        {
 5409            return false;
 5410        }
 5411
 5412        if self.has_visible_completions_menu() {
 5413            return true;
 5414        }
 5415
 5416        has_completion && self.edit_prediction_requires_modifier()
 5417    }
 5418
 5419    fn handle_modifiers_changed(
 5420        &mut self,
 5421        modifiers: Modifiers,
 5422        position_map: &PositionMap,
 5423        window: &mut Window,
 5424        cx: &mut Context<Self>,
 5425    ) {
 5426        if self.show_edit_predictions_in_menu() {
 5427            self.update_edit_prediction_preview(&modifiers, window, cx);
 5428        }
 5429
 5430        self.update_selection_mode(&modifiers, position_map, window, cx);
 5431
 5432        let mouse_position = window.mouse_position();
 5433        if !position_map.text_hitbox.is_hovered(window) {
 5434            return;
 5435        }
 5436
 5437        self.update_hovered_link(
 5438            position_map.point_for_position(mouse_position),
 5439            &position_map.snapshot,
 5440            modifiers,
 5441            window,
 5442            cx,
 5443        )
 5444    }
 5445
 5446    fn update_selection_mode(
 5447        &mut self,
 5448        modifiers: &Modifiers,
 5449        position_map: &PositionMap,
 5450        window: &mut Window,
 5451        cx: &mut Context<Self>,
 5452    ) {
 5453        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5454            return;
 5455        }
 5456
 5457        let mouse_position = window.mouse_position();
 5458        let point_for_position = position_map.point_for_position(mouse_position);
 5459        let position = point_for_position.previous_valid;
 5460
 5461        self.select(
 5462            SelectPhase::BeginColumnar {
 5463                position,
 5464                reset: false,
 5465                goal_column: point_for_position.exact_unclipped.column(),
 5466            },
 5467            window,
 5468            cx,
 5469        );
 5470    }
 5471
 5472    fn update_edit_prediction_preview(
 5473        &mut self,
 5474        modifiers: &Modifiers,
 5475        window: &mut Window,
 5476        cx: &mut Context<Self>,
 5477    ) {
 5478        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5479        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5480            return;
 5481        };
 5482
 5483        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5484            if matches!(
 5485                self.edit_prediction_preview,
 5486                EditPredictionPreview::Inactive { .. }
 5487            ) {
 5488                self.edit_prediction_preview = EditPredictionPreview::Active {
 5489                    previous_scroll_position: None,
 5490                    since: Instant::now(),
 5491                };
 5492
 5493                self.update_visible_inline_completion(window, cx);
 5494                cx.notify();
 5495            }
 5496        } else if let EditPredictionPreview::Active {
 5497            previous_scroll_position,
 5498            since,
 5499        } = self.edit_prediction_preview
 5500        {
 5501            if let (Some(previous_scroll_position), Some(position_map)) =
 5502                (previous_scroll_position, self.last_position_map.as_ref())
 5503            {
 5504                self.set_scroll_position(
 5505                    previous_scroll_position
 5506                        .scroll_position(&position_map.snapshot.display_snapshot),
 5507                    window,
 5508                    cx,
 5509                );
 5510            }
 5511
 5512            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 5513                released_too_fast: since.elapsed() < Duration::from_millis(200),
 5514            };
 5515            self.clear_row_highlights::<EditPredictionPreview>();
 5516            self.update_visible_inline_completion(window, cx);
 5517            cx.notify();
 5518        }
 5519    }
 5520
 5521    fn update_visible_inline_completion(
 5522        &mut self,
 5523        _window: &mut Window,
 5524        cx: &mut Context<Self>,
 5525    ) -> Option<()> {
 5526        let selection = self.selections.newest_anchor();
 5527        let cursor = selection.head();
 5528        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5529        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5530        let excerpt_id = cursor.excerpt_id;
 5531
 5532        let show_in_menu = self.show_edit_predictions_in_menu();
 5533        let completions_menu_has_precedence = !show_in_menu
 5534            && (self.context_menu.borrow().is_some()
 5535                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5536
 5537        if completions_menu_has_precedence
 5538            || !offset_selection.is_empty()
 5539            || self
 5540                .active_inline_completion
 5541                .as_ref()
 5542                .map_or(false, |completion| {
 5543                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5544                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5545                    !invalidation_range.contains(&offset_selection.head())
 5546                })
 5547        {
 5548            self.discard_inline_completion(false, cx);
 5549            return None;
 5550        }
 5551
 5552        self.take_active_inline_completion(cx);
 5553        let Some(provider) = self.edit_prediction_provider() else {
 5554            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5555            return None;
 5556        };
 5557
 5558        let (buffer, cursor_buffer_position) =
 5559            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5560
 5561        self.edit_prediction_settings =
 5562            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5563
 5564        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 5565
 5566        if self.edit_prediction_indent_conflict {
 5567            let cursor_point = cursor.to_point(&multibuffer);
 5568
 5569            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 5570
 5571            if let Some((_, indent)) = indents.iter().next() {
 5572                if indent.len == cursor_point.column {
 5573                    self.edit_prediction_indent_conflict = false;
 5574                }
 5575            }
 5576        }
 5577
 5578        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5579        let edits = inline_completion
 5580            .edits
 5581            .into_iter()
 5582            .flat_map(|(range, new_text)| {
 5583                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5584                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5585                Some((start..end, new_text))
 5586            })
 5587            .collect::<Vec<_>>();
 5588        if edits.is_empty() {
 5589            return None;
 5590        }
 5591
 5592        let first_edit_start = edits.first().unwrap().0.start;
 5593        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5594        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5595
 5596        let last_edit_end = edits.last().unwrap().0.end;
 5597        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5598        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5599
 5600        let cursor_row = cursor.to_point(&multibuffer).row;
 5601
 5602        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5603
 5604        let mut inlay_ids = Vec::new();
 5605        let invalidation_row_range;
 5606        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5607            Some(cursor_row..edit_end_row)
 5608        } else if cursor_row > edit_end_row {
 5609            Some(edit_start_row..cursor_row)
 5610        } else {
 5611            None
 5612        };
 5613        let is_move =
 5614            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5615        let completion = if is_move {
 5616            invalidation_row_range =
 5617                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5618            let target = first_edit_start;
 5619            InlineCompletion::Move { target, snapshot }
 5620        } else {
 5621            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5622                && !self.inline_completions_hidden_for_vim_mode;
 5623
 5624            if show_completions_in_buffer {
 5625                if edits
 5626                    .iter()
 5627                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5628                {
 5629                    let mut inlays = Vec::new();
 5630                    for (range, new_text) in &edits {
 5631                        let inlay = Inlay::inline_completion(
 5632                            post_inc(&mut self.next_inlay_id),
 5633                            range.start,
 5634                            new_text.as_str(),
 5635                        );
 5636                        inlay_ids.push(inlay.id);
 5637                        inlays.push(inlay);
 5638                    }
 5639
 5640                    self.splice_inlays(&[], inlays, cx);
 5641                } else {
 5642                    let background_color = cx.theme().status().deleted_background;
 5643                    self.highlight_text::<InlineCompletionHighlight>(
 5644                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5645                        HighlightStyle {
 5646                            background_color: Some(background_color),
 5647                            ..Default::default()
 5648                        },
 5649                        cx,
 5650                    );
 5651                }
 5652            }
 5653
 5654            invalidation_row_range = edit_start_row..edit_end_row;
 5655
 5656            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5657                if provider.show_tab_accept_marker() {
 5658                    EditDisplayMode::TabAccept
 5659                } else {
 5660                    EditDisplayMode::Inline
 5661                }
 5662            } else {
 5663                EditDisplayMode::DiffPopover
 5664            };
 5665
 5666            InlineCompletion::Edit {
 5667                edits,
 5668                edit_preview: inline_completion.edit_preview,
 5669                display_mode,
 5670                snapshot,
 5671            }
 5672        };
 5673
 5674        let invalidation_range = multibuffer
 5675            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5676            ..multibuffer.anchor_after(Point::new(
 5677                invalidation_row_range.end,
 5678                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5679            ));
 5680
 5681        self.stale_inline_completion_in_menu = None;
 5682        self.active_inline_completion = Some(InlineCompletionState {
 5683            inlay_ids,
 5684            completion,
 5685            completion_id: inline_completion.id,
 5686            invalidation_range,
 5687        });
 5688
 5689        cx.notify();
 5690
 5691        Some(())
 5692    }
 5693
 5694    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5695        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5696    }
 5697
 5698    fn render_code_actions_indicator(
 5699        &self,
 5700        _style: &EditorStyle,
 5701        row: DisplayRow,
 5702        is_active: bool,
 5703        cx: &mut Context<Self>,
 5704    ) -> Option<IconButton> {
 5705        if self.available_code_actions.is_some() {
 5706            Some(
 5707                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5708                    .shape(ui::IconButtonShape::Square)
 5709                    .icon_size(IconSize::XSmall)
 5710                    .icon_color(Color::Muted)
 5711                    .toggle_state(is_active)
 5712                    .tooltip({
 5713                        let focus_handle = self.focus_handle.clone();
 5714                        move |window, cx| {
 5715                            Tooltip::for_action_in(
 5716                                "Toggle Code Actions",
 5717                                &ToggleCodeActions {
 5718                                    deployed_from_indicator: None,
 5719                                },
 5720                                &focus_handle,
 5721                                window,
 5722                                cx,
 5723                            )
 5724                        }
 5725                    })
 5726                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5727                        window.focus(&editor.focus_handle(cx));
 5728                        editor.toggle_code_actions(
 5729                            &ToggleCodeActions {
 5730                                deployed_from_indicator: Some(row),
 5731                            },
 5732                            window,
 5733                            cx,
 5734                        );
 5735                    })),
 5736            )
 5737        } else {
 5738            None
 5739        }
 5740    }
 5741
 5742    fn clear_tasks(&mut self) {
 5743        self.tasks.clear()
 5744    }
 5745
 5746    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5747        if self.tasks.insert(key, value).is_some() {
 5748            // This case should hopefully be rare, but just in case...
 5749            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5750        }
 5751    }
 5752
 5753    fn build_tasks_context(
 5754        project: &Entity<Project>,
 5755        buffer: &Entity<Buffer>,
 5756        buffer_row: u32,
 5757        tasks: &Arc<RunnableTasks>,
 5758        cx: &mut Context<Self>,
 5759    ) -> Task<Option<task::TaskContext>> {
 5760        let position = Point::new(buffer_row, tasks.column);
 5761        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5762        let location = Location {
 5763            buffer: buffer.clone(),
 5764            range: range_start..range_start,
 5765        };
 5766        // Fill in the environmental variables from the tree-sitter captures
 5767        let mut captured_task_variables = TaskVariables::default();
 5768        for (capture_name, value) in tasks.extra_variables.clone() {
 5769            captured_task_variables.insert(
 5770                task::VariableName::Custom(capture_name.into()),
 5771                value.clone(),
 5772            );
 5773        }
 5774        project.update(cx, |project, cx| {
 5775            project.task_store().update(cx, |task_store, cx| {
 5776                task_store.task_context_for_location(captured_task_variables, location, cx)
 5777            })
 5778        })
 5779    }
 5780
 5781    pub fn spawn_nearest_task(
 5782        &mut self,
 5783        action: &SpawnNearestTask,
 5784        window: &mut Window,
 5785        cx: &mut Context<Self>,
 5786    ) {
 5787        let Some((workspace, _)) = self.workspace.clone() else {
 5788            return;
 5789        };
 5790        let Some(project) = self.project.clone() else {
 5791            return;
 5792        };
 5793
 5794        // Try to find a closest, enclosing node using tree-sitter that has a
 5795        // task
 5796        let Some((buffer, buffer_row, tasks)) = self
 5797            .find_enclosing_node_task(cx)
 5798            // Or find the task that's closest in row-distance.
 5799            .or_else(|| self.find_closest_task(cx))
 5800        else {
 5801            return;
 5802        };
 5803
 5804        let reveal_strategy = action.reveal;
 5805        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5806        cx.spawn_in(window, |_, mut cx| async move {
 5807            let context = task_context.await?;
 5808            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5809
 5810            let resolved = resolved_task.resolved.as_mut()?;
 5811            resolved.reveal = reveal_strategy;
 5812
 5813            workspace
 5814                .update(&mut cx, |workspace, cx| {
 5815                    workspace::tasks::schedule_resolved_task(
 5816                        workspace,
 5817                        task_source_kind,
 5818                        resolved_task,
 5819                        false,
 5820                        cx,
 5821                    );
 5822                })
 5823                .ok()
 5824        })
 5825        .detach();
 5826    }
 5827
 5828    fn find_closest_task(
 5829        &mut self,
 5830        cx: &mut Context<Self>,
 5831    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5832        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5833
 5834        let ((buffer_id, row), tasks) = self
 5835            .tasks
 5836            .iter()
 5837            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5838
 5839        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5840        let tasks = Arc::new(tasks.to_owned());
 5841        Some((buffer, *row, tasks))
 5842    }
 5843
 5844    fn find_enclosing_node_task(
 5845        &mut self,
 5846        cx: &mut Context<Self>,
 5847    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5848        let snapshot = self.buffer.read(cx).snapshot(cx);
 5849        let offset = self.selections.newest::<usize>(cx).head();
 5850        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5851        let buffer_id = excerpt.buffer().remote_id();
 5852
 5853        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5854        let mut cursor = layer.node().walk();
 5855
 5856        while cursor.goto_first_child_for_byte(offset).is_some() {
 5857            if cursor.node().end_byte() == offset {
 5858                cursor.goto_next_sibling();
 5859            }
 5860        }
 5861
 5862        // Ascend to the smallest ancestor that contains the range and has a task.
 5863        loop {
 5864            let node = cursor.node();
 5865            let node_range = node.byte_range();
 5866            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5867
 5868            // Check if this node contains our offset
 5869            if node_range.start <= offset && node_range.end >= offset {
 5870                // If it contains offset, check for task
 5871                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5872                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5873                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5874                }
 5875            }
 5876
 5877            if !cursor.goto_parent() {
 5878                break;
 5879            }
 5880        }
 5881        None
 5882    }
 5883
 5884    fn render_run_indicator(
 5885        &self,
 5886        _style: &EditorStyle,
 5887        is_active: bool,
 5888        row: DisplayRow,
 5889        cx: &mut Context<Self>,
 5890    ) -> IconButton {
 5891        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5892            .shape(ui::IconButtonShape::Square)
 5893            .icon_size(IconSize::XSmall)
 5894            .icon_color(Color::Muted)
 5895            .toggle_state(is_active)
 5896            .on_click(cx.listener(move |editor, _e, window, cx| {
 5897                window.focus(&editor.focus_handle(cx));
 5898                editor.toggle_code_actions(
 5899                    &ToggleCodeActions {
 5900                        deployed_from_indicator: Some(row),
 5901                    },
 5902                    window,
 5903                    cx,
 5904                );
 5905            }))
 5906    }
 5907
 5908    pub fn context_menu_visible(&self) -> bool {
 5909        !self.edit_prediction_preview_is_active()
 5910            && self
 5911                .context_menu
 5912                .borrow()
 5913                .as_ref()
 5914                .map_or(false, |menu| menu.visible())
 5915    }
 5916
 5917    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5918        self.context_menu
 5919            .borrow()
 5920            .as_ref()
 5921            .map(|menu| menu.origin())
 5922    }
 5923
 5924    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 5925    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 5926
 5927    #[allow(clippy::too_many_arguments)]
 5928    fn render_edit_prediction_popover(
 5929        &mut self,
 5930        text_bounds: &Bounds<Pixels>,
 5931        content_origin: gpui::Point<Pixels>,
 5932        editor_snapshot: &EditorSnapshot,
 5933        visible_row_range: Range<DisplayRow>,
 5934        scroll_top: f32,
 5935        scroll_bottom: f32,
 5936        line_layouts: &[LineWithInvisibles],
 5937        line_height: Pixels,
 5938        scroll_pixel_position: gpui::Point<Pixels>,
 5939        newest_selection_head: Option<DisplayPoint>,
 5940        editor_width: Pixels,
 5941        style: &EditorStyle,
 5942        window: &mut Window,
 5943        cx: &mut App,
 5944    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5945        let active_inline_completion = self.active_inline_completion.as_ref()?;
 5946
 5947        if self.edit_prediction_visible_in_cursor_popover(true) {
 5948            return None;
 5949        }
 5950
 5951        match &active_inline_completion.completion {
 5952            InlineCompletion::Move { target, .. } => {
 5953                let target_display_point = target.to_display_point(editor_snapshot);
 5954
 5955                if self.edit_prediction_requires_modifier() {
 5956                    if !self.edit_prediction_preview_is_active() {
 5957                        return None;
 5958                    }
 5959
 5960                    self.render_edit_prediction_modifier_jump_popover(
 5961                        text_bounds,
 5962                        content_origin,
 5963                        visible_row_range,
 5964                        line_layouts,
 5965                        line_height,
 5966                        scroll_pixel_position,
 5967                        newest_selection_head,
 5968                        target_display_point,
 5969                        window,
 5970                        cx,
 5971                    )
 5972                } else {
 5973                    self.render_edit_prediction_eager_jump_popover(
 5974                        text_bounds,
 5975                        content_origin,
 5976                        editor_snapshot,
 5977                        visible_row_range,
 5978                        scroll_top,
 5979                        scroll_bottom,
 5980                        line_height,
 5981                        scroll_pixel_position,
 5982                        target_display_point,
 5983                        editor_width,
 5984                        window,
 5985                        cx,
 5986                    )
 5987                }
 5988            }
 5989            InlineCompletion::Edit {
 5990                display_mode: EditDisplayMode::Inline,
 5991                ..
 5992            } => None,
 5993            InlineCompletion::Edit {
 5994                display_mode: EditDisplayMode::TabAccept,
 5995                edits,
 5996                ..
 5997            } => {
 5998                let range = &edits.first()?.0;
 5999                let target_display_point = range.end.to_display_point(editor_snapshot);
 6000
 6001                self.render_edit_prediction_end_of_line_popover(
 6002                    "Accept",
 6003                    editor_snapshot,
 6004                    visible_row_range,
 6005                    target_display_point,
 6006                    line_height,
 6007                    scroll_pixel_position,
 6008                    content_origin,
 6009                    editor_width,
 6010                    window,
 6011                    cx,
 6012                )
 6013            }
 6014            InlineCompletion::Edit {
 6015                edits,
 6016                edit_preview,
 6017                display_mode: EditDisplayMode::DiffPopover,
 6018                snapshot,
 6019            } => self.render_edit_prediction_diff_popover(
 6020                text_bounds,
 6021                content_origin,
 6022                editor_snapshot,
 6023                visible_row_range,
 6024                line_layouts,
 6025                line_height,
 6026                scroll_pixel_position,
 6027                newest_selection_head,
 6028                editor_width,
 6029                style,
 6030                edits,
 6031                edit_preview,
 6032                snapshot,
 6033                window,
 6034                cx,
 6035            ),
 6036        }
 6037    }
 6038
 6039    #[allow(clippy::too_many_arguments)]
 6040    fn render_edit_prediction_modifier_jump_popover(
 6041        &mut self,
 6042        text_bounds: &Bounds<Pixels>,
 6043        content_origin: gpui::Point<Pixels>,
 6044        visible_row_range: Range<DisplayRow>,
 6045        line_layouts: &[LineWithInvisibles],
 6046        line_height: Pixels,
 6047        scroll_pixel_position: gpui::Point<Pixels>,
 6048        newest_selection_head: Option<DisplayPoint>,
 6049        target_display_point: DisplayPoint,
 6050        window: &mut Window,
 6051        cx: &mut App,
 6052    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6053        let scrolled_content_origin =
 6054            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 6055
 6056        const SCROLL_PADDING_Y: Pixels = px(12.);
 6057
 6058        if target_display_point.row() < visible_row_range.start {
 6059            return self.render_edit_prediction_scroll_popover(
 6060                |_| SCROLL_PADDING_Y,
 6061                IconName::ArrowUp,
 6062                visible_row_range,
 6063                line_layouts,
 6064                newest_selection_head,
 6065                scrolled_content_origin,
 6066                window,
 6067                cx,
 6068            );
 6069        } else if target_display_point.row() >= visible_row_range.end {
 6070            return self.render_edit_prediction_scroll_popover(
 6071                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 6072                IconName::ArrowDown,
 6073                visible_row_range,
 6074                line_layouts,
 6075                newest_selection_head,
 6076                scrolled_content_origin,
 6077                window,
 6078                cx,
 6079            );
 6080        }
 6081
 6082        const POLE_WIDTH: Pixels = px(2.);
 6083
 6084        let line_layout =
 6085            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 6086        let target_column = target_display_point.column() as usize;
 6087
 6088        let target_x = line_layout.x_for_index(target_column);
 6089        let target_y =
 6090            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 6091
 6092        let flag_on_right = target_x < text_bounds.size.width / 2.;
 6093
 6094        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 6095        border_color.l += 0.001;
 6096
 6097        let mut element = v_flex()
 6098            .items_end()
 6099            .when(flag_on_right, |el| el.items_start())
 6100            .child(if flag_on_right {
 6101                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6102                    .rounded_bl(px(0.))
 6103                    .rounded_tl(px(0.))
 6104                    .border_l_2()
 6105                    .border_color(border_color)
 6106            } else {
 6107                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6108                    .rounded_br(px(0.))
 6109                    .rounded_tr(px(0.))
 6110                    .border_r_2()
 6111                    .border_color(border_color)
 6112            })
 6113            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 6114            .into_any();
 6115
 6116        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6117
 6118        let mut origin = scrolled_content_origin + point(target_x, target_y)
 6119            - point(
 6120                if flag_on_right {
 6121                    POLE_WIDTH
 6122                } else {
 6123                    size.width - POLE_WIDTH
 6124                },
 6125                size.height - line_height,
 6126            );
 6127
 6128        origin.x = origin.x.max(content_origin.x);
 6129
 6130        element.prepaint_at(origin, window, cx);
 6131
 6132        Some((element, origin))
 6133    }
 6134
 6135    #[allow(clippy::too_many_arguments)]
 6136    fn render_edit_prediction_scroll_popover(
 6137        &mut self,
 6138        to_y: impl Fn(Size<Pixels>) -> Pixels,
 6139        scroll_icon: IconName,
 6140        visible_row_range: Range<DisplayRow>,
 6141        line_layouts: &[LineWithInvisibles],
 6142        newest_selection_head: Option<DisplayPoint>,
 6143        scrolled_content_origin: gpui::Point<Pixels>,
 6144        window: &mut Window,
 6145        cx: &mut App,
 6146    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6147        let mut element = self
 6148            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 6149            .into_any();
 6150
 6151        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6152
 6153        let cursor = newest_selection_head?;
 6154        let cursor_row_layout =
 6155            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6156        let cursor_column = cursor.column() as usize;
 6157
 6158        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6159
 6160        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6161
 6162        element.prepaint_at(origin, window, cx);
 6163        Some((element, origin))
 6164    }
 6165
 6166    #[allow(clippy::too_many_arguments)]
 6167    fn render_edit_prediction_eager_jump_popover(
 6168        &mut self,
 6169        text_bounds: &Bounds<Pixels>,
 6170        content_origin: gpui::Point<Pixels>,
 6171        editor_snapshot: &EditorSnapshot,
 6172        visible_row_range: Range<DisplayRow>,
 6173        scroll_top: f32,
 6174        scroll_bottom: f32,
 6175        line_height: Pixels,
 6176        scroll_pixel_position: gpui::Point<Pixels>,
 6177        target_display_point: DisplayPoint,
 6178        editor_width: Pixels,
 6179        window: &mut Window,
 6180        cx: &mut App,
 6181    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6182        if target_display_point.row().as_f32() < scroll_top {
 6183            let mut element = self
 6184                .render_edit_prediction_line_popover(
 6185                    "Jump to Edit",
 6186                    Some(IconName::ArrowUp),
 6187                    window,
 6188                    cx,
 6189                )?
 6190                .into_any();
 6191
 6192            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6193            let offset = point(
 6194                (text_bounds.size.width - size.width) / 2.,
 6195                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6196            );
 6197
 6198            let origin = text_bounds.origin + offset;
 6199            element.prepaint_at(origin, window, cx);
 6200            Some((element, origin))
 6201        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6202            let mut element = self
 6203                .render_edit_prediction_line_popover(
 6204                    "Jump to Edit",
 6205                    Some(IconName::ArrowDown),
 6206                    window,
 6207                    cx,
 6208                )?
 6209                .into_any();
 6210
 6211            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6212            let offset = point(
 6213                (text_bounds.size.width - size.width) / 2.,
 6214                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6215            );
 6216
 6217            let origin = text_bounds.origin + offset;
 6218            element.prepaint_at(origin, window, cx);
 6219            Some((element, origin))
 6220        } else {
 6221            self.render_edit_prediction_end_of_line_popover(
 6222                "Jump to Edit",
 6223                editor_snapshot,
 6224                visible_row_range,
 6225                target_display_point,
 6226                line_height,
 6227                scroll_pixel_position,
 6228                content_origin,
 6229                editor_width,
 6230                window,
 6231                cx,
 6232            )
 6233        }
 6234    }
 6235
 6236    #[allow(clippy::too_many_arguments)]
 6237    fn render_edit_prediction_end_of_line_popover(
 6238        self: &mut Editor,
 6239        label: &'static str,
 6240        editor_snapshot: &EditorSnapshot,
 6241        visible_row_range: Range<DisplayRow>,
 6242        target_display_point: DisplayPoint,
 6243        line_height: Pixels,
 6244        scroll_pixel_position: gpui::Point<Pixels>,
 6245        content_origin: gpui::Point<Pixels>,
 6246        editor_width: Pixels,
 6247        window: &mut Window,
 6248        cx: &mut App,
 6249    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6250        let target_line_end = DisplayPoint::new(
 6251            target_display_point.row(),
 6252            editor_snapshot.line_len(target_display_point.row()),
 6253        );
 6254
 6255        let mut element = self
 6256            .render_edit_prediction_line_popover(label, None, window, cx)?
 6257            .into_any();
 6258
 6259        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6260
 6261        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 6262
 6263        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 6264        let mut origin = start_point
 6265            + line_origin
 6266            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 6267        origin.x = origin.x.max(content_origin.x);
 6268
 6269        let max_x = content_origin.x + editor_width - size.width;
 6270
 6271        if origin.x > max_x {
 6272            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 6273
 6274            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 6275                origin.y += offset;
 6276                IconName::ArrowUp
 6277            } else {
 6278                origin.y -= offset;
 6279                IconName::ArrowDown
 6280            };
 6281
 6282            element = self
 6283                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 6284                .into_any();
 6285
 6286            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6287
 6288            origin.x = content_origin.x + editor_width - size.width - px(2.);
 6289        }
 6290
 6291        element.prepaint_at(origin, window, cx);
 6292        Some((element, origin))
 6293    }
 6294
 6295    #[allow(clippy::too_many_arguments)]
 6296    fn render_edit_prediction_diff_popover(
 6297        self: &Editor,
 6298        text_bounds: &Bounds<Pixels>,
 6299        content_origin: gpui::Point<Pixels>,
 6300        editor_snapshot: &EditorSnapshot,
 6301        visible_row_range: Range<DisplayRow>,
 6302        line_layouts: &[LineWithInvisibles],
 6303        line_height: Pixels,
 6304        scroll_pixel_position: gpui::Point<Pixels>,
 6305        newest_selection_head: Option<DisplayPoint>,
 6306        editor_width: Pixels,
 6307        style: &EditorStyle,
 6308        edits: &Vec<(Range<Anchor>, String)>,
 6309        edit_preview: &Option<language::EditPreview>,
 6310        snapshot: &language::BufferSnapshot,
 6311        window: &mut Window,
 6312        cx: &mut App,
 6313    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6314        let edit_start = edits
 6315            .first()
 6316            .unwrap()
 6317            .0
 6318            .start
 6319            .to_display_point(editor_snapshot);
 6320        let edit_end = edits
 6321            .last()
 6322            .unwrap()
 6323            .0
 6324            .end
 6325            .to_display_point(editor_snapshot);
 6326
 6327        let is_visible = visible_row_range.contains(&edit_start.row())
 6328            || visible_row_range.contains(&edit_end.row());
 6329        if !is_visible {
 6330            return None;
 6331        }
 6332
 6333        let highlighted_edits =
 6334            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 6335
 6336        let styled_text = highlighted_edits.to_styled_text(&style.text);
 6337        let line_count = highlighted_edits.text.lines().count();
 6338
 6339        const BORDER_WIDTH: Pixels = px(1.);
 6340
 6341        let mut element = h_flex()
 6342            .items_start()
 6343            .child(
 6344                h_flex()
 6345                    .bg(cx.theme().colors().editor_background)
 6346                    .border(BORDER_WIDTH)
 6347                    .shadow_sm()
 6348                    .border_color(cx.theme().colors().border)
 6349                    .rounded_l_lg()
 6350                    .when(line_count > 1, |el| el.rounded_br_lg())
 6351                    .pr_1()
 6352                    .child(styled_text),
 6353            )
 6354            .child(
 6355                h_flex()
 6356                    .h(line_height + BORDER_WIDTH * px(2.))
 6357                    .px_1p5()
 6358                    .gap_1()
 6359                    // Workaround: For some reason, there's a gap if we don't do this
 6360                    .ml(-BORDER_WIDTH)
 6361                    .shadow(smallvec![gpui::BoxShadow {
 6362                        color: gpui::black().opacity(0.05),
 6363                        offset: point(px(1.), px(1.)),
 6364                        blur_radius: px(2.),
 6365                        spread_radius: px(0.),
 6366                    }])
 6367                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 6368                    .border(BORDER_WIDTH)
 6369                    .border_color(cx.theme().colors().border)
 6370                    .rounded_r_lg()
 6371                    .children(self.render_edit_prediction_accept_keybind(window, cx)),
 6372            )
 6373            .into_any();
 6374
 6375        let longest_row =
 6376            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 6377        let longest_line_width = if visible_row_range.contains(&longest_row) {
 6378            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 6379        } else {
 6380            layout_line(
 6381                longest_row,
 6382                editor_snapshot,
 6383                style,
 6384                editor_width,
 6385                |_| false,
 6386                window,
 6387                cx,
 6388            )
 6389            .width
 6390        };
 6391
 6392        let viewport_bounds =
 6393            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 6394                right: -EditorElement::SCROLLBAR_WIDTH,
 6395                ..Default::default()
 6396            });
 6397
 6398        let x_after_longest =
 6399            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 6400                - scroll_pixel_position.x;
 6401
 6402        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6403
 6404        // Fully visible if it can be displayed within the window (allow overlapping other
 6405        // panes). However, this is only allowed if the popover starts within text_bounds.
 6406        let can_position_to_the_right = x_after_longest < text_bounds.right()
 6407            && x_after_longest + element_bounds.width < viewport_bounds.right();
 6408
 6409        let mut origin = if can_position_to_the_right {
 6410            point(
 6411                x_after_longest,
 6412                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 6413                    - scroll_pixel_position.y,
 6414            )
 6415        } else {
 6416            let cursor_row = newest_selection_head.map(|head| head.row());
 6417            let above_edit = edit_start
 6418                .row()
 6419                .0
 6420                .checked_sub(line_count as u32)
 6421                .map(DisplayRow);
 6422            let below_edit = Some(edit_end.row() + 1);
 6423            let above_cursor =
 6424                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 6425            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 6426
 6427            // Place the edit popover adjacent to the edit if there is a location
 6428            // available that is onscreen and does not obscure the cursor. Otherwise,
 6429            // place it adjacent to the cursor.
 6430            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 6431                .into_iter()
 6432                .flatten()
 6433                .find(|&start_row| {
 6434                    let end_row = start_row + line_count as u32;
 6435                    visible_row_range.contains(&start_row)
 6436                        && visible_row_range.contains(&end_row)
 6437                        && cursor_row.map_or(true, |cursor_row| {
 6438                            !((start_row..end_row).contains(&cursor_row))
 6439                        })
 6440                })?;
 6441
 6442            content_origin
 6443                + point(
 6444                    -scroll_pixel_position.x,
 6445                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 6446                )
 6447        };
 6448
 6449        origin.x -= BORDER_WIDTH;
 6450
 6451        window.defer_draw(element, origin, 1);
 6452
 6453        // Do not return an element, since it will already be drawn due to defer_draw.
 6454        None
 6455    }
 6456
 6457    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 6458        px(30.)
 6459    }
 6460
 6461    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 6462        if self.read_only(cx) {
 6463            cx.theme().players().read_only()
 6464        } else {
 6465            self.style.as_ref().unwrap().local_player
 6466        }
 6467    }
 6468
 6469    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 6470        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 6471        let accept_keystroke = accept_binding.keystroke()?;
 6472
 6473        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6474
 6475        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 6476            Color::Accent
 6477        } else {
 6478            Color::Muted
 6479        };
 6480
 6481        h_flex()
 6482            .px_0p5()
 6483            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 6484            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6485            .text_size(TextSize::XSmall.rems(cx))
 6486            .child(h_flex().children(ui::render_modifiers(
 6487                &accept_keystroke.modifiers,
 6488                PlatformStyle::platform(),
 6489                Some(modifiers_color),
 6490                Some(IconSize::XSmall.rems().into()),
 6491                true,
 6492            )))
 6493            .when(is_platform_style_mac, |parent| {
 6494                parent.child(accept_keystroke.key.clone())
 6495            })
 6496            .when(!is_platform_style_mac, |parent| {
 6497                parent.child(
 6498                    Key::new(
 6499                        util::capitalize(&accept_keystroke.key),
 6500                        Some(Color::Default),
 6501                    )
 6502                    .size(Some(IconSize::XSmall.rems().into())),
 6503                )
 6504            })
 6505            .into()
 6506    }
 6507
 6508    fn render_edit_prediction_line_popover(
 6509        &self,
 6510        label: impl Into<SharedString>,
 6511        icon: Option<IconName>,
 6512        window: &mut Window,
 6513        cx: &App,
 6514    ) -> Option<Div> {
 6515        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 6516
 6517        let result = h_flex()
 6518            .py_0p5()
 6519            .pl_1()
 6520            .pr(padding_right)
 6521            .gap_1()
 6522            .rounded(px(6.))
 6523            .border_1()
 6524            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6525            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 6526            .shadow_sm()
 6527            .children(self.render_edit_prediction_accept_keybind(window, cx))
 6528            .child(Label::new(label).size(LabelSize::Small))
 6529            .when_some(icon, |element, icon| {
 6530                element.child(
 6531                    div()
 6532                        .mt(px(1.5))
 6533                        .child(Icon::new(icon).size(IconSize::Small)),
 6534                )
 6535            });
 6536
 6537        Some(result)
 6538    }
 6539
 6540    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 6541        let accent_color = cx.theme().colors().text_accent;
 6542        let editor_bg_color = cx.theme().colors().editor_background;
 6543        editor_bg_color.blend(accent_color.opacity(0.1))
 6544    }
 6545
 6546    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 6547        let accent_color = cx.theme().colors().text_accent;
 6548        let editor_bg_color = cx.theme().colors().editor_background;
 6549        editor_bg_color.blend(accent_color.opacity(0.6))
 6550    }
 6551
 6552    #[allow(clippy::too_many_arguments)]
 6553    fn render_edit_prediction_cursor_popover(
 6554        &self,
 6555        min_width: Pixels,
 6556        max_width: Pixels,
 6557        cursor_point: Point,
 6558        style: &EditorStyle,
 6559        accept_keystroke: Option<&gpui::Keystroke>,
 6560        _window: &Window,
 6561        cx: &mut Context<Editor>,
 6562    ) -> Option<AnyElement> {
 6563        let provider = self.edit_prediction_provider.as_ref()?;
 6564
 6565        if provider.provider.needs_terms_acceptance(cx) {
 6566            return Some(
 6567                h_flex()
 6568                    .min_w(min_width)
 6569                    .flex_1()
 6570                    .px_2()
 6571                    .py_1()
 6572                    .gap_3()
 6573                    .elevation_2(cx)
 6574                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 6575                    .id("accept-terms")
 6576                    .cursor_pointer()
 6577                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 6578                    .on_click(cx.listener(|this, _event, window, cx| {
 6579                        cx.stop_propagation();
 6580                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 6581                        window.dispatch_action(
 6582                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 6583                            cx,
 6584                        );
 6585                    }))
 6586                    .child(
 6587                        h_flex()
 6588                            .flex_1()
 6589                            .gap_2()
 6590                            .child(Icon::new(IconName::ZedPredict))
 6591                            .child(Label::new("Accept Terms of Service"))
 6592                            .child(div().w_full())
 6593                            .child(
 6594                                Icon::new(IconName::ArrowUpRight)
 6595                                    .color(Color::Muted)
 6596                                    .size(IconSize::Small),
 6597                            )
 6598                            .into_any_element(),
 6599                    )
 6600                    .into_any(),
 6601            );
 6602        }
 6603
 6604        let is_refreshing = provider.provider.is_refreshing(cx);
 6605
 6606        fn pending_completion_container() -> Div {
 6607            h_flex()
 6608                .h_full()
 6609                .flex_1()
 6610                .gap_2()
 6611                .child(Icon::new(IconName::ZedPredict))
 6612        }
 6613
 6614        let completion = match &self.active_inline_completion {
 6615            Some(prediction) => {
 6616                if !self.has_visible_completions_menu() {
 6617                    const RADIUS: Pixels = px(6.);
 6618                    const BORDER_WIDTH: Pixels = px(1.);
 6619
 6620                    return Some(
 6621                        h_flex()
 6622                            .elevation_2(cx)
 6623                            .border(BORDER_WIDTH)
 6624                            .border_color(cx.theme().colors().border)
 6625                            .rounded(RADIUS)
 6626                            .rounded_tl(px(0.))
 6627                            .overflow_hidden()
 6628                            .child(div().px_1p5().child(match &prediction.completion {
 6629                                InlineCompletion::Move { target, snapshot } => {
 6630                                    use text::ToPoint as _;
 6631                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 6632                                    {
 6633                                        Icon::new(IconName::ZedPredictDown)
 6634                                    } else {
 6635                                        Icon::new(IconName::ZedPredictUp)
 6636                                    }
 6637                                }
 6638                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 6639                            }))
 6640                            .child(
 6641                                h_flex()
 6642                                    .gap_1()
 6643                                    .py_1()
 6644                                    .px_2()
 6645                                    .rounded_r(RADIUS - BORDER_WIDTH)
 6646                                    .border_l_1()
 6647                                    .border_color(cx.theme().colors().border)
 6648                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6649                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 6650                                        el.child(
 6651                                            Label::new("Hold")
 6652                                                .size(LabelSize::Small)
 6653                                                .line_height_style(LineHeightStyle::UiLabel),
 6654                                        )
 6655                                    })
 6656                                    .child(h_flex().children(ui::render_modifiers(
 6657                                        &accept_keystroke?.modifiers,
 6658                                        PlatformStyle::platform(),
 6659                                        Some(Color::Default),
 6660                                        Some(IconSize::XSmall.rems().into()),
 6661                                        false,
 6662                                    ))),
 6663                            )
 6664                            .into_any(),
 6665                    );
 6666                }
 6667
 6668                self.render_edit_prediction_cursor_popover_preview(
 6669                    prediction,
 6670                    cursor_point,
 6671                    style,
 6672                    cx,
 6673                )?
 6674            }
 6675
 6676            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 6677                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 6678                    stale_completion,
 6679                    cursor_point,
 6680                    style,
 6681                    cx,
 6682                )?,
 6683
 6684                None => {
 6685                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6686                }
 6687            },
 6688
 6689            None => pending_completion_container().child(Label::new("No Prediction")),
 6690        };
 6691
 6692        let completion = if is_refreshing {
 6693            completion
 6694                .with_animation(
 6695                    "loading-completion",
 6696                    Animation::new(Duration::from_secs(2))
 6697                        .repeat()
 6698                        .with_easing(pulsating_between(0.4, 0.8)),
 6699                    |label, delta| label.opacity(delta),
 6700                )
 6701                .into_any_element()
 6702        } else {
 6703            completion.into_any_element()
 6704        };
 6705
 6706        let has_completion = self.active_inline_completion.is_some();
 6707
 6708        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6709        Some(
 6710            h_flex()
 6711                .min_w(min_width)
 6712                .max_w(max_width)
 6713                .flex_1()
 6714                .elevation_2(cx)
 6715                .border_color(cx.theme().colors().border)
 6716                .child(
 6717                    div()
 6718                        .flex_1()
 6719                        .py_1()
 6720                        .px_2()
 6721                        .overflow_hidden()
 6722                        .child(completion),
 6723                )
 6724                .when_some(accept_keystroke, |el, accept_keystroke| {
 6725                    if !accept_keystroke.modifiers.modified() {
 6726                        return el;
 6727                    }
 6728
 6729                    el.child(
 6730                        h_flex()
 6731                            .h_full()
 6732                            .border_l_1()
 6733                            .rounded_r_lg()
 6734                            .border_color(cx.theme().colors().border)
 6735                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6736                            .gap_1()
 6737                            .py_1()
 6738                            .px_2()
 6739                            .child(
 6740                                h_flex()
 6741                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6742                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6743                                    .child(h_flex().children(ui::render_modifiers(
 6744                                        &accept_keystroke.modifiers,
 6745                                        PlatformStyle::platform(),
 6746                                        Some(if !has_completion {
 6747                                            Color::Muted
 6748                                        } else {
 6749                                            Color::Default
 6750                                        }),
 6751                                        None,
 6752                                        false,
 6753                                    ))),
 6754                            )
 6755                            .child(Label::new("Preview").into_any_element())
 6756                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6757                    )
 6758                })
 6759                .into_any(),
 6760        )
 6761    }
 6762
 6763    fn render_edit_prediction_cursor_popover_preview(
 6764        &self,
 6765        completion: &InlineCompletionState,
 6766        cursor_point: Point,
 6767        style: &EditorStyle,
 6768        cx: &mut Context<Editor>,
 6769    ) -> Option<Div> {
 6770        use text::ToPoint as _;
 6771
 6772        fn render_relative_row_jump(
 6773            prefix: impl Into<String>,
 6774            current_row: u32,
 6775            target_row: u32,
 6776        ) -> Div {
 6777            let (row_diff, arrow) = if target_row < current_row {
 6778                (current_row - target_row, IconName::ArrowUp)
 6779            } else {
 6780                (target_row - current_row, IconName::ArrowDown)
 6781            };
 6782
 6783            h_flex()
 6784                .child(
 6785                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6786                        .color(Color::Muted)
 6787                        .size(LabelSize::Small),
 6788                )
 6789                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6790        }
 6791
 6792        match &completion.completion {
 6793            InlineCompletion::Move {
 6794                target, snapshot, ..
 6795            } => Some(
 6796                h_flex()
 6797                    .px_2()
 6798                    .gap_2()
 6799                    .flex_1()
 6800                    .child(
 6801                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6802                            Icon::new(IconName::ZedPredictDown)
 6803                        } else {
 6804                            Icon::new(IconName::ZedPredictUp)
 6805                        },
 6806                    )
 6807                    .child(Label::new("Jump to Edit")),
 6808            ),
 6809
 6810            InlineCompletion::Edit {
 6811                edits,
 6812                edit_preview,
 6813                snapshot,
 6814                display_mode: _,
 6815            } => {
 6816                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6817
 6818                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6819                    &snapshot,
 6820                    &edits,
 6821                    edit_preview.as_ref()?,
 6822                    true,
 6823                    cx,
 6824                )
 6825                .first_line_preview();
 6826
 6827                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6828                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 6829
 6830                let preview = h_flex()
 6831                    .gap_1()
 6832                    .min_w_16()
 6833                    .child(styled_text)
 6834                    .when(has_more_lines, |parent| parent.child(""));
 6835
 6836                let left = if first_edit_row != cursor_point.row {
 6837                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6838                        .into_any_element()
 6839                } else {
 6840                    Icon::new(IconName::ZedPredict).into_any_element()
 6841                };
 6842
 6843                Some(
 6844                    h_flex()
 6845                        .h_full()
 6846                        .flex_1()
 6847                        .gap_2()
 6848                        .pr_1()
 6849                        .overflow_x_hidden()
 6850                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6851                        .child(left)
 6852                        .child(preview),
 6853                )
 6854            }
 6855        }
 6856    }
 6857
 6858    fn render_context_menu(
 6859        &self,
 6860        style: &EditorStyle,
 6861        max_height_in_lines: u32,
 6862        y_flipped: bool,
 6863        window: &mut Window,
 6864        cx: &mut Context<Editor>,
 6865    ) -> Option<AnyElement> {
 6866        let menu = self.context_menu.borrow();
 6867        let menu = menu.as_ref()?;
 6868        if !menu.visible() {
 6869            return None;
 6870        };
 6871        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6872    }
 6873
 6874    fn render_context_menu_aside(
 6875        &mut self,
 6876        max_size: Size<Pixels>,
 6877        window: &mut Window,
 6878        cx: &mut Context<Editor>,
 6879    ) -> Option<AnyElement> {
 6880        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 6881            if menu.visible() {
 6882                menu.render_aside(self, max_size, window, cx)
 6883            } else {
 6884                None
 6885            }
 6886        })
 6887    }
 6888
 6889    fn hide_context_menu(
 6890        &mut self,
 6891        window: &mut Window,
 6892        cx: &mut Context<Self>,
 6893    ) -> Option<CodeContextMenu> {
 6894        cx.notify();
 6895        self.completion_tasks.clear();
 6896        let context_menu = self.context_menu.borrow_mut().take();
 6897        self.stale_inline_completion_in_menu.take();
 6898        self.update_visible_inline_completion(window, cx);
 6899        context_menu
 6900    }
 6901
 6902    fn show_snippet_choices(
 6903        &mut self,
 6904        choices: &Vec<String>,
 6905        selection: Range<Anchor>,
 6906        cx: &mut Context<Self>,
 6907    ) {
 6908        if selection.start.buffer_id.is_none() {
 6909            return;
 6910        }
 6911        let buffer_id = selection.start.buffer_id.unwrap();
 6912        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6913        let id = post_inc(&mut self.next_completion_id);
 6914
 6915        if let Some(buffer) = buffer {
 6916            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6917                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6918            ));
 6919        }
 6920    }
 6921
 6922    pub fn insert_snippet(
 6923        &mut self,
 6924        insertion_ranges: &[Range<usize>],
 6925        snippet: Snippet,
 6926        window: &mut Window,
 6927        cx: &mut Context<Self>,
 6928    ) -> Result<()> {
 6929        struct Tabstop<T> {
 6930            is_end_tabstop: bool,
 6931            ranges: Vec<Range<T>>,
 6932            choices: Option<Vec<String>>,
 6933        }
 6934
 6935        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6936            let snippet_text: Arc<str> = snippet.text.clone().into();
 6937            buffer.edit(
 6938                insertion_ranges
 6939                    .iter()
 6940                    .cloned()
 6941                    .map(|range| (range, snippet_text.clone())),
 6942                Some(AutoindentMode::EachLine),
 6943                cx,
 6944            );
 6945
 6946            let snapshot = &*buffer.read(cx);
 6947            let snippet = &snippet;
 6948            snippet
 6949                .tabstops
 6950                .iter()
 6951                .map(|tabstop| {
 6952                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6953                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6954                    });
 6955                    let mut tabstop_ranges = tabstop
 6956                        .ranges
 6957                        .iter()
 6958                        .flat_map(|tabstop_range| {
 6959                            let mut delta = 0_isize;
 6960                            insertion_ranges.iter().map(move |insertion_range| {
 6961                                let insertion_start = insertion_range.start as isize + delta;
 6962                                delta +=
 6963                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6964
 6965                                let start = ((insertion_start + tabstop_range.start) as usize)
 6966                                    .min(snapshot.len());
 6967                                let end = ((insertion_start + tabstop_range.end) as usize)
 6968                                    .min(snapshot.len());
 6969                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6970                            })
 6971                        })
 6972                        .collect::<Vec<_>>();
 6973                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6974
 6975                    Tabstop {
 6976                        is_end_tabstop,
 6977                        ranges: tabstop_ranges,
 6978                        choices: tabstop.choices.clone(),
 6979                    }
 6980                })
 6981                .collect::<Vec<_>>()
 6982        });
 6983        if let Some(tabstop) = tabstops.first() {
 6984            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6985                s.select_ranges(tabstop.ranges.iter().cloned());
 6986            });
 6987
 6988            if let Some(choices) = &tabstop.choices {
 6989                if let Some(selection) = tabstop.ranges.first() {
 6990                    self.show_snippet_choices(choices, selection.clone(), cx)
 6991                }
 6992            }
 6993
 6994            // If we're already at the last tabstop and it's at the end of the snippet,
 6995            // we're done, we don't need to keep the state around.
 6996            if !tabstop.is_end_tabstop {
 6997                let choices = tabstops
 6998                    .iter()
 6999                    .map(|tabstop| tabstop.choices.clone())
 7000                    .collect();
 7001
 7002                let ranges = tabstops
 7003                    .into_iter()
 7004                    .map(|tabstop| tabstop.ranges)
 7005                    .collect::<Vec<_>>();
 7006
 7007                self.snippet_stack.push(SnippetState {
 7008                    active_index: 0,
 7009                    ranges,
 7010                    choices,
 7011                });
 7012            }
 7013
 7014            // Check whether the just-entered snippet ends with an auto-closable bracket.
 7015            if self.autoclose_regions.is_empty() {
 7016                let snapshot = self.buffer.read(cx).snapshot(cx);
 7017                for selection in &mut self.selections.all::<Point>(cx) {
 7018                    let selection_head = selection.head();
 7019                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 7020                        continue;
 7021                    };
 7022
 7023                    let mut bracket_pair = None;
 7024                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 7025                    let prev_chars = snapshot
 7026                        .reversed_chars_at(selection_head)
 7027                        .collect::<String>();
 7028                    for (pair, enabled) in scope.brackets() {
 7029                        if enabled
 7030                            && pair.close
 7031                            && prev_chars.starts_with(pair.start.as_str())
 7032                            && next_chars.starts_with(pair.end.as_str())
 7033                        {
 7034                            bracket_pair = Some(pair.clone());
 7035                            break;
 7036                        }
 7037                    }
 7038                    if let Some(pair) = bracket_pair {
 7039                        let start = snapshot.anchor_after(selection_head);
 7040                        let end = snapshot.anchor_after(selection_head);
 7041                        self.autoclose_regions.push(AutocloseRegion {
 7042                            selection_id: selection.id,
 7043                            range: start..end,
 7044                            pair,
 7045                        });
 7046                    }
 7047                }
 7048            }
 7049        }
 7050        Ok(())
 7051    }
 7052
 7053    pub fn move_to_next_snippet_tabstop(
 7054        &mut self,
 7055        window: &mut Window,
 7056        cx: &mut Context<Self>,
 7057    ) -> bool {
 7058        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 7059    }
 7060
 7061    pub fn move_to_prev_snippet_tabstop(
 7062        &mut self,
 7063        window: &mut Window,
 7064        cx: &mut Context<Self>,
 7065    ) -> bool {
 7066        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 7067    }
 7068
 7069    pub fn move_to_snippet_tabstop(
 7070        &mut self,
 7071        bias: Bias,
 7072        window: &mut Window,
 7073        cx: &mut Context<Self>,
 7074    ) -> bool {
 7075        if let Some(mut snippet) = self.snippet_stack.pop() {
 7076            match bias {
 7077                Bias::Left => {
 7078                    if snippet.active_index > 0 {
 7079                        snippet.active_index -= 1;
 7080                    } else {
 7081                        self.snippet_stack.push(snippet);
 7082                        return false;
 7083                    }
 7084                }
 7085                Bias::Right => {
 7086                    if snippet.active_index + 1 < snippet.ranges.len() {
 7087                        snippet.active_index += 1;
 7088                    } else {
 7089                        self.snippet_stack.push(snippet);
 7090                        return false;
 7091                    }
 7092                }
 7093            }
 7094            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 7095                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7096                    s.select_anchor_ranges(current_ranges.iter().cloned())
 7097                });
 7098
 7099                if let Some(choices) = &snippet.choices[snippet.active_index] {
 7100                    if let Some(selection) = current_ranges.first() {
 7101                        self.show_snippet_choices(&choices, selection.clone(), cx);
 7102                    }
 7103                }
 7104
 7105                // If snippet state is not at the last tabstop, push it back on the stack
 7106                if snippet.active_index + 1 < snippet.ranges.len() {
 7107                    self.snippet_stack.push(snippet);
 7108                }
 7109                return true;
 7110            }
 7111        }
 7112
 7113        false
 7114    }
 7115
 7116    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 7117        self.transact(window, cx, |this, window, cx| {
 7118            this.select_all(&SelectAll, window, cx);
 7119            this.insert("", window, cx);
 7120        });
 7121    }
 7122
 7123    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 7124        self.transact(window, cx, |this, window, cx| {
 7125            this.select_autoclose_pair(window, cx);
 7126            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 7127            if !this.linked_edit_ranges.is_empty() {
 7128                let selections = this.selections.all::<MultiBufferPoint>(cx);
 7129                let snapshot = this.buffer.read(cx).snapshot(cx);
 7130
 7131                for selection in selections.iter() {
 7132                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 7133                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 7134                    if selection_start.buffer_id != selection_end.buffer_id {
 7135                        continue;
 7136                    }
 7137                    if let Some(ranges) =
 7138                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 7139                    {
 7140                        for (buffer, entries) in ranges {
 7141                            linked_ranges.entry(buffer).or_default().extend(entries);
 7142                        }
 7143                    }
 7144                }
 7145            }
 7146
 7147            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7148            if !this.selections.line_mode {
 7149                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 7150                for selection in &mut selections {
 7151                    if selection.is_empty() {
 7152                        let old_head = selection.head();
 7153                        let mut new_head =
 7154                            movement::left(&display_map, old_head.to_display_point(&display_map))
 7155                                .to_point(&display_map);
 7156                        if let Some((buffer, line_buffer_range)) = display_map
 7157                            .buffer_snapshot
 7158                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 7159                        {
 7160                            let indent_size =
 7161                                buffer.indent_size_for_line(line_buffer_range.start.row);
 7162                            let indent_len = match indent_size.kind {
 7163                                IndentKind::Space => {
 7164                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 7165                                }
 7166                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 7167                            };
 7168                            if old_head.column <= indent_size.len && old_head.column > 0 {
 7169                                let indent_len = indent_len.get();
 7170                                new_head = cmp::min(
 7171                                    new_head,
 7172                                    MultiBufferPoint::new(
 7173                                        old_head.row,
 7174                                        ((old_head.column - 1) / indent_len) * indent_len,
 7175                                    ),
 7176                                );
 7177                            }
 7178                        }
 7179
 7180                        selection.set_head(new_head, SelectionGoal::None);
 7181                    }
 7182                }
 7183            }
 7184
 7185            this.signature_help_state.set_backspace_pressed(true);
 7186            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7187                s.select(selections)
 7188            });
 7189            this.insert("", window, cx);
 7190            let empty_str: Arc<str> = Arc::from("");
 7191            for (buffer, edits) in linked_ranges {
 7192                let snapshot = buffer.read(cx).snapshot();
 7193                use text::ToPoint as TP;
 7194
 7195                let edits = edits
 7196                    .into_iter()
 7197                    .map(|range| {
 7198                        let end_point = TP::to_point(&range.end, &snapshot);
 7199                        let mut start_point = TP::to_point(&range.start, &snapshot);
 7200
 7201                        if end_point == start_point {
 7202                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 7203                                .saturating_sub(1);
 7204                            start_point =
 7205                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 7206                        };
 7207
 7208                        (start_point..end_point, empty_str.clone())
 7209                    })
 7210                    .sorted_by_key(|(range, _)| range.start)
 7211                    .collect::<Vec<_>>();
 7212                buffer.update(cx, |this, cx| {
 7213                    this.edit(edits, None, cx);
 7214                })
 7215            }
 7216            this.refresh_inline_completion(true, false, window, cx);
 7217            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 7218        });
 7219    }
 7220
 7221    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 7222        self.transact(window, cx, |this, window, cx| {
 7223            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7224                let line_mode = s.line_mode;
 7225                s.move_with(|map, selection| {
 7226                    if selection.is_empty() && !line_mode {
 7227                        let cursor = movement::right(map, selection.head());
 7228                        selection.end = cursor;
 7229                        selection.reversed = true;
 7230                        selection.goal = SelectionGoal::None;
 7231                    }
 7232                })
 7233            });
 7234            this.insert("", window, cx);
 7235            this.refresh_inline_completion(true, false, window, cx);
 7236        });
 7237    }
 7238
 7239    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 7240        if self.move_to_prev_snippet_tabstop(window, cx) {
 7241            return;
 7242        }
 7243
 7244        self.outdent(&Outdent, window, cx);
 7245    }
 7246
 7247    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 7248        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 7249            return;
 7250        }
 7251
 7252        let mut selections = self.selections.all_adjusted(cx);
 7253        let buffer = self.buffer.read(cx);
 7254        let snapshot = buffer.snapshot(cx);
 7255        let rows_iter = selections.iter().map(|s| s.head().row);
 7256        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 7257
 7258        let mut edits = Vec::new();
 7259        let mut prev_edited_row = 0;
 7260        let mut row_delta = 0;
 7261        for selection in &mut selections {
 7262            if selection.start.row != prev_edited_row {
 7263                row_delta = 0;
 7264            }
 7265            prev_edited_row = selection.end.row;
 7266
 7267            // If the selection is non-empty, then increase the indentation of the selected lines.
 7268            if !selection.is_empty() {
 7269                row_delta =
 7270                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7271                continue;
 7272            }
 7273
 7274            // If the selection is empty and the cursor is in the leading whitespace before the
 7275            // suggested indentation, then auto-indent the line.
 7276            let cursor = selection.head();
 7277            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 7278            if let Some(suggested_indent) =
 7279                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 7280            {
 7281                if cursor.column < suggested_indent.len
 7282                    && cursor.column <= current_indent.len
 7283                    && current_indent.len <= suggested_indent.len
 7284                {
 7285                    selection.start = Point::new(cursor.row, suggested_indent.len);
 7286                    selection.end = selection.start;
 7287                    if row_delta == 0 {
 7288                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 7289                            cursor.row,
 7290                            current_indent,
 7291                            suggested_indent,
 7292                        ));
 7293                        row_delta = suggested_indent.len - current_indent.len;
 7294                    }
 7295                    continue;
 7296                }
 7297            }
 7298
 7299            // Otherwise, insert a hard or soft tab.
 7300            let settings = buffer.settings_at(cursor, cx);
 7301            let tab_size = if settings.hard_tabs {
 7302                IndentSize::tab()
 7303            } else {
 7304                let tab_size = settings.tab_size.get();
 7305                let char_column = snapshot
 7306                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 7307                    .flat_map(str::chars)
 7308                    .count()
 7309                    + row_delta as usize;
 7310                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 7311                IndentSize::spaces(chars_to_next_tab_stop)
 7312            };
 7313            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 7314            selection.end = selection.start;
 7315            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 7316            row_delta += tab_size.len;
 7317        }
 7318
 7319        self.transact(window, cx, |this, window, cx| {
 7320            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7321            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7322                s.select(selections)
 7323            });
 7324            this.refresh_inline_completion(true, false, window, cx);
 7325        });
 7326    }
 7327
 7328    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 7329        if self.read_only(cx) {
 7330            return;
 7331        }
 7332        let mut selections = self.selections.all::<Point>(cx);
 7333        let mut prev_edited_row = 0;
 7334        let mut row_delta = 0;
 7335        let mut edits = Vec::new();
 7336        let buffer = self.buffer.read(cx);
 7337        let snapshot = buffer.snapshot(cx);
 7338        for selection in &mut selections {
 7339            if selection.start.row != prev_edited_row {
 7340                row_delta = 0;
 7341            }
 7342            prev_edited_row = selection.end.row;
 7343
 7344            row_delta =
 7345                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7346        }
 7347
 7348        self.transact(window, cx, |this, window, cx| {
 7349            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7350            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7351                s.select(selections)
 7352            });
 7353        });
 7354    }
 7355
 7356    fn indent_selection(
 7357        buffer: &MultiBuffer,
 7358        snapshot: &MultiBufferSnapshot,
 7359        selection: &mut Selection<Point>,
 7360        edits: &mut Vec<(Range<Point>, String)>,
 7361        delta_for_start_row: u32,
 7362        cx: &App,
 7363    ) -> u32 {
 7364        let settings = buffer.settings_at(selection.start, cx);
 7365        let tab_size = settings.tab_size.get();
 7366        let indent_kind = if settings.hard_tabs {
 7367            IndentKind::Tab
 7368        } else {
 7369            IndentKind::Space
 7370        };
 7371        let mut start_row = selection.start.row;
 7372        let mut end_row = selection.end.row + 1;
 7373
 7374        // If a selection ends at the beginning of a line, don't indent
 7375        // that last line.
 7376        if selection.end.column == 0 && selection.end.row > selection.start.row {
 7377            end_row -= 1;
 7378        }
 7379
 7380        // Avoid re-indenting a row that has already been indented by a
 7381        // previous selection, but still update this selection's column
 7382        // to reflect that indentation.
 7383        if delta_for_start_row > 0 {
 7384            start_row += 1;
 7385            selection.start.column += delta_for_start_row;
 7386            if selection.end.row == selection.start.row {
 7387                selection.end.column += delta_for_start_row;
 7388            }
 7389        }
 7390
 7391        let mut delta_for_end_row = 0;
 7392        let has_multiple_rows = start_row + 1 != end_row;
 7393        for row in start_row..end_row {
 7394            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 7395            let indent_delta = match (current_indent.kind, indent_kind) {
 7396                (IndentKind::Space, IndentKind::Space) => {
 7397                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 7398                    IndentSize::spaces(columns_to_next_tab_stop)
 7399                }
 7400                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 7401                (_, IndentKind::Tab) => IndentSize::tab(),
 7402            };
 7403
 7404            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 7405                0
 7406            } else {
 7407                selection.start.column
 7408            };
 7409            let row_start = Point::new(row, start);
 7410            edits.push((
 7411                row_start..row_start,
 7412                indent_delta.chars().collect::<String>(),
 7413            ));
 7414
 7415            // Update this selection's endpoints to reflect the indentation.
 7416            if row == selection.start.row {
 7417                selection.start.column += indent_delta.len;
 7418            }
 7419            if row == selection.end.row {
 7420                selection.end.column += indent_delta.len;
 7421                delta_for_end_row = indent_delta.len;
 7422            }
 7423        }
 7424
 7425        if selection.start.row == selection.end.row {
 7426            delta_for_start_row + delta_for_end_row
 7427        } else {
 7428            delta_for_end_row
 7429        }
 7430    }
 7431
 7432    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 7433        if self.read_only(cx) {
 7434            return;
 7435        }
 7436        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7437        let selections = self.selections.all::<Point>(cx);
 7438        let mut deletion_ranges = Vec::new();
 7439        let mut last_outdent = None;
 7440        {
 7441            let buffer = self.buffer.read(cx);
 7442            let snapshot = buffer.snapshot(cx);
 7443            for selection in &selections {
 7444                let settings = buffer.settings_at(selection.start, cx);
 7445                let tab_size = settings.tab_size.get();
 7446                let mut rows = selection.spanned_rows(false, &display_map);
 7447
 7448                // Avoid re-outdenting a row that has already been outdented by a
 7449                // previous selection.
 7450                if let Some(last_row) = last_outdent {
 7451                    if last_row == rows.start {
 7452                        rows.start = rows.start.next_row();
 7453                    }
 7454                }
 7455                let has_multiple_rows = rows.len() > 1;
 7456                for row in rows.iter_rows() {
 7457                    let indent_size = snapshot.indent_size_for_line(row);
 7458                    if indent_size.len > 0 {
 7459                        let deletion_len = match indent_size.kind {
 7460                            IndentKind::Space => {
 7461                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 7462                                if columns_to_prev_tab_stop == 0 {
 7463                                    tab_size
 7464                                } else {
 7465                                    columns_to_prev_tab_stop
 7466                                }
 7467                            }
 7468                            IndentKind::Tab => 1,
 7469                        };
 7470                        let start = if has_multiple_rows
 7471                            || deletion_len > selection.start.column
 7472                            || indent_size.len < selection.start.column
 7473                        {
 7474                            0
 7475                        } else {
 7476                            selection.start.column - deletion_len
 7477                        };
 7478                        deletion_ranges.push(
 7479                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 7480                        );
 7481                        last_outdent = Some(row);
 7482                    }
 7483                }
 7484            }
 7485        }
 7486
 7487        self.transact(window, cx, |this, window, cx| {
 7488            this.buffer.update(cx, |buffer, cx| {
 7489                let empty_str: Arc<str> = Arc::default();
 7490                buffer.edit(
 7491                    deletion_ranges
 7492                        .into_iter()
 7493                        .map(|range| (range, empty_str.clone())),
 7494                    None,
 7495                    cx,
 7496                );
 7497            });
 7498            let selections = this.selections.all::<usize>(cx);
 7499            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7500                s.select(selections)
 7501            });
 7502        });
 7503    }
 7504
 7505    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 7506        if self.read_only(cx) {
 7507            return;
 7508        }
 7509        let selections = self
 7510            .selections
 7511            .all::<usize>(cx)
 7512            .into_iter()
 7513            .map(|s| s.range());
 7514
 7515        self.transact(window, cx, |this, window, cx| {
 7516            this.buffer.update(cx, |buffer, cx| {
 7517                buffer.autoindent_ranges(selections, cx);
 7518            });
 7519            let selections = this.selections.all::<usize>(cx);
 7520            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7521                s.select(selections)
 7522            });
 7523        });
 7524    }
 7525
 7526    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 7527        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7528        let selections = self.selections.all::<Point>(cx);
 7529
 7530        let mut new_cursors = Vec::new();
 7531        let mut edit_ranges = Vec::new();
 7532        let mut selections = selections.iter().peekable();
 7533        while let Some(selection) = selections.next() {
 7534            let mut rows = selection.spanned_rows(false, &display_map);
 7535            let goal_display_column = selection.head().to_display_point(&display_map).column();
 7536
 7537            // Accumulate contiguous regions of rows that we want to delete.
 7538            while let Some(next_selection) = selections.peek() {
 7539                let next_rows = next_selection.spanned_rows(false, &display_map);
 7540                if next_rows.start <= rows.end {
 7541                    rows.end = next_rows.end;
 7542                    selections.next().unwrap();
 7543                } else {
 7544                    break;
 7545                }
 7546            }
 7547
 7548            let buffer = &display_map.buffer_snapshot;
 7549            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 7550            let edit_end;
 7551            let cursor_buffer_row;
 7552            if buffer.max_point().row >= rows.end.0 {
 7553                // If there's a line after the range, delete the \n from the end of the row range
 7554                // and position the cursor on the next line.
 7555                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 7556                cursor_buffer_row = rows.end;
 7557            } else {
 7558                // If there isn't a line after the range, delete the \n from the line before the
 7559                // start of the row range and position the cursor there.
 7560                edit_start = edit_start.saturating_sub(1);
 7561                edit_end = buffer.len();
 7562                cursor_buffer_row = rows.start.previous_row();
 7563            }
 7564
 7565            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 7566            *cursor.column_mut() =
 7567                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 7568
 7569            new_cursors.push((
 7570                selection.id,
 7571                buffer.anchor_after(cursor.to_point(&display_map)),
 7572            ));
 7573            edit_ranges.push(edit_start..edit_end);
 7574        }
 7575
 7576        self.transact(window, cx, |this, window, cx| {
 7577            let buffer = this.buffer.update(cx, |buffer, cx| {
 7578                let empty_str: Arc<str> = Arc::default();
 7579                buffer.edit(
 7580                    edit_ranges
 7581                        .into_iter()
 7582                        .map(|range| (range, empty_str.clone())),
 7583                    None,
 7584                    cx,
 7585                );
 7586                buffer.snapshot(cx)
 7587            });
 7588            let new_selections = new_cursors
 7589                .into_iter()
 7590                .map(|(id, cursor)| {
 7591                    let cursor = cursor.to_point(&buffer);
 7592                    Selection {
 7593                        id,
 7594                        start: cursor,
 7595                        end: cursor,
 7596                        reversed: false,
 7597                        goal: SelectionGoal::None,
 7598                    }
 7599                })
 7600                .collect();
 7601
 7602            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7603                s.select(new_selections);
 7604            });
 7605        });
 7606    }
 7607
 7608    pub fn join_lines_impl(
 7609        &mut self,
 7610        insert_whitespace: bool,
 7611        window: &mut Window,
 7612        cx: &mut Context<Self>,
 7613    ) {
 7614        if self.read_only(cx) {
 7615            return;
 7616        }
 7617        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 7618        for selection in self.selections.all::<Point>(cx) {
 7619            let start = MultiBufferRow(selection.start.row);
 7620            // Treat single line selections as if they include the next line. Otherwise this action
 7621            // would do nothing for single line selections individual cursors.
 7622            let end = if selection.start.row == selection.end.row {
 7623                MultiBufferRow(selection.start.row + 1)
 7624            } else {
 7625                MultiBufferRow(selection.end.row)
 7626            };
 7627
 7628            if let Some(last_row_range) = row_ranges.last_mut() {
 7629                if start <= last_row_range.end {
 7630                    last_row_range.end = end;
 7631                    continue;
 7632                }
 7633            }
 7634            row_ranges.push(start..end);
 7635        }
 7636
 7637        let snapshot = self.buffer.read(cx).snapshot(cx);
 7638        let mut cursor_positions = Vec::new();
 7639        for row_range in &row_ranges {
 7640            let anchor = snapshot.anchor_before(Point::new(
 7641                row_range.end.previous_row().0,
 7642                snapshot.line_len(row_range.end.previous_row()),
 7643            ));
 7644            cursor_positions.push(anchor..anchor);
 7645        }
 7646
 7647        self.transact(window, cx, |this, window, cx| {
 7648            for row_range in row_ranges.into_iter().rev() {
 7649                for row in row_range.iter_rows().rev() {
 7650                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 7651                    let next_line_row = row.next_row();
 7652                    let indent = snapshot.indent_size_for_line(next_line_row);
 7653                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7654
 7655                    let replace =
 7656                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7657                            " "
 7658                        } else {
 7659                            ""
 7660                        };
 7661
 7662                    this.buffer.update(cx, |buffer, cx| {
 7663                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7664                    });
 7665                }
 7666            }
 7667
 7668            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7669                s.select_anchor_ranges(cursor_positions)
 7670            });
 7671        });
 7672    }
 7673
 7674    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7675        self.join_lines_impl(true, window, cx);
 7676    }
 7677
 7678    pub fn sort_lines_case_sensitive(
 7679        &mut self,
 7680        _: &SortLinesCaseSensitive,
 7681        window: &mut Window,
 7682        cx: &mut Context<Self>,
 7683    ) {
 7684        self.manipulate_lines(window, cx, |lines| lines.sort())
 7685    }
 7686
 7687    pub fn sort_lines_case_insensitive(
 7688        &mut self,
 7689        _: &SortLinesCaseInsensitive,
 7690        window: &mut Window,
 7691        cx: &mut Context<Self>,
 7692    ) {
 7693        self.manipulate_lines(window, cx, |lines| {
 7694            lines.sort_by_key(|line| line.to_lowercase())
 7695        })
 7696    }
 7697
 7698    pub fn unique_lines_case_insensitive(
 7699        &mut self,
 7700        _: &UniqueLinesCaseInsensitive,
 7701        window: &mut Window,
 7702        cx: &mut Context<Self>,
 7703    ) {
 7704        self.manipulate_lines(window, cx, |lines| {
 7705            let mut seen = HashSet::default();
 7706            lines.retain(|line| seen.insert(line.to_lowercase()));
 7707        })
 7708    }
 7709
 7710    pub fn unique_lines_case_sensitive(
 7711        &mut self,
 7712        _: &UniqueLinesCaseSensitive,
 7713        window: &mut Window,
 7714        cx: &mut Context<Self>,
 7715    ) {
 7716        self.manipulate_lines(window, cx, |lines| {
 7717            let mut seen = HashSet::default();
 7718            lines.retain(|line| seen.insert(*line));
 7719        })
 7720    }
 7721
 7722    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7723        let Some(project) = self.project.clone() else {
 7724            return;
 7725        };
 7726        self.reload(project, window, cx)
 7727            .detach_and_notify_err(window, cx);
 7728    }
 7729
 7730    pub fn restore_file(
 7731        &mut self,
 7732        _: &::git::RestoreFile,
 7733        window: &mut Window,
 7734        cx: &mut Context<Self>,
 7735    ) {
 7736        let mut buffer_ids = HashSet::default();
 7737        let snapshot = self.buffer().read(cx).snapshot(cx);
 7738        for selection in self.selections.all::<usize>(cx) {
 7739            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 7740        }
 7741
 7742        let buffer = self.buffer().read(cx);
 7743        let ranges = buffer_ids
 7744            .into_iter()
 7745            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 7746            .collect::<Vec<_>>();
 7747
 7748        self.restore_hunks_in_ranges(ranges, window, cx);
 7749    }
 7750
 7751    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 7752        let selections = self
 7753            .selections
 7754            .all(cx)
 7755            .into_iter()
 7756            .map(|s| s.range())
 7757            .collect();
 7758        self.restore_hunks_in_ranges(selections, window, cx);
 7759    }
 7760
 7761    fn restore_hunks_in_ranges(
 7762        &mut self,
 7763        ranges: Vec<Range<Point>>,
 7764        window: &mut Window,
 7765        cx: &mut Context<Editor>,
 7766    ) {
 7767        let mut revert_changes = HashMap::default();
 7768        let chunk_by = self
 7769            .snapshot(window, cx)
 7770            .hunks_for_ranges(ranges)
 7771            .into_iter()
 7772            .chunk_by(|hunk| hunk.buffer_id);
 7773        for (buffer_id, hunks) in &chunk_by {
 7774            let hunks = hunks.collect::<Vec<_>>();
 7775            for hunk in &hunks {
 7776                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 7777            }
 7778            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 7779        }
 7780        drop(chunk_by);
 7781        if !revert_changes.is_empty() {
 7782            self.transact(window, cx, |editor, window, cx| {
 7783                editor.restore(revert_changes, window, cx);
 7784            });
 7785        }
 7786    }
 7787
 7788    pub fn open_active_item_in_terminal(
 7789        &mut self,
 7790        _: &OpenInTerminal,
 7791        window: &mut Window,
 7792        cx: &mut Context<Self>,
 7793    ) {
 7794        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7795            let project_path = buffer.read(cx).project_path(cx)?;
 7796            let project = self.project.as_ref()?.read(cx);
 7797            let entry = project.entry_for_path(&project_path, cx)?;
 7798            let parent = match &entry.canonical_path {
 7799                Some(canonical_path) => canonical_path.to_path_buf(),
 7800                None => project.absolute_path(&project_path, cx)?,
 7801            }
 7802            .parent()?
 7803            .to_path_buf();
 7804            Some(parent)
 7805        }) {
 7806            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7807        }
 7808    }
 7809
 7810    pub fn prepare_restore_change(
 7811        &self,
 7812        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7813        hunk: &MultiBufferDiffHunk,
 7814        cx: &mut App,
 7815    ) -> Option<()> {
 7816        if hunk.is_created_file() {
 7817            return None;
 7818        }
 7819        let buffer = self.buffer.read(cx);
 7820        let diff = buffer.diff_for(hunk.buffer_id)?;
 7821        let buffer = buffer.buffer(hunk.buffer_id)?;
 7822        let buffer = buffer.read(cx);
 7823        let original_text = diff
 7824            .read(cx)
 7825            .base_text()
 7826            .as_rope()
 7827            .slice(hunk.diff_base_byte_range.clone());
 7828        let buffer_snapshot = buffer.snapshot();
 7829        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7830        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7831            probe
 7832                .0
 7833                .start
 7834                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7835                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7836        }) {
 7837            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7838            Some(())
 7839        } else {
 7840            None
 7841        }
 7842    }
 7843
 7844    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7845        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7846    }
 7847
 7848    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7849        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7850    }
 7851
 7852    fn manipulate_lines<Fn>(
 7853        &mut self,
 7854        window: &mut Window,
 7855        cx: &mut Context<Self>,
 7856        mut callback: Fn,
 7857    ) where
 7858        Fn: FnMut(&mut Vec<&str>),
 7859    {
 7860        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7861        let buffer = self.buffer.read(cx).snapshot(cx);
 7862
 7863        let mut edits = Vec::new();
 7864
 7865        let selections = self.selections.all::<Point>(cx);
 7866        let mut selections = selections.iter().peekable();
 7867        let mut contiguous_row_selections = Vec::new();
 7868        let mut new_selections = Vec::new();
 7869        let mut added_lines = 0;
 7870        let mut removed_lines = 0;
 7871
 7872        while let Some(selection) = selections.next() {
 7873            let (start_row, end_row) = consume_contiguous_rows(
 7874                &mut contiguous_row_selections,
 7875                selection,
 7876                &display_map,
 7877                &mut selections,
 7878            );
 7879
 7880            let start_point = Point::new(start_row.0, 0);
 7881            let end_point = Point::new(
 7882                end_row.previous_row().0,
 7883                buffer.line_len(end_row.previous_row()),
 7884            );
 7885            let text = buffer
 7886                .text_for_range(start_point..end_point)
 7887                .collect::<String>();
 7888
 7889            let mut lines = text.split('\n').collect_vec();
 7890
 7891            let lines_before = lines.len();
 7892            callback(&mut lines);
 7893            let lines_after = lines.len();
 7894
 7895            edits.push((start_point..end_point, lines.join("\n")));
 7896
 7897            // Selections must change based on added and removed line count
 7898            let start_row =
 7899                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7900            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7901            new_selections.push(Selection {
 7902                id: selection.id,
 7903                start: start_row,
 7904                end: end_row,
 7905                goal: SelectionGoal::None,
 7906                reversed: selection.reversed,
 7907            });
 7908
 7909            if lines_after > lines_before {
 7910                added_lines += lines_after - lines_before;
 7911            } else if lines_before > lines_after {
 7912                removed_lines += lines_before - lines_after;
 7913            }
 7914        }
 7915
 7916        self.transact(window, cx, |this, window, cx| {
 7917            let buffer = this.buffer.update(cx, |buffer, cx| {
 7918                buffer.edit(edits, None, cx);
 7919                buffer.snapshot(cx)
 7920            });
 7921
 7922            // Recalculate offsets on newly edited buffer
 7923            let new_selections = new_selections
 7924                .iter()
 7925                .map(|s| {
 7926                    let start_point = Point::new(s.start.0, 0);
 7927                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7928                    Selection {
 7929                        id: s.id,
 7930                        start: buffer.point_to_offset(start_point),
 7931                        end: buffer.point_to_offset(end_point),
 7932                        goal: s.goal,
 7933                        reversed: s.reversed,
 7934                    }
 7935                })
 7936                .collect();
 7937
 7938            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7939                s.select(new_selections);
 7940            });
 7941
 7942            this.request_autoscroll(Autoscroll::fit(), cx);
 7943        });
 7944    }
 7945
 7946    pub fn convert_to_upper_case(
 7947        &mut self,
 7948        _: &ConvertToUpperCase,
 7949        window: &mut Window,
 7950        cx: &mut Context<Self>,
 7951    ) {
 7952        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7953    }
 7954
 7955    pub fn convert_to_lower_case(
 7956        &mut self,
 7957        _: &ConvertToLowerCase,
 7958        window: &mut Window,
 7959        cx: &mut Context<Self>,
 7960    ) {
 7961        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7962    }
 7963
 7964    pub fn convert_to_title_case(
 7965        &mut self,
 7966        _: &ConvertToTitleCase,
 7967        window: &mut Window,
 7968        cx: &mut Context<Self>,
 7969    ) {
 7970        self.manipulate_text(window, cx, |text| {
 7971            text.split('\n')
 7972                .map(|line| line.to_case(Case::Title))
 7973                .join("\n")
 7974        })
 7975    }
 7976
 7977    pub fn convert_to_snake_case(
 7978        &mut self,
 7979        _: &ConvertToSnakeCase,
 7980        window: &mut Window,
 7981        cx: &mut Context<Self>,
 7982    ) {
 7983        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7984    }
 7985
 7986    pub fn convert_to_kebab_case(
 7987        &mut self,
 7988        _: &ConvertToKebabCase,
 7989        window: &mut Window,
 7990        cx: &mut Context<Self>,
 7991    ) {
 7992        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7993    }
 7994
 7995    pub fn convert_to_upper_camel_case(
 7996        &mut self,
 7997        _: &ConvertToUpperCamelCase,
 7998        window: &mut Window,
 7999        cx: &mut Context<Self>,
 8000    ) {
 8001        self.manipulate_text(window, cx, |text| {
 8002            text.split('\n')
 8003                .map(|line| line.to_case(Case::UpperCamel))
 8004                .join("\n")
 8005        })
 8006    }
 8007
 8008    pub fn convert_to_lower_camel_case(
 8009        &mut self,
 8010        _: &ConvertToLowerCamelCase,
 8011        window: &mut Window,
 8012        cx: &mut Context<Self>,
 8013    ) {
 8014        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 8015    }
 8016
 8017    pub fn convert_to_opposite_case(
 8018        &mut self,
 8019        _: &ConvertToOppositeCase,
 8020        window: &mut Window,
 8021        cx: &mut Context<Self>,
 8022    ) {
 8023        self.manipulate_text(window, cx, |text| {
 8024            text.chars()
 8025                .fold(String::with_capacity(text.len()), |mut t, c| {
 8026                    if c.is_uppercase() {
 8027                        t.extend(c.to_lowercase());
 8028                    } else {
 8029                        t.extend(c.to_uppercase());
 8030                    }
 8031                    t
 8032                })
 8033        })
 8034    }
 8035
 8036    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 8037    where
 8038        Fn: FnMut(&str) -> String,
 8039    {
 8040        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8041        let buffer = self.buffer.read(cx).snapshot(cx);
 8042
 8043        let mut new_selections = Vec::new();
 8044        let mut edits = Vec::new();
 8045        let mut selection_adjustment = 0i32;
 8046
 8047        for selection in self.selections.all::<usize>(cx) {
 8048            let selection_is_empty = selection.is_empty();
 8049
 8050            let (start, end) = if selection_is_empty {
 8051                let word_range = movement::surrounding_word(
 8052                    &display_map,
 8053                    selection.start.to_display_point(&display_map),
 8054                );
 8055                let start = word_range.start.to_offset(&display_map, Bias::Left);
 8056                let end = word_range.end.to_offset(&display_map, Bias::Left);
 8057                (start, end)
 8058            } else {
 8059                (selection.start, selection.end)
 8060            };
 8061
 8062            let text = buffer.text_for_range(start..end).collect::<String>();
 8063            let old_length = text.len() as i32;
 8064            let text = callback(&text);
 8065
 8066            new_selections.push(Selection {
 8067                start: (start as i32 - selection_adjustment) as usize,
 8068                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 8069                goal: SelectionGoal::None,
 8070                ..selection
 8071            });
 8072
 8073            selection_adjustment += old_length - text.len() as i32;
 8074
 8075            edits.push((start..end, text));
 8076        }
 8077
 8078        self.transact(window, cx, |this, window, cx| {
 8079            this.buffer.update(cx, |buffer, cx| {
 8080                buffer.edit(edits, None, cx);
 8081            });
 8082
 8083            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8084                s.select(new_selections);
 8085            });
 8086
 8087            this.request_autoscroll(Autoscroll::fit(), cx);
 8088        });
 8089    }
 8090
 8091    pub fn duplicate(
 8092        &mut self,
 8093        upwards: bool,
 8094        whole_lines: bool,
 8095        window: &mut Window,
 8096        cx: &mut Context<Self>,
 8097    ) {
 8098        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8099        let buffer = &display_map.buffer_snapshot;
 8100        let selections = self.selections.all::<Point>(cx);
 8101
 8102        let mut edits = Vec::new();
 8103        let mut selections_iter = selections.iter().peekable();
 8104        while let Some(selection) = selections_iter.next() {
 8105            let mut rows = selection.spanned_rows(false, &display_map);
 8106            // duplicate line-wise
 8107            if whole_lines || selection.start == selection.end {
 8108                // Avoid duplicating the same lines twice.
 8109                while let Some(next_selection) = selections_iter.peek() {
 8110                    let next_rows = next_selection.spanned_rows(false, &display_map);
 8111                    if next_rows.start < rows.end {
 8112                        rows.end = next_rows.end;
 8113                        selections_iter.next().unwrap();
 8114                    } else {
 8115                        break;
 8116                    }
 8117                }
 8118
 8119                // Copy the text from the selected row region and splice it either at the start
 8120                // or end of the region.
 8121                let start = Point::new(rows.start.0, 0);
 8122                let end = Point::new(
 8123                    rows.end.previous_row().0,
 8124                    buffer.line_len(rows.end.previous_row()),
 8125                );
 8126                let text = buffer
 8127                    .text_for_range(start..end)
 8128                    .chain(Some("\n"))
 8129                    .collect::<String>();
 8130                let insert_location = if upwards {
 8131                    Point::new(rows.end.0, 0)
 8132                } else {
 8133                    start
 8134                };
 8135                edits.push((insert_location..insert_location, text));
 8136            } else {
 8137                // duplicate character-wise
 8138                let start = selection.start;
 8139                let end = selection.end;
 8140                let text = buffer.text_for_range(start..end).collect::<String>();
 8141                edits.push((selection.end..selection.end, text));
 8142            }
 8143        }
 8144
 8145        self.transact(window, cx, |this, _, cx| {
 8146            this.buffer.update(cx, |buffer, cx| {
 8147                buffer.edit(edits, None, cx);
 8148            });
 8149
 8150            this.request_autoscroll(Autoscroll::fit(), cx);
 8151        });
 8152    }
 8153
 8154    pub fn duplicate_line_up(
 8155        &mut self,
 8156        _: &DuplicateLineUp,
 8157        window: &mut Window,
 8158        cx: &mut Context<Self>,
 8159    ) {
 8160        self.duplicate(true, true, window, cx);
 8161    }
 8162
 8163    pub fn duplicate_line_down(
 8164        &mut self,
 8165        _: &DuplicateLineDown,
 8166        window: &mut Window,
 8167        cx: &mut Context<Self>,
 8168    ) {
 8169        self.duplicate(false, true, window, cx);
 8170    }
 8171
 8172    pub fn duplicate_selection(
 8173        &mut self,
 8174        _: &DuplicateSelection,
 8175        window: &mut Window,
 8176        cx: &mut Context<Self>,
 8177    ) {
 8178        self.duplicate(false, false, window, cx);
 8179    }
 8180
 8181    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 8182        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8183        let buffer = self.buffer.read(cx).snapshot(cx);
 8184
 8185        let mut edits = Vec::new();
 8186        let mut unfold_ranges = Vec::new();
 8187        let mut refold_creases = Vec::new();
 8188
 8189        let selections = self.selections.all::<Point>(cx);
 8190        let mut selections = selections.iter().peekable();
 8191        let mut contiguous_row_selections = Vec::new();
 8192        let mut new_selections = Vec::new();
 8193
 8194        while let Some(selection) = selections.next() {
 8195            // Find all the selections that span a contiguous row range
 8196            let (start_row, end_row) = consume_contiguous_rows(
 8197                &mut contiguous_row_selections,
 8198                selection,
 8199                &display_map,
 8200                &mut selections,
 8201            );
 8202
 8203            // Move the text spanned by the row range to be before the line preceding the row range
 8204            if start_row.0 > 0 {
 8205                let range_to_move = Point::new(
 8206                    start_row.previous_row().0,
 8207                    buffer.line_len(start_row.previous_row()),
 8208                )
 8209                    ..Point::new(
 8210                        end_row.previous_row().0,
 8211                        buffer.line_len(end_row.previous_row()),
 8212                    );
 8213                let insertion_point = display_map
 8214                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 8215                    .0;
 8216
 8217                // Don't move lines across excerpts
 8218                if buffer
 8219                    .excerpt_containing(insertion_point..range_to_move.end)
 8220                    .is_some()
 8221                {
 8222                    let text = buffer
 8223                        .text_for_range(range_to_move.clone())
 8224                        .flat_map(|s| s.chars())
 8225                        .skip(1)
 8226                        .chain(['\n'])
 8227                        .collect::<String>();
 8228
 8229                    edits.push((
 8230                        buffer.anchor_after(range_to_move.start)
 8231                            ..buffer.anchor_before(range_to_move.end),
 8232                        String::new(),
 8233                    ));
 8234                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8235                    edits.push((insertion_anchor..insertion_anchor, text));
 8236
 8237                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 8238
 8239                    // Move selections up
 8240                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8241                        |mut selection| {
 8242                            selection.start.row -= row_delta;
 8243                            selection.end.row -= row_delta;
 8244                            selection
 8245                        },
 8246                    ));
 8247
 8248                    // Move folds up
 8249                    unfold_ranges.push(range_to_move.clone());
 8250                    for fold in display_map.folds_in_range(
 8251                        buffer.anchor_before(range_to_move.start)
 8252                            ..buffer.anchor_after(range_to_move.end),
 8253                    ) {
 8254                        let mut start = fold.range.start.to_point(&buffer);
 8255                        let mut end = fold.range.end.to_point(&buffer);
 8256                        start.row -= row_delta;
 8257                        end.row -= row_delta;
 8258                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8259                    }
 8260                }
 8261            }
 8262
 8263            // If we didn't move line(s), preserve the existing selections
 8264            new_selections.append(&mut contiguous_row_selections);
 8265        }
 8266
 8267        self.transact(window, cx, |this, window, cx| {
 8268            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8269            this.buffer.update(cx, |buffer, cx| {
 8270                for (range, text) in edits {
 8271                    buffer.edit([(range, text)], None, cx);
 8272                }
 8273            });
 8274            this.fold_creases(refold_creases, true, window, cx);
 8275            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8276                s.select(new_selections);
 8277            })
 8278        });
 8279    }
 8280
 8281    pub fn move_line_down(
 8282        &mut self,
 8283        _: &MoveLineDown,
 8284        window: &mut Window,
 8285        cx: &mut Context<Self>,
 8286    ) {
 8287        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8288        let buffer = self.buffer.read(cx).snapshot(cx);
 8289
 8290        let mut edits = Vec::new();
 8291        let mut unfold_ranges = Vec::new();
 8292        let mut refold_creases = Vec::new();
 8293
 8294        let selections = self.selections.all::<Point>(cx);
 8295        let mut selections = selections.iter().peekable();
 8296        let mut contiguous_row_selections = Vec::new();
 8297        let mut new_selections = Vec::new();
 8298
 8299        while let Some(selection) = selections.next() {
 8300            // Find all the selections that span a contiguous row range
 8301            let (start_row, end_row) = consume_contiguous_rows(
 8302                &mut contiguous_row_selections,
 8303                selection,
 8304                &display_map,
 8305                &mut selections,
 8306            );
 8307
 8308            // Move the text spanned by the row range to be after the last line of the row range
 8309            if end_row.0 <= buffer.max_point().row {
 8310                let range_to_move =
 8311                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 8312                let insertion_point = display_map
 8313                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 8314                    .0;
 8315
 8316                // Don't move lines across excerpt boundaries
 8317                if buffer
 8318                    .excerpt_containing(range_to_move.start..insertion_point)
 8319                    .is_some()
 8320                {
 8321                    let mut text = String::from("\n");
 8322                    text.extend(buffer.text_for_range(range_to_move.clone()));
 8323                    text.pop(); // Drop trailing newline
 8324                    edits.push((
 8325                        buffer.anchor_after(range_to_move.start)
 8326                            ..buffer.anchor_before(range_to_move.end),
 8327                        String::new(),
 8328                    ));
 8329                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8330                    edits.push((insertion_anchor..insertion_anchor, text));
 8331
 8332                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 8333
 8334                    // Move selections down
 8335                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8336                        |mut selection| {
 8337                            selection.start.row += row_delta;
 8338                            selection.end.row += row_delta;
 8339                            selection
 8340                        },
 8341                    ));
 8342
 8343                    // Move folds down
 8344                    unfold_ranges.push(range_to_move.clone());
 8345                    for fold in display_map.folds_in_range(
 8346                        buffer.anchor_before(range_to_move.start)
 8347                            ..buffer.anchor_after(range_to_move.end),
 8348                    ) {
 8349                        let mut start = fold.range.start.to_point(&buffer);
 8350                        let mut end = fold.range.end.to_point(&buffer);
 8351                        start.row += row_delta;
 8352                        end.row += row_delta;
 8353                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8354                    }
 8355                }
 8356            }
 8357
 8358            // If we didn't move line(s), preserve the existing selections
 8359            new_selections.append(&mut contiguous_row_selections);
 8360        }
 8361
 8362        self.transact(window, cx, |this, window, cx| {
 8363            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8364            this.buffer.update(cx, |buffer, cx| {
 8365                for (range, text) in edits {
 8366                    buffer.edit([(range, text)], None, cx);
 8367                }
 8368            });
 8369            this.fold_creases(refold_creases, true, window, cx);
 8370            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8371                s.select(new_selections)
 8372            });
 8373        });
 8374    }
 8375
 8376    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 8377        let text_layout_details = &self.text_layout_details(window);
 8378        self.transact(window, cx, |this, window, cx| {
 8379            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8380                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 8381                let line_mode = s.line_mode;
 8382                s.move_with(|display_map, selection| {
 8383                    if !selection.is_empty() || line_mode {
 8384                        return;
 8385                    }
 8386
 8387                    let mut head = selection.head();
 8388                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 8389                    if head.column() == display_map.line_len(head.row()) {
 8390                        transpose_offset = display_map
 8391                            .buffer_snapshot
 8392                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8393                    }
 8394
 8395                    if transpose_offset == 0 {
 8396                        return;
 8397                    }
 8398
 8399                    *head.column_mut() += 1;
 8400                    head = display_map.clip_point(head, Bias::Right);
 8401                    let goal = SelectionGoal::HorizontalPosition(
 8402                        display_map
 8403                            .x_for_display_point(head, text_layout_details)
 8404                            .into(),
 8405                    );
 8406                    selection.collapse_to(head, goal);
 8407
 8408                    let transpose_start = display_map
 8409                        .buffer_snapshot
 8410                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8411                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 8412                        let transpose_end = display_map
 8413                            .buffer_snapshot
 8414                            .clip_offset(transpose_offset + 1, Bias::Right);
 8415                        if let Some(ch) =
 8416                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 8417                        {
 8418                            edits.push((transpose_start..transpose_offset, String::new()));
 8419                            edits.push((transpose_end..transpose_end, ch.to_string()));
 8420                        }
 8421                    }
 8422                });
 8423                edits
 8424            });
 8425            this.buffer
 8426                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8427            let selections = this.selections.all::<usize>(cx);
 8428            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8429                s.select(selections);
 8430            });
 8431        });
 8432    }
 8433
 8434    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 8435        self.rewrap_impl(IsVimMode::No, cx)
 8436    }
 8437
 8438    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 8439        let buffer = self.buffer.read(cx).snapshot(cx);
 8440        let selections = self.selections.all::<Point>(cx);
 8441        let mut selections = selections.iter().peekable();
 8442
 8443        let mut edits = Vec::new();
 8444        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 8445
 8446        while let Some(selection) = selections.next() {
 8447            let mut start_row = selection.start.row;
 8448            let mut end_row = selection.end.row;
 8449
 8450            // Skip selections that overlap with a range that has already been rewrapped.
 8451            let selection_range = start_row..end_row;
 8452            if rewrapped_row_ranges
 8453                .iter()
 8454                .any(|range| range.overlaps(&selection_range))
 8455            {
 8456                continue;
 8457            }
 8458
 8459            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 8460
 8461            // Since not all lines in the selection may be at the same indent
 8462            // level, choose the indent size that is the most common between all
 8463            // of the lines.
 8464            //
 8465            // If there is a tie, we use the deepest indent.
 8466            let (indent_size, indent_end) = {
 8467                let mut indent_size_occurrences = HashMap::default();
 8468                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 8469
 8470                for row in start_row..=end_row {
 8471                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 8472                    rows_by_indent_size.entry(indent).or_default().push(row);
 8473                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 8474                }
 8475
 8476                let indent_size = indent_size_occurrences
 8477                    .into_iter()
 8478                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 8479                    .map(|(indent, _)| indent)
 8480                    .unwrap_or_default();
 8481                let row = rows_by_indent_size[&indent_size][0];
 8482                let indent_end = Point::new(row, indent_size.len);
 8483
 8484                (indent_size, indent_end)
 8485            };
 8486
 8487            let mut line_prefix = indent_size.chars().collect::<String>();
 8488
 8489            let mut inside_comment = false;
 8490            if let Some(comment_prefix) =
 8491                buffer
 8492                    .language_scope_at(selection.head())
 8493                    .and_then(|language| {
 8494                        language
 8495                            .line_comment_prefixes()
 8496                            .iter()
 8497                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 8498                            .cloned()
 8499                    })
 8500            {
 8501                line_prefix.push_str(&comment_prefix);
 8502                inside_comment = true;
 8503            }
 8504
 8505            let language_settings = buffer.settings_at(selection.head(), cx);
 8506            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 8507                RewrapBehavior::InComments => inside_comment,
 8508                RewrapBehavior::InSelections => !selection.is_empty(),
 8509                RewrapBehavior::Anywhere => true,
 8510            };
 8511
 8512            let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
 8513            if !should_rewrap {
 8514                continue;
 8515            }
 8516
 8517            if selection.is_empty() {
 8518                'expand_upwards: while start_row > 0 {
 8519                    let prev_row = start_row - 1;
 8520                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 8521                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 8522                    {
 8523                        start_row = prev_row;
 8524                    } else {
 8525                        break 'expand_upwards;
 8526                    }
 8527                }
 8528
 8529                'expand_downwards: while end_row < buffer.max_point().row {
 8530                    let next_row = end_row + 1;
 8531                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 8532                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 8533                    {
 8534                        end_row = next_row;
 8535                    } else {
 8536                        break 'expand_downwards;
 8537                    }
 8538                }
 8539            }
 8540
 8541            let start = Point::new(start_row, 0);
 8542            let start_offset = start.to_offset(&buffer);
 8543            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 8544            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 8545            let Some(lines_without_prefixes) = selection_text
 8546                .lines()
 8547                .map(|line| {
 8548                    line.strip_prefix(&line_prefix)
 8549                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 8550                        .ok_or_else(|| {
 8551                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 8552                        })
 8553                })
 8554                .collect::<Result<Vec<_>, _>>()
 8555                .log_err()
 8556            else {
 8557                continue;
 8558            };
 8559
 8560            let wrap_column = buffer
 8561                .settings_at(Point::new(start_row, 0), cx)
 8562                .preferred_line_length as usize;
 8563            let wrapped_text = wrap_with_prefix(
 8564                line_prefix,
 8565                lines_without_prefixes.join(" "),
 8566                wrap_column,
 8567                tab_size,
 8568            );
 8569
 8570            // TODO: should always use char-based diff while still supporting cursor behavior that
 8571            // matches vim.
 8572            let mut diff_options = DiffOptions::default();
 8573            if is_vim_mode == IsVimMode::Yes {
 8574                diff_options.max_word_diff_len = 0;
 8575                diff_options.max_word_diff_line_count = 0;
 8576            } else {
 8577                diff_options.max_word_diff_len = usize::MAX;
 8578                diff_options.max_word_diff_line_count = usize::MAX;
 8579            }
 8580
 8581            for (old_range, new_text) in
 8582                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 8583            {
 8584                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 8585                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 8586                edits.push((edit_start..edit_end, new_text));
 8587            }
 8588
 8589            rewrapped_row_ranges.push(start_row..=end_row);
 8590        }
 8591
 8592        self.buffer
 8593            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8594    }
 8595
 8596    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 8597        let mut text = String::new();
 8598        let buffer = self.buffer.read(cx).snapshot(cx);
 8599        let mut selections = self.selections.all::<Point>(cx);
 8600        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8601        {
 8602            let max_point = buffer.max_point();
 8603            let mut is_first = true;
 8604            for selection in &mut selections {
 8605                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8606                if is_entire_line {
 8607                    selection.start = Point::new(selection.start.row, 0);
 8608                    if !selection.is_empty() && selection.end.column == 0 {
 8609                        selection.end = cmp::min(max_point, selection.end);
 8610                    } else {
 8611                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 8612                    }
 8613                    selection.goal = SelectionGoal::None;
 8614                }
 8615                if is_first {
 8616                    is_first = false;
 8617                } else {
 8618                    text += "\n";
 8619                }
 8620                let mut len = 0;
 8621                for chunk in buffer.text_for_range(selection.start..selection.end) {
 8622                    text.push_str(chunk);
 8623                    len += chunk.len();
 8624                }
 8625                clipboard_selections.push(ClipboardSelection {
 8626                    len,
 8627                    is_entire_line,
 8628                    start_column: selection.start.column,
 8629                });
 8630            }
 8631        }
 8632
 8633        self.transact(window, cx, |this, window, cx| {
 8634            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8635                s.select(selections);
 8636            });
 8637            this.insert("", window, cx);
 8638        });
 8639        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 8640    }
 8641
 8642    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8643        let item = self.cut_common(window, cx);
 8644        cx.write_to_clipboard(item);
 8645    }
 8646
 8647    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8648        self.change_selections(None, window, cx, |s| {
 8649            s.move_with(|snapshot, sel| {
 8650                if sel.is_empty() {
 8651                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8652                }
 8653            });
 8654        });
 8655        let item = self.cut_common(window, cx);
 8656        cx.set_global(KillRing(item))
 8657    }
 8658
 8659    pub fn kill_ring_yank(
 8660        &mut self,
 8661        _: &KillRingYank,
 8662        window: &mut Window,
 8663        cx: &mut Context<Self>,
 8664    ) {
 8665        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8666            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8667                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8668            } else {
 8669                return;
 8670            }
 8671        } else {
 8672            return;
 8673        };
 8674        self.do_paste(&text, metadata, false, window, cx);
 8675    }
 8676
 8677    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8678        let selections = self.selections.all::<Point>(cx);
 8679        let buffer = self.buffer.read(cx).read(cx);
 8680        let mut text = String::new();
 8681
 8682        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8683        {
 8684            let max_point = buffer.max_point();
 8685            let mut is_first = true;
 8686            for selection in selections.iter() {
 8687                let mut start = selection.start;
 8688                let mut end = selection.end;
 8689                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8690                if is_entire_line {
 8691                    start = Point::new(start.row, 0);
 8692                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8693                }
 8694                if is_first {
 8695                    is_first = false;
 8696                } else {
 8697                    text += "\n";
 8698                }
 8699                let mut len = 0;
 8700                for chunk in buffer.text_for_range(start..end) {
 8701                    text.push_str(chunk);
 8702                    len += chunk.len();
 8703                }
 8704                clipboard_selections.push(ClipboardSelection {
 8705                    len,
 8706                    is_entire_line,
 8707                    start_column: start.column,
 8708                });
 8709            }
 8710        }
 8711
 8712        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8713            text,
 8714            clipboard_selections,
 8715        ));
 8716    }
 8717
 8718    pub fn do_paste(
 8719        &mut self,
 8720        text: &String,
 8721        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8722        handle_entire_lines: bool,
 8723        window: &mut Window,
 8724        cx: &mut Context<Self>,
 8725    ) {
 8726        if self.read_only(cx) {
 8727            return;
 8728        }
 8729
 8730        let clipboard_text = Cow::Borrowed(text);
 8731
 8732        self.transact(window, cx, |this, window, cx| {
 8733            if let Some(mut clipboard_selections) = clipboard_selections {
 8734                let old_selections = this.selections.all::<usize>(cx);
 8735                let all_selections_were_entire_line =
 8736                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8737                let first_selection_start_column =
 8738                    clipboard_selections.first().map(|s| s.start_column);
 8739                if clipboard_selections.len() != old_selections.len() {
 8740                    clipboard_selections.drain(..);
 8741                }
 8742                let cursor_offset = this.selections.last::<usize>(cx).head();
 8743                let mut auto_indent_on_paste = true;
 8744
 8745                this.buffer.update(cx, |buffer, cx| {
 8746                    let snapshot = buffer.read(cx);
 8747                    auto_indent_on_paste =
 8748                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 8749
 8750                    let mut start_offset = 0;
 8751                    let mut edits = Vec::new();
 8752                    let mut original_start_columns = Vec::new();
 8753                    for (ix, selection) in old_selections.iter().enumerate() {
 8754                        let to_insert;
 8755                        let entire_line;
 8756                        let original_start_column;
 8757                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8758                            let end_offset = start_offset + clipboard_selection.len;
 8759                            to_insert = &clipboard_text[start_offset..end_offset];
 8760                            entire_line = clipboard_selection.is_entire_line;
 8761                            start_offset = end_offset + 1;
 8762                            original_start_column = Some(clipboard_selection.start_column);
 8763                        } else {
 8764                            to_insert = clipboard_text.as_str();
 8765                            entire_line = all_selections_were_entire_line;
 8766                            original_start_column = first_selection_start_column
 8767                        }
 8768
 8769                        // If the corresponding selection was empty when this slice of the
 8770                        // clipboard text was written, then the entire line containing the
 8771                        // selection was copied. If this selection is also currently empty,
 8772                        // then paste the line before the current line of the buffer.
 8773                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8774                            let column = selection.start.to_point(&snapshot).column as usize;
 8775                            let line_start = selection.start - column;
 8776                            line_start..line_start
 8777                        } else {
 8778                            selection.range()
 8779                        };
 8780
 8781                        edits.push((range, to_insert));
 8782                        original_start_columns.extend(original_start_column);
 8783                    }
 8784                    drop(snapshot);
 8785
 8786                    buffer.edit(
 8787                        edits,
 8788                        if auto_indent_on_paste {
 8789                            Some(AutoindentMode::Block {
 8790                                original_start_columns,
 8791                            })
 8792                        } else {
 8793                            None
 8794                        },
 8795                        cx,
 8796                    );
 8797                });
 8798
 8799                let selections = this.selections.all::<usize>(cx);
 8800                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8801                    s.select(selections)
 8802                });
 8803            } else {
 8804                this.insert(&clipboard_text, window, cx);
 8805            }
 8806        });
 8807    }
 8808
 8809    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8810        if let Some(item) = cx.read_from_clipboard() {
 8811            let entries = item.entries();
 8812
 8813            match entries.first() {
 8814                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8815                // of all the pasted entries.
 8816                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8817                    .do_paste(
 8818                        clipboard_string.text(),
 8819                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8820                        true,
 8821                        window,
 8822                        cx,
 8823                    ),
 8824                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8825            }
 8826        }
 8827    }
 8828
 8829    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8830        if self.read_only(cx) {
 8831            return;
 8832        }
 8833
 8834        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8835            if let Some((selections, _)) =
 8836                self.selection_history.transaction(transaction_id).cloned()
 8837            {
 8838                self.change_selections(None, window, cx, |s| {
 8839                    s.select_anchors(selections.to_vec());
 8840                });
 8841            } else {
 8842                log::error!(
 8843                    "No entry in selection_history found for undo. \
 8844                     This may correspond to a bug where undo does not update the selection. \
 8845                     If this is occurring, please add details to \
 8846                     https://github.com/zed-industries/zed/issues/22692"
 8847                );
 8848            }
 8849            self.request_autoscroll(Autoscroll::fit(), cx);
 8850            self.unmark_text(window, cx);
 8851            self.refresh_inline_completion(true, false, window, cx);
 8852            cx.emit(EditorEvent::Edited { transaction_id });
 8853            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8854        }
 8855    }
 8856
 8857    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8858        if self.read_only(cx) {
 8859            return;
 8860        }
 8861
 8862        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8863            if let Some((_, Some(selections))) =
 8864                self.selection_history.transaction(transaction_id).cloned()
 8865            {
 8866                self.change_selections(None, window, cx, |s| {
 8867                    s.select_anchors(selections.to_vec());
 8868                });
 8869            } else {
 8870                log::error!(
 8871                    "No entry in selection_history found for redo. \
 8872                     This may correspond to a bug where undo does not update the selection. \
 8873                     If this is occurring, please add details to \
 8874                     https://github.com/zed-industries/zed/issues/22692"
 8875                );
 8876            }
 8877            self.request_autoscroll(Autoscroll::fit(), cx);
 8878            self.unmark_text(window, cx);
 8879            self.refresh_inline_completion(true, false, window, cx);
 8880            cx.emit(EditorEvent::Edited { transaction_id });
 8881        }
 8882    }
 8883
 8884    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8885        self.buffer
 8886            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8887    }
 8888
 8889    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8890        self.buffer
 8891            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8892    }
 8893
 8894    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8895        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8896            let line_mode = s.line_mode;
 8897            s.move_with(|map, selection| {
 8898                let cursor = if selection.is_empty() && !line_mode {
 8899                    movement::left(map, selection.start)
 8900                } else {
 8901                    selection.start
 8902                };
 8903                selection.collapse_to(cursor, SelectionGoal::None);
 8904            });
 8905        })
 8906    }
 8907
 8908    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8909        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8910            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8911        })
 8912    }
 8913
 8914    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8915        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8916            let line_mode = s.line_mode;
 8917            s.move_with(|map, selection| {
 8918                let cursor = if selection.is_empty() && !line_mode {
 8919                    movement::right(map, selection.end)
 8920                } else {
 8921                    selection.end
 8922                };
 8923                selection.collapse_to(cursor, SelectionGoal::None)
 8924            });
 8925        })
 8926    }
 8927
 8928    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8929        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8930            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8931        })
 8932    }
 8933
 8934    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8935        if self.take_rename(true, window, cx).is_some() {
 8936            return;
 8937        }
 8938
 8939        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8940            cx.propagate();
 8941            return;
 8942        }
 8943
 8944        let text_layout_details = &self.text_layout_details(window);
 8945        let selection_count = self.selections.count();
 8946        let first_selection = self.selections.first_anchor();
 8947
 8948        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8949            let line_mode = s.line_mode;
 8950            s.move_with(|map, selection| {
 8951                if !selection.is_empty() && !line_mode {
 8952                    selection.goal = SelectionGoal::None;
 8953                }
 8954                let (cursor, goal) = movement::up(
 8955                    map,
 8956                    selection.start,
 8957                    selection.goal,
 8958                    false,
 8959                    text_layout_details,
 8960                );
 8961                selection.collapse_to(cursor, goal);
 8962            });
 8963        });
 8964
 8965        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8966        {
 8967            cx.propagate();
 8968        }
 8969    }
 8970
 8971    pub fn move_up_by_lines(
 8972        &mut self,
 8973        action: &MoveUpByLines,
 8974        window: &mut Window,
 8975        cx: &mut Context<Self>,
 8976    ) {
 8977        if self.take_rename(true, window, cx).is_some() {
 8978            return;
 8979        }
 8980
 8981        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8982            cx.propagate();
 8983            return;
 8984        }
 8985
 8986        let text_layout_details = &self.text_layout_details(window);
 8987
 8988        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8989            let line_mode = s.line_mode;
 8990            s.move_with(|map, selection| {
 8991                if !selection.is_empty() && !line_mode {
 8992                    selection.goal = SelectionGoal::None;
 8993                }
 8994                let (cursor, goal) = movement::up_by_rows(
 8995                    map,
 8996                    selection.start,
 8997                    action.lines,
 8998                    selection.goal,
 8999                    false,
 9000                    text_layout_details,
 9001                );
 9002                selection.collapse_to(cursor, goal);
 9003            });
 9004        })
 9005    }
 9006
 9007    pub fn move_down_by_lines(
 9008        &mut self,
 9009        action: &MoveDownByLines,
 9010        window: &mut Window,
 9011        cx: &mut Context<Self>,
 9012    ) {
 9013        if self.take_rename(true, window, cx).is_some() {
 9014            return;
 9015        }
 9016
 9017        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9018            cx.propagate();
 9019            return;
 9020        }
 9021
 9022        let text_layout_details = &self.text_layout_details(window);
 9023
 9024        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9025            let line_mode = s.line_mode;
 9026            s.move_with(|map, selection| {
 9027                if !selection.is_empty() && !line_mode {
 9028                    selection.goal = SelectionGoal::None;
 9029                }
 9030                let (cursor, goal) = movement::down_by_rows(
 9031                    map,
 9032                    selection.start,
 9033                    action.lines,
 9034                    selection.goal,
 9035                    false,
 9036                    text_layout_details,
 9037                );
 9038                selection.collapse_to(cursor, goal);
 9039            });
 9040        })
 9041    }
 9042
 9043    pub fn select_down_by_lines(
 9044        &mut self,
 9045        action: &SelectDownByLines,
 9046        window: &mut Window,
 9047        cx: &mut Context<Self>,
 9048    ) {
 9049        let text_layout_details = &self.text_layout_details(window);
 9050        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9051            s.move_heads_with(|map, head, goal| {
 9052                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9053            })
 9054        })
 9055    }
 9056
 9057    pub fn select_up_by_lines(
 9058        &mut self,
 9059        action: &SelectUpByLines,
 9060        window: &mut Window,
 9061        cx: &mut Context<Self>,
 9062    ) {
 9063        let text_layout_details = &self.text_layout_details(window);
 9064        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9065            s.move_heads_with(|map, head, goal| {
 9066                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9067            })
 9068        })
 9069    }
 9070
 9071    pub fn select_page_up(
 9072        &mut self,
 9073        _: &SelectPageUp,
 9074        window: &mut Window,
 9075        cx: &mut Context<Self>,
 9076    ) {
 9077        let Some(row_count) = self.visible_row_count() else {
 9078            return;
 9079        };
 9080
 9081        let text_layout_details = &self.text_layout_details(window);
 9082
 9083        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9084            s.move_heads_with(|map, head, goal| {
 9085                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 9086            })
 9087        })
 9088    }
 9089
 9090    pub fn move_page_up(
 9091        &mut self,
 9092        action: &MovePageUp,
 9093        window: &mut Window,
 9094        cx: &mut Context<Self>,
 9095    ) {
 9096        if self.take_rename(true, window, cx).is_some() {
 9097            return;
 9098        }
 9099
 9100        if self
 9101            .context_menu
 9102            .borrow_mut()
 9103            .as_mut()
 9104            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 9105            .unwrap_or(false)
 9106        {
 9107            return;
 9108        }
 9109
 9110        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9111            cx.propagate();
 9112            return;
 9113        }
 9114
 9115        let Some(row_count) = self.visible_row_count() else {
 9116            return;
 9117        };
 9118
 9119        let autoscroll = if action.center_cursor {
 9120            Autoscroll::center()
 9121        } else {
 9122            Autoscroll::fit()
 9123        };
 9124
 9125        let text_layout_details = &self.text_layout_details(window);
 9126
 9127        self.change_selections(Some(autoscroll), window, cx, |s| {
 9128            let line_mode = s.line_mode;
 9129            s.move_with(|map, selection| {
 9130                if !selection.is_empty() && !line_mode {
 9131                    selection.goal = SelectionGoal::None;
 9132                }
 9133                let (cursor, goal) = movement::up_by_rows(
 9134                    map,
 9135                    selection.end,
 9136                    row_count,
 9137                    selection.goal,
 9138                    false,
 9139                    text_layout_details,
 9140                );
 9141                selection.collapse_to(cursor, goal);
 9142            });
 9143        });
 9144    }
 9145
 9146    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 9147        let text_layout_details = &self.text_layout_details(window);
 9148        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9149            s.move_heads_with(|map, head, goal| {
 9150                movement::up(map, head, goal, false, text_layout_details)
 9151            })
 9152        })
 9153    }
 9154
 9155    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 9156        self.take_rename(true, window, cx);
 9157
 9158        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9159            cx.propagate();
 9160            return;
 9161        }
 9162
 9163        let text_layout_details = &self.text_layout_details(window);
 9164        let selection_count = self.selections.count();
 9165        let first_selection = self.selections.first_anchor();
 9166
 9167        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9168            let line_mode = s.line_mode;
 9169            s.move_with(|map, selection| {
 9170                if !selection.is_empty() && !line_mode {
 9171                    selection.goal = SelectionGoal::None;
 9172                }
 9173                let (cursor, goal) = movement::down(
 9174                    map,
 9175                    selection.end,
 9176                    selection.goal,
 9177                    false,
 9178                    text_layout_details,
 9179                );
 9180                selection.collapse_to(cursor, goal);
 9181            });
 9182        });
 9183
 9184        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9185        {
 9186            cx.propagate();
 9187        }
 9188    }
 9189
 9190    pub fn select_page_down(
 9191        &mut self,
 9192        _: &SelectPageDown,
 9193        window: &mut Window,
 9194        cx: &mut Context<Self>,
 9195    ) {
 9196        let Some(row_count) = self.visible_row_count() else {
 9197            return;
 9198        };
 9199
 9200        let text_layout_details = &self.text_layout_details(window);
 9201
 9202        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9203            s.move_heads_with(|map, head, goal| {
 9204                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 9205            })
 9206        })
 9207    }
 9208
 9209    pub fn move_page_down(
 9210        &mut self,
 9211        action: &MovePageDown,
 9212        window: &mut Window,
 9213        cx: &mut Context<Self>,
 9214    ) {
 9215        if self.take_rename(true, window, cx).is_some() {
 9216            return;
 9217        }
 9218
 9219        if self
 9220            .context_menu
 9221            .borrow_mut()
 9222            .as_mut()
 9223            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 9224            .unwrap_or(false)
 9225        {
 9226            return;
 9227        }
 9228
 9229        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9230            cx.propagate();
 9231            return;
 9232        }
 9233
 9234        let Some(row_count) = self.visible_row_count() else {
 9235            return;
 9236        };
 9237
 9238        let autoscroll = if action.center_cursor {
 9239            Autoscroll::center()
 9240        } else {
 9241            Autoscroll::fit()
 9242        };
 9243
 9244        let text_layout_details = &self.text_layout_details(window);
 9245        self.change_selections(Some(autoscroll), window, cx, |s| {
 9246            let line_mode = s.line_mode;
 9247            s.move_with(|map, selection| {
 9248                if !selection.is_empty() && !line_mode {
 9249                    selection.goal = SelectionGoal::None;
 9250                }
 9251                let (cursor, goal) = movement::down_by_rows(
 9252                    map,
 9253                    selection.end,
 9254                    row_count,
 9255                    selection.goal,
 9256                    false,
 9257                    text_layout_details,
 9258                );
 9259                selection.collapse_to(cursor, goal);
 9260            });
 9261        });
 9262    }
 9263
 9264    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 9265        let text_layout_details = &self.text_layout_details(window);
 9266        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9267            s.move_heads_with(|map, head, goal| {
 9268                movement::down(map, head, goal, false, text_layout_details)
 9269            })
 9270        });
 9271    }
 9272
 9273    pub fn context_menu_first(
 9274        &mut self,
 9275        _: &ContextMenuFirst,
 9276        _window: &mut Window,
 9277        cx: &mut Context<Self>,
 9278    ) {
 9279        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9280            context_menu.select_first(self.completion_provider.as_deref(), cx);
 9281        }
 9282    }
 9283
 9284    pub fn context_menu_prev(
 9285        &mut self,
 9286        _: &ContextMenuPrevious,
 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_prev(self.completion_provider.as_deref(), cx);
 9292        }
 9293    }
 9294
 9295    pub fn context_menu_next(
 9296        &mut self,
 9297        _: &ContextMenuNext,
 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_next(self.completion_provider.as_deref(), cx);
 9303        }
 9304    }
 9305
 9306    pub fn context_menu_last(
 9307        &mut self,
 9308        _: &ContextMenuLast,
 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_last(self.completion_provider.as_deref(), cx);
 9314        }
 9315    }
 9316
 9317    pub fn move_to_previous_word_start(
 9318        &mut self,
 9319        _: &MoveToPreviousWordStart,
 9320        window: &mut Window,
 9321        cx: &mut Context<Self>,
 9322    ) {
 9323        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9324            s.move_cursors_with(|map, head, _| {
 9325                (
 9326                    movement::previous_word_start(map, head),
 9327                    SelectionGoal::None,
 9328                )
 9329            });
 9330        })
 9331    }
 9332
 9333    pub fn move_to_previous_subword_start(
 9334        &mut self,
 9335        _: &MoveToPreviousSubwordStart,
 9336        window: &mut Window,
 9337        cx: &mut Context<Self>,
 9338    ) {
 9339        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9340            s.move_cursors_with(|map, head, _| {
 9341                (
 9342                    movement::previous_subword_start(map, head),
 9343                    SelectionGoal::None,
 9344                )
 9345            });
 9346        })
 9347    }
 9348
 9349    pub fn select_to_previous_word_start(
 9350        &mut self,
 9351        _: &SelectToPreviousWordStart,
 9352        window: &mut Window,
 9353        cx: &mut Context<Self>,
 9354    ) {
 9355        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9356            s.move_heads_with(|map, head, _| {
 9357                (
 9358                    movement::previous_word_start(map, head),
 9359                    SelectionGoal::None,
 9360                )
 9361            });
 9362        })
 9363    }
 9364
 9365    pub fn select_to_previous_subword_start(
 9366        &mut self,
 9367        _: &SelectToPreviousSubwordStart,
 9368        window: &mut Window,
 9369        cx: &mut Context<Self>,
 9370    ) {
 9371        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9372            s.move_heads_with(|map, head, _| {
 9373                (
 9374                    movement::previous_subword_start(map, head),
 9375                    SelectionGoal::None,
 9376                )
 9377            });
 9378        })
 9379    }
 9380
 9381    pub fn delete_to_previous_word_start(
 9382        &mut self,
 9383        action: &DeleteToPreviousWordStart,
 9384        window: &mut Window,
 9385        cx: &mut Context<Self>,
 9386    ) {
 9387        self.transact(window, cx, |this, window, cx| {
 9388            this.select_autoclose_pair(window, cx);
 9389            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9390                let line_mode = s.line_mode;
 9391                s.move_with(|map, selection| {
 9392                    if selection.is_empty() && !line_mode {
 9393                        let cursor = if action.ignore_newlines {
 9394                            movement::previous_word_start(map, selection.head())
 9395                        } else {
 9396                            movement::previous_word_start_or_newline(map, selection.head())
 9397                        };
 9398                        selection.set_head(cursor, SelectionGoal::None);
 9399                    }
 9400                });
 9401            });
 9402            this.insert("", window, cx);
 9403        });
 9404    }
 9405
 9406    pub fn delete_to_previous_subword_start(
 9407        &mut self,
 9408        _: &DeleteToPreviousSubwordStart,
 9409        window: &mut Window,
 9410        cx: &mut Context<Self>,
 9411    ) {
 9412        self.transact(window, cx, |this, window, cx| {
 9413            this.select_autoclose_pair(window, cx);
 9414            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9415                let line_mode = s.line_mode;
 9416                s.move_with(|map, selection| {
 9417                    if selection.is_empty() && !line_mode {
 9418                        let cursor = movement::previous_subword_start(map, selection.head());
 9419                        selection.set_head(cursor, SelectionGoal::None);
 9420                    }
 9421                });
 9422            });
 9423            this.insert("", window, cx);
 9424        });
 9425    }
 9426
 9427    pub fn move_to_next_word_end(
 9428        &mut self,
 9429        _: &MoveToNextWordEnd,
 9430        window: &mut Window,
 9431        cx: &mut Context<Self>,
 9432    ) {
 9433        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9434            s.move_cursors_with(|map, head, _| {
 9435                (movement::next_word_end(map, head), SelectionGoal::None)
 9436            });
 9437        })
 9438    }
 9439
 9440    pub fn move_to_next_subword_end(
 9441        &mut self,
 9442        _: &MoveToNextSubwordEnd,
 9443        window: &mut Window,
 9444        cx: &mut Context<Self>,
 9445    ) {
 9446        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9447            s.move_cursors_with(|map, head, _| {
 9448                (movement::next_subword_end(map, head), SelectionGoal::None)
 9449            });
 9450        })
 9451    }
 9452
 9453    pub fn select_to_next_word_end(
 9454        &mut self,
 9455        _: &SelectToNextWordEnd,
 9456        window: &mut Window,
 9457        cx: &mut Context<Self>,
 9458    ) {
 9459        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9460            s.move_heads_with(|map, head, _| {
 9461                (movement::next_word_end(map, head), SelectionGoal::None)
 9462            });
 9463        })
 9464    }
 9465
 9466    pub fn select_to_next_subword_end(
 9467        &mut self,
 9468        _: &SelectToNextSubwordEnd,
 9469        window: &mut Window,
 9470        cx: &mut Context<Self>,
 9471    ) {
 9472        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9473            s.move_heads_with(|map, head, _| {
 9474                (movement::next_subword_end(map, head), SelectionGoal::None)
 9475            });
 9476        })
 9477    }
 9478
 9479    pub fn delete_to_next_word_end(
 9480        &mut self,
 9481        action: &DeleteToNextWordEnd,
 9482        window: &mut Window,
 9483        cx: &mut Context<Self>,
 9484    ) {
 9485        self.transact(window, cx, |this, window, cx| {
 9486            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9487                let line_mode = s.line_mode;
 9488                s.move_with(|map, selection| {
 9489                    if selection.is_empty() && !line_mode {
 9490                        let cursor = if action.ignore_newlines {
 9491                            movement::next_word_end(map, selection.head())
 9492                        } else {
 9493                            movement::next_word_end_or_newline(map, selection.head())
 9494                        };
 9495                        selection.set_head(cursor, SelectionGoal::None);
 9496                    }
 9497                });
 9498            });
 9499            this.insert("", window, cx);
 9500        });
 9501    }
 9502
 9503    pub fn delete_to_next_subword_end(
 9504        &mut self,
 9505        _: &DeleteToNextSubwordEnd,
 9506        window: &mut Window,
 9507        cx: &mut Context<Self>,
 9508    ) {
 9509        self.transact(window, cx, |this, window, cx| {
 9510            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9511                s.move_with(|map, selection| {
 9512                    if selection.is_empty() {
 9513                        let cursor = movement::next_subword_end(map, selection.head());
 9514                        selection.set_head(cursor, SelectionGoal::None);
 9515                    }
 9516                });
 9517            });
 9518            this.insert("", window, cx);
 9519        });
 9520    }
 9521
 9522    pub fn move_to_beginning_of_line(
 9523        &mut self,
 9524        action: &MoveToBeginningOfLine,
 9525        window: &mut Window,
 9526        cx: &mut Context<Self>,
 9527    ) {
 9528        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9529            s.move_cursors_with(|map, head, _| {
 9530                (
 9531                    movement::indented_line_beginning(
 9532                        map,
 9533                        head,
 9534                        action.stop_at_soft_wraps,
 9535                        action.stop_at_indent,
 9536                    ),
 9537                    SelectionGoal::None,
 9538                )
 9539            });
 9540        })
 9541    }
 9542
 9543    pub fn select_to_beginning_of_line(
 9544        &mut self,
 9545        action: &SelectToBeginningOfLine,
 9546        window: &mut Window,
 9547        cx: &mut Context<Self>,
 9548    ) {
 9549        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9550            s.move_heads_with(|map, head, _| {
 9551                (
 9552                    movement::indented_line_beginning(
 9553                        map,
 9554                        head,
 9555                        action.stop_at_soft_wraps,
 9556                        action.stop_at_indent,
 9557                    ),
 9558                    SelectionGoal::None,
 9559                )
 9560            });
 9561        });
 9562    }
 9563
 9564    pub fn delete_to_beginning_of_line(
 9565        &mut self,
 9566        action: &DeleteToBeginningOfLine,
 9567        window: &mut Window,
 9568        cx: &mut Context<Self>,
 9569    ) {
 9570        self.transact(window, cx, |this, window, cx| {
 9571            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9572                s.move_with(|_, selection| {
 9573                    selection.reversed = true;
 9574                });
 9575            });
 9576
 9577            this.select_to_beginning_of_line(
 9578                &SelectToBeginningOfLine {
 9579                    stop_at_soft_wraps: false,
 9580                    stop_at_indent: action.stop_at_indent,
 9581                },
 9582                window,
 9583                cx,
 9584            );
 9585            this.backspace(&Backspace, window, cx);
 9586        });
 9587    }
 9588
 9589    pub fn move_to_end_of_line(
 9590        &mut self,
 9591        action: &MoveToEndOfLine,
 9592        window: &mut Window,
 9593        cx: &mut Context<Self>,
 9594    ) {
 9595        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9596            s.move_cursors_with(|map, head, _| {
 9597                (
 9598                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9599                    SelectionGoal::None,
 9600                )
 9601            });
 9602        })
 9603    }
 9604
 9605    pub fn select_to_end_of_line(
 9606        &mut self,
 9607        action: &SelectToEndOfLine,
 9608        window: &mut Window,
 9609        cx: &mut Context<Self>,
 9610    ) {
 9611        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9612            s.move_heads_with(|map, head, _| {
 9613                (
 9614                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9615                    SelectionGoal::None,
 9616                )
 9617            });
 9618        })
 9619    }
 9620
 9621    pub fn delete_to_end_of_line(
 9622        &mut self,
 9623        _: &DeleteToEndOfLine,
 9624        window: &mut Window,
 9625        cx: &mut Context<Self>,
 9626    ) {
 9627        self.transact(window, cx, |this, window, cx| {
 9628            this.select_to_end_of_line(
 9629                &SelectToEndOfLine {
 9630                    stop_at_soft_wraps: false,
 9631                },
 9632                window,
 9633                cx,
 9634            );
 9635            this.delete(&Delete, window, cx);
 9636        });
 9637    }
 9638
 9639    pub fn cut_to_end_of_line(
 9640        &mut self,
 9641        _: &CutToEndOfLine,
 9642        window: &mut Window,
 9643        cx: &mut Context<Self>,
 9644    ) {
 9645        self.transact(window, cx, |this, window, cx| {
 9646            this.select_to_end_of_line(
 9647                &SelectToEndOfLine {
 9648                    stop_at_soft_wraps: false,
 9649                },
 9650                window,
 9651                cx,
 9652            );
 9653            this.cut(&Cut, window, cx);
 9654        });
 9655    }
 9656
 9657    pub fn move_to_start_of_paragraph(
 9658        &mut self,
 9659        _: &MoveToStartOfParagraph,
 9660        window: &mut Window,
 9661        cx: &mut Context<Self>,
 9662    ) {
 9663        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9664            cx.propagate();
 9665            return;
 9666        }
 9667
 9668        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9669            s.move_with(|map, selection| {
 9670                selection.collapse_to(
 9671                    movement::start_of_paragraph(map, selection.head(), 1),
 9672                    SelectionGoal::None,
 9673                )
 9674            });
 9675        })
 9676    }
 9677
 9678    pub fn move_to_end_of_paragraph(
 9679        &mut self,
 9680        _: &MoveToEndOfParagraph,
 9681        window: &mut Window,
 9682        cx: &mut Context<Self>,
 9683    ) {
 9684        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9685            cx.propagate();
 9686            return;
 9687        }
 9688
 9689        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9690            s.move_with(|map, selection| {
 9691                selection.collapse_to(
 9692                    movement::end_of_paragraph(map, selection.head(), 1),
 9693                    SelectionGoal::None,
 9694                )
 9695            });
 9696        })
 9697    }
 9698
 9699    pub fn select_to_start_of_paragraph(
 9700        &mut self,
 9701        _: &SelectToStartOfParagraph,
 9702        window: &mut Window,
 9703        cx: &mut Context<Self>,
 9704    ) {
 9705        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9706            cx.propagate();
 9707            return;
 9708        }
 9709
 9710        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9711            s.move_heads_with(|map, head, _| {
 9712                (
 9713                    movement::start_of_paragraph(map, head, 1),
 9714                    SelectionGoal::None,
 9715                )
 9716            });
 9717        })
 9718    }
 9719
 9720    pub fn select_to_end_of_paragraph(
 9721        &mut self,
 9722        _: &SelectToEndOfParagraph,
 9723        window: &mut Window,
 9724        cx: &mut Context<Self>,
 9725    ) {
 9726        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9727            cx.propagate();
 9728            return;
 9729        }
 9730
 9731        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9732            s.move_heads_with(|map, head, _| {
 9733                (
 9734                    movement::end_of_paragraph(map, head, 1),
 9735                    SelectionGoal::None,
 9736                )
 9737            });
 9738        })
 9739    }
 9740
 9741    pub fn move_to_start_of_excerpt(
 9742        &mut self,
 9743        _: &MoveToStartOfExcerpt,
 9744        window: &mut Window,
 9745        cx: &mut Context<Self>,
 9746    ) {
 9747        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9748            cx.propagate();
 9749            return;
 9750        }
 9751
 9752        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9753            s.move_with(|map, selection| {
 9754                selection.collapse_to(
 9755                    movement::start_of_excerpt(
 9756                        map,
 9757                        selection.head(),
 9758                        workspace::searchable::Direction::Prev,
 9759                    ),
 9760                    SelectionGoal::None,
 9761                )
 9762            });
 9763        })
 9764    }
 9765
 9766    pub fn move_to_end_of_excerpt(
 9767        &mut self,
 9768        _: &MoveToEndOfExcerpt,
 9769        window: &mut Window,
 9770        cx: &mut Context<Self>,
 9771    ) {
 9772        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9773            cx.propagate();
 9774            return;
 9775        }
 9776
 9777        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9778            s.move_with(|map, selection| {
 9779                selection.collapse_to(
 9780                    movement::end_of_excerpt(
 9781                        map,
 9782                        selection.head(),
 9783                        workspace::searchable::Direction::Next,
 9784                    ),
 9785                    SelectionGoal::None,
 9786                )
 9787            });
 9788        })
 9789    }
 9790
 9791    pub fn select_to_start_of_excerpt(
 9792        &mut self,
 9793        _: &SelectToStartOfExcerpt,
 9794        window: &mut Window,
 9795        cx: &mut Context<Self>,
 9796    ) {
 9797        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9798            cx.propagate();
 9799            return;
 9800        }
 9801
 9802        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9803            s.move_heads_with(|map, head, _| {
 9804                (
 9805                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
 9806                    SelectionGoal::None,
 9807                )
 9808            });
 9809        })
 9810    }
 9811
 9812    pub fn select_to_end_of_excerpt(
 9813        &mut self,
 9814        _: &SelectToEndOfExcerpt,
 9815        window: &mut Window,
 9816        cx: &mut Context<Self>,
 9817    ) {
 9818        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9819            cx.propagate();
 9820            return;
 9821        }
 9822
 9823        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9824            s.move_heads_with(|map, head, _| {
 9825                (
 9826                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
 9827                    SelectionGoal::None,
 9828                )
 9829            });
 9830        })
 9831    }
 9832
 9833    pub fn move_to_beginning(
 9834        &mut self,
 9835        _: &MoveToBeginning,
 9836        window: &mut Window,
 9837        cx: &mut Context<Self>,
 9838    ) {
 9839        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9840            cx.propagate();
 9841            return;
 9842        }
 9843
 9844        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9845            s.select_ranges(vec![0..0]);
 9846        });
 9847    }
 9848
 9849    pub fn select_to_beginning(
 9850        &mut self,
 9851        _: &SelectToBeginning,
 9852        window: &mut Window,
 9853        cx: &mut Context<Self>,
 9854    ) {
 9855        let mut selection = self.selections.last::<Point>(cx);
 9856        selection.set_head(Point::zero(), SelectionGoal::None);
 9857
 9858        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9859            s.select(vec![selection]);
 9860        });
 9861    }
 9862
 9863    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9864        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9865            cx.propagate();
 9866            return;
 9867        }
 9868
 9869        let cursor = self.buffer.read(cx).read(cx).len();
 9870        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9871            s.select_ranges(vec![cursor..cursor])
 9872        });
 9873    }
 9874
 9875    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9876        self.nav_history = nav_history;
 9877    }
 9878
 9879    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9880        self.nav_history.as_ref()
 9881    }
 9882
 9883    fn push_to_nav_history(
 9884        &mut self,
 9885        cursor_anchor: Anchor,
 9886        new_position: Option<Point>,
 9887        cx: &mut Context<Self>,
 9888    ) {
 9889        if let Some(nav_history) = self.nav_history.as_mut() {
 9890            let buffer = self.buffer.read(cx).read(cx);
 9891            let cursor_position = cursor_anchor.to_point(&buffer);
 9892            let scroll_state = self.scroll_manager.anchor();
 9893            let scroll_top_row = scroll_state.top_row(&buffer);
 9894            drop(buffer);
 9895
 9896            if let Some(new_position) = new_position {
 9897                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9898                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9899                    return;
 9900                }
 9901            }
 9902
 9903            nav_history.push(
 9904                Some(NavigationData {
 9905                    cursor_anchor,
 9906                    cursor_position,
 9907                    scroll_anchor: scroll_state,
 9908                    scroll_top_row,
 9909                }),
 9910                cx,
 9911            );
 9912        }
 9913    }
 9914
 9915    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9916        let buffer = self.buffer.read(cx).snapshot(cx);
 9917        let mut selection = self.selections.first::<usize>(cx);
 9918        selection.set_head(buffer.len(), SelectionGoal::None);
 9919        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9920            s.select(vec![selection]);
 9921        });
 9922    }
 9923
 9924    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9925        let end = self.buffer.read(cx).read(cx).len();
 9926        self.change_selections(None, window, cx, |s| {
 9927            s.select_ranges(vec![0..end]);
 9928        });
 9929    }
 9930
 9931    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9932        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9933        let mut selections = self.selections.all::<Point>(cx);
 9934        let max_point = display_map.buffer_snapshot.max_point();
 9935        for selection in &mut selections {
 9936            let rows = selection.spanned_rows(true, &display_map);
 9937            selection.start = Point::new(rows.start.0, 0);
 9938            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9939            selection.reversed = false;
 9940        }
 9941        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9942            s.select(selections);
 9943        });
 9944    }
 9945
 9946    pub fn split_selection_into_lines(
 9947        &mut self,
 9948        _: &SplitSelectionIntoLines,
 9949        window: &mut Window,
 9950        cx: &mut Context<Self>,
 9951    ) {
 9952        let selections = self
 9953            .selections
 9954            .all::<Point>(cx)
 9955            .into_iter()
 9956            .map(|selection| selection.start..selection.end)
 9957            .collect::<Vec<_>>();
 9958        self.unfold_ranges(&selections, true, true, cx);
 9959
 9960        let mut new_selection_ranges = Vec::new();
 9961        {
 9962            let buffer = self.buffer.read(cx).read(cx);
 9963            for selection in selections {
 9964                for row in selection.start.row..selection.end.row {
 9965                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9966                    new_selection_ranges.push(cursor..cursor);
 9967                }
 9968
 9969                let is_multiline_selection = selection.start.row != selection.end.row;
 9970                // Don't insert last one if it's a multi-line selection ending at the start of a line,
 9971                // so this action feels more ergonomic when paired with other selection operations
 9972                let should_skip_last = is_multiline_selection && selection.end.column == 0;
 9973                if !should_skip_last {
 9974                    new_selection_ranges.push(selection.end..selection.end);
 9975                }
 9976            }
 9977        }
 9978        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9979            s.select_ranges(new_selection_ranges);
 9980        });
 9981    }
 9982
 9983    pub fn add_selection_above(
 9984        &mut self,
 9985        _: &AddSelectionAbove,
 9986        window: &mut Window,
 9987        cx: &mut Context<Self>,
 9988    ) {
 9989        self.add_selection(true, window, cx);
 9990    }
 9991
 9992    pub fn add_selection_below(
 9993        &mut self,
 9994        _: &AddSelectionBelow,
 9995        window: &mut Window,
 9996        cx: &mut Context<Self>,
 9997    ) {
 9998        self.add_selection(false, window, cx);
 9999    }
10000
10001    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
10002        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10003        let mut selections = self.selections.all::<Point>(cx);
10004        let text_layout_details = self.text_layout_details(window);
10005        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10006            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10007            let range = oldest_selection.display_range(&display_map).sorted();
10008
10009            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10010            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10011            let positions = start_x.min(end_x)..start_x.max(end_x);
10012
10013            selections.clear();
10014            let mut stack = Vec::new();
10015            for row in range.start.row().0..=range.end.row().0 {
10016                if let Some(selection) = self.selections.build_columnar_selection(
10017                    &display_map,
10018                    DisplayRow(row),
10019                    &positions,
10020                    oldest_selection.reversed,
10021                    &text_layout_details,
10022                ) {
10023                    stack.push(selection.id);
10024                    selections.push(selection);
10025                }
10026            }
10027
10028            if above {
10029                stack.reverse();
10030            }
10031
10032            AddSelectionsState { above, stack }
10033        });
10034
10035        let last_added_selection = *state.stack.last().unwrap();
10036        let mut new_selections = Vec::new();
10037        if above == state.above {
10038            let end_row = if above {
10039                DisplayRow(0)
10040            } else {
10041                display_map.max_point().row()
10042            };
10043
10044            'outer: for selection in selections {
10045                if selection.id == last_added_selection {
10046                    let range = selection.display_range(&display_map).sorted();
10047                    debug_assert_eq!(range.start.row(), range.end.row());
10048                    let mut row = range.start.row();
10049                    let positions =
10050                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10051                            px(start)..px(end)
10052                        } else {
10053                            let start_x =
10054                                display_map.x_for_display_point(range.start, &text_layout_details);
10055                            let end_x =
10056                                display_map.x_for_display_point(range.end, &text_layout_details);
10057                            start_x.min(end_x)..start_x.max(end_x)
10058                        };
10059
10060                    while row != end_row {
10061                        if above {
10062                            row.0 -= 1;
10063                        } else {
10064                            row.0 += 1;
10065                        }
10066
10067                        if let Some(new_selection) = self.selections.build_columnar_selection(
10068                            &display_map,
10069                            row,
10070                            &positions,
10071                            selection.reversed,
10072                            &text_layout_details,
10073                        ) {
10074                            state.stack.push(new_selection.id);
10075                            if above {
10076                                new_selections.push(new_selection);
10077                                new_selections.push(selection);
10078                            } else {
10079                                new_selections.push(selection);
10080                                new_selections.push(new_selection);
10081                            }
10082
10083                            continue 'outer;
10084                        }
10085                    }
10086                }
10087
10088                new_selections.push(selection);
10089            }
10090        } else {
10091            new_selections = selections;
10092            new_selections.retain(|s| s.id != last_added_selection);
10093            state.stack.pop();
10094        }
10095
10096        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10097            s.select(new_selections);
10098        });
10099        if state.stack.len() > 1 {
10100            self.add_selections_state = Some(state);
10101        }
10102    }
10103
10104    pub fn select_next_match_internal(
10105        &mut self,
10106        display_map: &DisplaySnapshot,
10107        replace_newest: bool,
10108        autoscroll: Option<Autoscroll>,
10109        window: &mut Window,
10110        cx: &mut Context<Self>,
10111    ) -> Result<()> {
10112        fn select_next_match_ranges(
10113            this: &mut Editor,
10114            range: Range<usize>,
10115            replace_newest: bool,
10116            auto_scroll: Option<Autoscroll>,
10117            window: &mut Window,
10118            cx: &mut Context<Editor>,
10119        ) {
10120            this.unfold_ranges(&[range.clone()], false, true, cx);
10121            this.change_selections(auto_scroll, window, cx, |s| {
10122                if replace_newest {
10123                    s.delete(s.newest_anchor().id);
10124                }
10125                s.insert_range(range.clone());
10126            });
10127        }
10128
10129        let buffer = &display_map.buffer_snapshot;
10130        let mut selections = self.selections.all::<usize>(cx);
10131        if let Some(mut select_next_state) = self.select_next_state.take() {
10132            let query = &select_next_state.query;
10133            if !select_next_state.done {
10134                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10135                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10136                let mut next_selected_range = None;
10137
10138                let bytes_after_last_selection =
10139                    buffer.bytes_in_range(last_selection.end..buffer.len());
10140                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10141                let query_matches = query
10142                    .stream_find_iter(bytes_after_last_selection)
10143                    .map(|result| (last_selection.end, result))
10144                    .chain(
10145                        query
10146                            .stream_find_iter(bytes_before_first_selection)
10147                            .map(|result| (0, result)),
10148                    );
10149
10150                for (start_offset, query_match) in query_matches {
10151                    let query_match = query_match.unwrap(); // can only fail due to I/O
10152                    let offset_range =
10153                        start_offset + query_match.start()..start_offset + query_match.end();
10154                    let display_range = offset_range.start.to_display_point(display_map)
10155                        ..offset_range.end.to_display_point(display_map);
10156
10157                    if !select_next_state.wordwise
10158                        || (!movement::is_inside_word(display_map, display_range.start)
10159                            && !movement::is_inside_word(display_map, display_range.end))
10160                    {
10161                        // TODO: This is n^2, because we might check all the selections
10162                        if !selections
10163                            .iter()
10164                            .any(|selection| selection.range().overlaps(&offset_range))
10165                        {
10166                            next_selected_range = Some(offset_range);
10167                            break;
10168                        }
10169                    }
10170                }
10171
10172                if let Some(next_selected_range) = next_selected_range {
10173                    select_next_match_ranges(
10174                        self,
10175                        next_selected_range,
10176                        replace_newest,
10177                        autoscroll,
10178                        window,
10179                        cx,
10180                    );
10181                } else {
10182                    select_next_state.done = true;
10183                }
10184            }
10185
10186            self.select_next_state = Some(select_next_state);
10187        } else {
10188            let mut only_carets = true;
10189            let mut same_text_selected = true;
10190            let mut selected_text = None;
10191
10192            let mut selections_iter = selections.iter().peekable();
10193            while let Some(selection) = selections_iter.next() {
10194                if selection.start != selection.end {
10195                    only_carets = false;
10196                }
10197
10198                if same_text_selected {
10199                    if selected_text.is_none() {
10200                        selected_text =
10201                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10202                    }
10203
10204                    if let Some(next_selection) = selections_iter.peek() {
10205                        if next_selection.range().len() == selection.range().len() {
10206                            let next_selected_text = buffer
10207                                .text_for_range(next_selection.range())
10208                                .collect::<String>();
10209                            if Some(next_selected_text) != selected_text {
10210                                same_text_selected = false;
10211                                selected_text = None;
10212                            }
10213                        } else {
10214                            same_text_selected = false;
10215                            selected_text = None;
10216                        }
10217                    }
10218                }
10219            }
10220
10221            if only_carets {
10222                for selection in &mut selections {
10223                    let word_range = movement::surrounding_word(
10224                        display_map,
10225                        selection.start.to_display_point(display_map),
10226                    );
10227                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
10228                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
10229                    selection.goal = SelectionGoal::None;
10230                    selection.reversed = false;
10231                    select_next_match_ranges(
10232                        self,
10233                        selection.start..selection.end,
10234                        replace_newest,
10235                        autoscroll,
10236                        window,
10237                        cx,
10238                    );
10239                }
10240
10241                if selections.len() == 1 {
10242                    let selection = selections
10243                        .last()
10244                        .expect("ensured that there's only one selection");
10245                    let query = buffer
10246                        .text_for_range(selection.start..selection.end)
10247                        .collect::<String>();
10248                    let is_empty = query.is_empty();
10249                    let select_state = SelectNextState {
10250                        query: AhoCorasick::new(&[query])?,
10251                        wordwise: true,
10252                        done: is_empty,
10253                    };
10254                    self.select_next_state = Some(select_state);
10255                } else {
10256                    self.select_next_state = None;
10257                }
10258            } else if let Some(selected_text) = selected_text {
10259                self.select_next_state = Some(SelectNextState {
10260                    query: AhoCorasick::new(&[selected_text])?,
10261                    wordwise: false,
10262                    done: false,
10263                });
10264                self.select_next_match_internal(
10265                    display_map,
10266                    replace_newest,
10267                    autoscroll,
10268                    window,
10269                    cx,
10270                )?;
10271            }
10272        }
10273        Ok(())
10274    }
10275
10276    pub fn select_all_matches(
10277        &mut self,
10278        _action: &SelectAllMatches,
10279        window: &mut Window,
10280        cx: &mut Context<Self>,
10281    ) -> Result<()> {
10282        self.push_to_selection_history();
10283        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10284
10285        self.select_next_match_internal(&display_map, false, None, window, cx)?;
10286        let Some(select_next_state) = self.select_next_state.as_mut() else {
10287            return Ok(());
10288        };
10289        if select_next_state.done {
10290            return Ok(());
10291        }
10292
10293        let mut new_selections = self.selections.all::<usize>(cx);
10294
10295        let buffer = &display_map.buffer_snapshot;
10296        let query_matches = select_next_state
10297            .query
10298            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10299
10300        for query_match in query_matches {
10301            let query_match = query_match.unwrap(); // can only fail due to I/O
10302            let offset_range = query_match.start()..query_match.end();
10303            let display_range = offset_range.start.to_display_point(&display_map)
10304                ..offset_range.end.to_display_point(&display_map);
10305
10306            if !select_next_state.wordwise
10307                || (!movement::is_inside_word(&display_map, display_range.start)
10308                    && !movement::is_inside_word(&display_map, display_range.end))
10309            {
10310                self.selections.change_with(cx, |selections| {
10311                    new_selections.push(Selection {
10312                        id: selections.new_selection_id(),
10313                        start: offset_range.start,
10314                        end: offset_range.end,
10315                        reversed: false,
10316                        goal: SelectionGoal::None,
10317                    });
10318                });
10319            }
10320        }
10321
10322        new_selections.sort_by_key(|selection| selection.start);
10323        let mut ix = 0;
10324        while ix + 1 < new_selections.len() {
10325            let current_selection = &new_selections[ix];
10326            let next_selection = &new_selections[ix + 1];
10327            if current_selection.range().overlaps(&next_selection.range()) {
10328                if current_selection.id < next_selection.id {
10329                    new_selections.remove(ix + 1);
10330                } else {
10331                    new_selections.remove(ix);
10332                }
10333            } else {
10334                ix += 1;
10335            }
10336        }
10337
10338        let reversed = self.selections.oldest::<usize>(cx).reversed;
10339
10340        for selection in new_selections.iter_mut() {
10341            selection.reversed = reversed;
10342        }
10343
10344        select_next_state.done = true;
10345        self.unfold_ranges(
10346            &new_selections
10347                .iter()
10348                .map(|selection| selection.range())
10349                .collect::<Vec<_>>(),
10350            false,
10351            false,
10352            cx,
10353        );
10354        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10355            selections.select(new_selections)
10356        });
10357
10358        Ok(())
10359    }
10360
10361    pub fn select_next(
10362        &mut self,
10363        action: &SelectNext,
10364        window: &mut Window,
10365        cx: &mut Context<Self>,
10366    ) -> Result<()> {
10367        self.push_to_selection_history();
10368        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10369        self.select_next_match_internal(
10370            &display_map,
10371            action.replace_newest,
10372            Some(Autoscroll::newest()),
10373            window,
10374            cx,
10375        )?;
10376        Ok(())
10377    }
10378
10379    pub fn select_previous(
10380        &mut self,
10381        action: &SelectPrevious,
10382        window: &mut Window,
10383        cx: &mut Context<Self>,
10384    ) -> Result<()> {
10385        self.push_to_selection_history();
10386        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10387        let buffer = &display_map.buffer_snapshot;
10388        let mut selections = self.selections.all::<usize>(cx);
10389        if let Some(mut select_prev_state) = self.select_prev_state.take() {
10390            let query = &select_prev_state.query;
10391            if !select_prev_state.done {
10392                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10393                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10394                let mut next_selected_range = None;
10395                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10396                let bytes_before_last_selection =
10397                    buffer.reversed_bytes_in_range(0..last_selection.start);
10398                let bytes_after_first_selection =
10399                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10400                let query_matches = query
10401                    .stream_find_iter(bytes_before_last_selection)
10402                    .map(|result| (last_selection.start, result))
10403                    .chain(
10404                        query
10405                            .stream_find_iter(bytes_after_first_selection)
10406                            .map(|result| (buffer.len(), result)),
10407                    );
10408                for (end_offset, query_match) in query_matches {
10409                    let query_match = query_match.unwrap(); // can only fail due to I/O
10410                    let offset_range =
10411                        end_offset - query_match.end()..end_offset - query_match.start();
10412                    let display_range = offset_range.start.to_display_point(&display_map)
10413                        ..offset_range.end.to_display_point(&display_map);
10414
10415                    if !select_prev_state.wordwise
10416                        || (!movement::is_inside_word(&display_map, display_range.start)
10417                            && !movement::is_inside_word(&display_map, display_range.end))
10418                    {
10419                        next_selected_range = Some(offset_range);
10420                        break;
10421                    }
10422                }
10423
10424                if let Some(next_selected_range) = next_selected_range {
10425                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10426                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10427                        if action.replace_newest {
10428                            s.delete(s.newest_anchor().id);
10429                        }
10430                        s.insert_range(next_selected_range);
10431                    });
10432                } else {
10433                    select_prev_state.done = true;
10434                }
10435            }
10436
10437            self.select_prev_state = Some(select_prev_state);
10438        } else {
10439            let mut only_carets = true;
10440            let mut same_text_selected = true;
10441            let mut selected_text = None;
10442
10443            let mut selections_iter = selections.iter().peekable();
10444            while let Some(selection) = selections_iter.next() {
10445                if selection.start != selection.end {
10446                    only_carets = false;
10447                }
10448
10449                if same_text_selected {
10450                    if selected_text.is_none() {
10451                        selected_text =
10452                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10453                    }
10454
10455                    if let Some(next_selection) = selections_iter.peek() {
10456                        if next_selection.range().len() == selection.range().len() {
10457                            let next_selected_text = buffer
10458                                .text_for_range(next_selection.range())
10459                                .collect::<String>();
10460                            if Some(next_selected_text) != selected_text {
10461                                same_text_selected = false;
10462                                selected_text = None;
10463                            }
10464                        } else {
10465                            same_text_selected = false;
10466                            selected_text = None;
10467                        }
10468                    }
10469                }
10470            }
10471
10472            if only_carets {
10473                for selection in &mut selections {
10474                    let word_range = movement::surrounding_word(
10475                        &display_map,
10476                        selection.start.to_display_point(&display_map),
10477                    );
10478                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10479                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10480                    selection.goal = SelectionGoal::None;
10481                    selection.reversed = false;
10482                }
10483                if selections.len() == 1 {
10484                    let selection = selections
10485                        .last()
10486                        .expect("ensured that there's only one selection");
10487                    let query = buffer
10488                        .text_for_range(selection.start..selection.end)
10489                        .collect::<String>();
10490                    let is_empty = query.is_empty();
10491                    let select_state = SelectNextState {
10492                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10493                        wordwise: true,
10494                        done: is_empty,
10495                    };
10496                    self.select_prev_state = Some(select_state);
10497                } else {
10498                    self.select_prev_state = None;
10499                }
10500
10501                self.unfold_ranges(
10502                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10503                    false,
10504                    true,
10505                    cx,
10506                );
10507                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10508                    s.select(selections);
10509                });
10510            } else if let Some(selected_text) = selected_text {
10511                self.select_prev_state = Some(SelectNextState {
10512                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10513                    wordwise: false,
10514                    done: false,
10515                });
10516                self.select_previous(action, window, cx)?;
10517            }
10518        }
10519        Ok(())
10520    }
10521
10522    pub fn toggle_comments(
10523        &mut self,
10524        action: &ToggleComments,
10525        window: &mut Window,
10526        cx: &mut Context<Self>,
10527    ) {
10528        if self.read_only(cx) {
10529            return;
10530        }
10531        let text_layout_details = &self.text_layout_details(window);
10532        self.transact(window, cx, |this, window, cx| {
10533            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10534            let mut edits = Vec::new();
10535            let mut selection_edit_ranges = Vec::new();
10536            let mut last_toggled_row = None;
10537            let snapshot = this.buffer.read(cx).read(cx);
10538            let empty_str: Arc<str> = Arc::default();
10539            let mut suffixes_inserted = Vec::new();
10540            let ignore_indent = action.ignore_indent;
10541
10542            fn comment_prefix_range(
10543                snapshot: &MultiBufferSnapshot,
10544                row: MultiBufferRow,
10545                comment_prefix: &str,
10546                comment_prefix_whitespace: &str,
10547                ignore_indent: bool,
10548            ) -> Range<Point> {
10549                let indent_size = if ignore_indent {
10550                    0
10551                } else {
10552                    snapshot.indent_size_for_line(row).len
10553                };
10554
10555                let start = Point::new(row.0, indent_size);
10556
10557                let mut line_bytes = snapshot
10558                    .bytes_in_range(start..snapshot.max_point())
10559                    .flatten()
10560                    .copied();
10561
10562                // If this line currently begins with the line comment prefix, then record
10563                // the range containing the prefix.
10564                if line_bytes
10565                    .by_ref()
10566                    .take(comment_prefix.len())
10567                    .eq(comment_prefix.bytes())
10568                {
10569                    // Include any whitespace that matches the comment prefix.
10570                    let matching_whitespace_len = line_bytes
10571                        .zip(comment_prefix_whitespace.bytes())
10572                        .take_while(|(a, b)| a == b)
10573                        .count() as u32;
10574                    let end = Point::new(
10575                        start.row,
10576                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10577                    );
10578                    start..end
10579                } else {
10580                    start..start
10581                }
10582            }
10583
10584            fn comment_suffix_range(
10585                snapshot: &MultiBufferSnapshot,
10586                row: MultiBufferRow,
10587                comment_suffix: &str,
10588                comment_suffix_has_leading_space: bool,
10589            ) -> Range<Point> {
10590                let end = Point::new(row.0, snapshot.line_len(row));
10591                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10592
10593                let mut line_end_bytes = snapshot
10594                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10595                    .flatten()
10596                    .copied();
10597
10598                let leading_space_len = if suffix_start_column > 0
10599                    && line_end_bytes.next() == Some(b' ')
10600                    && comment_suffix_has_leading_space
10601                {
10602                    1
10603                } else {
10604                    0
10605                };
10606
10607                // If this line currently begins with the line comment prefix, then record
10608                // the range containing the prefix.
10609                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10610                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
10611                    start..end
10612                } else {
10613                    end..end
10614                }
10615            }
10616
10617            // TODO: Handle selections that cross excerpts
10618            for selection in &mut selections {
10619                let start_column = snapshot
10620                    .indent_size_for_line(MultiBufferRow(selection.start.row))
10621                    .len;
10622                let language = if let Some(language) =
10623                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10624                {
10625                    language
10626                } else {
10627                    continue;
10628                };
10629
10630                selection_edit_ranges.clear();
10631
10632                // If multiple selections contain a given row, avoid processing that
10633                // row more than once.
10634                let mut start_row = MultiBufferRow(selection.start.row);
10635                if last_toggled_row == Some(start_row) {
10636                    start_row = start_row.next_row();
10637                }
10638                let end_row =
10639                    if selection.end.row > selection.start.row && selection.end.column == 0 {
10640                        MultiBufferRow(selection.end.row - 1)
10641                    } else {
10642                        MultiBufferRow(selection.end.row)
10643                    };
10644                last_toggled_row = Some(end_row);
10645
10646                if start_row > end_row {
10647                    continue;
10648                }
10649
10650                // If the language has line comments, toggle those.
10651                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10652
10653                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10654                if ignore_indent {
10655                    full_comment_prefixes = full_comment_prefixes
10656                        .into_iter()
10657                        .map(|s| Arc::from(s.trim_end()))
10658                        .collect();
10659                }
10660
10661                if !full_comment_prefixes.is_empty() {
10662                    let first_prefix = full_comment_prefixes
10663                        .first()
10664                        .expect("prefixes is non-empty");
10665                    let prefix_trimmed_lengths = full_comment_prefixes
10666                        .iter()
10667                        .map(|p| p.trim_end_matches(' ').len())
10668                        .collect::<SmallVec<[usize; 4]>>();
10669
10670                    let mut all_selection_lines_are_comments = true;
10671
10672                    for row in start_row.0..=end_row.0 {
10673                        let row = MultiBufferRow(row);
10674                        if start_row < end_row && snapshot.is_line_blank(row) {
10675                            continue;
10676                        }
10677
10678                        let prefix_range = full_comment_prefixes
10679                            .iter()
10680                            .zip(prefix_trimmed_lengths.iter().copied())
10681                            .map(|(prefix, trimmed_prefix_len)| {
10682                                comment_prefix_range(
10683                                    snapshot.deref(),
10684                                    row,
10685                                    &prefix[..trimmed_prefix_len],
10686                                    &prefix[trimmed_prefix_len..],
10687                                    ignore_indent,
10688                                )
10689                            })
10690                            .max_by_key(|range| range.end.column - range.start.column)
10691                            .expect("prefixes is non-empty");
10692
10693                        if prefix_range.is_empty() {
10694                            all_selection_lines_are_comments = false;
10695                        }
10696
10697                        selection_edit_ranges.push(prefix_range);
10698                    }
10699
10700                    if all_selection_lines_are_comments {
10701                        edits.extend(
10702                            selection_edit_ranges
10703                                .iter()
10704                                .cloned()
10705                                .map(|range| (range, empty_str.clone())),
10706                        );
10707                    } else {
10708                        let min_column = selection_edit_ranges
10709                            .iter()
10710                            .map(|range| range.start.column)
10711                            .min()
10712                            .unwrap_or(0);
10713                        edits.extend(selection_edit_ranges.iter().map(|range| {
10714                            let position = Point::new(range.start.row, min_column);
10715                            (position..position, first_prefix.clone())
10716                        }));
10717                    }
10718                } else if let Some((full_comment_prefix, comment_suffix)) =
10719                    language.block_comment_delimiters()
10720                {
10721                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10722                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10723                    let prefix_range = comment_prefix_range(
10724                        snapshot.deref(),
10725                        start_row,
10726                        comment_prefix,
10727                        comment_prefix_whitespace,
10728                        ignore_indent,
10729                    );
10730                    let suffix_range = comment_suffix_range(
10731                        snapshot.deref(),
10732                        end_row,
10733                        comment_suffix.trim_start_matches(' '),
10734                        comment_suffix.starts_with(' '),
10735                    );
10736
10737                    if prefix_range.is_empty() || suffix_range.is_empty() {
10738                        edits.push((
10739                            prefix_range.start..prefix_range.start,
10740                            full_comment_prefix.clone(),
10741                        ));
10742                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10743                        suffixes_inserted.push((end_row, comment_suffix.len()));
10744                    } else {
10745                        edits.push((prefix_range, empty_str.clone()));
10746                        edits.push((suffix_range, empty_str.clone()));
10747                    }
10748                } else {
10749                    continue;
10750                }
10751            }
10752
10753            drop(snapshot);
10754            this.buffer.update(cx, |buffer, cx| {
10755                buffer.edit(edits, None, cx);
10756            });
10757
10758            // Adjust selections so that they end before any comment suffixes that
10759            // were inserted.
10760            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10761            let mut selections = this.selections.all::<Point>(cx);
10762            let snapshot = this.buffer.read(cx).read(cx);
10763            for selection in &mut selections {
10764                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10765                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10766                        Ordering::Less => {
10767                            suffixes_inserted.next();
10768                            continue;
10769                        }
10770                        Ordering::Greater => break,
10771                        Ordering::Equal => {
10772                            if selection.end.column == snapshot.line_len(row) {
10773                                if selection.is_empty() {
10774                                    selection.start.column -= suffix_len as u32;
10775                                }
10776                                selection.end.column -= suffix_len as u32;
10777                            }
10778                            break;
10779                        }
10780                    }
10781                }
10782            }
10783
10784            drop(snapshot);
10785            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10786                s.select(selections)
10787            });
10788
10789            let selections = this.selections.all::<Point>(cx);
10790            let selections_on_single_row = selections.windows(2).all(|selections| {
10791                selections[0].start.row == selections[1].start.row
10792                    && selections[0].end.row == selections[1].end.row
10793                    && selections[0].start.row == selections[0].end.row
10794            });
10795            let selections_selecting = selections
10796                .iter()
10797                .any(|selection| selection.start != selection.end);
10798            let advance_downwards = action.advance_downwards
10799                && selections_on_single_row
10800                && !selections_selecting
10801                && !matches!(this.mode, EditorMode::SingleLine { .. });
10802
10803            if advance_downwards {
10804                let snapshot = this.buffer.read(cx).snapshot(cx);
10805
10806                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10807                    s.move_cursors_with(|display_snapshot, display_point, _| {
10808                        let mut point = display_point.to_point(display_snapshot);
10809                        point.row += 1;
10810                        point = snapshot.clip_point(point, Bias::Left);
10811                        let display_point = point.to_display_point(display_snapshot);
10812                        let goal = SelectionGoal::HorizontalPosition(
10813                            display_snapshot
10814                                .x_for_display_point(display_point, text_layout_details)
10815                                .into(),
10816                        );
10817                        (display_point, goal)
10818                    })
10819                });
10820            }
10821        });
10822    }
10823
10824    pub fn select_enclosing_symbol(
10825        &mut self,
10826        _: &SelectEnclosingSymbol,
10827        window: &mut Window,
10828        cx: &mut Context<Self>,
10829    ) {
10830        let buffer = self.buffer.read(cx).snapshot(cx);
10831        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10832
10833        fn update_selection(
10834            selection: &Selection<usize>,
10835            buffer_snap: &MultiBufferSnapshot,
10836        ) -> Option<Selection<usize>> {
10837            let cursor = selection.head();
10838            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10839            for symbol in symbols.iter().rev() {
10840                let start = symbol.range.start.to_offset(buffer_snap);
10841                let end = symbol.range.end.to_offset(buffer_snap);
10842                let new_range = start..end;
10843                if start < selection.start || end > selection.end {
10844                    return Some(Selection {
10845                        id: selection.id,
10846                        start: new_range.start,
10847                        end: new_range.end,
10848                        goal: SelectionGoal::None,
10849                        reversed: selection.reversed,
10850                    });
10851                }
10852            }
10853            None
10854        }
10855
10856        let mut selected_larger_symbol = false;
10857        let new_selections = old_selections
10858            .iter()
10859            .map(|selection| match update_selection(selection, &buffer) {
10860                Some(new_selection) => {
10861                    if new_selection.range() != selection.range() {
10862                        selected_larger_symbol = true;
10863                    }
10864                    new_selection
10865                }
10866                None => selection.clone(),
10867            })
10868            .collect::<Vec<_>>();
10869
10870        if selected_larger_symbol {
10871            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10872                s.select(new_selections);
10873            });
10874        }
10875    }
10876
10877    pub fn select_larger_syntax_node(
10878        &mut self,
10879        _: &SelectLargerSyntaxNode,
10880        window: &mut Window,
10881        cx: &mut Context<Self>,
10882    ) {
10883        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10884        let buffer = self.buffer.read(cx).snapshot(cx);
10885        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10886
10887        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10888        let mut selected_larger_node = false;
10889        let new_selections = old_selections
10890            .iter()
10891            .map(|selection| {
10892                let old_range = selection.start..selection.end;
10893                let mut new_range = old_range.clone();
10894                let mut new_node = None;
10895                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10896                {
10897                    new_node = Some(node);
10898                    new_range = match containing_range {
10899                        MultiOrSingleBufferOffsetRange::Single(_) => break,
10900                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
10901                    };
10902                    if !display_map.intersects_fold(new_range.start)
10903                        && !display_map.intersects_fold(new_range.end)
10904                    {
10905                        break;
10906                    }
10907                }
10908
10909                if let Some(node) = new_node {
10910                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10911                    // nodes. Parent and grandparent are also logged because this operation will not
10912                    // visit nodes that have the same range as their parent.
10913                    log::info!("Node: {node:?}");
10914                    let parent = node.parent();
10915                    log::info!("Parent: {parent:?}");
10916                    let grandparent = parent.and_then(|x| x.parent());
10917                    log::info!("Grandparent: {grandparent:?}");
10918                }
10919
10920                selected_larger_node |= new_range != old_range;
10921                Selection {
10922                    id: selection.id,
10923                    start: new_range.start,
10924                    end: new_range.end,
10925                    goal: SelectionGoal::None,
10926                    reversed: selection.reversed,
10927                }
10928            })
10929            .collect::<Vec<_>>();
10930
10931        if selected_larger_node {
10932            stack.push(old_selections);
10933            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10934                s.select(new_selections);
10935            });
10936        }
10937        self.select_larger_syntax_node_stack = stack;
10938    }
10939
10940    pub fn select_smaller_syntax_node(
10941        &mut self,
10942        _: &SelectSmallerSyntaxNode,
10943        window: &mut Window,
10944        cx: &mut Context<Self>,
10945    ) {
10946        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10947        if let Some(selections) = stack.pop() {
10948            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10949                s.select(selections.to_vec());
10950            });
10951        }
10952        self.select_larger_syntax_node_stack = stack;
10953    }
10954
10955    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10956        if !EditorSettings::get_global(cx).gutter.runnables {
10957            self.clear_tasks();
10958            return Task::ready(());
10959        }
10960        let project = self.project.as_ref().map(Entity::downgrade);
10961        cx.spawn_in(window, |this, mut cx| async move {
10962            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10963            let Some(project) = project.and_then(|p| p.upgrade()) else {
10964                return;
10965            };
10966            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10967                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10968            }) else {
10969                return;
10970            };
10971
10972            let hide_runnables = project
10973                .update(&mut cx, |project, cx| {
10974                    // Do not display any test indicators in non-dev server remote projects.
10975                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10976                })
10977                .unwrap_or(true);
10978            if hide_runnables {
10979                return;
10980            }
10981            let new_rows =
10982                cx.background_spawn({
10983                    let snapshot = display_snapshot.clone();
10984                    async move {
10985                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10986                    }
10987                })
10988                    .await;
10989
10990            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10991            this.update(&mut cx, |this, _| {
10992                this.clear_tasks();
10993                for (key, value) in rows {
10994                    this.insert_tasks(key, value);
10995                }
10996            })
10997            .ok();
10998        })
10999    }
11000    fn fetch_runnable_ranges(
11001        snapshot: &DisplaySnapshot,
11002        range: Range<Anchor>,
11003    ) -> Vec<language::RunnableRange> {
11004        snapshot.buffer_snapshot.runnable_ranges(range).collect()
11005    }
11006
11007    fn runnable_rows(
11008        project: Entity<Project>,
11009        snapshot: DisplaySnapshot,
11010        runnable_ranges: Vec<RunnableRange>,
11011        mut cx: AsyncWindowContext,
11012    ) -> Vec<((BufferId, u32), RunnableTasks)> {
11013        runnable_ranges
11014            .into_iter()
11015            .filter_map(|mut runnable| {
11016                let tasks = cx
11017                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11018                    .ok()?;
11019                if tasks.is_empty() {
11020                    return None;
11021                }
11022
11023                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11024
11025                let row = snapshot
11026                    .buffer_snapshot
11027                    .buffer_line_for_row(MultiBufferRow(point.row))?
11028                    .1
11029                    .start
11030                    .row;
11031
11032                let context_range =
11033                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11034                Some((
11035                    (runnable.buffer_id, row),
11036                    RunnableTasks {
11037                        templates: tasks,
11038                        offset: snapshot
11039                            .buffer_snapshot
11040                            .anchor_before(runnable.run_range.start),
11041                        context_range,
11042                        column: point.column,
11043                        extra_variables: runnable.extra_captures,
11044                    },
11045                ))
11046            })
11047            .collect()
11048    }
11049
11050    fn templates_with_tags(
11051        project: &Entity<Project>,
11052        runnable: &mut Runnable,
11053        cx: &mut App,
11054    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11055        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11056            let (worktree_id, file) = project
11057                .buffer_for_id(runnable.buffer, cx)
11058                .and_then(|buffer| buffer.read(cx).file())
11059                .map(|file| (file.worktree_id(cx), file.clone()))
11060                .unzip();
11061
11062            (
11063                project.task_store().read(cx).task_inventory().cloned(),
11064                worktree_id,
11065                file,
11066            )
11067        });
11068
11069        let tags = mem::take(&mut runnable.tags);
11070        let mut tags: Vec<_> = tags
11071            .into_iter()
11072            .flat_map(|tag| {
11073                let tag = tag.0.clone();
11074                inventory
11075                    .as_ref()
11076                    .into_iter()
11077                    .flat_map(|inventory| {
11078                        inventory.read(cx).list_tasks(
11079                            file.clone(),
11080                            Some(runnable.language.clone()),
11081                            worktree_id,
11082                            cx,
11083                        )
11084                    })
11085                    .filter(move |(_, template)| {
11086                        template.tags.iter().any(|source_tag| source_tag == &tag)
11087                    })
11088            })
11089            .sorted_by_key(|(kind, _)| kind.to_owned())
11090            .collect();
11091        if let Some((leading_tag_source, _)) = tags.first() {
11092            // Strongest source wins; if we have worktree tag binding, prefer that to
11093            // global and language bindings;
11094            // if we have a global binding, prefer that to language binding.
11095            let first_mismatch = tags
11096                .iter()
11097                .position(|(tag_source, _)| tag_source != leading_tag_source);
11098            if let Some(index) = first_mismatch {
11099                tags.truncate(index);
11100            }
11101        }
11102
11103        tags
11104    }
11105
11106    pub fn move_to_enclosing_bracket(
11107        &mut self,
11108        _: &MoveToEnclosingBracket,
11109        window: &mut Window,
11110        cx: &mut Context<Self>,
11111    ) {
11112        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11113            s.move_offsets_with(|snapshot, selection| {
11114                let Some(enclosing_bracket_ranges) =
11115                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11116                else {
11117                    return;
11118                };
11119
11120                let mut best_length = usize::MAX;
11121                let mut best_inside = false;
11122                let mut best_in_bracket_range = false;
11123                let mut best_destination = None;
11124                for (open, close) in enclosing_bracket_ranges {
11125                    let close = close.to_inclusive();
11126                    let length = close.end() - open.start;
11127                    let inside = selection.start >= open.end && selection.end <= *close.start();
11128                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
11129                        || close.contains(&selection.head());
11130
11131                    // If best is next to a bracket and current isn't, skip
11132                    if !in_bracket_range && best_in_bracket_range {
11133                        continue;
11134                    }
11135
11136                    // Prefer smaller lengths unless best is inside and current isn't
11137                    if length > best_length && (best_inside || !inside) {
11138                        continue;
11139                    }
11140
11141                    best_length = length;
11142                    best_inside = inside;
11143                    best_in_bracket_range = in_bracket_range;
11144                    best_destination = Some(
11145                        if close.contains(&selection.start) && close.contains(&selection.end) {
11146                            if inside {
11147                                open.end
11148                            } else {
11149                                open.start
11150                            }
11151                        } else if inside {
11152                            *close.start()
11153                        } else {
11154                            *close.end()
11155                        },
11156                    );
11157                }
11158
11159                if let Some(destination) = best_destination {
11160                    selection.collapse_to(destination, SelectionGoal::None);
11161                }
11162            })
11163        });
11164    }
11165
11166    pub fn undo_selection(
11167        &mut self,
11168        _: &UndoSelection,
11169        window: &mut Window,
11170        cx: &mut Context<Self>,
11171    ) {
11172        self.end_selection(window, cx);
11173        self.selection_history.mode = SelectionHistoryMode::Undoing;
11174        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11175            self.change_selections(None, window, cx, |s| {
11176                s.select_anchors(entry.selections.to_vec())
11177            });
11178            self.select_next_state = entry.select_next_state;
11179            self.select_prev_state = entry.select_prev_state;
11180            self.add_selections_state = entry.add_selections_state;
11181            self.request_autoscroll(Autoscroll::newest(), cx);
11182        }
11183        self.selection_history.mode = SelectionHistoryMode::Normal;
11184    }
11185
11186    pub fn redo_selection(
11187        &mut self,
11188        _: &RedoSelection,
11189        window: &mut Window,
11190        cx: &mut Context<Self>,
11191    ) {
11192        self.end_selection(window, cx);
11193        self.selection_history.mode = SelectionHistoryMode::Redoing;
11194        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11195            self.change_selections(None, window, cx, |s| {
11196                s.select_anchors(entry.selections.to_vec())
11197            });
11198            self.select_next_state = entry.select_next_state;
11199            self.select_prev_state = entry.select_prev_state;
11200            self.add_selections_state = entry.add_selections_state;
11201            self.request_autoscroll(Autoscroll::newest(), cx);
11202        }
11203        self.selection_history.mode = SelectionHistoryMode::Normal;
11204    }
11205
11206    pub fn expand_excerpts(
11207        &mut self,
11208        action: &ExpandExcerpts,
11209        _: &mut Window,
11210        cx: &mut Context<Self>,
11211    ) {
11212        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11213    }
11214
11215    pub fn expand_excerpts_down(
11216        &mut self,
11217        action: &ExpandExcerptsDown,
11218        _: &mut Window,
11219        cx: &mut Context<Self>,
11220    ) {
11221        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11222    }
11223
11224    pub fn expand_excerpts_up(
11225        &mut self,
11226        action: &ExpandExcerptsUp,
11227        _: &mut Window,
11228        cx: &mut Context<Self>,
11229    ) {
11230        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11231    }
11232
11233    pub fn expand_excerpts_for_direction(
11234        &mut self,
11235        lines: u32,
11236        direction: ExpandExcerptDirection,
11237
11238        cx: &mut Context<Self>,
11239    ) {
11240        let selections = self.selections.disjoint_anchors();
11241
11242        let lines = if lines == 0 {
11243            EditorSettings::get_global(cx).expand_excerpt_lines
11244        } else {
11245            lines
11246        };
11247
11248        self.buffer.update(cx, |buffer, cx| {
11249            let snapshot = buffer.snapshot(cx);
11250            let mut excerpt_ids = selections
11251                .iter()
11252                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11253                .collect::<Vec<_>>();
11254            excerpt_ids.sort();
11255            excerpt_ids.dedup();
11256            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11257        })
11258    }
11259
11260    pub fn expand_excerpt(
11261        &mut self,
11262        excerpt: ExcerptId,
11263        direction: ExpandExcerptDirection,
11264        cx: &mut Context<Self>,
11265    ) {
11266        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11267        self.buffer.update(cx, |buffer, cx| {
11268            buffer.expand_excerpts([excerpt], lines, direction, cx)
11269        })
11270    }
11271
11272    pub fn go_to_singleton_buffer_point(
11273        &mut self,
11274        point: Point,
11275        window: &mut Window,
11276        cx: &mut Context<Self>,
11277    ) {
11278        self.go_to_singleton_buffer_range(point..point, window, cx);
11279    }
11280
11281    pub fn go_to_singleton_buffer_range(
11282        &mut self,
11283        range: Range<Point>,
11284        window: &mut Window,
11285        cx: &mut Context<Self>,
11286    ) {
11287        let multibuffer = self.buffer().read(cx);
11288        let Some(buffer) = multibuffer.as_singleton() else {
11289            return;
11290        };
11291        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11292            return;
11293        };
11294        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11295            return;
11296        };
11297        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11298            s.select_anchor_ranges([start..end])
11299        });
11300    }
11301
11302    fn go_to_diagnostic(
11303        &mut self,
11304        _: &GoToDiagnostic,
11305        window: &mut Window,
11306        cx: &mut Context<Self>,
11307    ) {
11308        self.go_to_diagnostic_impl(Direction::Next, window, cx)
11309    }
11310
11311    fn go_to_prev_diagnostic(
11312        &mut self,
11313        _: &GoToPreviousDiagnostic,
11314        window: &mut Window,
11315        cx: &mut Context<Self>,
11316    ) {
11317        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11318    }
11319
11320    pub fn go_to_diagnostic_impl(
11321        &mut self,
11322        direction: Direction,
11323        window: &mut Window,
11324        cx: &mut Context<Self>,
11325    ) {
11326        let buffer = self.buffer.read(cx).snapshot(cx);
11327        let selection = self.selections.newest::<usize>(cx);
11328
11329        // If there is an active Diagnostic Popover jump to its diagnostic instead.
11330        if direction == Direction::Next {
11331            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11332                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11333                    return;
11334                };
11335                self.activate_diagnostics(
11336                    buffer_id,
11337                    popover.local_diagnostic.diagnostic.group_id,
11338                    window,
11339                    cx,
11340                );
11341                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11342                    let primary_range_start = active_diagnostics.primary_range.start;
11343                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11344                        let mut new_selection = s.newest_anchor().clone();
11345                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11346                        s.select_anchors(vec![new_selection.clone()]);
11347                    });
11348                    self.refresh_inline_completion(false, true, window, cx);
11349                }
11350                return;
11351            }
11352        }
11353
11354        let active_group_id = self
11355            .active_diagnostics
11356            .as_ref()
11357            .map(|active_group| active_group.group_id);
11358        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11359            active_diagnostics
11360                .primary_range
11361                .to_offset(&buffer)
11362                .to_inclusive()
11363        });
11364        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11365            if active_primary_range.contains(&selection.head()) {
11366                *active_primary_range.start()
11367            } else {
11368                selection.head()
11369            }
11370        } else {
11371            selection.head()
11372        };
11373
11374        let snapshot = self.snapshot(window, cx);
11375        let primary_diagnostics_before = buffer
11376            .diagnostics_in_range::<usize>(0..search_start)
11377            .filter(|entry| entry.diagnostic.is_primary)
11378            .filter(|entry| entry.range.start != entry.range.end)
11379            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11380            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11381            .collect::<Vec<_>>();
11382        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11383            primary_diagnostics_before
11384                .iter()
11385                .position(|entry| entry.diagnostic.group_id == active_group_id)
11386        });
11387
11388        let primary_diagnostics_after = buffer
11389            .diagnostics_in_range::<usize>(search_start..buffer.len())
11390            .filter(|entry| entry.diagnostic.is_primary)
11391            .filter(|entry| entry.range.start != entry.range.end)
11392            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11393            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11394            .collect::<Vec<_>>();
11395        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11396            primary_diagnostics_after
11397                .iter()
11398                .enumerate()
11399                .rev()
11400                .find_map(|(i, entry)| {
11401                    if entry.diagnostic.group_id == active_group_id {
11402                        Some(i)
11403                    } else {
11404                        None
11405                    }
11406                })
11407        });
11408
11409        let next_primary_diagnostic = match direction {
11410            Direction::Prev => primary_diagnostics_before
11411                .iter()
11412                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11413                .rev()
11414                .next(),
11415            Direction::Next => primary_diagnostics_after
11416                .iter()
11417                .skip(
11418                    last_same_group_diagnostic_after
11419                        .map(|index| index + 1)
11420                        .unwrap_or(0),
11421                )
11422                .next(),
11423        };
11424
11425        // Cycle around to the start of the buffer, potentially moving back to the start of
11426        // the currently active diagnostic.
11427        let cycle_around = || match direction {
11428            Direction::Prev => primary_diagnostics_after
11429                .iter()
11430                .rev()
11431                .chain(primary_diagnostics_before.iter().rev())
11432                .next(),
11433            Direction::Next => primary_diagnostics_before
11434                .iter()
11435                .chain(primary_diagnostics_after.iter())
11436                .next(),
11437        };
11438
11439        if let Some((primary_range, group_id)) = next_primary_diagnostic
11440            .or_else(cycle_around)
11441            .map(|entry| (&entry.range, entry.diagnostic.group_id))
11442        {
11443            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11444                return;
11445            };
11446            self.activate_diagnostics(buffer_id, group_id, window, cx);
11447            if self.active_diagnostics.is_some() {
11448                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11449                    s.select(vec![Selection {
11450                        id: selection.id,
11451                        start: primary_range.start,
11452                        end: primary_range.start,
11453                        reversed: false,
11454                        goal: SelectionGoal::None,
11455                    }]);
11456                });
11457                self.refresh_inline_completion(false, true, window, cx);
11458            }
11459        }
11460    }
11461
11462    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11463        let snapshot = self.snapshot(window, cx);
11464        let selection = self.selections.newest::<Point>(cx);
11465        self.go_to_hunk_after_or_before_position(
11466            &snapshot,
11467            selection.head(),
11468            Direction::Next,
11469            window,
11470            cx,
11471        );
11472    }
11473
11474    fn go_to_hunk_after_or_before_position(
11475        &mut self,
11476        snapshot: &EditorSnapshot,
11477        position: Point,
11478        direction: Direction,
11479        window: &mut Window,
11480        cx: &mut Context<Editor>,
11481    ) {
11482        let row = if direction == Direction::Next {
11483            self.hunk_after_position(snapshot, position)
11484                .map(|hunk| hunk.row_range.start)
11485        } else {
11486            self.hunk_before_position(snapshot, position)
11487        };
11488
11489        if let Some(row) = row {
11490            let destination = Point::new(row.0, 0);
11491            let autoscroll = Autoscroll::center();
11492
11493            self.unfold_ranges(&[destination..destination], false, false, cx);
11494            self.change_selections(Some(autoscroll), window, cx, |s| {
11495                s.select_ranges([destination..destination]);
11496            });
11497        }
11498    }
11499
11500    fn hunk_after_position(
11501        &mut self,
11502        snapshot: &EditorSnapshot,
11503        position: Point,
11504    ) -> Option<MultiBufferDiffHunk> {
11505        snapshot
11506            .buffer_snapshot
11507            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11508            .find(|hunk| hunk.row_range.start.0 > position.row)
11509            .or_else(|| {
11510                snapshot
11511                    .buffer_snapshot
11512                    .diff_hunks_in_range(Point::zero()..position)
11513                    .find(|hunk| hunk.row_range.end.0 < position.row)
11514            })
11515    }
11516
11517    fn go_to_prev_hunk(
11518        &mut self,
11519        _: &GoToPreviousHunk,
11520        window: &mut Window,
11521        cx: &mut Context<Self>,
11522    ) {
11523        let snapshot = self.snapshot(window, cx);
11524        let selection = self.selections.newest::<Point>(cx);
11525        self.go_to_hunk_after_or_before_position(
11526            &snapshot,
11527            selection.head(),
11528            Direction::Prev,
11529            window,
11530            cx,
11531        );
11532    }
11533
11534    fn hunk_before_position(
11535        &mut self,
11536        snapshot: &EditorSnapshot,
11537        position: Point,
11538    ) -> Option<MultiBufferRow> {
11539        snapshot
11540            .buffer_snapshot
11541            .diff_hunk_before(position)
11542            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11543    }
11544
11545    pub fn go_to_definition(
11546        &mut self,
11547        _: &GoToDefinition,
11548        window: &mut Window,
11549        cx: &mut Context<Self>,
11550    ) -> Task<Result<Navigated>> {
11551        let definition =
11552            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11553        cx.spawn_in(window, |editor, mut cx| async move {
11554            if definition.await? == Navigated::Yes {
11555                return Ok(Navigated::Yes);
11556            }
11557            match editor.update_in(&mut cx, |editor, window, cx| {
11558                editor.find_all_references(&FindAllReferences, window, cx)
11559            })? {
11560                Some(references) => references.await,
11561                None => Ok(Navigated::No),
11562            }
11563        })
11564    }
11565
11566    pub fn go_to_declaration(
11567        &mut self,
11568        _: &GoToDeclaration,
11569        window: &mut Window,
11570        cx: &mut Context<Self>,
11571    ) -> Task<Result<Navigated>> {
11572        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11573    }
11574
11575    pub fn go_to_declaration_split(
11576        &mut self,
11577        _: &GoToDeclaration,
11578        window: &mut Window,
11579        cx: &mut Context<Self>,
11580    ) -> Task<Result<Navigated>> {
11581        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11582    }
11583
11584    pub fn go_to_implementation(
11585        &mut self,
11586        _: &GoToImplementation,
11587        window: &mut Window,
11588        cx: &mut Context<Self>,
11589    ) -> Task<Result<Navigated>> {
11590        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11591    }
11592
11593    pub fn go_to_implementation_split(
11594        &mut self,
11595        _: &GoToImplementationSplit,
11596        window: &mut Window,
11597        cx: &mut Context<Self>,
11598    ) -> Task<Result<Navigated>> {
11599        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11600    }
11601
11602    pub fn go_to_type_definition(
11603        &mut self,
11604        _: &GoToTypeDefinition,
11605        window: &mut Window,
11606        cx: &mut Context<Self>,
11607    ) -> Task<Result<Navigated>> {
11608        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11609    }
11610
11611    pub fn go_to_definition_split(
11612        &mut self,
11613        _: &GoToDefinitionSplit,
11614        window: &mut Window,
11615        cx: &mut Context<Self>,
11616    ) -> Task<Result<Navigated>> {
11617        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11618    }
11619
11620    pub fn go_to_type_definition_split(
11621        &mut self,
11622        _: &GoToTypeDefinitionSplit,
11623        window: &mut Window,
11624        cx: &mut Context<Self>,
11625    ) -> Task<Result<Navigated>> {
11626        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11627    }
11628
11629    fn go_to_definition_of_kind(
11630        &mut self,
11631        kind: GotoDefinitionKind,
11632        split: bool,
11633        window: &mut Window,
11634        cx: &mut Context<Self>,
11635    ) -> Task<Result<Navigated>> {
11636        let Some(provider) = self.semantics_provider.clone() else {
11637            return Task::ready(Ok(Navigated::No));
11638        };
11639        let head = self.selections.newest::<usize>(cx).head();
11640        let buffer = self.buffer.read(cx);
11641        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11642            text_anchor
11643        } else {
11644            return Task::ready(Ok(Navigated::No));
11645        };
11646
11647        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11648            return Task::ready(Ok(Navigated::No));
11649        };
11650
11651        cx.spawn_in(window, |editor, mut cx| async move {
11652            let definitions = definitions.await?;
11653            let navigated = editor
11654                .update_in(&mut cx, |editor, window, cx| {
11655                    editor.navigate_to_hover_links(
11656                        Some(kind),
11657                        definitions
11658                            .into_iter()
11659                            .filter(|location| {
11660                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11661                            })
11662                            .map(HoverLink::Text)
11663                            .collect::<Vec<_>>(),
11664                        split,
11665                        window,
11666                        cx,
11667                    )
11668                })?
11669                .await?;
11670            anyhow::Ok(navigated)
11671        })
11672    }
11673
11674    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11675        let selection = self.selections.newest_anchor();
11676        let head = selection.head();
11677        let tail = selection.tail();
11678
11679        let Some((buffer, start_position)) =
11680            self.buffer.read(cx).text_anchor_for_position(head, cx)
11681        else {
11682            return;
11683        };
11684
11685        let end_position = if head != tail {
11686            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11687                return;
11688            };
11689            Some(pos)
11690        } else {
11691            None
11692        };
11693
11694        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11695            let url = if let Some(end_pos) = end_position {
11696                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11697            } else {
11698                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11699            };
11700
11701            if let Some(url) = url {
11702                editor.update(&mut cx, |_, cx| {
11703                    cx.open_url(&url);
11704                })
11705            } else {
11706                Ok(())
11707            }
11708        });
11709
11710        url_finder.detach();
11711    }
11712
11713    pub fn open_selected_filename(
11714        &mut self,
11715        _: &OpenSelectedFilename,
11716        window: &mut Window,
11717        cx: &mut Context<Self>,
11718    ) {
11719        let Some(workspace) = self.workspace() else {
11720            return;
11721        };
11722
11723        let position = self.selections.newest_anchor().head();
11724
11725        let Some((buffer, buffer_position)) =
11726            self.buffer.read(cx).text_anchor_for_position(position, cx)
11727        else {
11728            return;
11729        };
11730
11731        let project = self.project.clone();
11732
11733        cx.spawn_in(window, |_, mut cx| async move {
11734            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11735
11736            if let Some((_, path)) = result {
11737                workspace
11738                    .update_in(&mut cx, |workspace, window, cx| {
11739                        workspace.open_resolved_path(path, window, cx)
11740                    })?
11741                    .await?;
11742            }
11743            anyhow::Ok(())
11744        })
11745        .detach();
11746    }
11747
11748    pub(crate) fn navigate_to_hover_links(
11749        &mut self,
11750        kind: Option<GotoDefinitionKind>,
11751        mut definitions: Vec<HoverLink>,
11752        split: bool,
11753        window: &mut Window,
11754        cx: &mut Context<Editor>,
11755    ) -> Task<Result<Navigated>> {
11756        // If there is one definition, just open it directly
11757        if definitions.len() == 1 {
11758            let definition = definitions.pop().unwrap();
11759
11760            enum TargetTaskResult {
11761                Location(Option<Location>),
11762                AlreadyNavigated,
11763            }
11764
11765            let target_task = match definition {
11766                HoverLink::Text(link) => {
11767                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11768                }
11769                HoverLink::InlayHint(lsp_location, server_id) => {
11770                    let computation =
11771                        self.compute_target_location(lsp_location, server_id, window, cx);
11772                    cx.background_spawn(async move {
11773                        let location = computation.await?;
11774                        Ok(TargetTaskResult::Location(location))
11775                    })
11776                }
11777                HoverLink::Url(url) => {
11778                    cx.open_url(&url);
11779                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11780                }
11781                HoverLink::File(path) => {
11782                    if let Some(workspace) = self.workspace() {
11783                        cx.spawn_in(window, |_, mut cx| async move {
11784                            workspace
11785                                .update_in(&mut cx, |workspace, window, cx| {
11786                                    workspace.open_resolved_path(path, window, cx)
11787                                })?
11788                                .await
11789                                .map(|_| TargetTaskResult::AlreadyNavigated)
11790                        })
11791                    } else {
11792                        Task::ready(Ok(TargetTaskResult::Location(None)))
11793                    }
11794                }
11795            };
11796            cx.spawn_in(window, |editor, mut cx| async move {
11797                let target = match target_task.await.context("target resolution task")? {
11798                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11799                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11800                    TargetTaskResult::Location(Some(target)) => target,
11801                };
11802
11803                editor.update_in(&mut cx, |editor, window, cx| {
11804                    let Some(workspace) = editor.workspace() else {
11805                        return Navigated::No;
11806                    };
11807                    let pane = workspace.read(cx).active_pane().clone();
11808
11809                    let range = target.range.to_point(target.buffer.read(cx));
11810                    let range = editor.range_for_match(&range);
11811                    let range = collapse_multiline_range(range);
11812
11813                    if !split
11814                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11815                    {
11816                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11817                    } else {
11818                        window.defer(cx, move |window, cx| {
11819                            let target_editor: Entity<Self> =
11820                                workspace.update(cx, |workspace, cx| {
11821                                    let pane = if split {
11822                                        workspace.adjacent_pane(window, cx)
11823                                    } else {
11824                                        workspace.active_pane().clone()
11825                                    };
11826
11827                                    workspace.open_project_item(
11828                                        pane,
11829                                        target.buffer.clone(),
11830                                        true,
11831                                        true,
11832                                        window,
11833                                        cx,
11834                                    )
11835                                });
11836                            target_editor.update(cx, |target_editor, cx| {
11837                                // When selecting a definition in a different buffer, disable the nav history
11838                                // to avoid creating a history entry at the previous cursor location.
11839                                pane.update(cx, |pane, _| pane.disable_history());
11840                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11841                                pane.update(cx, |pane, _| pane.enable_history());
11842                            });
11843                        });
11844                    }
11845                    Navigated::Yes
11846                })
11847            })
11848        } else if !definitions.is_empty() {
11849            cx.spawn_in(window, |editor, mut cx| async move {
11850                let (title, location_tasks, workspace) = editor
11851                    .update_in(&mut cx, |editor, window, cx| {
11852                        let tab_kind = match kind {
11853                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11854                            _ => "Definitions",
11855                        };
11856                        let title = definitions
11857                            .iter()
11858                            .find_map(|definition| match definition {
11859                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11860                                    let buffer = origin.buffer.read(cx);
11861                                    format!(
11862                                        "{} for {}",
11863                                        tab_kind,
11864                                        buffer
11865                                            .text_for_range(origin.range.clone())
11866                                            .collect::<String>()
11867                                    )
11868                                }),
11869                                HoverLink::InlayHint(_, _) => None,
11870                                HoverLink::Url(_) => None,
11871                                HoverLink::File(_) => None,
11872                            })
11873                            .unwrap_or(tab_kind.to_string());
11874                        let location_tasks = definitions
11875                            .into_iter()
11876                            .map(|definition| match definition {
11877                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11878                                HoverLink::InlayHint(lsp_location, server_id) => editor
11879                                    .compute_target_location(lsp_location, server_id, window, cx),
11880                                HoverLink::Url(_) => Task::ready(Ok(None)),
11881                                HoverLink::File(_) => Task::ready(Ok(None)),
11882                            })
11883                            .collect::<Vec<_>>();
11884                        (title, location_tasks, editor.workspace().clone())
11885                    })
11886                    .context("location tasks preparation")?;
11887
11888                let locations = future::join_all(location_tasks)
11889                    .await
11890                    .into_iter()
11891                    .filter_map(|location| location.transpose())
11892                    .collect::<Result<_>>()
11893                    .context("location tasks")?;
11894
11895                let Some(workspace) = workspace else {
11896                    return Ok(Navigated::No);
11897                };
11898                let opened = workspace
11899                    .update_in(&mut cx, |workspace, window, cx| {
11900                        Self::open_locations_in_multibuffer(
11901                            workspace,
11902                            locations,
11903                            title,
11904                            split,
11905                            MultibufferSelectionMode::First,
11906                            window,
11907                            cx,
11908                        )
11909                    })
11910                    .ok();
11911
11912                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11913            })
11914        } else {
11915            Task::ready(Ok(Navigated::No))
11916        }
11917    }
11918
11919    fn compute_target_location(
11920        &self,
11921        lsp_location: lsp::Location,
11922        server_id: LanguageServerId,
11923        window: &mut Window,
11924        cx: &mut Context<Self>,
11925    ) -> Task<anyhow::Result<Option<Location>>> {
11926        let Some(project) = self.project.clone() else {
11927            return Task::ready(Ok(None));
11928        };
11929
11930        cx.spawn_in(window, move |editor, mut cx| async move {
11931            let location_task = editor.update(&mut cx, |_, cx| {
11932                project.update(cx, |project, cx| {
11933                    let language_server_name = project
11934                        .language_server_statuses(cx)
11935                        .find(|(id, _)| server_id == *id)
11936                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11937                    language_server_name.map(|language_server_name| {
11938                        project.open_local_buffer_via_lsp(
11939                            lsp_location.uri.clone(),
11940                            server_id,
11941                            language_server_name,
11942                            cx,
11943                        )
11944                    })
11945                })
11946            })?;
11947            let location = match location_task {
11948                Some(task) => Some({
11949                    let target_buffer_handle = task.await.context("open local buffer")?;
11950                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11951                        let target_start = target_buffer
11952                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11953                        let target_end = target_buffer
11954                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11955                        target_buffer.anchor_after(target_start)
11956                            ..target_buffer.anchor_before(target_end)
11957                    })?;
11958                    Location {
11959                        buffer: target_buffer_handle,
11960                        range,
11961                    }
11962                }),
11963                None => None,
11964            };
11965            Ok(location)
11966        })
11967    }
11968
11969    pub fn find_all_references(
11970        &mut self,
11971        _: &FindAllReferences,
11972        window: &mut Window,
11973        cx: &mut Context<Self>,
11974    ) -> Option<Task<Result<Navigated>>> {
11975        let selection = self.selections.newest::<usize>(cx);
11976        let multi_buffer = self.buffer.read(cx);
11977        let head = selection.head();
11978
11979        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11980        let head_anchor = multi_buffer_snapshot.anchor_at(
11981            head,
11982            if head < selection.tail() {
11983                Bias::Right
11984            } else {
11985                Bias::Left
11986            },
11987        );
11988
11989        match self
11990            .find_all_references_task_sources
11991            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11992        {
11993            Ok(_) => {
11994                log::info!(
11995                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11996                );
11997                return None;
11998            }
11999            Err(i) => {
12000                self.find_all_references_task_sources.insert(i, head_anchor);
12001            }
12002        }
12003
12004        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12005        let workspace = self.workspace()?;
12006        let project = workspace.read(cx).project().clone();
12007        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12008        Some(cx.spawn_in(window, |editor, mut cx| async move {
12009            let _cleanup = defer({
12010                let mut cx = cx.clone();
12011                move || {
12012                    let _ = editor.update(&mut cx, |editor, _| {
12013                        if let Ok(i) =
12014                            editor
12015                                .find_all_references_task_sources
12016                                .binary_search_by(|anchor| {
12017                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
12018                                })
12019                        {
12020                            editor.find_all_references_task_sources.remove(i);
12021                        }
12022                    });
12023                }
12024            });
12025
12026            let locations = references.await?;
12027            if locations.is_empty() {
12028                return anyhow::Ok(Navigated::No);
12029            }
12030
12031            workspace.update_in(&mut cx, |workspace, window, cx| {
12032                let title = locations
12033                    .first()
12034                    .as_ref()
12035                    .map(|location| {
12036                        let buffer = location.buffer.read(cx);
12037                        format!(
12038                            "References to `{}`",
12039                            buffer
12040                                .text_for_range(location.range.clone())
12041                                .collect::<String>()
12042                        )
12043                    })
12044                    .unwrap();
12045                Self::open_locations_in_multibuffer(
12046                    workspace,
12047                    locations,
12048                    title,
12049                    false,
12050                    MultibufferSelectionMode::First,
12051                    window,
12052                    cx,
12053                );
12054                Navigated::Yes
12055            })
12056        }))
12057    }
12058
12059    /// Opens a multibuffer with the given project locations in it
12060    pub fn open_locations_in_multibuffer(
12061        workspace: &mut Workspace,
12062        mut locations: Vec<Location>,
12063        title: String,
12064        split: bool,
12065        multibuffer_selection_mode: MultibufferSelectionMode,
12066        window: &mut Window,
12067        cx: &mut Context<Workspace>,
12068    ) {
12069        // If there are multiple definitions, open them in a multibuffer
12070        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12071        let mut locations = locations.into_iter().peekable();
12072        let mut ranges = Vec::new();
12073        let capability = workspace.project().read(cx).capability();
12074
12075        let excerpt_buffer = cx.new(|cx| {
12076            let mut multibuffer = MultiBuffer::new(capability);
12077            while let Some(location) = locations.next() {
12078                let buffer = location.buffer.read(cx);
12079                let mut ranges_for_buffer = Vec::new();
12080                let range = location.range.to_offset(buffer);
12081                ranges_for_buffer.push(range.clone());
12082
12083                while let Some(next_location) = locations.peek() {
12084                    if next_location.buffer == location.buffer {
12085                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
12086                        locations.next();
12087                    } else {
12088                        break;
12089                    }
12090                }
12091
12092                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12093                ranges.extend(multibuffer.push_excerpts_with_context_lines(
12094                    location.buffer.clone(),
12095                    ranges_for_buffer,
12096                    DEFAULT_MULTIBUFFER_CONTEXT,
12097                    cx,
12098                ))
12099            }
12100
12101            multibuffer.with_title(title)
12102        });
12103
12104        let editor = cx.new(|cx| {
12105            Editor::for_multibuffer(
12106                excerpt_buffer,
12107                Some(workspace.project().clone()),
12108                true,
12109                window,
12110                cx,
12111            )
12112        });
12113        editor.update(cx, |editor, cx| {
12114            match multibuffer_selection_mode {
12115                MultibufferSelectionMode::First => {
12116                    if let Some(first_range) = ranges.first() {
12117                        editor.change_selections(None, window, cx, |selections| {
12118                            selections.clear_disjoint();
12119                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12120                        });
12121                    }
12122                    editor.highlight_background::<Self>(
12123                        &ranges,
12124                        |theme| theme.editor_highlighted_line_background,
12125                        cx,
12126                    );
12127                }
12128                MultibufferSelectionMode::All => {
12129                    editor.change_selections(None, window, cx, |selections| {
12130                        selections.clear_disjoint();
12131                        selections.select_anchor_ranges(ranges);
12132                    });
12133                }
12134            }
12135            editor.register_buffers_with_language_servers(cx);
12136        });
12137
12138        let item = Box::new(editor);
12139        let item_id = item.item_id();
12140
12141        if split {
12142            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12143        } else {
12144            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12145                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12146                    pane.close_current_preview_item(window, cx)
12147                } else {
12148                    None
12149                }
12150            });
12151            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12152        }
12153        workspace.active_pane().update(cx, |pane, cx| {
12154            pane.set_preview_item_id(Some(item_id), cx);
12155        });
12156    }
12157
12158    pub fn rename(
12159        &mut self,
12160        _: &Rename,
12161        window: &mut Window,
12162        cx: &mut Context<Self>,
12163    ) -> Option<Task<Result<()>>> {
12164        use language::ToOffset as _;
12165
12166        let provider = self.semantics_provider.clone()?;
12167        let selection = self.selections.newest_anchor().clone();
12168        let (cursor_buffer, cursor_buffer_position) = self
12169            .buffer
12170            .read(cx)
12171            .text_anchor_for_position(selection.head(), cx)?;
12172        let (tail_buffer, cursor_buffer_position_end) = self
12173            .buffer
12174            .read(cx)
12175            .text_anchor_for_position(selection.tail(), cx)?;
12176        if tail_buffer != cursor_buffer {
12177            return None;
12178        }
12179
12180        let snapshot = cursor_buffer.read(cx).snapshot();
12181        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12182        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12183        let prepare_rename = provider
12184            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12185            .unwrap_or_else(|| Task::ready(Ok(None)));
12186        drop(snapshot);
12187
12188        Some(cx.spawn_in(window, |this, mut cx| async move {
12189            let rename_range = if let Some(range) = prepare_rename.await? {
12190                Some(range)
12191            } else {
12192                this.update(&mut cx, |this, cx| {
12193                    let buffer = this.buffer.read(cx).snapshot(cx);
12194                    let mut buffer_highlights = this
12195                        .document_highlights_for_position(selection.head(), &buffer)
12196                        .filter(|highlight| {
12197                            highlight.start.excerpt_id == selection.head().excerpt_id
12198                                && highlight.end.excerpt_id == selection.head().excerpt_id
12199                        });
12200                    buffer_highlights
12201                        .next()
12202                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12203                })?
12204            };
12205            if let Some(rename_range) = rename_range {
12206                this.update_in(&mut cx, |this, window, cx| {
12207                    let snapshot = cursor_buffer.read(cx).snapshot();
12208                    let rename_buffer_range = rename_range.to_offset(&snapshot);
12209                    let cursor_offset_in_rename_range =
12210                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12211                    let cursor_offset_in_rename_range_end =
12212                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12213
12214                    this.take_rename(false, window, cx);
12215                    let buffer = this.buffer.read(cx).read(cx);
12216                    let cursor_offset = selection.head().to_offset(&buffer);
12217                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12218                    let rename_end = rename_start + rename_buffer_range.len();
12219                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12220                    let mut old_highlight_id = None;
12221                    let old_name: Arc<str> = buffer
12222                        .chunks(rename_start..rename_end, true)
12223                        .map(|chunk| {
12224                            if old_highlight_id.is_none() {
12225                                old_highlight_id = chunk.syntax_highlight_id;
12226                            }
12227                            chunk.text
12228                        })
12229                        .collect::<String>()
12230                        .into();
12231
12232                    drop(buffer);
12233
12234                    // Position the selection in the rename editor so that it matches the current selection.
12235                    this.show_local_selections = false;
12236                    let rename_editor = cx.new(|cx| {
12237                        let mut editor = Editor::single_line(window, cx);
12238                        editor.buffer.update(cx, |buffer, cx| {
12239                            buffer.edit([(0..0, old_name.clone())], None, cx)
12240                        });
12241                        let rename_selection_range = match cursor_offset_in_rename_range
12242                            .cmp(&cursor_offset_in_rename_range_end)
12243                        {
12244                            Ordering::Equal => {
12245                                editor.select_all(&SelectAll, window, cx);
12246                                return editor;
12247                            }
12248                            Ordering::Less => {
12249                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12250                            }
12251                            Ordering::Greater => {
12252                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12253                            }
12254                        };
12255                        if rename_selection_range.end > old_name.len() {
12256                            editor.select_all(&SelectAll, window, cx);
12257                        } else {
12258                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12259                                s.select_ranges([rename_selection_range]);
12260                            });
12261                        }
12262                        editor
12263                    });
12264                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12265                        if e == &EditorEvent::Focused {
12266                            cx.emit(EditorEvent::FocusedIn)
12267                        }
12268                    })
12269                    .detach();
12270
12271                    let write_highlights =
12272                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12273                    let read_highlights =
12274                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
12275                    let ranges = write_highlights
12276                        .iter()
12277                        .flat_map(|(_, ranges)| ranges.iter())
12278                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12279                        .cloned()
12280                        .collect();
12281
12282                    this.highlight_text::<Rename>(
12283                        ranges,
12284                        HighlightStyle {
12285                            fade_out: Some(0.6),
12286                            ..Default::default()
12287                        },
12288                        cx,
12289                    );
12290                    let rename_focus_handle = rename_editor.focus_handle(cx);
12291                    window.focus(&rename_focus_handle);
12292                    let block_id = this.insert_blocks(
12293                        [BlockProperties {
12294                            style: BlockStyle::Flex,
12295                            placement: BlockPlacement::Below(range.start),
12296                            height: 1,
12297                            render: Arc::new({
12298                                let rename_editor = rename_editor.clone();
12299                                move |cx: &mut BlockContext| {
12300                                    let mut text_style = cx.editor_style.text.clone();
12301                                    if let Some(highlight_style) = old_highlight_id
12302                                        .and_then(|h| h.style(&cx.editor_style.syntax))
12303                                    {
12304                                        text_style = text_style.highlight(highlight_style);
12305                                    }
12306                                    div()
12307                                        .block_mouse_down()
12308                                        .pl(cx.anchor_x)
12309                                        .child(EditorElement::new(
12310                                            &rename_editor,
12311                                            EditorStyle {
12312                                                background: cx.theme().system().transparent,
12313                                                local_player: cx.editor_style.local_player,
12314                                                text: text_style,
12315                                                scrollbar_width: cx.editor_style.scrollbar_width,
12316                                                syntax: cx.editor_style.syntax.clone(),
12317                                                status: cx.editor_style.status.clone(),
12318                                                inlay_hints_style: HighlightStyle {
12319                                                    font_weight: Some(FontWeight::BOLD),
12320                                                    ..make_inlay_hints_style(cx.app)
12321                                                },
12322                                                inline_completion_styles: make_suggestion_styles(
12323                                                    cx.app,
12324                                                ),
12325                                                ..EditorStyle::default()
12326                                            },
12327                                        ))
12328                                        .into_any_element()
12329                                }
12330                            }),
12331                            priority: 0,
12332                        }],
12333                        Some(Autoscroll::fit()),
12334                        cx,
12335                    )[0];
12336                    this.pending_rename = Some(RenameState {
12337                        range,
12338                        old_name,
12339                        editor: rename_editor,
12340                        block_id,
12341                    });
12342                })?;
12343            }
12344
12345            Ok(())
12346        }))
12347    }
12348
12349    pub fn confirm_rename(
12350        &mut self,
12351        _: &ConfirmRename,
12352        window: &mut Window,
12353        cx: &mut Context<Self>,
12354    ) -> Option<Task<Result<()>>> {
12355        let rename = self.take_rename(false, window, cx)?;
12356        let workspace = self.workspace()?.downgrade();
12357        let (buffer, start) = self
12358            .buffer
12359            .read(cx)
12360            .text_anchor_for_position(rename.range.start, cx)?;
12361        let (end_buffer, _) = self
12362            .buffer
12363            .read(cx)
12364            .text_anchor_for_position(rename.range.end, cx)?;
12365        if buffer != end_buffer {
12366            return None;
12367        }
12368
12369        let old_name = rename.old_name;
12370        let new_name = rename.editor.read(cx).text(cx);
12371
12372        let rename = self.semantics_provider.as_ref()?.perform_rename(
12373            &buffer,
12374            start,
12375            new_name.clone(),
12376            cx,
12377        )?;
12378
12379        Some(cx.spawn_in(window, |editor, mut cx| async move {
12380            let project_transaction = rename.await?;
12381            Self::open_project_transaction(
12382                &editor,
12383                workspace,
12384                project_transaction,
12385                format!("Rename: {}{}", old_name, new_name),
12386                cx.clone(),
12387            )
12388            .await?;
12389
12390            editor.update(&mut cx, |editor, cx| {
12391                editor.refresh_document_highlights(cx);
12392            })?;
12393            Ok(())
12394        }))
12395    }
12396
12397    fn take_rename(
12398        &mut self,
12399        moving_cursor: bool,
12400        window: &mut Window,
12401        cx: &mut Context<Self>,
12402    ) -> Option<RenameState> {
12403        let rename = self.pending_rename.take()?;
12404        if rename.editor.focus_handle(cx).is_focused(window) {
12405            window.focus(&self.focus_handle);
12406        }
12407
12408        self.remove_blocks(
12409            [rename.block_id].into_iter().collect(),
12410            Some(Autoscroll::fit()),
12411            cx,
12412        );
12413        self.clear_highlights::<Rename>(cx);
12414        self.show_local_selections = true;
12415
12416        if moving_cursor {
12417            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12418                editor.selections.newest::<usize>(cx).head()
12419            });
12420
12421            // Update the selection to match the position of the selection inside
12422            // the rename editor.
12423            let snapshot = self.buffer.read(cx).read(cx);
12424            let rename_range = rename.range.to_offset(&snapshot);
12425            let cursor_in_editor = snapshot
12426                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12427                .min(rename_range.end);
12428            drop(snapshot);
12429
12430            self.change_selections(None, window, cx, |s| {
12431                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12432            });
12433        } else {
12434            self.refresh_document_highlights(cx);
12435        }
12436
12437        Some(rename)
12438    }
12439
12440    pub fn pending_rename(&self) -> Option<&RenameState> {
12441        self.pending_rename.as_ref()
12442    }
12443
12444    fn format(
12445        &mut self,
12446        _: &Format,
12447        window: &mut Window,
12448        cx: &mut Context<Self>,
12449    ) -> Option<Task<Result<()>>> {
12450        let project = match &self.project {
12451            Some(project) => project.clone(),
12452            None => return None,
12453        };
12454
12455        Some(self.perform_format(
12456            project,
12457            FormatTrigger::Manual,
12458            FormatTarget::Buffers,
12459            window,
12460            cx,
12461        ))
12462    }
12463
12464    fn format_selections(
12465        &mut self,
12466        _: &FormatSelections,
12467        window: &mut Window,
12468        cx: &mut Context<Self>,
12469    ) -> Option<Task<Result<()>>> {
12470        let project = match &self.project {
12471            Some(project) => project.clone(),
12472            None => return None,
12473        };
12474
12475        let ranges = self
12476            .selections
12477            .all_adjusted(cx)
12478            .into_iter()
12479            .map(|selection| selection.range())
12480            .collect_vec();
12481
12482        Some(self.perform_format(
12483            project,
12484            FormatTrigger::Manual,
12485            FormatTarget::Ranges(ranges),
12486            window,
12487            cx,
12488        ))
12489    }
12490
12491    fn perform_format(
12492        &mut self,
12493        project: Entity<Project>,
12494        trigger: FormatTrigger,
12495        target: FormatTarget,
12496        window: &mut Window,
12497        cx: &mut Context<Self>,
12498    ) -> Task<Result<()>> {
12499        let buffer = self.buffer.clone();
12500        let (buffers, target) = match target {
12501            FormatTarget::Buffers => {
12502                let mut buffers = buffer.read(cx).all_buffers();
12503                if trigger == FormatTrigger::Save {
12504                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
12505                }
12506                (buffers, LspFormatTarget::Buffers)
12507            }
12508            FormatTarget::Ranges(selection_ranges) => {
12509                let multi_buffer = buffer.read(cx);
12510                let snapshot = multi_buffer.read(cx);
12511                let mut buffers = HashSet::default();
12512                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12513                    BTreeMap::new();
12514                for selection_range in selection_ranges {
12515                    for (buffer, buffer_range, _) in
12516                        snapshot.range_to_buffer_ranges(selection_range)
12517                    {
12518                        let buffer_id = buffer.remote_id();
12519                        let start = buffer.anchor_before(buffer_range.start);
12520                        let end = buffer.anchor_after(buffer_range.end);
12521                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12522                        buffer_id_to_ranges
12523                            .entry(buffer_id)
12524                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12525                            .or_insert_with(|| vec![start..end]);
12526                    }
12527                }
12528                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12529            }
12530        };
12531
12532        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12533        let format = project.update(cx, |project, cx| {
12534            project.format(buffers, target, true, trigger, cx)
12535        });
12536
12537        cx.spawn_in(window, |_, mut cx| async move {
12538            let transaction = futures::select_biased! {
12539                () = timeout => {
12540                    log::warn!("timed out waiting for formatting");
12541                    None
12542                }
12543                transaction = format.log_err().fuse() => transaction,
12544            };
12545
12546            buffer
12547                .update(&mut cx, |buffer, cx| {
12548                    if let Some(transaction) = transaction {
12549                        if !buffer.is_singleton() {
12550                            buffer.push_transaction(&transaction.0, cx);
12551                        }
12552                    }
12553                    cx.notify();
12554                })
12555                .ok();
12556
12557            Ok(())
12558        })
12559    }
12560
12561    fn organize_imports(
12562        &mut self,
12563        _: &OrganizeImports,
12564        window: &mut Window,
12565        cx: &mut Context<Self>,
12566    ) -> Option<Task<Result<()>>> {
12567        let project = match &self.project {
12568            Some(project) => project.clone(),
12569            None => return None,
12570        };
12571        Some(self.perform_code_action_kind(
12572            project,
12573            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12574            window,
12575            cx,
12576        ))
12577    }
12578
12579    fn perform_code_action_kind(
12580        &mut self,
12581        project: Entity<Project>,
12582        kind: CodeActionKind,
12583        window: &mut Window,
12584        cx: &mut Context<Self>,
12585    ) -> Task<Result<()>> {
12586        let buffer = self.buffer.clone();
12587        let buffers = buffer.read(cx).all_buffers();
12588        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12589        let apply_action = project.update(cx, |project, cx| {
12590            project.apply_code_action_kind(buffers, kind, true, cx)
12591        });
12592        cx.spawn_in(window, |_, mut cx| async move {
12593            let transaction = futures::select_biased! {
12594                () = timeout => {
12595                    log::warn!("timed out waiting for executing code action");
12596                    None
12597                }
12598                transaction = apply_action.log_err().fuse() => transaction,
12599            };
12600            buffer
12601                .update(&mut cx, |buffer, cx| {
12602                    // check if we need this
12603                    if let Some(transaction) = transaction {
12604                        if !buffer.is_singleton() {
12605                            buffer.push_transaction(&transaction.0, cx);
12606                        }
12607                    }
12608                    cx.notify();
12609                })
12610                .ok();
12611            Ok(())
12612        })
12613    }
12614
12615    fn restart_language_server(
12616        &mut self,
12617        _: &RestartLanguageServer,
12618        _: &mut Window,
12619        cx: &mut Context<Self>,
12620    ) {
12621        if let Some(project) = self.project.clone() {
12622            self.buffer.update(cx, |multi_buffer, cx| {
12623                project.update(cx, |project, cx| {
12624                    project.restart_language_servers_for_buffers(
12625                        multi_buffer.all_buffers().into_iter().collect(),
12626                        cx,
12627                    );
12628                });
12629            })
12630        }
12631    }
12632
12633    fn cancel_language_server_work(
12634        workspace: &mut Workspace,
12635        _: &actions::CancelLanguageServerWork,
12636        _: &mut Window,
12637        cx: &mut Context<Workspace>,
12638    ) {
12639        let project = workspace.project();
12640        let buffers = workspace
12641            .active_item(cx)
12642            .and_then(|item| item.act_as::<Editor>(cx))
12643            .map_or(HashSet::default(), |editor| {
12644                editor.read(cx).buffer.read(cx).all_buffers()
12645            });
12646        project.update(cx, |project, cx| {
12647            project.cancel_language_server_work_for_buffers(buffers, cx);
12648        });
12649    }
12650
12651    fn show_character_palette(
12652        &mut self,
12653        _: &ShowCharacterPalette,
12654        window: &mut Window,
12655        _: &mut Context<Self>,
12656    ) {
12657        window.show_character_palette();
12658    }
12659
12660    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12661        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12662            let buffer = self.buffer.read(cx).snapshot(cx);
12663            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12664            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12665            let is_valid = buffer
12666                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12667                .any(|entry| {
12668                    entry.diagnostic.is_primary
12669                        && !entry.range.is_empty()
12670                        && entry.range.start == primary_range_start
12671                        && entry.diagnostic.message == active_diagnostics.primary_message
12672                });
12673
12674            if is_valid != active_diagnostics.is_valid {
12675                active_diagnostics.is_valid = is_valid;
12676                if is_valid {
12677                    let mut new_styles = HashMap::default();
12678                    for (block_id, diagnostic) in &active_diagnostics.blocks {
12679                        new_styles.insert(
12680                            *block_id,
12681                            diagnostic_block_renderer(diagnostic.clone(), None, true),
12682                        );
12683                    }
12684                    self.display_map.update(cx, |display_map, _cx| {
12685                        display_map.replace_blocks(new_styles);
12686                    });
12687                } else {
12688                    self.dismiss_diagnostics(cx);
12689                }
12690            }
12691        }
12692    }
12693
12694    fn activate_diagnostics(
12695        &mut self,
12696        buffer_id: BufferId,
12697        group_id: usize,
12698        window: &mut Window,
12699        cx: &mut Context<Self>,
12700    ) {
12701        self.dismiss_diagnostics(cx);
12702        let snapshot = self.snapshot(window, cx);
12703        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12704            let buffer = self.buffer.read(cx).snapshot(cx);
12705
12706            let mut primary_range = None;
12707            let mut primary_message = None;
12708            let diagnostic_group = buffer
12709                .diagnostic_group(buffer_id, group_id)
12710                .filter_map(|entry| {
12711                    let start = entry.range.start;
12712                    let end = entry.range.end;
12713                    if snapshot.is_line_folded(MultiBufferRow(start.row))
12714                        && (start.row == end.row
12715                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
12716                    {
12717                        return None;
12718                    }
12719                    if entry.diagnostic.is_primary {
12720                        primary_range = Some(entry.range.clone());
12721                        primary_message = Some(entry.diagnostic.message.clone());
12722                    }
12723                    Some(entry)
12724                })
12725                .collect::<Vec<_>>();
12726            let primary_range = primary_range?;
12727            let primary_message = primary_message?;
12728
12729            let blocks = display_map
12730                .insert_blocks(
12731                    diagnostic_group.iter().map(|entry| {
12732                        let diagnostic = entry.diagnostic.clone();
12733                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12734                        BlockProperties {
12735                            style: BlockStyle::Fixed,
12736                            placement: BlockPlacement::Below(
12737                                buffer.anchor_after(entry.range.start),
12738                            ),
12739                            height: message_height,
12740                            render: diagnostic_block_renderer(diagnostic, None, true),
12741                            priority: 0,
12742                        }
12743                    }),
12744                    cx,
12745                )
12746                .into_iter()
12747                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12748                .collect();
12749
12750            Some(ActiveDiagnosticGroup {
12751                primary_range: buffer.anchor_before(primary_range.start)
12752                    ..buffer.anchor_after(primary_range.end),
12753                primary_message,
12754                group_id,
12755                blocks,
12756                is_valid: true,
12757            })
12758        });
12759    }
12760
12761    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12762        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12763            self.display_map.update(cx, |display_map, cx| {
12764                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12765            });
12766            cx.notify();
12767        }
12768    }
12769
12770    /// Disable inline diagnostics rendering for this editor.
12771    pub fn disable_inline_diagnostics(&mut self) {
12772        self.inline_diagnostics_enabled = false;
12773        self.inline_diagnostics_update = Task::ready(());
12774        self.inline_diagnostics.clear();
12775    }
12776
12777    pub fn inline_diagnostics_enabled(&self) -> bool {
12778        self.inline_diagnostics_enabled
12779    }
12780
12781    pub fn show_inline_diagnostics(&self) -> bool {
12782        self.show_inline_diagnostics
12783    }
12784
12785    pub fn toggle_inline_diagnostics(
12786        &mut self,
12787        _: &ToggleInlineDiagnostics,
12788        window: &mut Window,
12789        cx: &mut Context<'_, Editor>,
12790    ) {
12791        self.show_inline_diagnostics = !self.show_inline_diagnostics;
12792        self.refresh_inline_diagnostics(false, window, cx);
12793    }
12794
12795    fn refresh_inline_diagnostics(
12796        &mut self,
12797        debounce: bool,
12798        window: &mut Window,
12799        cx: &mut Context<Self>,
12800    ) {
12801        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12802            self.inline_diagnostics_update = Task::ready(());
12803            self.inline_diagnostics.clear();
12804            return;
12805        }
12806
12807        let debounce_ms = ProjectSettings::get_global(cx)
12808            .diagnostics
12809            .inline
12810            .update_debounce_ms;
12811        let debounce = if debounce && debounce_ms > 0 {
12812            Some(Duration::from_millis(debounce_ms))
12813        } else {
12814            None
12815        };
12816        self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12817            if let Some(debounce) = debounce {
12818                cx.background_executor().timer(debounce).await;
12819            }
12820            let Some(snapshot) = editor
12821                .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12822                .ok()
12823            else {
12824                return;
12825            };
12826
12827            let new_inline_diagnostics = cx
12828                .background_spawn(async move {
12829                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12830                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12831                        let message = diagnostic_entry
12832                            .diagnostic
12833                            .message
12834                            .split_once('\n')
12835                            .map(|(line, _)| line)
12836                            .map(SharedString::new)
12837                            .unwrap_or_else(|| {
12838                                SharedString::from(diagnostic_entry.diagnostic.message)
12839                            });
12840                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12841                        let (Ok(i) | Err(i)) = inline_diagnostics
12842                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12843                        inline_diagnostics.insert(
12844                            i,
12845                            (
12846                                start_anchor,
12847                                InlineDiagnostic {
12848                                    message,
12849                                    group_id: diagnostic_entry.diagnostic.group_id,
12850                                    start: diagnostic_entry.range.start.to_point(&snapshot),
12851                                    is_primary: diagnostic_entry.diagnostic.is_primary,
12852                                    severity: diagnostic_entry.diagnostic.severity,
12853                                },
12854                            ),
12855                        );
12856                    }
12857                    inline_diagnostics
12858                })
12859                .await;
12860
12861            editor
12862                .update(&mut cx, |editor, cx| {
12863                    editor.inline_diagnostics = new_inline_diagnostics;
12864                    cx.notify();
12865                })
12866                .ok();
12867        });
12868    }
12869
12870    pub fn set_selections_from_remote(
12871        &mut self,
12872        selections: Vec<Selection<Anchor>>,
12873        pending_selection: Option<Selection<Anchor>>,
12874        window: &mut Window,
12875        cx: &mut Context<Self>,
12876    ) {
12877        let old_cursor_position = self.selections.newest_anchor().head();
12878        self.selections.change_with(cx, |s| {
12879            s.select_anchors(selections);
12880            if let Some(pending_selection) = pending_selection {
12881                s.set_pending(pending_selection, SelectMode::Character);
12882            } else {
12883                s.clear_pending();
12884            }
12885        });
12886        self.selections_did_change(false, &old_cursor_position, true, window, cx);
12887    }
12888
12889    fn push_to_selection_history(&mut self) {
12890        self.selection_history.push(SelectionHistoryEntry {
12891            selections: self.selections.disjoint_anchors(),
12892            select_next_state: self.select_next_state.clone(),
12893            select_prev_state: self.select_prev_state.clone(),
12894            add_selections_state: self.add_selections_state.clone(),
12895        });
12896    }
12897
12898    pub fn transact(
12899        &mut self,
12900        window: &mut Window,
12901        cx: &mut Context<Self>,
12902        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12903    ) -> Option<TransactionId> {
12904        self.start_transaction_at(Instant::now(), window, cx);
12905        update(self, window, cx);
12906        self.end_transaction_at(Instant::now(), cx)
12907    }
12908
12909    pub fn start_transaction_at(
12910        &mut self,
12911        now: Instant,
12912        window: &mut Window,
12913        cx: &mut Context<Self>,
12914    ) {
12915        self.end_selection(window, cx);
12916        if let Some(tx_id) = self
12917            .buffer
12918            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12919        {
12920            self.selection_history
12921                .insert_transaction(tx_id, self.selections.disjoint_anchors());
12922            cx.emit(EditorEvent::TransactionBegun {
12923                transaction_id: tx_id,
12924            })
12925        }
12926    }
12927
12928    pub fn end_transaction_at(
12929        &mut self,
12930        now: Instant,
12931        cx: &mut Context<Self>,
12932    ) -> Option<TransactionId> {
12933        if let Some(transaction_id) = self
12934            .buffer
12935            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12936        {
12937            if let Some((_, end_selections)) =
12938                self.selection_history.transaction_mut(transaction_id)
12939            {
12940                *end_selections = Some(self.selections.disjoint_anchors());
12941            } else {
12942                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12943            }
12944
12945            cx.emit(EditorEvent::Edited { transaction_id });
12946            Some(transaction_id)
12947        } else {
12948            None
12949        }
12950    }
12951
12952    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12953        if self.selection_mark_mode {
12954            self.change_selections(None, window, cx, |s| {
12955                s.move_with(|_, sel| {
12956                    sel.collapse_to(sel.head(), SelectionGoal::None);
12957                });
12958            })
12959        }
12960        self.selection_mark_mode = true;
12961        cx.notify();
12962    }
12963
12964    pub fn swap_selection_ends(
12965        &mut self,
12966        _: &actions::SwapSelectionEnds,
12967        window: &mut Window,
12968        cx: &mut Context<Self>,
12969    ) {
12970        self.change_selections(None, window, cx, |s| {
12971            s.move_with(|_, sel| {
12972                if sel.start != sel.end {
12973                    sel.reversed = !sel.reversed
12974                }
12975            });
12976        });
12977        self.request_autoscroll(Autoscroll::newest(), cx);
12978        cx.notify();
12979    }
12980
12981    pub fn toggle_fold(
12982        &mut self,
12983        _: &actions::ToggleFold,
12984        window: &mut Window,
12985        cx: &mut Context<Self>,
12986    ) {
12987        if self.is_singleton(cx) {
12988            let selection = self.selections.newest::<Point>(cx);
12989
12990            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12991            let range = if selection.is_empty() {
12992                let point = selection.head().to_display_point(&display_map);
12993                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12994                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12995                    .to_point(&display_map);
12996                start..end
12997            } else {
12998                selection.range()
12999            };
13000            if display_map.folds_in_range(range).next().is_some() {
13001                self.unfold_lines(&Default::default(), window, cx)
13002            } else {
13003                self.fold(&Default::default(), window, cx)
13004            }
13005        } else {
13006            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13007            let buffer_ids: HashSet<_> = self
13008                .selections
13009                .disjoint_anchor_ranges()
13010                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13011                .collect();
13012
13013            let should_unfold = buffer_ids
13014                .iter()
13015                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13016
13017            for buffer_id in buffer_ids {
13018                if should_unfold {
13019                    self.unfold_buffer(buffer_id, cx);
13020                } else {
13021                    self.fold_buffer(buffer_id, cx);
13022                }
13023            }
13024        }
13025    }
13026
13027    pub fn toggle_fold_recursive(
13028        &mut self,
13029        _: &actions::ToggleFoldRecursive,
13030        window: &mut Window,
13031        cx: &mut Context<Self>,
13032    ) {
13033        let selection = self.selections.newest::<Point>(cx);
13034
13035        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13036        let range = if selection.is_empty() {
13037            let point = selection.head().to_display_point(&display_map);
13038            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13039            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13040                .to_point(&display_map);
13041            start..end
13042        } else {
13043            selection.range()
13044        };
13045        if display_map.folds_in_range(range).next().is_some() {
13046            self.unfold_recursive(&Default::default(), window, cx)
13047        } else {
13048            self.fold_recursive(&Default::default(), window, cx)
13049        }
13050    }
13051
13052    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13053        if self.is_singleton(cx) {
13054            let mut to_fold = Vec::new();
13055            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13056            let selections = self.selections.all_adjusted(cx);
13057
13058            for selection in selections {
13059                let range = selection.range().sorted();
13060                let buffer_start_row = range.start.row;
13061
13062                if range.start.row != range.end.row {
13063                    let mut found = false;
13064                    let mut row = range.start.row;
13065                    while row <= range.end.row {
13066                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13067                        {
13068                            found = true;
13069                            row = crease.range().end.row + 1;
13070                            to_fold.push(crease);
13071                        } else {
13072                            row += 1
13073                        }
13074                    }
13075                    if found {
13076                        continue;
13077                    }
13078                }
13079
13080                for row in (0..=range.start.row).rev() {
13081                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13082                        if crease.range().end.row >= buffer_start_row {
13083                            to_fold.push(crease);
13084                            if row <= range.start.row {
13085                                break;
13086                            }
13087                        }
13088                    }
13089                }
13090            }
13091
13092            self.fold_creases(to_fold, true, window, cx);
13093        } else {
13094            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13095            let buffer_ids = self
13096                .selections
13097                .disjoint_anchor_ranges()
13098                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13099                .collect::<HashSet<_>>();
13100            for buffer_id in buffer_ids {
13101                self.fold_buffer(buffer_id, cx);
13102            }
13103        }
13104    }
13105
13106    fn fold_at_level(
13107        &mut self,
13108        fold_at: &FoldAtLevel,
13109        window: &mut Window,
13110        cx: &mut Context<Self>,
13111    ) {
13112        if !self.buffer.read(cx).is_singleton() {
13113            return;
13114        }
13115
13116        let fold_at_level = fold_at.0;
13117        let snapshot = self.buffer.read(cx).snapshot(cx);
13118        let mut to_fold = Vec::new();
13119        let mut stack = vec![(0, snapshot.max_row().0, 1)];
13120
13121        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13122            while start_row < end_row {
13123                match self
13124                    .snapshot(window, cx)
13125                    .crease_for_buffer_row(MultiBufferRow(start_row))
13126                {
13127                    Some(crease) => {
13128                        let nested_start_row = crease.range().start.row + 1;
13129                        let nested_end_row = crease.range().end.row;
13130
13131                        if current_level < fold_at_level {
13132                            stack.push((nested_start_row, nested_end_row, current_level + 1));
13133                        } else if current_level == fold_at_level {
13134                            to_fold.push(crease);
13135                        }
13136
13137                        start_row = nested_end_row + 1;
13138                    }
13139                    None => start_row += 1,
13140                }
13141            }
13142        }
13143
13144        self.fold_creases(to_fold, true, window, cx);
13145    }
13146
13147    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13148        if self.buffer.read(cx).is_singleton() {
13149            let mut fold_ranges = Vec::new();
13150            let snapshot = self.buffer.read(cx).snapshot(cx);
13151
13152            for row in 0..snapshot.max_row().0 {
13153                if let Some(foldable_range) = self
13154                    .snapshot(window, cx)
13155                    .crease_for_buffer_row(MultiBufferRow(row))
13156                {
13157                    fold_ranges.push(foldable_range);
13158                }
13159            }
13160
13161            self.fold_creases(fold_ranges, true, window, cx);
13162        } else {
13163            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13164                editor
13165                    .update_in(&mut cx, |editor, _, cx| {
13166                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13167                            editor.fold_buffer(buffer_id, cx);
13168                        }
13169                    })
13170                    .ok();
13171            });
13172        }
13173    }
13174
13175    pub fn fold_function_bodies(
13176        &mut self,
13177        _: &actions::FoldFunctionBodies,
13178        window: &mut Window,
13179        cx: &mut Context<Self>,
13180    ) {
13181        let snapshot = self.buffer.read(cx).snapshot(cx);
13182
13183        let ranges = snapshot
13184            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13185            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13186            .collect::<Vec<_>>();
13187
13188        let creases = ranges
13189            .into_iter()
13190            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13191            .collect();
13192
13193        self.fold_creases(creases, true, window, cx);
13194    }
13195
13196    pub fn fold_recursive(
13197        &mut self,
13198        _: &actions::FoldRecursive,
13199        window: &mut Window,
13200        cx: &mut Context<Self>,
13201    ) {
13202        let mut to_fold = Vec::new();
13203        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13204        let selections = self.selections.all_adjusted(cx);
13205
13206        for selection in selections {
13207            let range = selection.range().sorted();
13208            let buffer_start_row = range.start.row;
13209
13210            if range.start.row != range.end.row {
13211                let mut found = false;
13212                for row in range.start.row..=range.end.row {
13213                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13214                        found = true;
13215                        to_fold.push(crease);
13216                    }
13217                }
13218                if found {
13219                    continue;
13220                }
13221            }
13222
13223            for row in (0..=range.start.row).rev() {
13224                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13225                    if crease.range().end.row >= buffer_start_row {
13226                        to_fold.push(crease);
13227                    } else {
13228                        break;
13229                    }
13230                }
13231            }
13232        }
13233
13234        self.fold_creases(to_fold, true, window, cx);
13235    }
13236
13237    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13238        let buffer_row = fold_at.buffer_row;
13239        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13240
13241        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13242            let autoscroll = self
13243                .selections
13244                .all::<Point>(cx)
13245                .iter()
13246                .any(|selection| crease.range().overlaps(&selection.range()));
13247
13248            self.fold_creases(vec![crease], autoscroll, window, cx);
13249        }
13250    }
13251
13252    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13253        if self.is_singleton(cx) {
13254            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13255            let buffer = &display_map.buffer_snapshot;
13256            let selections = self.selections.all::<Point>(cx);
13257            let ranges = selections
13258                .iter()
13259                .map(|s| {
13260                    let range = s.display_range(&display_map).sorted();
13261                    let mut start = range.start.to_point(&display_map);
13262                    let mut end = range.end.to_point(&display_map);
13263                    start.column = 0;
13264                    end.column = buffer.line_len(MultiBufferRow(end.row));
13265                    start..end
13266                })
13267                .collect::<Vec<_>>();
13268
13269            self.unfold_ranges(&ranges, true, true, cx);
13270        } else {
13271            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13272            let buffer_ids = self
13273                .selections
13274                .disjoint_anchor_ranges()
13275                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13276                .collect::<HashSet<_>>();
13277            for buffer_id in buffer_ids {
13278                self.unfold_buffer(buffer_id, cx);
13279            }
13280        }
13281    }
13282
13283    pub fn unfold_recursive(
13284        &mut self,
13285        _: &UnfoldRecursive,
13286        _window: &mut Window,
13287        cx: &mut Context<Self>,
13288    ) {
13289        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13290        let selections = self.selections.all::<Point>(cx);
13291        let ranges = selections
13292            .iter()
13293            .map(|s| {
13294                let mut range = s.display_range(&display_map).sorted();
13295                *range.start.column_mut() = 0;
13296                *range.end.column_mut() = display_map.line_len(range.end.row());
13297                let start = range.start.to_point(&display_map);
13298                let end = range.end.to_point(&display_map);
13299                start..end
13300            })
13301            .collect::<Vec<_>>();
13302
13303        self.unfold_ranges(&ranges, true, true, cx);
13304    }
13305
13306    pub fn unfold_at(
13307        &mut self,
13308        unfold_at: &UnfoldAt,
13309        _window: &mut Window,
13310        cx: &mut Context<Self>,
13311    ) {
13312        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13313
13314        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13315            ..Point::new(
13316                unfold_at.buffer_row.0,
13317                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13318            );
13319
13320        let autoscroll = self
13321            .selections
13322            .all::<Point>(cx)
13323            .iter()
13324            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13325
13326        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13327    }
13328
13329    pub fn unfold_all(
13330        &mut self,
13331        _: &actions::UnfoldAll,
13332        _window: &mut Window,
13333        cx: &mut Context<Self>,
13334    ) {
13335        if self.buffer.read(cx).is_singleton() {
13336            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13337            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13338        } else {
13339            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13340                editor
13341                    .update(&mut cx, |editor, cx| {
13342                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13343                            editor.unfold_buffer(buffer_id, cx);
13344                        }
13345                    })
13346                    .ok();
13347            });
13348        }
13349    }
13350
13351    pub fn fold_selected_ranges(
13352        &mut self,
13353        _: &FoldSelectedRanges,
13354        window: &mut Window,
13355        cx: &mut Context<Self>,
13356    ) {
13357        let selections = self.selections.all::<Point>(cx);
13358        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13359        let line_mode = self.selections.line_mode;
13360        let ranges = selections
13361            .into_iter()
13362            .map(|s| {
13363                if line_mode {
13364                    let start = Point::new(s.start.row, 0);
13365                    let end = Point::new(
13366                        s.end.row,
13367                        display_map
13368                            .buffer_snapshot
13369                            .line_len(MultiBufferRow(s.end.row)),
13370                    );
13371                    Crease::simple(start..end, display_map.fold_placeholder.clone())
13372                } else {
13373                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13374                }
13375            })
13376            .collect::<Vec<_>>();
13377        self.fold_creases(ranges, true, window, cx);
13378    }
13379
13380    pub fn fold_ranges<T: ToOffset + Clone>(
13381        &mut self,
13382        ranges: Vec<Range<T>>,
13383        auto_scroll: bool,
13384        window: &mut Window,
13385        cx: &mut Context<Self>,
13386    ) {
13387        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13388        let ranges = ranges
13389            .into_iter()
13390            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13391            .collect::<Vec<_>>();
13392        self.fold_creases(ranges, auto_scroll, window, cx);
13393    }
13394
13395    pub fn fold_creases<T: ToOffset + Clone>(
13396        &mut self,
13397        creases: Vec<Crease<T>>,
13398        auto_scroll: bool,
13399        window: &mut Window,
13400        cx: &mut Context<Self>,
13401    ) {
13402        if creases.is_empty() {
13403            return;
13404        }
13405
13406        let mut buffers_affected = HashSet::default();
13407        let multi_buffer = self.buffer().read(cx);
13408        for crease in &creases {
13409            if let Some((_, buffer, _)) =
13410                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13411            {
13412                buffers_affected.insert(buffer.read(cx).remote_id());
13413            };
13414        }
13415
13416        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13417
13418        if auto_scroll {
13419            self.request_autoscroll(Autoscroll::fit(), cx);
13420        }
13421
13422        cx.notify();
13423
13424        if let Some(active_diagnostics) = self.active_diagnostics.take() {
13425            // Clear diagnostics block when folding a range that contains it.
13426            let snapshot = self.snapshot(window, cx);
13427            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13428                drop(snapshot);
13429                self.active_diagnostics = Some(active_diagnostics);
13430                self.dismiss_diagnostics(cx);
13431            } else {
13432                self.active_diagnostics = Some(active_diagnostics);
13433            }
13434        }
13435
13436        self.scrollbar_marker_state.dirty = true;
13437    }
13438
13439    /// Removes any folds whose ranges intersect any of the given ranges.
13440    pub fn unfold_ranges<T: ToOffset + Clone>(
13441        &mut self,
13442        ranges: &[Range<T>],
13443        inclusive: bool,
13444        auto_scroll: bool,
13445        cx: &mut Context<Self>,
13446    ) {
13447        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13448            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13449        });
13450    }
13451
13452    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13453        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13454            return;
13455        }
13456        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13457        self.display_map.update(cx, |display_map, cx| {
13458            display_map.fold_buffers([buffer_id], cx)
13459        });
13460        cx.emit(EditorEvent::BufferFoldToggled {
13461            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13462            folded: true,
13463        });
13464        cx.notify();
13465    }
13466
13467    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13468        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13469            return;
13470        }
13471        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13472        self.display_map.update(cx, |display_map, cx| {
13473            display_map.unfold_buffers([buffer_id], cx);
13474        });
13475        cx.emit(EditorEvent::BufferFoldToggled {
13476            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13477            folded: false,
13478        });
13479        cx.notify();
13480    }
13481
13482    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13483        self.display_map.read(cx).is_buffer_folded(buffer)
13484    }
13485
13486    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13487        self.display_map.read(cx).folded_buffers()
13488    }
13489
13490    /// Removes any folds with the given ranges.
13491    pub fn remove_folds_with_type<T: ToOffset + Clone>(
13492        &mut self,
13493        ranges: &[Range<T>],
13494        type_id: TypeId,
13495        auto_scroll: bool,
13496        cx: &mut Context<Self>,
13497    ) {
13498        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13499            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13500        });
13501    }
13502
13503    fn remove_folds_with<T: ToOffset + Clone>(
13504        &mut self,
13505        ranges: &[Range<T>],
13506        auto_scroll: bool,
13507        cx: &mut Context<Self>,
13508        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13509    ) {
13510        if ranges.is_empty() {
13511            return;
13512        }
13513
13514        let mut buffers_affected = HashSet::default();
13515        let multi_buffer = self.buffer().read(cx);
13516        for range in ranges {
13517            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13518                buffers_affected.insert(buffer.read(cx).remote_id());
13519            };
13520        }
13521
13522        self.display_map.update(cx, update);
13523
13524        if auto_scroll {
13525            self.request_autoscroll(Autoscroll::fit(), cx);
13526        }
13527
13528        cx.notify();
13529        self.scrollbar_marker_state.dirty = true;
13530        self.active_indent_guides_state.dirty = true;
13531    }
13532
13533    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13534        self.display_map.read(cx).fold_placeholder.clone()
13535    }
13536
13537    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13538        self.buffer.update(cx, |buffer, cx| {
13539            buffer.set_all_diff_hunks_expanded(cx);
13540        });
13541    }
13542
13543    pub fn expand_all_diff_hunks(
13544        &mut self,
13545        _: &ExpandAllDiffHunks,
13546        _window: &mut Window,
13547        cx: &mut Context<Self>,
13548    ) {
13549        self.buffer.update(cx, |buffer, cx| {
13550            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13551        });
13552    }
13553
13554    pub fn toggle_selected_diff_hunks(
13555        &mut self,
13556        _: &ToggleSelectedDiffHunks,
13557        _window: &mut Window,
13558        cx: &mut Context<Self>,
13559    ) {
13560        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13561        self.toggle_diff_hunks_in_ranges(ranges, cx);
13562    }
13563
13564    pub fn diff_hunks_in_ranges<'a>(
13565        &'a self,
13566        ranges: &'a [Range<Anchor>],
13567        buffer: &'a MultiBufferSnapshot,
13568    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13569        ranges.iter().flat_map(move |range| {
13570            let end_excerpt_id = range.end.excerpt_id;
13571            let range = range.to_point(buffer);
13572            let mut peek_end = range.end;
13573            if range.end.row < buffer.max_row().0 {
13574                peek_end = Point::new(range.end.row + 1, 0);
13575            }
13576            buffer
13577                .diff_hunks_in_range(range.start..peek_end)
13578                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13579        })
13580    }
13581
13582    pub fn has_stageable_diff_hunks_in_ranges(
13583        &self,
13584        ranges: &[Range<Anchor>],
13585        snapshot: &MultiBufferSnapshot,
13586    ) -> bool {
13587        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13588        hunks.any(|hunk| hunk.status().has_secondary_hunk())
13589    }
13590
13591    pub fn toggle_staged_selected_diff_hunks(
13592        &mut self,
13593        _: &::git::ToggleStaged,
13594        _: &mut Window,
13595        cx: &mut Context<Self>,
13596    ) {
13597        let snapshot = self.buffer.read(cx).snapshot(cx);
13598        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13599        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13600        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13601    }
13602
13603    pub fn stage_and_next(
13604        &mut self,
13605        _: &::git::StageAndNext,
13606        window: &mut Window,
13607        cx: &mut Context<Self>,
13608    ) {
13609        self.do_stage_or_unstage_and_next(true, window, cx);
13610    }
13611
13612    pub fn unstage_and_next(
13613        &mut self,
13614        _: &::git::UnstageAndNext,
13615        window: &mut Window,
13616        cx: &mut Context<Self>,
13617    ) {
13618        self.do_stage_or_unstage_and_next(false, window, cx);
13619    }
13620
13621    pub fn stage_or_unstage_diff_hunks(
13622        &mut self,
13623        stage: bool,
13624        ranges: Vec<Range<Anchor>>,
13625        cx: &mut Context<Self>,
13626    ) {
13627        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
13628        cx.spawn(|this, mut cx| async move {
13629            task.await?;
13630            this.update(&mut cx, |this, cx| {
13631                let snapshot = this.buffer.read(cx).snapshot(cx);
13632                let chunk_by = this
13633                    .diff_hunks_in_ranges(&ranges, &snapshot)
13634                    .chunk_by(|hunk| hunk.buffer_id);
13635                for (buffer_id, hunks) in &chunk_by {
13636                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
13637                }
13638            })
13639        })
13640        .detach_and_log_err(cx);
13641    }
13642
13643    fn save_buffers_for_ranges_if_needed(
13644        &mut self,
13645        ranges: &[Range<Anchor>],
13646        cx: &mut Context<'_, Editor>,
13647    ) -> Task<Result<()>> {
13648        let multibuffer = self.buffer.read(cx);
13649        let snapshot = multibuffer.read(cx);
13650        let buffer_ids: HashSet<_> = ranges
13651            .iter()
13652            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
13653            .collect();
13654        drop(snapshot);
13655
13656        let mut buffers = HashSet::default();
13657        for buffer_id in buffer_ids {
13658            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
13659                let buffer = buffer_entity.read(cx);
13660                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
13661                {
13662                    buffers.insert(buffer_entity);
13663                }
13664            }
13665        }
13666
13667        if let Some(project) = &self.project {
13668            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
13669        } else {
13670            Task::ready(Ok(()))
13671        }
13672    }
13673
13674    fn do_stage_or_unstage_and_next(
13675        &mut self,
13676        stage: bool,
13677        window: &mut Window,
13678        cx: &mut Context<Self>,
13679    ) {
13680        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13681
13682        if ranges.iter().any(|range| range.start != range.end) {
13683            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13684            return;
13685        }
13686
13687        let snapshot = self.snapshot(window, cx);
13688        let newest_range = self.selections.newest::<Point>(cx).range();
13689
13690        let run_twice = snapshot
13691            .hunks_for_ranges([newest_range])
13692            .first()
13693            .is_some_and(|hunk| {
13694                let next_line = Point::new(hunk.row_range.end.0 + 1, 0);
13695                self.hunk_after_position(&snapshot, next_line)
13696                    .is_some_and(|other| other.row_range == hunk.row_range)
13697            });
13698
13699        if run_twice {
13700            self.go_to_next_hunk(&GoToHunk, window, cx);
13701        }
13702        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13703        self.go_to_next_hunk(&GoToHunk, window, cx);
13704    }
13705
13706    fn do_stage_or_unstage(
13707        &self,
13708        stage: bool,
13709        buffer_id: BufferId,
13710        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13711        cx: &mut App,
13712    ) -> Option<()> {
13713        let project = self.project.as_ref()?;
13714        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
13715        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
13716        let buffer_snapshot = buffer.read(cx).snapshot();
13717        let file_exists = buffer_snapshot
13718            .file()
13719            .is_some_and(|file| file.disk_state().exists());
13720        diff.update(cx, |diff, cx| {
13721            diff.stage_or_unstage_hunks(
13722                stage,
13723                &hunks
13724                    .map(|hunk| buffer_diff::DiffHunk {
13725                        buffer_range: hunk.buffer_range,
13726                        diff_base_byte_range: hunk.diff_base_byte_range,
13727                        secondary_status: hunk.secondary_status,
13728                        range: Point::zero()..Point::zero(), // unused
13729                    })
13730                    .collect::<Vec<_>>(),
13731                &buffer_snapshot,
13732                file_exists,
13733                cx,
13734            )
13735        });
13736        None
13737    }
13738
13739    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13740        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13741        self.buffer
13742            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13743    }
13744
13745    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13746        self.buffer.update(cx, |buffer, cx| {
13747            let ranges = vec![Anchor::min()..Anchor::max()];
13748            if !buffer.all_diff_hunks_expanded()
13749                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13750            {
13751                buffer.collapse_diff_hunks(ranges, cx);
13752                true
13753            } else {
13754                false
13755            }
13756        })
13757    }
13758
13759    fn toggle_diff_hunks_in_ranges(
13760        &mut self,
13761        ranges: Vec<Range<Anchor>>,
13762        cx: &mut Context<'_, Editor>,
13763    ) {
13764        self.buffer.update(cx, |buffer, cx| {
13765            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13766            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13767        })
13768    }
13769
13770    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13771        self.buffer.update(cx, |buffer, cx| {
13772            let snapshot = buffer.snapshot(cx);
13773            let excerpt_id = range.end.excerpt_id;
13774            let point_range = range.to_point(&snapshot);
13775            let expand = !buffer.single_hunk_is_expanded(range, cx);
13776            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13777        })
13778    }
13779
13780    pub(crate) fn apply_all_diff_hunks(
13781        &mut self,
13782        _: &ApplyAllDiffHunks,
13783        window: &mut Window,
13784        cx: &mut Context<Self>,
13785    ) {
13786        let buffers = self.buffer.read(cx).all_buffers();
13787        for branch_buffer in buffers {
13788            branch_buffer.update(cx, |branch_buffer, cx| {
13789                branch_buffer.merge_into_base(Vec::new(), cx);
13790            });
13791        }
13792
13793        if let Some(project) = self.project.clone() {
13794            self.save(true, project, window, cx).detach_and_log_err(cx);
13795        }
13796    }
13797
13798    pub(crate) fn apply_selected_diff_hunks(
13799        &mut self,
13800        _: &ApplyDiffHunk,
13801        window: &mut Window,
13802        cx: &mut Context<Self>,
13803    ) {
13804        let snapshot = self.snapshot(window, cx);
13805        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
13806        let mut ranges_by_buffer = HashMap::default();
13807        self.transact(window, cx, |editor, _window, cx| {
13808            for hunk in hunks {
13809                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13810                    ranges_by_buffer
13811                        .entry(buffer.clone())
13812                        .or_insert_with(Vec::new)
13813                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13814                }
13815            }
13816
13817            for (buffer, ranges) in ranges_by_buffer {
13818                buffer.update(cx, |buffer, cx| {
13819                    buffer.merge_into_base(ranges, cx);
13820                });
13821            }
13822        });
13823
13824        if let Some(project) = self.project.clone() {
13825            self.save(true, project, window, cx).detach_and_log_err(cx);
13826        }
13827    }
13828
13829    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13830        if hovered != self.gutter_hovered {
13831            self.gutter_hovered = hovered;
13832            cx.notify();
13833        }
13834    }
13835
13836    pub fn insert_blocks(
13837        &mut self,
13838        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13839        autoscroll: Option<Autoscroll>,
13840        cx: &mut Context<Self>,
13841    ) -> Vec<CustomBlockId> {
13842        let blocks = self
13843            .display_map
13844            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13845        if let Some(autoscroll) = autoscroll {
13846            self.request_autoscroll(autoscroll, cx);
13847        }
13848        cx.notify();
13849        blocks
13850    }
13851
13852    pub fn resize_blocks(
13853        &mut self,
13854        heights: HashMap<CustomBlockId, u32>,
13855        autoscroll: Option<Autoscroll>,
13856        cx: &mut Context<Self>,
13857    ) {
13858        self.display_map
13859            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13860        if let Some(autoscroll) = autoscroll {
13861            self.request_autoscroll(autoscroll, cx);
13862        }
13863        cx.notify();
13864    }
13865
13866    pub fn replace_blocks(
13867        &mut self,
13868        renderers: HashMap<CustomBlockId, RenderBlock>,
13869        autoscroll: Option<Autoscroll>,
13870        cx: &mut Context<Self>,
13871    ) {
13872        self.display_map
13873            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13874        if let Some(autoscroll) = autoscroll {
13875            self.request_autoscroll(autoscroll, cx);
13876        }
13877        cx.notify();
13878    }
13879
13880    pub fn remove_blocks(
13881        &mut self,
13882        block_ids: HashSet<CustomBlockId>,
13883        autoscroll: Option<Autoscroll>,
13884        cx: &mut Context<Self>,
13885    ) {
13886        self.display_map.update(cx, |display_map, cx| {
13887            display_map.remove_blocks(block_ids, cx)
13888        });
13889        if let Some(autoscroll) = autoscroll {
13890            self.request_autoscroll(autoscroll, cx);
13891        }
13892        cx.notify();
13893    }
13894
13895    pub fn row_for_block(
13896        &self,
13897        block_id: CustomBlockId,
13898        cx: &mut Context<Self>,
13899    ) -> Option<DisplayRow> {
13900        self.display_map
13901            .update(cx, |map, cx| map.row_for_block(block_id, cx))
13902    }
13903
13904    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13905        self.focused_block = Some(focused_block);
13906    }
13907
13908    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13909        self.focused_block.take()
13910    }
13911
13912    pub fn insert_creases(
13913        &mut self,
13914        creases: impl IntoIterator<Item = Crease<Anchor>>,
13915        cx: &mut Context<Self>,
13916    ) -> Vec<CreaseId> {
13917        self.display_map
13918            .update(cx, |map, cx| map.insert_creases(creases, cx))
13919    }
13920
13921    pub fn remove_creases(
13922        &mut self,
13923        ids: impl IntoIterator<Item = CreaseId>,
13924        cx: &mut Context<Self>,
13925    ) {
13926        self.display_map
13927            .update(cx, |map, cx| map.remove_creases(ids, cx));
13928    }
13929
13930    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13931        self.display_map
13932            .update(cx, |map, cx| map.snapshot(cx))
13933            .longest_row()
13934    }
13935
13936    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13937        self.display_map
13938            .update(cx, |map, cx| map.snapshot(cx))
13939            .max_point()
13940    }
13941
13942    pub fn text(&self, cx: &App) -> String {
13943        self.buffer.read(cx).read(cx).text()
13944    }
13945
13946    pub fn is_empty(&self, cx: &App) -> bool {
13947        self.buffer.read(cx).read(cx).is_empty()
13948    }
13949
13950    pub fn text_option(&self, cx: &App) -> Option<String> {
13951        let text = self.text(cx);
13952        let text = text.trim();
13953
13954        if text.is_empty() {
13955            return None;
13956        }
13957
13958        Some(text.to_string())
13959    }
13960
13961    pub fn set_text(
13962        &mut self,
13963        text: impl Into<Arc<str>>,
13964        window: &mut Window,
13965        cx: &mut Context<Self>,
13966    ) {
13967        self.transact(window, cx, |this, _, cx| {
13968            this.buffer
13969                .read(cx)
13970                .as_singleton()
13971                .expect("you can only call set_text on editors for singleton buffers")
13972                .update(cx, |buffer, cx| buffer.set_text(text, cx));
13973        });
13974    }
13975
13976    pub fn display_text(&self, cx: &mut App) -> String {
13977        self.display_map
13978            .update(cx, |map, cx| map.snapshot(cx))
13979            .text()
13980    }
13981
13982    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
13983        let mut wrap_guides = smallvec::smallvec![];
13984
13985        if self.show_wrap_guides == Some(false) {
13986            return wrap_guides;
13987        }
13988
13989        let settings = self.buffer.read(cx).settings_at(0, cx);
13990        if settings.show_wrap_guides {
13991            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
13992                wrap_guides.push((soft_wrap as usize, true));
13993            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
13994                wrap_guides.push((soft_wrap as usize, true));
13995            }
13996            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
13997        }
13998
13999        wrap_guides
14000    }
14001
14002    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14003        let settings = self.buffer.read(cx).settings_at(0, cx);
14004        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14005        match mode {
14006            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14007                SoftWrap::None
14008            }
14009            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14010            language_settings::SoftWrap::PreferredLineLength => {
14011                SoftWrap::Column(settings.preferred_line_length)
14012            }
14013            language_settings::SoftWrap::Bounded => {
14014                SoftWrap::Bounded(settings.preferred_line_length)
14015            }
14016        }
14017    }
14018
14019    pub fn set_soft_wrap_mode(
14020        &mut self,
14021        mode: language_settings::SoftWrap,
14022
14023        cx: &mut Context<Self>,
14024    ) {
14025        self.soft_wrap_mode_override = Some(mode);
14026        cx.notify();
14027    }
14028
14029    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14030        self.text_style_refinement = Some(style);
14031    }
14032
14033    /// called by the Element so we know what style we were most recently rendered with.
14034    pub(crate) fn set_style(
14035        &mut self,
14036        style: EditorStyle,
14037        window: &mut Window,
14038        cx: &mut Context<Self>,
14039    ) {
14040        let rem_size = window.rem_size();
14041        self.display_map.update(cx, |map, cx| {
14042            map.set_font(
14043                style.text.font(),
14044                style.text.font_size.to_pixels(rem_size),
14045                cx,
14046            )
14047        });
14048        self.style = Some(style);
14049    }
14050
14051    pub fn style(&self) -> Option<&EditorStyle> {
14052        self.style.as_ref()
14053    }
14054
14055    // Called by the element. This method is not designed to be called outside of the editor
14056    // element's layout code because it does not notify when rewrapping is computed synchronously.
14057    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14058        self.display_map
14059            .update(cx, |map, cx| map.set_wrap_width(width, cx))
14060    }
14061
14062    pub fn set_soft_wrap(&mut self) {
14063        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14064    }
14065
14066    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14067        if self.soft_wrap_mode_override.is_some() {
14068            self.soft_wrap_mode_override.take();
14069        } else {
14070            let soft_wrap = match self.soft_wrap_mode(cx) {
14071                SoftWrap::GitDiff => return,
14072                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14073                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14074                    language_settings::SoftWrap::None
14075                }
14076            };
14077            self.soft_wrap_mode_override = Some(soft_wrap);
14078        }
14079        cx.notify();
14080    }
14081
14082    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14083        let Some(workspace) = self.workspace() else {
14084            return;
14085        };
14086        let fs = workspace.read(cx).app_state().fs.clone();
14087        let current_show = TabBarSettings::get_global(cx).show;
14088        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14089            setting.show = Some(!current_show);
14090        });
14091    }
14092
14093    pub fn toggle_indent_guides(
14094        &mut self,
14095        _: &ToggleIndentGuides,
14096        _: &mut Window,
14097        cx: &mut Context<Self>,
14098    ) {
14099        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14100            self.buffer
14101                .read(cx)
14102                .settings_at(0, cx)
14103                .indent_guides
14104                .enabled
14105        });
14106        self.show_indent_guides = Some(!currently_enabled);
14107        cx.notify();
14108    }
14109
14110    fn should_show_indent_guides(&self) -> Option<bool> {
14111        self.show_indent_guides
14112    }
14113
14114    pub fn toggle_line_numbers(
14115        &mut self,
14116        _: &ToggleLineNumbers,
14117        _: &mut Window,
14118        cx: &mut Context<Self>,
14119    ) {
14120        let mut editor_settings = EditorSettings::get_global(cx).clone();
14121        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14122        EditorSettings::override_global(editor_settings, cx);
14123    }
14124
14125    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14126        self.use_relative_line_numbers
14127            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14128    }
14129
14130    pub fn toggle_relative_line_numbers(
14131        &mut self,
14132        _: &ToggleRelativeLineNumbers,
14133        _: &mut Window,
14134        cx: &mut Context<Self>,
14135    ) {
14136        let is_relative = self.should_use_relative_line_numbers(cx);
14137        self.set_relative_line_number(Some(!is_relative), cx)
14138    }
14139
14140    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14141        self.use_relative_line_numbers = is_relative;
14142        cx.notify();
14143    }
14144
14145    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14146        self.show_gutter = show_gutter;
14147        cx.notify();
14148    }
14149
14150    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14151        self.show_scrollbars = show_scrollbars;
14152        cx.notify();
14153    }
14154
14155    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14156        self.show_line_numbers = Some(show_line_numbers);
14157        cx.notify();
14158    }
14159
14160    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14161        self.show_git_diff_gutter = Some(show_git_diff_gutter);
14162        cx.notify();
14163    }
14164
14165    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14166        self.show_code_actions = Some(show_code_actions);
14167        cx.notify();
14168    }
14169
14170    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14171        self.show_runnables = Some(show_runnables);
14172        cx.notify();
14173    }
14174
14175    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14176        if self.display_map.read(cx).masked != masked {
14177            self.display_map.update(cx, |map, _| map.masked = masked);
14178        }
14179        cx.notify()
14180    }
14181
14182    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14183        self.show_wrap_guides = Some(show_wrap_guides);
14184        cx.notify();
14185    }
14186
14187    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14188        self.show_indent_guides = Some(show_indent_guides);
14189        cx.notify();
14190    }
14191
14192    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14193        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14194            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14195                if let Some(dir) = file.abs_path(cx).parent() {
14196                    return Some(dir.to_owned());
14197                }
14198            }
14199
14200            if let Some(project_path) = buffer.read(cx).project_path(cx) {
14201                return Some(project_path.path.to_path_buf());
14202            }
14203        }
14204
14205        None
14206    }
14207
14208    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14209        self.active_excerpt(cx)?
14210            .1
14211            .read(cx)
14212            .file()
14213            .and_then(|f| f.as_local())
14214    }
14215
14216    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14217        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14218            let buffer = buffer.read(cx);
14219            if let Some(project_path) = buffer.project_path(cx) {
14220                let project = self.project.as_ref()?.read(cx);
14221                project.absolute_path(&project_path, cx)
14222            } else {
14223                buffer
14224                    .file()
14225                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14226            }
14227        })
14228    }
14229
14230    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14231        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14232            let project_path = buffer.read(cx).project_path(cx)?;
14233            let project = self.project.as_ref()?.read(cx);
14234            let entry = project.entry_for_path(&project_path, cx)?;
14235            let path = entry.path.to_path_buf();
14236            Some(path)
14237        })
14238    }
14239
14240    pub fn reveal_in_finder(
14241        &mut self,
14242        _: &RevealInFileManager,
14243        _window: &mut Window,
14244        cx: &mut Context<Self>,
14245    ) {
14246        if let Some(target) = self.target_file(cx) {
14247            cx.reveal_path(&target.abs_path(cx));
14248        }
14249    }
14250
14251    pub fn copy_path(
14252        &mut self,
14253        _: &zed_actions::workspace::CopyPath,
14254        _window: &mut Window,
14255        cx: &mut Context<Self>,
14256    ) {
14257        if let Some(path) = self.target_file_abs_path(cx) {
14258            if let Some(path) = path.to_str() {
14259                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14260            }
14261        }
14262    }
14263
14264    pub fn copy_relative_path(
14265        &mut self,
14266        _: &zed_actions::workspace::CopyRelativePath,
14267        _window: &mut Window,
14268        cx: &mut Context<Self>,
14269    ) {
14270        if let Some(path) = self.target_file_path(cx) {
14271            if let Some(path) = path.to_str() {
14272                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14273            }
14274        }
14275    }
14276
14277    pub fn copy_file_name_without_extension(
14278        &mut self,
14279        _: &CopyFileNameWithoutExtension,
14280        _: &mut Window,
14281        cx: &mut Context<Self>,
14282    ) {
14283        if let Some(file) = self.target_file(cx) {
14284            if let Some(file_stem) = file.path().file_stem() {
14285                if let Some(name) = file_stem.to_str() {
14286                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14287                }
14288            }
14289        }
14290    }
14291
14292    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14293        if let Some(file) = self.target_file(cx) {
14294            if let Some(file_name) = file.path().file_name() {
14295                if let Some(name) = file_name.to_str() {
14296                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14297                }
14298            }
14299        }
14300    }
14301
14302    pub fn toggle_git_blame(
14303        &mut self,
14304        _: &ToggleGitBlame,
14305        window: &mut Window,
14306        cx: &mut Context<Self>,
14307    ) {
14308        self.show_git_blame_gutter = !self.show_git_blame_gutter;
14309
14310        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14311            self.start_git_blame(true, window, cx);
14312        }
14313
14314        cx.notify();
14315    }
14316
14317    pub fn toggle_git_blame_inline(
14318        &mut self,
14319        _: &ToggleGitBlameInline,
14320        window: &mut Window,
14321        cx: &mut Context<Self>,
14322    ) {
14323        self.toggle_git_blame_inline_internal(true, window, cx);
14324        cx.notify();
14325    }
14326
14327    pub fn git_blame_inline_enabled(&self) -> bool {
14328        self.git_blame_inline_enabled
14329    }
14330
14331    pub fn toggle_selection_menu(
14332        &mut self,
14333        _: &ToggleSelectionMenu,
14334        _: &mut Window,
14335        cx: &mut Context<Self>,
14336    ) {
14337        self.show_selection_menu = self
14338            .show_selection_menu
14339            .map(|show_selections_menu| !show_selections_menu)
14340            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14341
14342        cx.notify();
14343    }
14344
14345    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14346        self.show_selection_menu
14347            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14348    }
14349
14350    fn start_git_blame(
14351        &mut self,
14352        user_triggered: bool,
14353        window: &mut Window,
14354        cx: &mut Context<Self>,
14355    ) {
14356        if let Some(project) = self.project.as_ref() {
14357            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14358                return;
14359            };
14360
14361            if buffer.read(cx).file().is_none() {
14362                return;
14363            }
14364
14365            let focused = self.focus_handle(cx).contains_focused(window, cx);
14366
14367            let project = project.clone();
14368            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14369            self.blame_subscription =
14370                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14371            self.blame = Some(blame);
14372        }
14373    }
14374
14375    fn toggle_git_blame_inline_internal(
14376        &mut self,
14377        user_triggered: bool,
14378        window: &mut Window,
14379        cx: &mut Context<Self>,
14380    ) {
14381        if self.git_blame_inline_enabled {
14382            self.git_blame_inline_enabled = false;
14383            self.show_git_blame_inline = false;
14384            self.show_git_blame_inline_delay_task.take();
14385        } else {
14386            self.git_blame_inline_enabled = true;
14387            self.start_git_blame_inline(user_triggered, window, cx);
14388        }
14389
14390        cx.notify();
14391    }
14392
14393    fn start_git_blame_inline(
14394        &mut self,
14395        user_triggered: bool,
14396        window: &mut Window,
14397        cx: &mut Context<Self>,
14398    ) {
14399        self.start_git_blame(user_triggered, window, cx);
14400
14401        if ProjectSettings::get_global(cx)
14402            .git
14403            .inline_blame_delay()
14404            .is_some()
14405        {
14406            self.start_inline_blame_timer(window, cx);
14407        } else {
14408            self.show_git_blame_inline = true
14409        }
14410    }
14411
14412    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14413        self.blame.as_ref()
14414    }
14415
14416    pub fn show_git_blame_gutter(&self) -> bool {
14417        self.show_git_blame_gutter
14418    }
14419
14420    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14421        self.show_git_blame_gutter && self.has_blame_entries(cx)
14422    }
14423
14424    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14425        self.show_git_blame_inline
14426            && (self.focus_handle.is_focused(window)
14427                || self
14428                    .git_blame_inline_tooltip
14429                    .as_ref()
14430                    .and_then(|t| t.upgrade())
14431                    .is_some())
14432            && !self.newest_selection_head_on_empty_line(cx)
14433            && self.has_blame_entries(cx)
14434    }
14435
14436    fn has_blame_entries(&self, cx: &App) -> bool {
14437        self.blame()
14438            .map_or(false, |blame| blame.read(cx).has_generated_entries())
14439    }
14440
14441    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14442        let cursor_anchor = self.selections.newest_anchor().head();
14443
14444        let snapshot = self.buffer.read(cx).snapshot(cx);
14445        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14446
14447        snapshot.line_len(buffer_row) == 0
14448    }
14449
14450    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14451        let buffer_and_selection = maybe!({
14452            let selection = self.selections.newest::<Point>(cx);
14453            let selection_range = selection.range();
14454
14455            let multi_buffer = self.buffer().read(cx);
14456            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14457            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14458
14459            let (buffer, range, _) = if selection.reversed {
14460                buffer_ranges.first()
14461            } else {
14462                buffer_ranges.last()
14463            }?;
14464
14465            let selection = text::ToPoint::to_point(&range.start, &buffer).row
14466                ..text::ToPoint::to_point(&range.end, &buffer).row;
14467            Some((
14468                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14469                selection,
14470            ))
14471        });
14472
14473        let Some((buffer, selection)) = buffer_and_selection else {
14474            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14475        };
14476
14477        let Some(project) = self.project.as_ref() else {
14478            return Task::ready(Err(anyhow!("editor does not have project")));
14479        };
14480
14481        project.update(cx, |project, cx| {
14482            project.get_permalink_to_line(&buffer, selection, cx)
14483        })
14484    }
14485
14486    pub fn copy_permalink_to_line(
14487        &mut self,
14488        _: &CopyPermalinkToLine,
14489        window: &mut Window,
14490        cx: &mut Context<Self>,
14491    ) {
14492        let permalink_task = self.get_permalink_to_line(cx);
14493        let workspace = self.workspace();
14494
14495        cx.spawn_in(window, |_, mut cx| async move {
14496            match permalink_task.await {
14497                Ok(permalink) => {
14498                    cx.update(|_, cx| {
14499                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14500                    })
14501                    .ok();
14502                }
14503                Err(err) => {
14504                    let message = format!("Failed to copy permalink: {err}");
14505
14506                    Err::<(), anyhow::Error>(err).log_err();
14507
14508                    if let Some(workspace) = workspace {
14509                        workspace
14510                            .update_in(&mut cx, |workspace, _, cx| {
14511                                struct CopyPermalinkToLine;
14512
14513                                workspace.show_toast(
14514                                    Toast::new(
14515                                        NotificationId::unique::<CopyPermalinkToLine>(),
14516                                        message,
14517                                    ),
14518                                    cx,
14519                                )
14520                            })
14521                            .ok();
14522                    }
14523                }
14524            }
14525        })
14526        .detach();
14527    }
14528
14529    pub fn copy_file_location(
14530        &mut self,
14531        _: &CopyFileLocation,
14532        _: &mut Window,
14533        cx: &mut Context<Self>,
14534    ) {
14535        let selection = self.selections.newest::<Point>(cx).start.row + 1;
14536        if let Some(file) = self.target_file(cx) {
14537            if let Some(path) = file.path().to_str() {
14538                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14539            }
14540        }
14541    }
14542
14543    pub fn open_permalink_to_line(
14544        &mut self,
14545        _: &OpenPermalinkToLine,
14546        window: &mut Window,
14547        cx: &mut Context<Self>,
14548    ) {
14549        let permalink_task = self.get_permalink_to_line(cx);
14550        let workspace = self.workspace();
14551
14552        cx.spawn_in(window, |_, mut cx| async move {
14553            match permalink_task.await {
14554                Ok(permalink) => {
14555                    cx.update(|_, cx| {
14556                        cx.open_url(permalink.as_ref());
14557                    })
14558                    .ok();
14559                }
14560                Err(err) => {
14561                    let message = format!("Failed to open permalink: {err}");
14562
14563                    Err::<(), anyhow::Error>(err).log_err();
14564
14565                    if let Some(workspace) = workspace {
14566                        workspace
14567                            .update(&mut cx, |workspace, cx| {
14568                                struct OpenPermalinkToLine;
14569
14570                                workspace.show_toast(
14571                                    Toast::new(
14572                                        NotificationId::unique::<OpenPermalinkToLine>(),
14573                                        message,
14574                                    ),
14575                                    cx,
14576                                )
14577                            })
14578                            .ok();
14579                    }
14580                }
14581            }
14582        })
14583        .detach();
14584    }
14585
14586    pub fn insert_uuid_v4(
14587        &mut self,
14588        _: &InsertUuidV4,
14589        window: &mut Window,
14590        cx: &mut Context<Self>,
14591    ) {
14592        self.insert_uuid(UuidVersion::V4, window, cx);
14593    }
14594
14595    pub fn insert_uuid_v7(
14596        &mut self,
14597        _: &InsertUuidV7,
14598        window: &mut Window,
14599        cx: &mut Context<Self>,
14600    ) {
14601        self.insert_uuid(UuidVersion::V7, window, cx);
14602    }
14603
14604    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14605        self.transact(window, cx, |this, window, cx| {
14606            let edits = this
14607                .selections
14608                .all::<Point>(cx)
14609                .into_iter()
14610                .map(|selection| {
14611                    let uuid = match version {
14612                        UuidVersion::V4 => uuid::Uuid::new_v4(),
14613                        UuidVersion::V7 => uuid::Uuid::now_v7(),
14614                    };
14615
14616                    (selection.range(), uuid.to_string())
14617                });
14618            this.edit(edits, cx);
14619            this.refresh_inline_completion(true, false, window, cx);
14620        });
14621    }
14622
14623    pub fn open_selections_in_multibuffer(
14624        &mut self,
14625        _: &OpenSelectionsInMultibuffer,
14626        window: &mut Window,
14627        cx: &mut Context<Self>,
14628    ) {
14629        let multibuffer = self.buffer.read(cx);
14630
14631        let Some(buffer) = multibuffer.as_singleton() else {
14632            return;
14633        };
14634
14635        let Some(workspace) = self.workspace() else {
14636            return;
14637        };
14638
14639        let locations = self
14640            .selections
14641            .disjoint_anchors()
14642            .iter()
14643            .map(|range| Location {
14644                buffer: buffer.clone(),
14645                range: range.start.text_anchor..range.end.text_anchor,
14646            })
14647            .collect::<Vec<_>>();
14648
14649        let title = multibuffer.title(cx).to_string();
14650
14651        cx.spawn_in(window, |_, mut cx| async move {
14652            workspace.update_in(&mut cx, |workspace, window, cx| {
14653                Self::open_locations_in_multibuffer(
14654                    workspace,
14655                    locations,
14656                    format!("Selections for '{title}'"),
14657                    false,
14658                    MultibufferSelectionMode::All,
14659                    window,
14660                    cx,
14661                );
14662            })
14663        })
14664        .detach();
14665    }
14666
14667    /// Adds a row highlight for the given range. If a row has multiple highlights, the
14668    /// last highlight added will be used.
14669    ///
14670    /// If the range ends at the beginning of a line, then that line will not be highlighted.
14671    pub fn highlight_rows<T: 'static>(
14672        &mut self,
14673        range: Range<Anchor>,
14674        color: Hsla,
14675        should_autoscroll: bool,
14676        cx: &mut Context<Self>,
14677    ) {
14678        let snapshot = self.buffer().read(cx).snapshot(cx);
14679        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14680        let ix = row_highlights.binary_search_by(|highlight| {
14681            Ordering::Equal
14682                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14683                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14684        });
14685
14686        if let Err(mut ix) = ix {
14687            let index = post_inc(&mut self.highlight_order);
14688
14689            // If this range intersects with the preceding highlight, then merge it with
14690            // the preceding highlight. Otherwise insert a new highlight.
14691            let mut merged = false;
14692            if ix > 0 {
14693                let prev_highlight = &mut row_highlights[ix - 1];
14694                if prev_highlight
14695                    .range
14696                    .end
14697                    .cmp(&range.start, &snapshot)
14698                    .is_ge()
14699                {
14700                    ix -= 1;
14701                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14702                        prev_highlight.range.end = range.end;
14703                    }
14704                    merged = true;
14705                    prev_highlight.index = index;
14706                    prev_highlight.color = color;
14707                    prev_highlight.should_autoscroll = should_autoscroll;
14708                }
14709            }
14710
14711            if !merged {
14712                row_highlights.insert(
14713                    ix,
14714                    RowHighlight {
14715                        range: range.clone(),
14716                        index,
14717                        color,
14718                        should_autoscroll,
14719                    },
14720                );
14721            }
14722
14723            // If any of the following highlights intersect with this one, merge them.
14724            while let Some(next_highlight) = row_highlights.get(ix + 1) {
14725                let highlight = &row_highlights[ix];
14726                if next_highlight
14727                    .range
14728                    .start
14729                    .cmp(&highlight.range.end, &snapshot)
14730                    .is_le()
14731                {
14732                    if next_highlight
14733                        .range
14734                        .end
14735                        .cmp(&highlight.range.end, &snapshot)
14736                        .is_gt()
14737                    {
14738                        row_highlights[ix].range.end = next_highlight.range.end;
14739                    }
14740                    row_highlights.remove(ix + 1);
14741                } else {
14742                    break;
14743                }
14744            }
14745        }
14746    }
14747
14748    /// Remove any highlighted row ranges of the given type that intersect the
14749    /// given ranges.
14750    pub fn remove_highlighted_rows<T: 'static>(
14751        &mut self,
14752        ranges_to_remove: Vec<Range<Anchor>>,
14753        cx: &mut Context<Self>,
14754    ) {
14755        let snapshot = self.buffer().read(cx).snapshot(cx);
14756        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14757        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14758        row_highlights.retain(|highlight| {
14759            while let Some(range_to_remove) = ranges_to_remove.peek() {
14760                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14761                    Ordering::Less | Ordering::Equal => {
14762                        ranges_to_remove.next();
14763                    }
14764                    Ordering::Greater => {
14765                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14766                            Ordering::Less | Ordering::Equal => {
14767                                return false;
14768                            }
14769                            Ordering::Greater => break,
14770                        }
14771                    }
14772                }
14773            }
14774
14775            true
14776        })
14777    }
14778
14779    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14780    pub fn clear_row_highlights<T: 'static>(&mut self) {
14781        self.highlighted_rows.remove(&TypeId::of::<T>());
14782    }
14783
14784    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14785    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14786        self.highlighted_rows
14787            .get(&TypeId::of::<T>())
14788            .map_or(&[] as &[_], |vec| vec.as_slice())
14789            .iter()
14790            .map(|highlight| (highlight.range.clone(), highlight.color))
14791    }
14792
14793    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14794    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14795    /// Allows to ignore certain kinds of highlights.
14796    pub fn highlighted_display_rows(
14797        &self,
14798        window: &mut Window,
14799        cx: &mut App,
14800    ) -> BTreeMap<DisplayRow, Background> {
14801        let snapshot = self.snapshot(window, cx);
14802        let mut used_highlight_orders = HashMap::default();
14803        self.highlighted_rows
14804            .iter()
14805            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14806            .fold(
14807                BTreeMap::<DisplayRow, Background>::new(),
14808                |mut unique_rows, highlight| {
14809                    let start = highlight.range.start.to_display_point(&snapshot);
14810                    let end = highlight.range.end.to_display_point(&snapshot);
14811                    let start_row = start.row().0;
14812                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14813                        && end.column() == 0
14814                    {
14815                        end.row().0.saturating_sub(1)
14816                    } else {
14817                        end.row().0
14818                    };
14819                    for row in start_row..=end_row {
14820                        let used_index =
14821                            used_highlight_orders.entry(row).or_insert(highlight.index);
14822                        if highlight.index >= *used_index {
14823                            *used_index = highlight.index;
14824                            unique_rows.insert(DisplayRow(row), highlight.color.into());
14825                        }
14826                    }
14827                    unique_rows
14828                },
14829            )
14830    }
14831
14832    pub fn highlighted_display_row_for_autoscroll(
14833        &self,
14834        snapshot: &DisplaySnapshot,
14835    ) -> Option<DisplayRow> {
14836        self.highlighted_rows
14837            .values()
14838            .flat_map(|highlighted_rows| highlighted_rows.iter())
14839            .filter_map(|highlight| {
14840                if highlight.should_autoscroll {
14841                    Some(highlight.range.start.to_display_point(snapshot).row())
14842                } else {
14843                    None
14844                }
14845            })
14846            .min()
14847    }
14848
14849    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14850        self.highlight_background::<SearchWithinRange>(
14851            ranges,
14852            |colors| colors.editor_document_highlight_read_background,
14853            cx,
14854        )
14855    }
14856
14857    pub fn set_breadcrumb_header(&mut self, new_header: String) {
14858        self.breadcrumb_header = Some(new_header);
14859    }
14860
14861    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14862        self.clear_background_highlights::<SearchWithinRange>(cx);
14863    }
14864
14865    pub fn highlight_background<T: 'static>(
14866        &mut self,
14867        ranges: &[Range<Anchor>],
14868        color_fetcher: fn(&ThemeColors) -> Hsla,
14869        cx: &mut Context<Self>,
14870    ) {
14871        self.background_highlights
14872            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14873        self.scrollbar_marker_state.dirty = true;
14874        cx.notify();
14875    }
14876
14877    pub fn clear_background_highlights<T: 'static>(
14878        &mut self,
14879        cx: &mut Context<Self>,
14880    ) -> Option<BackgroundHighlight> {
14881        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14882        if !text_highlights.1.is_empty() {
14883            self.scrollbar_marker_state.dirty = true;
14884            cx.notify();
14885        }
14886        Some(text_highlights)
14887    }
14888
14889    pub fn highlight_gutter<T: 'static>(
14890        &mut self,
14891        ranges: &[Range<Anchor>],
14892        color_fetcher: fn(&App) -> Hsla,
14893        cx: &mut Context<Self>,
14894    ) {
14895        self.gutter_highlights
14896            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14897        cx.notify();
14898    }
14899
14900    pub fn clear_gutter_highlights<T: 'static>(
14901        &mut self,
14902        cx: &mut Context<Self>,
14903    ) -> Option<GutterHighlight> {
14904        cx.notify();
14905        self.gutter_highlights.remove(&TypeId::of::<T>())
14906    }
14907
14908    #[cfg(feature = "test-support")]
14909    pub fn all_text_background_highlights(
14910        &self,
14911        window: &mut Window,
14912        cx: &mut Context<Self>,
14913    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14914        let snapshot = self.snapshot(window, cx);
14915        let buffer = &snapshot.buffer_snapshot;
14916        let start = buffer.anchor_before(0);
14917        let end = buffer.anchor_after(buffer.len());
14918        let theme = cx.theme().colors();
14919        self.background_highlights_in_range(start..end, &snapshot, theme)
14920    }
14921
14922    #[cfg(feature = "test-support")]
14923    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14924        let snapshot = self.buffer().read(cx).snapshot(cx);
14925
14926        let highlights = self
14927            .background_highlights
14928            .get(&TypeId::of::<items::BufferSearchHighlights>());
14929
14930        if let Some((_color, ranges)) = highlights {
14931            ranges
14932                .iter()
14933                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14934                .collect_vec()
14935        } else {
14936            vec![]
14937        }
14938    }
14939
14940    fn document_highlights_for_position<'a>(
14941        &'a self,
14942        position: Anchor,
14943        buffer: &'a MultiBufferSnapshot,
14944    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
14945        let read_highlights = self
14946            .background_highlights
14947            .get(&TypeId::of::<DocumentHighlightRead>())
14948            .map(|h| &h.1);
14949        let write_highlights = self
14950            .background_highlights
14951            .get(&TypeId::of::<DocumentHighlightWrite>())
14952            .map(|h| &h.1);
14953        let left_position = position.bias_left(buffer);
14954        let right_position = position.bias_right(buffer);
14955        read_highlights
14956            .into_iter()
14957            .chain(write_highlights)
14958            .flat_map(move |ranges| {
14959                let start_ix = match ranges.binary_search_by(|probe| {
14960                    let cmp = probe.end.cmp(&left_position, buffer);
14961                    if cmp.is_ge() {
14962                        Ordering::Greater
14963                    } else {
14964                        Ordering::Less
14965                    }
14966                }) {
14967                    Ok(i) | Err(i) => i,
14968                };
14969
14970                ranges[start_ix..]
14971                    .iter()
14972                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
14973            })
14974    }
14975
14976    pub fn has_background_highlights<T: 'static>(&self) -> bool {
14977        self.background_highlights
14978            .get(&TypeId::of::<T>())
14979            .map_or(false, |(_, highlights)| !highlights.is_empty())
14980    }
14981
14982    pub fn background_highlights_in_range(
14983        &self,
14984        search_range: Range<Anchor>,
14985        display_snapshot: &DisplaySnapshot,
14986        theme: &ThemeColors,
14987    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14988        let mut results = Vec::new();
14989        for (color_fetcher, ranges) in self.background_highlights.values() {
14990            let color = color_fetcher(theme);
14991            let start_ix = match ranges.binary_search_by(|probe| {
14992                let cmp = probe
14993                    .end
14994                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14995                if cmp.is_gt() {
14996                    Ordering::Greater
14997                } else {
14998                    Ordering::Less
14999                }
15000            }) {
15001                Ok(i) | Err(i) => i,
15002            };
15003            for range in &ranges[start_ix..] {
15004                if range
15005                    .start
15006                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15007                    .is_ge()
15008                {
15009                    break;
15010                }
15011
15012                let start = range.start.to_display_point(display_snapshot);
15013                let end = range.end.to_display_point(display_snapshot);
15014                results.push((start..end, color))
15015            }
15016        }
15017        results
15018    }
15019
15020    pub fn background_highlight_row_ranges<T: 'static>(
15021        &self,
15022        search_range: Range<Anchor>,
15023        display_snapshot: &DisplaySnapshot,
15024        count: usize,
15025    ) -> Vec<RangeInclusive<DisplayPoint>> {
15026        let mut results = Vec::new();
15027        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15028            return vec![];
15029        };
15030
15031        let start_ix = match ranges.binary_search_by(|probe| {
15032            let cmp = probe
15033                .end
15034                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15035            if cmp.is_gt() {
15036                Ordering::Greater
15037            } else {
15038                Ordering::Less
15039            }
15040        }) {
15041            Ok(i) | Err(i) => i,
15042        };
15043        let mut push_region = |start: Option<Point>, end: Option<Point>| {
15044            if let (Some(start_display), Some(end_display)) = (start, end) {
15045                results.push(
15046                    start_display.to_display_point(display_snapshot)
15047                        ..=end_display.to_display_point(display_snapshot),
15048                );
15049            }
15050        };
15051        let mut start_row: Option<Point> = None;
15052        let mut end_row: Option<Point> = None;
15053        if ranges.len() > count {
15054            return Vec::new();
15055        }
15056        for range in &ranges[start_ix..] {
15057            if range
15058                .start
15059                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15060                .is_ge()
15061            {
15062                break;
15063            }
15064            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15065            if let Some(current_row) = &end_row {
15066                if end.row == current_row.row {
15067                    continue;
15068                }
15069            }
15070            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15071            if start_row.is_none() {
15072                assert_eq!(end_row, None);
15073                start_row = Some(start);
15074                end_row = Some(end);
15075                continue;
15076            }
15077            if let Some(current_end) = end_row.as_mut() {
15078                if start.row > current_end.row + 1 {
15079                    push_region(start_row, end_row);
15080                    start_row = Some(start);
15081                    end_row = Some(end);
15082                } else {
15083                    // Merge two hunks.
15084                    *current_end = end;
15085                }
15086            } else {
15087                unreachable!();
15088            }
15089        }
15090        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15091        push_region(start_row, end_row);
15092        results
15093    }
15094
15095    pub fn gutter_highlights_in_range(
15096        &self,
15097        search_range: Range<Anchor>,
15098        display_snapshot: &DisplaySnapshot,
15099        cx: &App,
15100    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15101        let mut results = Vec::new();
15102        for (color_fetcher, ranges) in self.gutter_highlights.values() {
15103            let color = color_fetcher(cx);
15104            let start_ix = match ranges.binary_search_by(|probe| {
15105                let cmp = probe
15106                    .end
15107                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15108                if cmp.is_gt() {
15109                    Ordering::Greater
15110                } else {
15111                    Ordering::Less
15112                }
15113            }) {
15114                Ok(i) | Err(i) => i,
15115            };
15116            for range in &ranges[start_ix..] {
15117                if range
15118                    .start
15119                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15120                    .is_ge()
15121                {
15122                    break;
15123                }
15124
15125                let start = range.start.to_display_point(display_snapshot);
15126                let end = range.end.to_display_point(display_snapshot);
15127                results.push((start..end, color))
15128            }
15129        }
15130        results
15131    }
15132
15133    /// Get the text ranges corresponding to the redaction query
15134    pub fn redacted_ranges(
15135        &self,
15136        search_range: Range<Anchor>,
15137        display_snapshot: &DisplaySnapshot,
15138        cx: &App,
15139    ) -> Vec<Range<DisplayPoint>> {
15140        display_snapshot
15141            .buffer_snapshot
15142            .redacted_ranges(search_range, |file| {
15143                if let Some(file) = file {
15144                    file.is_private()
15145                        && EditorSettings::get(
15146                            Some(SettingsLocation {
15147                                worktree_id: file.worktree_id(cx),
15148                                path: file.path().as_ref(),
15149                            }),
15150                            cx,
15151                        )
15152                        .redact_private_values
15153                } else {
15154                    false
15155                }
15156            })
15157            .map(|range| {
15158                range.start.to_display_point(display_snapshot)
15159                    ..range.end.to_display_point(display_snapshot)
15160            })
15161            .collect()
15162    }
15163
15164    pub fn highlight_text<T: 'static>(
15165        &mut self,
15166        ranges: Vec<Range<Anchor>>,
15167        style: HighlightStyle,
15168        cx: &mut Context<Self>,
15169    ) {
15170        self.display_map.update(cx, |map, _| {
15171            map.highlight_text(TypeId::of::<T>(), ranges, style)
15172        });
15173        cx.notify();
15174    }
15175
15176    pub(crate) fn highlight_inlays<T: 'static>(
15177        &mut self,
15178        highlights: Vec<InlayHighlight>,
15179        style: HighlightStyle,
15180        cx: &mut Context<Self>,
15181    ) {
15182        self.display_map.update(cx, |map, _| {
15183            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15184        });
15185        cx.notify();
15186    }
15187
15188    pub fn text_highlights<'a, T: 'static>(
15189        &'a self,
15190        cx: &'a App,
15191    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15192        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15193    }
15194
15195    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15196        let cleared = self
15197            .display_map
15198            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15199        if cleared {
15200            cx.notify();
15201        }
15202    }
15203
15204    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15205        (self.read_only(cx) || self.blink_manager.read(cx).visible())
15206            && self.focus_handle.is_focused(window)
15207    }
15208
15209    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15210        self.show_cursor_when_unfocused = is_enabled;
15211        cx.notify();
15212    }
15213
15214    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15215        cx.notify();
15216    }
15217
15218    fn on_buffer_event(
15219        &mut self,
15220        multibuffer: &Entity<MultiBuffer>,
15221        event: &multi_buffer::Event,
15222        window: &mut Window,
15223        cx: &mut Context<Self>,
15224    ) {
15225        match event {
15226            multi_buffer::Event::Edited {
15227                singleton_buffer_edited,
15228                edited_buffer: buffer_edited,
15229            } => {
15230                self.scrollbar_marker_state.dirty = true;
15231                self.active_indent_guides_state.dirty = true;
15232                self.refresh_active_diagnostics(cx);
15233                self.refresh_code_actions(window, cx);
15234                if self.has_active_inline_completion() {
15235                    self.update_visible_inline_completion(window, cx);
15236                }
15237                if let Some(buffer) = buffer_edited {
15238                    let buffer_id = buffer.read(cx).remote_id();
15239                    if !self.registered_buffers.contains_key(&buffer_id) {
15240                        if let Some(project) = self.project.as_ref() {
15241                            project.update(cx, |project, cx| {
15242                                self.registered_buffers.insert(
15243                                    buffer_id,
15244                                    project.register_buffer_with_language_servers(&buffer, cx),
15245                                );
15246                            })
15247                        }
15248                    }
15249                }
15250                cx.emit(EditorEvent::BufferEdited);
15251                cx.emit(SearchEvent::MatchesInvalidated);
15252                if *singleton_buffer_edited {
15253                    if let Some(project) = &self.project {
15254                        #[allow(clippy::mutable_key_type)]
15255                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15256                            multibuffer
15257                                .all_buffers()
15258                                .into_iter()
15259                                .filter_map(|buffer| {
15260                                    buffer.update(cx, |buffer, cx| {
15261                                        let language = buffer.language()?;
15262                                        let should_discard = project.update(cx, |project, cx| {
15263                                            project.is_local()
15264                                                && !project.has_language_servers_for(buffer, cx)
15265                                        });
15266                                        should_discard.not().then_some(language.clone())
15267                                    })
15268                                })
15269                                .collect::<HashSet<_>>()
15270                        });
15271                        if !languages_affected.is_empty() {
15272                            self.refresh_inlay_hints(
15273                                InlayHintRefreshReason::BufferEdited(languages_affected),
15274                                cx,
15275                            );
15276                        }
15277                    }
15278                }
15279
15280                let Some(project) = &self.project else { return };
15281                let (telemetry, is_via_ssh) = {
15282                    let project = project.read(cx);
15283                    let telemetry = project.client().telemetry().clone();
15284                    let is_via_ssh = project.is_via_ssh();
15285                    (telemetry, is_via_ssh)
15286                };
15287                refresh_linked_ranges(self, window, cx);
15288                telemetry.log_edit_event("editor", is_via_ssh);
15289            }
15290            multi_buffer::Event::ExcerptsAdded {
15291                buffer,
15292                predecessor,
15293                excerpts,
15294            } => {
15295                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15296                let buffer_id = buffer.read(cx).remote_id();
15297                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15298                    if let Some(project) = &self.project {
15299                        get_uncommitted_diff_for_buffer(
15300                            project,
15301                            [buffer.clone()],
15302                            self.buffer.clone(),
15303                            cx,
15304                        )
15305                        .detach();
15306                    }
15307                }
15308                cx.emit(EditorEvent::ExcerptsAdded {
15309                    buffer: buffer.clone(),
15310                    predecessor: *predecessor,
15311                    excerpts: excerpts.clone(),
15312                });
15313                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15314            }
15315            multi_buffer::Event::ExcerptsRemoved { ids } => {
15316                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15317                let buffer = self.buffer.read(cx);
15318                self.registered_buffers
15319                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15320                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15321            }
15322            multi_buffer::Event::ExcerptsEdited {
15323                excerpt_ids,
15324                buffer_ids,
15325            } => {
15326                self.display_map.update(cx, |map, cx| {
15327                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
15328                });
15329                cx.emit(EditorEvent::ExcerptsEdited {
15330                    ids: excerpt_ids.clone(),
15331                })
15332            }
15333            multi_buffer::Event::ExcerptsExpanded { ids } => {
15334                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15335                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15336            }
15337            multi_buffer::Event::Reparsed(buffer_id) => {
15338                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15339
15340                cx.emit(EditorEvent::Reparsed(*buffer_id));
15341            }
15342            multi_buffer::Event::DiffHunksToggled => {
15343                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15344            }
15345            multi_buffer::Event::LanguageChanged(buffer_id) => {
15346                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15347                cx.emit(EditorEvent::Reparsed(*buffer_id));
15348                cx.notify();
15349            }
15350            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15351            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15352            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15353                cx.emit(EditorEvent::TitleChanged)
15354            }
15355            // multi_buffer::Event::DiffBaseChanged => {
15356            //     self.scrollbar_marker_state.dirty = true;
15357            //     cx.emit(EditorEvent::DiffBaseChanged);
15358            //     cx.notify();
15359            // }
15360            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15361            multi_buffer::Event::DiagnosticsUpdated => {
15362                self.refresh_active_diagnostics(cx);
15363                self.refresh_inline_diagnostics(true, window, cx);
15364                self.scrollbar_marker_state.dirty = true;
15365                cx.notify();
15366            }
15367            _ => {}
15368        };
15369    }
15370
15371    fn on_display_map_changed(
15372        &mut self,
15373        _: Entity<DisplayMap>,
15374        _: &mut Window,
15375        cx: &mut Context<Self>,
15376    ) {
15377        cx.notify();
15378    }
15379
15380    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15381        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15382        self.update_edit_prediction_settings(cx);
15383        self.refresh_inline_completion(true, false, window, cx);
15384        self.refresh_inlay_hints(
15385            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15386                self.selections.newest_anchor().head(),
15387                &self.buffer.read(cx).snapshot(cx),
15388                cx,
15389            )),
15390            cx,
15391        );
15392
15393        let old_cursor_shape = self.cursor_shape;
15394
15395        {
15396            let editor_settings = EditorSettings::get_global(cx);
15397            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15398            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15399            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15400        }
15401
15402        if old_cursor_shape != self.cursor_shape {
15403            cx.emit(EditorEvent::CursorShapeChanged);
15404        }
15405
15406        let project_settings = ProjectSettings::get_global(cx);
15407        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15408
15409        if self.mode == EditorMode::Full {
15410            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15411            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15412            if self.show_inline_diagnostics != show_inline_diagnostics {
15413                self.show_inline_diagnostics = show_inline_diagnostics;
15414                self.refresh_inline_diagnostics(false, window, cx);
15415            }
15416
15417            if self.git_blame_inline_enabled != inline_blame_enabled {
15418                self.toggle_git_blame_inline_internal(false, window, cx);
15419            }
15420        }
15421
15422        cx.notify();
15423    }
15424
15425    pub fn set_searchable(&mut self, searchable: bool) {
15426        self.searchable = searchable;
15427    }
15428
15429    pub fn searchable(&self) -> bool {
15430        self.searchable
15431    }
15432
15433    fn open_proposed_changes_editor(
15434        &mut self,
15435        _: &OpenProposedChangesEditor,
15436        window: &mut Window,
15437        cx: &mut Context<Self>,
15438    ) {
15439        let Some(workspace) = self.workspace() else {
15440            cx.propagate();
15441            return;
15442        };
15443
15444        let selections = self.selections.all::<usize>(cx);
15445        let multi_buffer = self.buffer.read(cx);
15446        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15447        let mut new_selections_by_buffer = HashMap::default();
15448        for selection in selections {
15449            for (buffer, range, _) in
15450                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15451            {
15452                let mut range = range.to_point(buffer);
15453                range.start.column = 0;
15454                range.end.column = buffer.line_len(range.end.row);
15455                new_selections_by_buffer
15456                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15457                    .or_insert(Vec::new())
15458                    .push(range)
15459            }
15460        }
15461
15462        let proposed_changes_buffers = new_selections_by_buffer
15463            .into_iter()
15464            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15465            .collect::<Vec<_>>();
15466        let proposed_changes_editor = cx.new(|cx| {
15467            ProposedChangesEditor::new(
15468                "Proposed changes",
15469                proposed_changes_buffers,
15470                self.project.clone(),
15471                window,
15472                cx,
15473            )
15474        });
15475
15476        window.defer(cx, move |window, cx| {
15477            workspace.update(cx, |workspace, cx| {
15478                workspace.active_pane().update(cx, |pane, cx| {
15479                    pane.add_item(
15480                        Box::new(proposed_changes_editor),
15481                        true,
15482                        true,
15483                        None,
15484                        window,
15485                        cx,
15486                    );
15487                });
15488            });
15489        });
15490    }
15491
15492    pub fn open_excerpts_in_split(
15493        &mut self,
15494        _: &OpenExcerptsSplit,
15495        window: &mut Window,
15496        cx: &mut Context<Self>,
15497    ) {
15498        self.open_excerpts_common(None, true, window, cx)
15499    }
15500
15501    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15502        self.open_excerpts_common(None, false, window, cx)
15503    }
15504
15505    fn open_excerpts_common(
15506        &mut self,
15507        jump_data: Option<JumpData>,
15508        split: bool,
15509        window: &mut Window,
15510        cx: &mut Context<Self>,
15511    ) {
15512        let Some(workspace) = self.workspace() else {
15513            cx.propagate();
15514            return;
15515        };
15516
15517        if self.buffer.read(cx).is_singleton() {
15518            cx.propagate();
15519            return;
15520        }
15521
15522        let mut new_selections_by_buffer = HashMap::default();
15523        match &jump_data {
15524            Some(JumpData::MultiBufferPoint {
15525                excerpt_id,
15526                position,
15527                anchor,
15528                line_offset_from_top,
15529            }) => {
15530                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15531                if let Some(buffer) = multi_buffer_snapshot
15532                    .buffer_id_for_excerpt(*excerpt_id)
15533                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15534                {
15535                    let buffer_snapshot = buffer.read(cx).snapshot();
15536                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15537                        language::ToPoint::to_point(anchor, &buffer_snapshot)
15538                    } else {
15539                        buffer_snapshot.clip_point(*position, Bias::Left)
15540                    };
15541                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15542                    new_selections_by_buffer.insert(
15543                        buffer,
15544                        (
15545                            vec![jump_to_offset..jump_to_offset],
15546                            Some(*line_offset_from_top),
15547                        ),
15548                    );
15549                }
15550            }
15551            Some(JumpData::MultiBufferRow {
15552                row,
15553                line_offset_from_top,
15554            }) => {
15555                let point = MultiBufferPoint::new(row.0, 0);
15556                if let Some((buffer, buffer_point, _)) =
15557                    self.buffer.read(cx).point_to_buffer_point(point, cx)
15558                {
15559                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15560                    new_selections_by_buffer
15561                        .entry(buffer)
15562                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
15563                        .0
15564                        .push(buffer_offset..buffer_offset)
15565                }
15566            }
15567            None => {
15568                let selections = self.selections.all::<usize>(cx);
15569                let multi_buffer = self.buffer.read(cx);
15570                for selection in selections {
15571                    for (snapshot, range, _, anchor) in multi_buffer
15572                        .snapshot(cx)
15573                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15574                    {
15575                        if let Some(anchor) = anchor {
15576                            // selection is in a deleted hunk
15577                            let Some(buffer_id) = anchor.buffer_id else {
15578                                continue;
15579                            };
15580                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15581                                continue;
15582                            };
15583                            let offset = text::ToOffset::to_offset(
15584                                &anchor.text_anchor,
15585                                &buffer_handle.read(cx).snapshot(),
15586                            );
15587                            let range = offset..offset;
15588                            new_selections_by_buffer
15589                                .entry(buffer_handle)
15590                                .or_insert((Vec::new(), None))
15591                                .0
15592                                .push(range)
15593                        } else {
15594                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15595                            else {
15596                                continue;
15597                            };
15598                            new_selections_by_buffer
15599                                .entry(buffer_handle)
15600                                .or_insert((Vec::new(), None))
15601                                .0
15602                                .push(range)
15603                        }
15604                    }
15605                }
15606            }
15607        }
15608
15609        if new_selections_by_buffer.is_empty() {
15610            return;
15611        }
15612
15613        // We defer the pane interaction because we ourselves are a workspace item
15614        // and activating a new item causes the pane to call a method on us reentrantly,
15615        // which panics if we're on the stack.
15616        window.defer(cx, move |window, cx| {
15617            workspace.update(cx, |workspace, cx| {
15618                let pane = if split {
15619                    workspace.adjacent_pane(window, cx)
15620                } else {
15621                    workspace.active_pane().clone()
15622                };
15623
15624                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15625                    let editor = buffer
15626                        .read(cx)
15627                        .file()
15628                        .is_none()
15629                        .then(|| {
15630                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15631                            // so `workspace.open_project_item` will never find them, always opening a new editor.
15632                            // Instead, we try to activate the existing editor in the pane first.
15633                            let (editor, pane_item_index) =
15634                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
15635                                    let editor = item.downcast::<Editor>()?;
15636                                    let singleton_buffer =
15637                                        editor.read(cx).buffer().read(cx).as_singleton()?;
15638                                    if singleton_buffer == buffer {
15639                                        Some((editor, i))
15640                                    } else {
15641                                        None
15642                                    }
15643                                })?;
15644                            pane.update(cx, |pane, cx| {
15645                                pane.activate_item(pane_item_index, true, true, window, cx)
15646                            });
15647                            Some(editor)
15648                        })
15649                        .flatten()
15650                        .unwrap_or_else(|| {
15651                            workspace.open_project_item::<Self>(
15652                                pane.clone(),
15653                                buffer,
15654                                true,
15655                                true,
15656                                window,
15657                                cx,
15658                            )
15659                        });
15660
15661                    editor.update(cx, |editor, cx| {
15662                        let autoscroll = match scroll_offset {
15663                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15664                            None => Autoscroll::newest(),
15665                        };
15666                        let nav_history = editor.nav_history.take();
15667                        editor.change_selections(Some(autoscroll), window, cx, |s| {
15668                            s.select_ranges(ranges);
15669                        });
15670                        editor.nav_history = nav_history;
15671                    });
15672                }
15673            })
15674        });
15675    }
15676
15677    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15678        let snapshot = self.buffer.read(cx).read(cx);
15679        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15680        Some(
15681            ranges
15682                .iter()
15683                .map(move |range| {
15684                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15685                })
15686                .collect(),
15687        )
15688    }
15689
15690    fn selection_replacement_ranges(
15691        &self,
15692        range: Range<OffsetUtf16>,
15693        cx: &mut App,
15694    ) -> Vec<Range<OffsetUtf16>> {
15695        let selections = self.selections.all::<OffsetUtf16>(cx);
15696        let newest_selection = selections
15697            .iter()
15698            .max_by_key(|selection| selection.id)
15699            .unwrap();
15700        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15701        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15702        let snapshot = self.buffer.read(cx).read(cx);
15703        selections
15704            .into_iter()
15705            .map(|mut selection| {
15706                selection.start.0 =
15707                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
15708                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15709                snapshot.clip_offset_utf16(selection.start, Bias::Left)
15710                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15711            })
15712            .collect()
15713    }
15714
15715    fn report_editor_event(
15716        &self,
15717        event_type: &'static str,
15718        file_extension: Option<String>,
15719        cx: &App,
15720    ) {
15721        if cfg!(any(test, feature = "test-support")) {
15722            return;
15723        }
15724
15725        let Some(project) = &self.project else { return };
15726
15727        // If None, we are in a file without an extension
15728        let file = self
15729            .buffer
15730            .read(cx)
15731            .as_singleton()
15732            .and_then(|b| b.read(cx).file());
15733        let file_extension = file_extension.or(file
15734            .as_ref()
15735            .and_then(|file| Path::new(file.file_name(cx)).extension())
15736            .and_then(|e| e.to_str())
15737            .map(|a| a.to_string()));
15738
15739        let vim_mode = cx
15740            .global::<SettingsStore>()
15741            .raw_user_settings()
15742            .get("vim_mode")
15743            == Some(&serde_json::Value::Bool(true));
15744
15745        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15746        let copilot_enabled = edit_predictions_provider
15747            == language::language_settings::EditPredictionProvider::Copilot;
15748        let copilot_enabled_for_language = self
15749            .buffer
15750            .read(cx)
15751            .settings_at(0, cx)
15752            .show_edit_predictions;
15753
15754        let project = project.read(cx);
15755        telemetry::event!(
15756            event_type,
15757            file_extension,
15758            vim_mode,
15759            copilot_enabled,
15760            copilot_enabled_for_language,
15761            edit_predictions_provider,
15762            is_via_ssh = project.is_via_ssh(),
15763        );
15764    }
15765
15766    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15767    /// with each line being an array of {text, highlight} objects.
15768    fn copy_highlight_json(
15769        &mut self,
15770        _: &CopyHighlightJson,
15771        window: &mut Window,
15772        cx: &mut Context<Self>,
15773    ) {
15774        #[derive(Serialize)]
15775        struct Chunk<'a> {
15776            text: String,
15777            highlight: Option<&'a str>,
15778        }
15779
15780        let snapshot = self.buffer.read(cx).snapshot(cx);
15781        let range = self
15782            .selected_text_range(false, window, cx)
15783            .and_then(|selection| {
15784                if selection.range.is_empty() {
15785                    None
15786                } else {
15787                    Some(selection.range)
15788                }
15789            })
15790            .unwrap_or_else(|| 0..snapshot.len());
15791
15792        let chunks = snapshot.chunks(range, true);
15793        let mut lines = Vec::new();
15794        let mut line: VecDeque<Chunk> = VecDeque::new();
15795
15796        let Some(style) = self.style.as_ref() else {
15797            return;
15798        };
15799
15800        for chunk in chunks {
15801            let highlight = chunk
15802                .syntax_highlight_id
15803                .and_then(|id| id.name(&style.syntax));
15804            let mut chunk_lines = chunk.text.split('\n').peekable();
15805            while let Some(text) = chunk_lines.next() {
15806                let mut merged_with_last_token = false;
15807                if let Some(last_token) = line.back_mut() {
15808                    if last_token.highlight == highlight {
15809                        last_token.text.push_str(text);
15810                        merged_with_last_token = true;
15811                    }
15812                }
15813
15814                if !merged_with_last_token {
15815                    line.push_back(Chunk {
15816                        text: text.into(),
15817                        highlight,
15818                    });
15819                }
15820
15821                if chunk_lines.peek().is_some() {
15822                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
15823                        line.pop_front();
15824                    }
15825                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
15826                        line.pop_back();
15827                    }
15828
15829                    lines.push(mem::take(&mut line));
15830                }
15831            }
15832        }
15833
15834        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15835            return;
15836        };
15837        cx.write_to_clipboard(ClipboardItem::new_string(lines));
15838    }
15839
15840    pub fn open_context_menu(
15841        &mut self,
15842        _: &OpenContextMenu,
15843        window: &mut Window,
15844        cx: &mut Context<Self>,
15845    ) {
15846        self.request_autoscroll(Autoscroll::newest(), cx);
15847        let position = self.selections.newest_display(cx).start;
15848        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15849    }
15850
15851    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15852        &self.inlay_hint_cache
15853    }
15854
15855    pub fn replay_insert_event(
15856        &mut self,
15857        text: &str,
15858        relative_utf16_range: Option<Range<isize>>,
15859        window: &mut Window,
15860        cx: &mut Context<Self>,
15861    ) {
15862        if !self.input_enabled {
15863            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15864            return;
15865        }
15866        if let Some(relative_utf16_range) = relative_utf16_range {
15867            let selections = self.selections.all::<OffsetUtf16>(cx);
15868            self.change_selections(None, window, cx, |s| {
15869                let new_ranges = selections.into_iter().map(|range| {
15870                    let start = OffsetUtf16(
15871                        range
15872                            .head()
15873                            .0
15874                            .saturating_add_signed(relative_utf16_range.start),
15875                    );
15876                    let end = OffsetUtf16(
15877                        range
15878                            .head()
15879                            .0
15880                            .saturating_add_signed(relative_utf16_range.end),
15881                    );
15882                    start..end
15883                });
15884                s.select_ranges(new_ranges);
15885            });
15886        }
15887
15888        self.handle_input(text, window, cx);
15889    }
15890
15891    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15892        let Some(provider) = self.semantics_provider.as_ref() else {
15893            return false;
15894        };
15895
15896        let mut supports = false;
15897        self.buffer().update(cx, |this, cx| {
15898            this.for_each_buffer(|buffer| {
15899                supports |= provider.supports_inlay_hints(buffer, cx);
15900            });
15901        });
15902
15903        supports
15904    }
15905
15906    pub fn is_focused(&self, window: &Window) -> bool {
15907        self.focus_handle.is_focused(window)
15908    }
15909
15910    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15911        cx.emit(EditorEvent::Focused);
15912
15913        if let Some(descendant) = self
15914            .last_focused_descendant
15915            .take()
15916            .and_then(|descendant| descendant.upgrade())
15917        {
15918            window.focus(&descendant);
15919        } else {
15920            if let Some(blame) = self.blame.as_ref() {
15921                blame.update(cx, GitBlame::focus)
15922            }
15923
15924            self.blink_manager.update(cx, BlinkManager::enable);
15925            self.show_cursor_names(window, cx);
15926            self.buffer.update(cx, |buffer, cx| {
15927                buffer.finalize_last_transaction(cx);
15928                if self.leader_peer_id.is_none() {
15929                    buffer.set_active_selections(
15930                        &self.selections.disjoint_anchors(),
15931                        self.selections.line_mode,
15932                        self.cursor_shape,
15933                        cx,
15934                    );
15935                }
15936            });
15937        }
15938    }
15939
15940    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15941        cx.emit(EditorEvent::FocusedIn)
15942    }
15943
15944    fn handle_focus_out(
15945        &mut self,
15946        event: FocusOutEvent,
15947        _window: &mut Window,
15948        cx: &mut Context<Self>,
15949    ) {
15950        if event.blurred != self.focus_handle {
15951            self.last_focused_descendant = Some(event.blurred);
15952        }
15953        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
15954    }
15955
15956    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15957        self.blink_manager.update(cx, BlinkManager::disable);
15958        self.buffer
15959            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
15960
15961        if let Some(blame) = self.blame.as_ref() {
15962            blame.update(cx, GitBlame::blur)
15963        }
15964        if !self.hover_state.focused(window, cx) {
15965            hide_hover(self, cx);
15966        }
15967        if !self
15968            .context_menu
15969            .borrow()
15970            .as_ref()
15971            .is_some_and(|context_menu| context_menu.focused(window, cx))
15972        {
15973            self.hide_context_menu(window, cx);
15974        }
15975        self.discard_inline_completion(false, cx);
15976        cx.emit(EditorEvent::Blurred);
15977        cx.notify();
15978    }
15979
15980    pub fn register_action<A: Action>(
15981        &mut self,
15982        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
15983    ) -> Subscription {
15984        let id = self.next_editor_action_id.post_inc();
15985        let listener = Arc::new(listener);
15986        self.editor_actions.borrow_mut().insert(
15987            id,
15988            Box::new(move |window, _| {
15989                let listener = listener.clone();
15990                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
15991                    let action = action.downcast_ref().unwrap();
15992                    if phase == DispatchPhase::Bubble {
15993                        listener(action, window, cx)
15994                    }
15995                })
15996            }),
15997        );
15998
15999        let editor_actions = self.editor_actions.clone();
16000        Subscription::new(move || {
16001            editor_actions.borrow_mut().remove(&id);
16002        })
16003    }
16004
16005    pub fn file_header_size(&self) -> u32 {
16006        FILE_HEADER_HEIGHT
16007    }
16008
16009    pub fn restore(
16010        &mut self,
16011        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16012        window: &mut Window,
16013        cx: &mut Context<Self>,
16014    ) {
16015        let workspace = self.workspace();
16016        let project = self.project.as_ref();
16017        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16018            let mut tasks = Vec::new();
16019            for (buffer_id, changes) in revert_changes {
16020                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16021                    buffer.update(cx, |buffer, cx| {
16022                        buffer.edit(
16023                            changes
16024                                .into_iter()
16025                                .map(|(range, text)| (range, text.to_string())),
16026                            None,
16027                            cx,
16028                        );
16029                    });
16030
16031                    if let Some(project) =
16032                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16033                    {
16034                        project.update(cx, |project, cx| {
16035                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16036                        })
16037                    }
16038                }
16039            }
16040            tasks
16041        });
16042        cx.spawn_in(window, |_, mut cx| async move {
16043            for (buffer, task) in save_tasks {
16044                let result = task.await;
16045                if result.is_err() {
16046                    let Some(path) = buffer
16047                        .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16048                        .ok()
16049                    else {
16050                        continue;
16051                    };
16052                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16053                        let Some(task) = cx
16054                            .update_window_entity(&workspace, |workspace, window, cx| {
16055                                workspace
16056                                    .open_path_preview(path, None, false, false, false, window, cx)
16057                            })
16058                            .ok()
16059                        else {
16060                            continue;
16061                        };
16062                        task.await.log_err();
16063                    }
16064                }
16065            }
16066        })
16067        .detach();
16068        self.change_selections(None, window, cx, |selections| selections.refresh());
16069    }
16070
16071    pub fn to_pixel_point(
16072        &self,
16073        source: multi_buffer::Anchor,
16074        editor_snapshot: &EditorSnapshot,
16075        window: &mut Window,
16076    ) -> Option<gpui::Point<Pixels>> {
16077        let source_point = source.to_display_point(editor_snapshot);
16078        self.display_to_pixel_point(source_point, editor_snapshot, window)
16079    }
16080
16081    pub fn display_to_pixel_point(
16082        &self,
16083        source: DisplayPoint,
16084        editor_snapshot: &EditorSnapshot,
16085        window: &mut Window,
16086    ) -> Option<gpui::Point<Pixels>> {
16087        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16088        let text_layout_details = self.text_layout_details(window);
16089        let scroll_top = text_layout_details
16090            .scroll_anchor
16091            .scroll_position(editor_snapshot)
16092            .y;
16093
16094        if source.row().as_f32() < scroll_top.floor() {
16095            return None;
16096        }
16097        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16098        let source_y = line_height * (source.row().as_f32() - scroll_top);
16099        Some(gpui::Point::new(source_x, source_y))
16100    }
16101
16102    pub fn has_visible_completions_menu(&self) -> bool {
16103        !self.edit_prediction_preview_is_active()
16104            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16105                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16106            })
16107    }
16108
16109    pub fn register_addon<T: Addon>(&mut self, instance: T) {
16110        self.addons
16111            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16112    }
16113
16114    pub fn unregister_addon<T: Addon>(&mut self) {
16115        self.addons.remove(&std::any::TypeId::of::<T>());
16116    }
16117
16118    pub fn addon<T: Addon>(&self) -> Option<&T> {
16119        let type_id = std::any::TypeId::of::<T>();
16120        self.addons
16121            .get(&type_id)
16122            .and_then(|item| item.to_any().downcast_ref::<T>())
16123    }
16124
16125    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16126        let text_layout_details = self.text_layout_details(window);
16127        let style = &text_layout_details.editor_style;
16128        let font_id = window.text_system().resolve_font(&style.text.font());
16129        let font_size = style.text.font_size.to_pixels(window.rem_size());
16130        let line_height = style.text.line_height_in_pixels(window.rem_size());
16131        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16132
16133        gpui::Size::new(em_width, line_height)
16134    }
16135
16136    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16137        self.load_diff_task.clone()
16138    }
16139
16140    fn read_selections_from_db(
16141        &mut self,
16142        item_id: u64,
16143        workspace_id: WorkspaceId,
16144        window: &mut Window,
16145        cx: &mut Context<Editor>,
16146    ) {
16147        if !self.is_singleton(cx)
16148            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16149        {
16150            return;
16151        }
16152        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16153            return;
16154        };
16155        if selections.is_empty() {
16156            return;
16157        }
16158
16159        let snapshot = self.buffer.read(cx).snapshot(cx);
16160        self.change_selections(None, window, cx, |s| {
16161            s.select_ranges(selections.into_iter().map(|(start, end)| {
16162                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16163            }));
16164        });
16165    }
16166}
16167
16168fn insert_extra_newline_brackets(
16169    buffer: &MultiBufferSnapshot,
16170    range: Range<usize>,
16171    language: &language::LanguageScope,
16172) -> bool {
16173    let leading_whitespace_len = buffer
16174        .reversed_chars_at(range.start)
16175        .take_while(|c| c.is_whitespace() && *c != '\n')
16176        .map(|c| c.len_utf8())
16177        .sum::<usize>();
16178    let trailing_whitespace_len = buffer
16179        .chars_at(range.end)
16180        .take_while(|c| c.is_whitespace() && *c != '\n')
16181        .map(|c| c.len_utf8())
16182        .sum::<usize>();
16183    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16184
16185    language.brackets().any(|(pair, enabled)| {
16186        let pair_start = pair.start.trim_end();
16187        let pair_end = pair.end.trim_start();
16188
16189        enabled
16190            && pair.newline
16191            && buffer.contains_str_at(range.end, pair_end)
16192            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16193    })
16194}
16195
16196fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16197    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16198        [(buffer, range, _)] => (*buffer, range.clone()),
16199        _ => return false,
16200    };
16201    let pair = {
16202        let mut result: Option<BracketMatch> = None;
16203
16204        for pair in buffer
16205            .all_bracket_ranges(range.clone())
16206            .filter(move |pair| {
16207                pair.open_range.start <= range.start && pair.close_range.end >= range.end
16208            })
16209        {
16210            let len = pair.close_range.end - pair.open_range.start;
16211
16212            if let Some(existing) = &result {
16213                let existing_len = existing.close_range.end - existing.open_range.start;
16214                if len > existing_len {
16215                    continue;
16216                }
16217            }
16218
16219            result = Some(pair);
16220        }
16221
16222        result
16223    };
16224    let Some(pair) = pair else {
16225        return false;
16226    };
16227    pair.newline_only
16228        && buffer
16229            .chars_for_range(pair.open_range.end..range.start)
16230            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16231            .all(|c| c.is_whitespace() && c != '\n')
16232}
16233
16234fn get_uncommitted_diff_for_buffer(
16235    project: &Entity<Project>,
16236    buffers: impl IntoIterator<Item = Entity<Buffer>>,
16237    buffer: Entity<MultiBuffer>,
16238    cx: &mut App,
16239) -> Task<()> {
16240    let mut tasks = Vec::new();
16241    project.update(cx, |project, cx| {
16242        for buffer in buffers {
16243            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16244        }
16245    });
16246    cx.spawn(|mut cx| async move {
16247        let diffs = future::join_all(tasks).await;
16248        buffer
16249            .update(&mut cx, |buffer, cx| {
16250                for diff in diffs.into_iter().flatten() {
16251                    buffer.add_diff(diff, cx);
16252                }
16253            })
16254            .ok();
16255    })
16256}
16257
16258fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16259    let tab_size = tab_size.get() as usize;
16260    let mut width = offset;
16261
16262    for ch in text.chars() {
16263        width += if ch == '\t' {
16264            tab_size - (width % tab_size)
16265        } else {
16266            1
16267        };
16268    }
16269
16270    width - offset
16271}
16272
16273#[cfg(test)]
16274mod tests {
16275    use super::*;
16276
16277    #[test]
16278    fn test_string_size_with_expanded_tabs() {
16279        let nz = |val| NonZeroU32::new(val).unwrap();
16280        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16281        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16282        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16283        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16284        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16285        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16286        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16287        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16288    }
16289}
16290
16291/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16292struct WordBreakingTokenizer<'a> {
16293    input: &'a str,
16294}
16295
16296impl<'a> WordBreakingTokenizer<'a> {
16297    fn new(input: &'a str) -> Self {
16298        Self { input }
16299    }
16300}
16301
16302fn is_char_ideographic(ch: char) -> bool {
16303    use unicode_script::Script::*;
16304    use unicode_script::UnicodeScript;
16305    matches!(ch.script(), Han | Tangut | Yi)
16306}
16307
16308fn is_grapheme_ideographic(text: &str) -> bool {
16309    text.chars().any(is_char_ideographic)
16310}
16311
16312fn is_grapheme_whitespace(text: &str) -> bool {
16313    text.chars().any(|x| x.is_whitespace())
16314}
16315
16316fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16317    text.chars().next().map_or(false, |ch| {
16318        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16319    })
16320}
16321
16322#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16323struct WordBreakToken<'a> {
16324    token: &'a str,
16325    grapheme_len: usize,
16326    is_whitespace: bool,
16327}
16328
16329impl<'a> Iterator for WordBreakingTokenizer<'a> {
16330    /// Yields a span, the count of graphemes in the token, and whether it was
16331    /// whitespace. Note that it also breaks at word boundaries.
16332    type Item = WordBreakToken<'a>;
16333
16334    fn next(&mut self) -> Option<Self::Item> {
16335        use unicode_segmentation::UnicodeSegmentation;
16336        if self.input.is_empty() {
16337            return None;
16338        }
16339
16340        let mut iter = self.input.graphemes(true).peekable();
16341        let mut offset = 0;
16342        let mut graphemes = 0;
16343        if let Some(first_grapheme) = iter.next() {
16344            let is_whitespace = is_grapheme_whitespace(first_grapheme);
16345            offset += first_grapheme.len();
16346            graphemes += 1;
16347            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16348                if let Some(grapheme) = iter.peek().copied() {
16349                    if should_stay_with_preceding_ideograph(grapheme) {
16350                        offset += grapheme.len();
16351                        graphemes += 1;
16352                    }
16353                }
16354            } else {
16355                let mut words = self.input[offset..].split_word_bound_indices().peekable();
16356                let mut next_word_bound = words.peek().copied();
16357                if next_word_bound.map_or(false, |(i, _)| i == 0) {
16358                    next_word_bound = words.next();
16359                }
16360                while let Some(grapheme) = iter.peek().copied() {
16361                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
16362                        break;
16363                    };
16364                    if is_grapheme_whitespace(grapheme) != is_whitespace {
16365                        break;
16366                    };
16367                    offset += grapheme.len();
16368                    graphemes += 1;
16369                    iter.next();
16370                }
16371            }
16372            let token = &self.input[..offset];
16373            self.input = &self.input[offset..];
16374            if is_whitespace {
16375                Some(WordBreakToken {
16376                    token: " ",
16377                    grapheme_len: 1,
16378                    is_whitespace: true,
16379                })
16380            } else {
16381                Some(WordBreakToken {
16382                    token,
16383                    grapheme_len: graphemes,
16384                    is_whitespace: false,
16385                })
16386            }
16387        } else {
16388            None
16389        }
16390    }
16391}
16392
16393#[test]
16394fn test_word_breaking_tokenizer() {
16395    let tests: &[(&str, &[(&str, usize, bool)])] = &[
16396        ("", &[]),
16397        ("  ", &[(" ", 1, true)]),
16398        ("Ʒ", &[("Ʒ", 1, false)]),
16399        ("Ǽ", &[("Ǽ", 1, false)]),
16400        ("", &[("", 1, false)]),
16401        ("⋑⋑", &[("⋑⋑", 2, false)]),
16402        (
16403            "原理,进而",
16404            &[
16405                ("", 1, false),
16406                ("理,", 2, false),
16407                ("", 1, false),
16408                ("", 1, false),
16409            ],
16410        ),
16411        (
16412            "hello world",
16413            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16414        ),
16415        (
16416            "hello, world",
16417            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16418        ),
16419        (
16420            "  hello world",
16421            &[
16422                (" ", 1, true),
16423                ("hello", 5, false),
16424                (" ", 1, true),
16425                ("world", 5, false),
16426            ],
16427        ),
16428        (
16429            "这是什么 \n 钢笔",
16430            &[
16431                ("", 1, false),
16432                ("", 1, false),
16433                ("", 1, false),
16434                ("", 1, false),
16435                (" ", 1, true),
16436                ("", 1, false),
16437                ("", 1, false),
16438            ],
16439        ),
16440        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16441    ];
16442
16443    for (input, result) in tests {
16444        assert_eq!(
16445            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16446            result
16447                .iter()
16448                .copied()
16449                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16450                    token,
16451                    grapheme_len,
16452                    is_whitespace,
16453                })
16454                .collect::<Vec<_>>()
16455        );
16456    }
16457}
16458
16459fn wrap_with_prefix(
16460    line_prefix: String,
16461    unwrapped_text: String,
16462    wrap_column: usize,
16463    tab_size: NonZeroU32,
16464) -> String {
16465    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16466    let mut wrapped_text = String::new();
16467    let mut current_line = line_prefix.clone();
16468
16469    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16470    let mut current_line_len = line_prefix_len;
16471    for WordBreakToken {
16472        token,
16473        grapheme_len,
16474        is_whitespace,
16475    } in tokenizer
16476    {
16477        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16478            wrapped_text.push_str(current_line.trim_end());
16479            wrapped_text.push('\n');
16480            current_line.truncate(line_prefix.len());
16481            current_line_len = line_prefix_len;
16482            if !is_whitespace {
16483                current_line.push_str(token);
16484                current_line_len += grapheme_len;
16485            }
16486        } else if !is_whitespace {
16487            current_line.push_str(token);
16488            current_line_len += grapheme_len;
16489        } else if current_line_len != line_prefix_len {
16490            current_line.push(' ');
16491            current_line_len += 1;
16492        }
16493    }
16494
16495    if !current_line.is_empty() {
16496        wrapped_text.push_str(&current_line);
16497    }
16498    wrapped_text
16499}
16500
16501#[test]
16502fn test_wrap_with_prefix() {
16503    assert_eq!(
16504        wrap_with_prefix(
16505            "# ".to_string(),
16506            "abcdefg".to_string(),
16507            4,
16508            NonZeroU32::new(4).unwrap()
16509        ),
16510        "# abcdefg"
16511    );
16512    assert_eq!(
16513        wrap_with_prefix(
16514            "".to_string(),
16515            "\thello world".to_string(),
16516            8,
16517            NonZeroU32::new(4).unwrap()
16518        ),
16519        "hello\nworld"
16520    );
16521    assert_eq!(
16522        wrap_with_prefix(
16523            "// ".to_string(),
16524            "xx \nyy zz aa bb cc".to_string(),
16525            12,
16526            NonZeroU32::new(4).unwrap()
16527        ),
16528        "// xx yy zz\n// aa bb cc"
16529    );
16530    assert_eq!(
16531        wrap_with_prefix(
16532            String::new(),
16533            "这是什么 \n 钢笔".to_string(),
16534            3,
16535            NonZeroU32::new(4).unwrap()
16536        ),
16537        "这是什\n么 钢\n"
16538    );
16539}
16540
16541pub trait CollaborationHub {
16542    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16543    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16544    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16545}
16546
16547impl CollaborationHub for Entity<Project> {
16548    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16549        self.read(cx).collaborators()
16550    }
16551
16552    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16553        self.read(cx).user_store().read(cx).participant_indices()
16554    }
16555
16556    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16557        let this = self.read(cx);
16558        let user_ids = this.collaborators().values().map(|c| c.user_id);
16559        this.user_store().read_with(cx, |user_store, cx| {
16560            user_store.participant_names(user_ids, cx)
16561        })
16562    }
16563}
16564
16565pub trait SemanticsProvider {
16566    fn hover(
16567        &self,
16568        buffer: &Entity<Buffer>,
16569        position: text::Anchor,
16570        cx: &mut App,
16571    ) -> Option<Task<Vec<project::Hover>>>;
16572
16573    fn inlay_hints(
16574        &self,
16575        buffer_handle: Entity<Buffer>,
16576        range: Range<text::Anchor>,
16577        cx: &mut App,
16578    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16579
16580    fn resolve_inlay_hint(
16581        &self,
16582        hint: InlayHint,
16583        buffer_handle: Entity<Buffer>,
16584        server_id: LanguageServerId,
16585        cx: &mut App,
16586    ) -> Option<Task<anyhow::Result<InlayHint>>>;
16587
16588    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16589
16590    fn document_highlights(
16591        &self,
16592        buffer: &Entity<Buffer>,
16593        position: text::Anchor,
16594        cx: &mut App,
16595    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16596
16597    fn definitions(
16598        &self,
16599        buffer: &Entity<Buffer>,
16600        position: text::Anchor,
16601        kind: GotoDefinitionKind,
16602        cx: &mut App,
16603    ) -> Option<Task<Result<Vec<LocationLink>>>>;
16604
16605    fn range_for_rename(
16606        &self,
16607        buffer: &Entity<Buffer>,
16608        position: text::Anchor,
16609        cx: &mut App,
16610    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16611
16612    fn perform_rename(
16613        &self,
16614        buffer: &Entity<Buffer>,
16615        position: text::Anchor,
16616        new_name: String,
16617        cx: &mut App,
16618    ) -> Option<Task<Result<ProjectTransaction>>>;
16619}
16620
16621pub trait CompletionProvider {
16622    fn completions(
16623        &self,
16624        buffer: &Entity<Buffer>,
16625        buffer_position: text::Anchor,
16626        trigger: CompletionContext,
16627        window: &mut Window,
16628        cx: &mut Context<Editor>,
16629    ) -> Task<Result<Vec<Completion>>>;
16630
16631    fn resolve_completions(
16632        &self,
16633        buffer: Entity<Buffer>,
16634        completion_indices: Vec<usize>,
16635        completions: Rc<RefCell<Box<[Completion]>>>,
16636        cx: &mut Context<Editor>,
16637    ) -> Task<Result<bool>>;
16638
16639    fn apply_additional_edits_for_completion(
16640        &self,
16641        _buffer: Entity<Buffer>,
16642        _completions: Rc<RefCell<Box<[Completion]>>>,
16643        _completion_index: usize,
16644        _push_to_history: bool,
16645        _cx: &mut Context<Editor>,
16646    ) -> Task<Result<Option<language::Transaction>>> {
16647        Task::ready(Ok(None))
16648    }
16649
16650    fn is_completion_trigger(
16651        &self,
16652        buffer: &Entity<Buffer>,
16653        position: language::Anchor,
16654        text: &str,
16655        trigger_in_words: bool,
16656        cx: &mut Context<Editor>,
16657    ) -> bool;
16658
16659    fn sort_completions(&self) -> bool {
16660        true
16661    }
16662}
16663
16664pub trait CodeActionProvider {
16665    fn id(&self) -> Arc<str>;
16666
16667    fn code_actions(
16668        &self,
16669        buffer: &Entity<Buffer>,
16670        range: Range<text::Anchor>,
16671        window: &mut Window,
16672        cx: &mut App,
16673    ) -> Task<Result<Vec<CodeAction>>>;
16674
16675    fn apply_code_action(
16676        &self,
16677        buffer_handle: Entity<Buffer>,
16678        action: CodeAction,
16679        excerpt_id: ExcerptId,
16680        push_to_history: bool,
16681        window: &mut Window,
16682        cx: &mut App,
16683    ) -> Task<Result<ProjectTransaction>>;
16684}
16685
16686impl CodeActionProvider for Entity<Project> {
16687    fn id(&self) -> Arc<str> {
16688        "project".into()
16689    }
16690
16691    fn code_actions(
16692        &self,
16693        buffer: &Entity<Buffer>,
16694        range: Range<text::Anchor>,
16695        _window: &mut Window,
16696        cx: &mut App,
16697    ) -> Task<Result<Vec<CodeAction>>> {
16698        self.update(cx, |project, cx| {
16699            project.code_actions(buffer, range, None, cx)
16700        })
16701    }
16702
16703    fn apply_code_action(
16704        &self,
16705        buffer_handle: Entity<Buffer>,
16706        action: CodeAction,
16707        _excerpt_id: ExcerptId,
16708        push_to_history: bool,
16709        _window: &mut Window,
16710        cx: &mut App,
16711    ) -> Task<Result<ProjectTransaction>> {
16712        self.update(cx, |project, cx| {
16713            project.apply_code_action(buffer_handle, action, push_to_history, cx)
16714        })
16715    }
16716}
16717
16718fn snippet_completions(
16719    project: &Project,
16720    buffer: &Entity<Buffer>,
16721    buffer_position: text::Anchor,
16722    cx: &mut App,
16723) -> Task<Result<Vec<Completion>>> {
16724    let language = buffer.read(cx).language_at(buffer_position);
16725    let language_name = language.as_ref().map(|language| language.lsp_id());
16726    let snippet_store = project.snippets().read(cx);
16727    let snippets = snippet_store.snippets_for(language_name, cx);
16728
16729    if snippets.is_empty() {
16730        return Task::ready(Ok(vec![]));
16731    }
16732    let snapshot = buffer.read(cx).text_snapshot();
16733    let chars: String = snapshot
16734        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16735        .collect();
16736
16737    let scope = language.map(|language| language.default_scope());
16738    let executor = cx.background_executor().clone();
16739
16740    cx.background_spawn(async move {
16741        let classifier = CharClassifier::new(scope).for_completion(true);
16742        let mut last_word = chars
16743            .chars()
16744            .take_while(|c| classifier.is_word(*c))
16745            .collect::<String>();
16746        last_word = last_word.chars().rev().collect();
16747
16748        if last_word.is_empty() {
16749            return Ok(vec![]);
16750        }
16751
16752        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16753        let to_lsp = |point: &text::Anchor| {
16754            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16755            point_to_lsp(end)
16756        };
16757        let lsp_end = to_lsp(&buffer_position);
16758
16759        let candidates = snippets
16760            .iter()
16761            .enumerate()
16762            .flat_map(|(ix, snippet)| {
16763                snippet
16764                    .prefix
16765                    .iter()
16766                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16767            })
16768            .collect::<Vec<StringMatchCandidate>>();
16769
16770        let mut matches = fuzzy::match_strings(
16771            &candidates,
16772            &last_word,
16773            last_word.chars().any(|c| c.is_uppercase()),
16774            100,
16775            &Default::default(),
16776            executor,
16777        )
16778        .await;
16779
16780        // Remove all candidates where the query's start does not match the start of any word in the candidate
16781        if let Some(query_start) = last_word.chars().next() {
16782            matches.retain(|string_match| {
16783                split_words(&string_match.string).any(|word| {
16784                    // Check that the first codepoint of the word as lowercase matches the first
16785                    // codepoint of the query as lowercase
16786                    word.chars()
16787                        .flat_map(|codepoint| codepoint.to_lowercase())
16788                        .zip(query_start.to_lowercase())
16789                        .all(|(word_cp, query_cp)| word_cp == query_cp)
16790                })
16791            });
16792        }
16793
16794        let matched_strings = matches
16795            .into_iter()
16796            .map(|m| m.string)
16797            .collect::<HashSet<_>>();
16798
16799        let result: Vec<Completion> = snippets
16800            .into_iter()
16801            .filter_map(|snippet| {
16802                let matching_prefix = snippet
16803                    .prefix
16804                    .iter()
16805                    .find(|prefix| matched_strings.contains(*prefix))?;
16806                let start = as_offset - last_word.len();
16807                let start = snapshot.anchor_before(start);
16808                let range = start..buffer_position;
16809                let lsp_start = to_lsp(&start);
16810                let lsp_range = lsp::Range {
16811                    start: lsp_start,
16812                    end: lsp_end,
16813                };
16814                Some(Completion {
16815                    old_range: range,
16816                    new_text: snippet.body.clone(),
16817                    resolved: false,
16818                    label: CodeLabel {
16819                        text: matching_prefix.clone(),
16820                        runs: vec![],
16821                        filter_range: 0..matching_prefix.len(),
16822                    },
16823                    server_id: LanguageServerId(usize::MAX),
16824                    documentation: snippet
16825                        .description
16826                        .clone()
16827                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
16828                    lsp_completion: lsp::CompletionItem {
16829                        label: snippet.prefix.first().unwrap().clone(),
16830                        kind: Some(CompletionItemKind::SNIPPET),
16831                        label_details: snippet.description.as_ref().map(|description| {
16832                            lsp::CompletionItemLabelDetails {
16833                                detail: Some(description.clone()),
16834                                description: None,
16835                            }
16836                        }),
16837                        insert_text_format: Some(InsertTextFormat::SNIPPET),
16838                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16839                            lsp::InsertReplaceEdit {
16840                                new_text: snippet.body.clone(),
16841                                insert: lsp_range,
16842                                replace: lsp_range,
16843                            },
16844                        )),
16845                        filter_text: Some(snippet.body.clone()),
16846                        sort_text: Some(char::MAX.to_string()),
16847                        ..Default::default()
16848                    },
16849                    confirm: None,
16850                })
16851            })
16852            .collect();
16853
16854        Ok(result)
16855    })
16856}
16857
16858impl CompletionProvider for Entity<Project> {
16859    fn completions(
16860        &self,
16861        buffer: &Entity<Buffer>,
16862        buffer_position: text::Anchor,
16863        options: CompletionContext,
16864        _window: &mut Window,
16865        cx: &mut Context<Editor>,
16866    ) -> Task<Result<Vec<Completion>>> {
16867        self.update(cx, |project, cx| {
16868            let snippets = snippet_completions(project, buffer, buffer_position, cx);
16869            let project_completions = project.completions(buffer, buffer_position, options, cx);
16870            cx.background_spawn(async move {
16871                let mut completions = project_completions.await?;
16872                let snippets_completions = snippets.await?;
16873                completions.extend(snippets_completions);
16874                Ok(completions)
16875            })
16876        })
16877    }
16878
16879    fn resolve_completions(
16880        &self,
16881        buffer: Entity<Buffer>,
16882        completion_indices: Vec<usize>,
16883        completions: Rc<RefCell<Box<[Completion]>>>,
16884        cx: &mut Context<Editor>,
16885    ) -> Task<Result<bool>> {
16886        self.update(cx, |project, cx| {
16887            project.lsp_store().update(cx, |lsp_store, cx| {
16888                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16889            })
16890        })
16891    }
16892
16893    fn apply_additional_edits_for_completion(
16894        &self,
16895        buffer: Entity<Buffer>,
16896        completions: Rc<RefCell<Box<[Completion]>>>,
16897        completion_index: usize,
16898        push_to_history: bool,
16899        cx: &mut Context<Editor>,
16900    ) -> Task<Result<Option<language::Transaction>>> {
16901        self.update(cx, |project, cx| {
16902            project.lsp_store().update(cx, |lsp_store, cx| {
16903                lsp_store.apply_additional_edits_for_completion(
16904                    buffer,
16905                    completions,
16906                    completion_index,
16907                    push_to_history,
16908                    cx,
16909                )
16910            })
16911        })
16912    }
16913
16914    fn is_completion_trigger(
16915        &self,
16916        buffer: &Entity<Buffer>,
16917        position: language::Anchor,
16918        text: &str,
16919        trigger_in_words: bool,
16920        cx: &mut Context<Editor>,
16921    ) -> bool {
16922        let mut chars = text.chars();
16923        let char = if let Some(char) = chars.next() {
16924            char
16925        } else {
16926            return false;
16927        };
16928        if chars.next().is_some() {
16929            return false;
16930        }
16931
16932        let buffer = buffer.read(cx);
16933        let snapshot = buffer.snapshot();
16934        if !snapshot.settings_at(position, cx).show_completions_on_input {
16935            return false;
16936        }
16937        let classifier = snapshot.char_classifier_at(position).for_completion(true);
16938        if trigger_in_words && classifier.is_word(char) {
16939            return true;
16940        }
16941
16942        buffer.completion_triggers().contains(text)
16943    }
16944}
16945
16946impl SemanticsProvider for Entity<Project> {
16947    fn hover(
16948        &self,
16949        buffer: &Entity<Buffer>,
16950        position: text::Anchor,
16951        cx: &mut App,
16952    ) -> Option<Task<Vec<project::Hover>>> {
16953        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
16954    }
16955
16956    fn document_highlights(
16957        &self,
16958        buffer: &Entity<Buffer>,
16959        position: text::Anchor,
16960        cx: &mut App,
16961    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
16962        Some(self.update(cx, |project, cx| {
16963            project.document_highlights(buffer, position, cx)
16964        }))
16965    }
16966
16967    fn definitions(
16968        &self,
16969        buffer: &Entity<Buffer>,
16970        position: text::Anchor,
16971        kind: GotoDefinitionKind,
16972        cx: &mut App,
16973    ) -> Option<Task<Result<Vec<LocationLink>>>> {
16974        Some(self.update(cx, |project, cx| match kind {
16975            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
16976            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
16977            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
16978            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
16979        }))
16980    }
16981
16982    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
16983        // TODO: make this work for remote projects
16984        self.update(cx, |this, cx| {
16985            buffer.update(cx, |buffer, cx| {
16986                this.any_language_server_supports_inlay_hints(buffer, cx)
16987            })
16988        })
16989    }
16990
16991    fn inlay_hints(
16992        &self,
16993        buffer_handle: Entity<Buffer>,
16994        range: Range<text::Anchor>,
16995        cx: &mut App,
16996    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
16997        Some(self.update(cx, |project, cx| {
16998            project.inlay_hints(buffer_handle, range, cx)
16999        }))
17000    }
17001
17002    fn resolve_inlay_hint(
17003        &self,
17004        hint: InlayHint,
17005        buffer_handle: Entity<Buffer>,
17006        server_id: LanguageServerId,
17007        cx: &mut App,
17008    ) -> Option<Task<anyhow::Result<InlayHint>>> {
17009        Some(self.update(cx, |project, cx| {
17010            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
17011        }))
17012    }
17013
17014    fn range_for_rename(
17015        &self,
17016        buffer: &Entity<Buffer>,
17017        position: text::Anchor,
17018        cx: &mut App,
17019    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17020        Some(self.update(cx, |project, cx| {
17021            let buffer = buffer.clone();
17022            let task = project.prepare_rename(buffer.clone(), position, cx);
17023            cx.spawn(|_, mut cx| async move {
17024                Ok(match task.await? {
17025                    PrepareRenameResponse::Success(range) => Some(range),
17026                    PrepareRenameResponse::InvalidPosition => None,
17027                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17028                        // Fallback on using TreeSitter info to determine identifier range
17029                        buffer.update(&mut cx, |buffer, _| {
17030                            let snapshot = buffer.snapshot();
17031                            let (range, kind) = snapshot.surrounding_word(position);
17032                            if kind != Some(CharKind::Word) {
17033                                return None;
17034                            }
17035                            Some(
17036                                snapshot.anchor_before(range.start)
17037                                    ..snapshot.anchor_after(range.end),
17038                            )
17039                        })?
17040                    }
17041                })
17042            })
17043        }))
17044    }
17045
17046    fn perform_rename(
17047        &self,
17048        buffer: &Entity<Buffer>,
17049        position: text::Anchor,
17050        new_name: String,
17051        cx: &mut App,
17052    ) -> Option<Task<Result<ProjectTransaction>>> {
17053        Some(self.update(cx, |project, cx| {
17054            project.perform_rename(buffer.clone(), position, new_name, cx)
17055        }))
17056    }
17057}
17058
17059fn inlay_hint_settings(
17060    location: Anchor,
17061    snapshot: &MultiBufferSnapshot,
17062    cx: &mut Context<Editor>,
17063) -> InlayHintSettings {
17064    let file = snapshot.file_at(location);
17065    let language = snapshot.language_at(location).map(|l| l.name());
17066    language_settings(language, file, cx).inlay_hints
17067}
17068
17069fn consume_contiguous_rows(
17070    contiguous_row_selections: &mut Vec<Selection<Point>>,
17071    selection: &Selection<Point>,
17072    display_map: &DisplaySnapshot,
17073    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17074) -> (MultiBufferRow, MultiBufferRow) {
17075    contiguous_row_selections.push(selection.clone());
17076    let start_row = MultiBufferRow(selection.start.row);
17077    let mut end_row = ending_row(selection, display_map);
17078
17079    while let Some(next_selection) = selections.peek() {
17080        if next_selection.start.row <= end_row.0 {
17081            end_row = ending_row(next_selection, display_map);
17082            contiguous_row_selections.push(selections.next().unwrap().clone());
17083        } else {
17084            break;
17085        }
17086    }
17087    (start_row, end_row)
17088}
17089
17090fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17091    if next_selection.end.column > 0 || next_selection.is_empty() {
17092        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17093    } else {
17094        MultiBufferRow(next_selection.end.row)
17095    }
17096}
17097
17098impl EditorSnapshot {
17099    pub fn remote_selections_in_range<'a>(
17100        &'a self,
17101        range: &'a Range<Anchor>,
17102        collaboration_hub: &dyn CollaborationHub,
17103        cx: &'a App,
17104    ) -> impl 'a + Iterator<Item = RemoteSelection> {
17105        let participant_names = collaboration_hub.user_names(cx);
17106        let participant_indices = collaboration_hub.user_participant_indices(cx);
17107        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17108        let collaborators_by_replica_id = collaborators_by_peer_id
17109            .iter()
17110            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17111            .collect::<HashMap<_, _>>();
17112        self.buffer_snapshot
17113            .selections_in_range(range, false)
17114            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17115                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17116                let participant_index = participant_indices.get(&collaborator.user_id).copied();
17117                let user_name = participant_names.get(&collaborator.user_id).cloned();
17118                Some(RemoteSelection {
17119                    replica_id,
17120                    selection,
17121                    cursor_shape,
17122                    line_mode,
17123                    participant_index,
17124                    peer_id: collaborator.peer_id,
17125                    user_name,
17126                })
17127            })
17128    }
17129
17130    pub fn hunks_for_ranges(
17131        &self,
17132        ranges: impl IntoIterator<Item = Range<Point>>,
17133    ) -> Vec<MultiBufferDiffHunk> {
17134        let mut hunks = Vec::new();
17135        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17136            HashMap::default();
17137        for query_range in ranges {
17138            let query_rows =
17139                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17140            for hunk in self.buffer_snapshot.diff_hunks_in_range(
17141                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17142            ) {
17143                // Include deleted hunks that are adjacent to the query range, because
17144                // otherwise they would be missed.
17145                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
17146                if hunk.status().is_deleted() {
17147                    intersects_range |= hunk.row_range.start == query_rows.end;
17148                    intersects_range |= hunk.row_range.end == query_rows.start;
17149                }
17150                if intersects_range {
17151                    if !processed_buffer_rows
17152                        .entry(hunk.buffer_id)
17153                        .or_default()
17154                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17155                    {
17156                        continue;
17157                    }
17158                    hunks.push(hunk);
17159                }
17160            }
17161        }
17162
17163        hunks
17164    }
17165
17166    fn display_diff_hunks_for_rows<'a>(
17167        &'a self,
17168        display_rows: Range<DisplayRow>,
17169        folded_buffers: &'a HashSet<BufferId>,
17170    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17171        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17172        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17173
17174        self.buffer_snapshot
17175            .diff_hunks_in_range(buffer_start..buffer_end)
17176            .filter_map(|hunk| {
17177                if folded_buffers.contains(&hunk.buffer_id) {
17178                    return None;
17179                }
17180
17181                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17182                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17183
17184                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17185                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17186
17187                let display_hunk = if hunk_display_start.column() != 0 {
17188                    DisplayDiffHunk::Folded {
17189                        display_row: hunk_display_start.row(),
17190                    }
17191                } else {
17192                    let mut end_row = hunk_display_end.row();
17193                    if hunk_display_end.column() > 0 {
17194                        end_row.0 += 1;
17195                    }
17196                    let is_created_file = hunk.is_created_file();
17197                    DisplayDiffHunk::Unfolded {
17198                        status: hunk.status(),
17199                        diff_base_byte_range: hunk.diff_base_byte_range,
17200                        display_row_range: hunk_display_start.row()..end_row,
17201                        multi_buffer_range: Anchor::range_in_buffer(
17202                            hunk.excerpt_id,
17203                            hunk.buffer_id,
17204                            hunk.buffer_range,
17205                        ),
17206                        is_created_file,
17207                    }
17208                };
17209
17210                Some(display_hunk)
17211            })
17212    }
17213
17214    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17215        self.display_snapshot.buffer_snapshot.language_at(position)
17216    }
17217
17218    pub fn is_focused(&self) -> bool {
17219        self.is_focused
17220    }
17221
17222    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17223        self.placeholder_text.as_ref()
17224    }
17225
17226    pub fn scroll_position(&self) -> gpui::Point<f32> {
17227        self.scroll_anchor.scroll_position(&self.display_snapshot)
17228    }
17229
17230    fn gutter_dimensions(
17231        &self,
17232        font_id: FontId,
17233        font_size: Pixels,
17234        max_line_number_width: Pixels,
17235        cx: &App,
17236    ) -> Option<GutterDimensions> {
17237        if !self.show_gutter {
17238            return None;
17239        }
17240
17241        let descent = cx.text_system().descent(font_id, font_size);
17242        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17243        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17244
17245        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17246            matches!(
17247                ProjectSettings::get_global(cx).git.git_gutter,
17248                Some(GitGutterSetting::TrackedFiles)
17249            )
17250        });
17251        let gutter_settings = EditorSettings::get_global(cx).gutter;
17252        let show_line_numbers = self
17253            .show_line_numbers
17254            .unwrap_or(gutter_settings.line_numbers);
17255        let line_gutter_width = if show_line_numbers {
17256            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17257            let min_width_for_number_on_gutter = em_advance * 4.0;
17258            max_line_number_width.max(min_width_for_number_on_gutter)
17259        } else {
17260            0.0.into()
17261        };
17262
17263        let show_code_actions = self
17264            .show_code_actions
17265            .unwrap_or(gutter_settings.code_actions);
17266
17267        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17268
17269        let git_blame_entries_width =
17270            self.git_blame_gutter_max_author_length
17271                .map(|max_author_length| {
17272                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17273
17274                    /// The number of characters to dedicate to gaps and margins.
17275                    const SPACING_WIDTH: usize = 4;
17276
17277                    let max_char_count = max_author_length
17278                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17279                        + ::git::SHORT_SHA_LENGTH
17280                        + MAX_RELATIVE_TIMESTAMP.len()
17281                        + SPACING_WIDTH;
17282
17283                    em_advance * max_char_count
17284                });
17285
17286        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17287        left_padding += if show_code_actions || show_runnables {
17288            em_width * 3.0
17289        } else if show_git_gutter && show_line_numbers {
17290            em_width * 2.0
17291        } else if show_git_gutter || show_line_numbers {
17292            em_width
17293        } else {
17294            px(0.)
17295        };
17296
17297        let right_padding = if gutter_settings.folds && show_line_numbers {
17298            em_width * 4.0
17299        } else if gutter_settings.folds {
17300            em_width * 3.0
17301        } else if show_line_numbers {
17302            em_width
17303        } else {
17304            px(0.)
17305        };
17306
17307        Some(GutterDimensions {
17308            left_padding,
17309            right_padding,
17310            width: line_gutter_width + left_padding + right_padding,
17311            margin: -descent,
17312            git_blame_entries_width,
17313        })
17314    }
17315
17316    pub fn render_crease_toggle(
17317        &self,
17318        buffer_row: MultiBufferRow,
17319        row_contains_cursor: bool,
17320        editor: Entity<Editor>,
17321        window: &mut Window,
17322        cx: &mut App,
17323    ) -> Option<AnyElement> {
17324        let folded = self.is_line_folded(buffer_row);
17325        let mut is_foldable = false;
17326
17327        if let Some(crease) = self
17328            .crease_snapshot
17329            .query_row(buffer_row, &self.buffer_snapshot)
17330        {
17331            is_foldable = true;
17332            match crease {
17333                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17334                    if let Some(render_toggle) = render_toggle {
17335                        let toggle_callback =
17336                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17337                                if folded {
17338                                    editor.update(cx, |editor, cx| {
17339                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17340                                    });
17341                                } else {
17342                                    editor.update(cx, |editor, cx| {
17343                                        editor.unfold_at(
17344                                            &crate::UnfoldAt { buffer_row },
17345                                            window,
17346                                            cx,
17347                                        )
17348                                    });
17349                                }
17350                            });
17351                        return Some((render_toggle)(
17352                            buffer_row,
17353                            folded,
17354                            toggle_callback,
17355                            window,
17356                            cx,
17357                        ));
17358                    }
17359                }
17360            }
17361        }
17362
17363        is_foldable |= self.starts_indent(buffer_row);
17364
17365        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17366            Some(
17367                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17368                    .toggle_state(folded)
17369                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17370                        if folded {
17371                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17372                        } else {
17373                            this.fold_at(&FoldAt { buffer_row }, window, cx);
17374                        }
17375                    }))
17376                    .into_any_element(),
17377            )
17378        } else {
17379            None
17380        }
17381    }
17382
17383    pub fn render_crease_trailer(
17384        &self,
17385        buffer_row: MultiBufferRow,
17386        window: &mut Window,
17387        cx: &mut App,
17388    ) -> Option<AnyElement> {
17389        let folded = self.is_line_folded(buffer_row);
17390        if let Crease::Inline { render_trailer, .. } = self
17391            .crease_snapshot
17392            .query_row(buffer_row, &self.buffer_snapshot)?
17393        {
17394            let render_trailer = render_trailer.as_ref()?;
17395            Some(render_trailer(buffer_row, folded, window, cx))
17396        } else {
17397            None
17398        }
17399    }
17400}
17401
17402impl Deref for EditorSnapshot {
17403    type Target = DisplaySnapshot;
17404
17405    fn deref(&self) -> &Self::Target {
17406        &self.display_snapshot
17407    }
17408}
17409
17410#[derive(Clone, Debug, PartialEq, Eq)]
17411pub enum EditorEvent {
17412    InputIgnored {
17413        text: Arc<str>,
17414    },
17415    InputHandled {
17416        utf16_range_to_replace: Option<Range<isize>>,
17417        text: Arc<str>,
17418    },
17419    ExcerptsAdded {
17420        buffer: Entity<Buffer>,
17421        predecessor: ExcerptId,
17422        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17423    },
17424    ExcerptsRemoved {
17425        ids: Vec<ExcerptId>,
17426    },
17427    BufferFoldToggled {
17428        ids: Vec<ExcerptId>,
17429        folded: bool,
17430    },
17431    ExcerptsEdited {
17432        ids: Vec<ExcerptId>,
17433    },
17434    ExcerptsExpanded {
17435        ids: Vec<ExcerptId>,
17436    },
17437    BufferEdited,
17438    Edited {
17439        transaction_id: clock::Lamport,
17440    },
17441    Reparsed(BufferId),
17442    Focused,
17443    FocusedIn,
17444    Blurred,
17445    DirtyChanged,
17446    Saved,
17447    TitleChanged,
17448    DiffBaseChanged,
17449    SelectionsChanged {
17450        local: bool,
17451    },
17452    ScrollPositionChanged {
17453        local: bool,
17454        autoscroll: bool,
17455    },
17456    Closed,
17457    TransactionUndone {
17458        transaction_id: clock::Lamport,
17459    },
17460    TransactionBegun {
17461        transaction_id: clock::Lamport,
17462    },
17463    Reloaded,
17464    CursorShapeChanged,
17465}
17466
17467impl EventEmitter<EditorEvent> for Editor {}
17468
17469impl Focusable for Editor {
17470    fn focus_handle(&self, _cx: &App) -> FocusHandle {
17471        self.focus_handle.clone()
17472    }
17473}
17474
17475impl Render for Editor {
17476    fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17477        let settings = ThemeSettings::get_global(cx);
17478
17479        let mut text_style = match self.mode {
17480            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17481                color: cx.theme().colors().editor_foreground,
17482                font_family: settings.ui_font.family.clone(),
17483                font_features: settings.ui_font.features.clone(),
17484                font_fallbacks: settings.ui_font.fallbacks.clone(),
17485                font_size: rems(0.875).into(),
17486                font_weight: settings.ui_font.weight,
17487                line_height: relative(settings.buffer_line_height.value()),
17488                ..Default::default()
17489            },
17490            EditorMode::Full => TextStyle {
17491                color: cx.theme().colors().editor_foreground,
17492                font_family: settings.buffer_font.family.clone(),
17493                font_features: settings.buffer_font.features.clone(),
17494                font_fallbacks: settings.buffer_font.fallbacks.clone(),
17495                font_size: settings.buffer_font_size(cx).into(),
17496                font_weight: settings.buffer_font.weight,
17497                line_height: relative(settings.buffer_line_height.value()),
17498                ..Default::default()
17499            },
17500        };
17501        if let Some(text_style_refinement) = &self.text_style_refinement {
17502            text_style.refine(text_style_refinement)
17503        }
17504
17505        let background = match self.mode {
17506            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17507            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17508            EditorMode::Full => cx.theme().colors().editor_background,
17509        };
17510
17511        EditorElement::new(
17512            &cx.entity(),
17513            EditorStyle {
17514                background,
17515                local_player: cx.theme().players().local(),
17516                text: text_style,
17517                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17518                syntax: cx.theme().syntax().clone(),
17519                status: cx.theme().status().clone(),
17520                inlay_hints_style: make_inlay_hints_style(cx),
17521                inline_completion_styles: make_suggestion_styles(cx),
17522                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17523            },
17524        )
17525    }
17526}
17527
17528impl EntityInputHandler for Editor {
17529    fn text_for_range(
17530        &mut self,
17531        range_utf16: Range<usize>,
17532        adjusted_range: &mut Option<Range<usize>>,
17533        _: &mut Window,
17534        cx: &mut Context<Self>,
17535    ) -> Option<String> {
17536        let snapshot = self.buffer.read(cx).read(cx);
17537        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17538        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17539        if (start.0..end.0) != range_utf16 {
17540            adjusted_range.replace(start.0..end.0);
17541        }
17542        Some(snapshot.text_for_range(start..end).collect())
17543    }
17544
17545    fn selected_text_range(
17546        &mut self,
17547        ignore_disabled_input: bool,
17548        _: &mut Window,
17549        cx: &mut Context<Self>,
17550    ) -> Option<UTF16Selection> {
17551        // Prevent the IME menu from appearing when holding down an alphabetic key
17552        // while input is disabled.
17553        if !ignore_disabled_input && !self.input_enabled {
17554            return None;
17555        }
17556
17557        let selection = self.selections.newest::<OffsetUtf16>(cx);
17558        let range = selection.range();
17559
17560        Some(UTF16Selection {
17561            range: range.start.0..range.end.0,
17562            reversed: selection.reversed,
17563        })
17564    }
17565
17566    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17567        let snapshot = self.buffer.read(cx).read(cx);
17568        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17569        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17570    }
17571
17572    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17573        self.clear_highlights::<InputComposition>(cx);
17574        self.ime_transaction.take();
17575    }
17576
17577    fn replace_text_in_range(
17578        &mut self,
17579        range_utf16: Option<Range<usize>>,
17580        text: &str,
17581        window: &mut Window,
17582        cx: &mut Context<Self>,
17583    ) {
17584        if !self.input_enabled {
17585            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17586            return;
17587        }
17588
17589        self.transact(window, cx, |this, window, cx| {
17590            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17591                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17592                Some(this.selection_replacement_ranges(range_utf16, cx))
17593            } else {
17594                this.marked_text_ranges(cx)
17595            };
17596
17597            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17598                let newest_selection_id = this.selections.newest_anchor().id;
17599                this.selections
17600                    .all::<OffsetUtf16>(cx)
17601                    .iter()
17602                    .zip(ranges_to_replace.iter())
17603                    .find_map(|(selection, range)| {
17604                        if selection.id == newest_selection_id {
17605                            Some(
17606                                (range.start.0 as isize - selection.head().0 as isize)
17607                                    ..(range.end.0 as isize - selection.head().0 as isize),
17608                            )
17609                        } else {
17610                            None
17611                        }
17612                    })
17613            });
17614
17615            cx.emit(EditorEvent::InputHandled {
17616                utf16_range_to_replace: range_to_replace,
17617                text: text.into(),
17618            });
17619
17620            if let Some(new_selected_ranges) = new_selected_ranges {
17621                this.change_selections(None, window, cx, |selections| {
17622                    selections.select_ranges(new_selected_ranges)
17623                });
17624                this.backspace(&Default::default(), window, cx);
17625            }
17626
17627            this.handle_input(text, window, cx);
17628        });
17629
17630        if let Some(transaction) = self.ime_transaction {
17631            self.buffer.update(cx, |buffer, cx| {
17632                buffer.group_until_transaction(transaction, cx);
17633            });
17634        }
17635
17636        self.unmark_text(window, cx);
17637    }
17638
17639    fn replace_and_mark_text_in_range(
17640        &mut self,
17641        range_utf16: Option<Range<usize>>,
17642        text: &str,
17643        new_selected_range_utf16: Option<Range<usize>>,
17644        window: &mut Window,
17645        cx: &mut Context<Self>,
17646    ) {
17647        if !self.input_enabled {
17648            return;
17649        }
17650
17651        let transaction = self.transact(window, cx, |this, window, cx| {
17652            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17653                let snapshot = this.buffer.read(cx).read(cx);
17654                if let Some(relative_range_utf16) = range_utf16.as_ref() {
17655                    for marked_range in &mut marked_ranges {
17656                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17657                        marked_range.start.0 += relative_range_utf16.start;
17658                        marked_range.start =
17659                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17660                        marked_range.end =
17661                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17662                    }
17663                }
17664                Some(marked_ranges)
17665            } else if let Some(range_utf16) = range_utf16 {
17666                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17667                Some(this.selection_replacement_ranges(range_utf16, cx))
17668            } else {
17669                None
17670            };
17671
17672            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17673                let newest_selection_id = this.selections.newest_anchor().id;
17674                this.selections
17675                    .all::<OffsetUtf16>(cx)
17676                    .iter()
17677                    .zip(ranges_to_replace.iter())
17678                    .find_map(|(selection, range)| {
17679                        if selection.id == newest_selection_id {
17680                            Some(
17681                                (range.start.0 as isize - selection.head().0 as isize)
17682                                    ..(range.end.0 as isize - selection.head().0 as isize),
17683                            )
17684                        } else {
17685                            None
17686                        }
17687                    })
17688            });
17689
17690            cx.emit(EditorEvent::InputHandled {
17691                utf16_range_to_replace: range_to_replace,
17692                text: text.into(),
17693            });
17694
17695            if let Some(ranges) = ranges_to_replace {
17696                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17697            }
17698
17699            let marked_ranges = {
17700                let snapshot = this.buffer.read(cx).read(cx);
17701                this.selections
17702                    .disjoint_anchors()
17703                    .iter()
17704                    .map(|selection| {
17705                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17706                    })
17707                    .collect::<Vec<_>>()
17708            };
17709
17710            if text.is_empty() {
17711                this.unmark_text(window, cx);
17712            } else {
17713                this.highlight_text::<InputComposition>(
17714                    marked_ranges.clone(),
17715                    HighlightStyle {
17716                        underline: Some(UnderlineStyle {
17717                            thickness: px(1.),
17718                            color: None,
17719                            wavy: false,
17720                        }),
17721                        ..Default::default()
17722                    },
17723                    cx,
17724                );
17725            }
17726
17727            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17728            let use_autoclose = this.use_autoclose;
17729            let use_auto_surround = this.use_auto_surround;
17730            this.set_use_autoclose(false);
17731            this.set_use_auto_surround(false);
17732            this.handle_input(text, window, cx);
17733            this.set_use_autoclose(use_autoclose);
17734            this.set_use_auto_surround(use_auto_surround);
17735
17736            if let Some(new_selected_range) = new_selected_range_utf16 {
17737                let snapshot = this.buffer.read(cx).read(cx);
17738                let new_selected_ranges = marked_ranges
17739                    .into_iter()
17740                    .map(|marked_range| {
17741                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17742                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17743                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17744                        snapshot.clip_offset_utf16(new_start, Bias::Left)
17745                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17746                    })
17747                    .collect::<Vec<_>>();
17748
17749                drop(snapshot);
17750                this.change_selections(None, window, cx, |selections| {
17751                    selections.select_ranges(new_selected_ranges)
17752                });
17753            }
17754        });
17755
17756        self.ime_transaction = self.ime_transaction.or(transaction);
17757        if let Some(transaction) = self.ime_transaction {
17758            self.buffer.update(cx, |buffer, cx| {
17759                buffer.group_until_transaction(transaction, cx);
17760            });
17761        }
17762
17763        if self.text_highlights::<InputComposition>(cx).is_none() {
17764            self.ime_transaction.take();
17765        }
17766    }
17767
17768    fn bounds_for_range(
17769        &mut self,
17770        range_utf16: Range<usize>,
17771        element_bounds: gpui::Bounds<Pixels>,
17772        window: &mut Window,
17773        cx: &mut Context<Self>,
17774    ) -> Option<gpui::Bounds<Pixels>> {
17775        let text_layout_details = self.text_layout_details(window);
17776        let gpui::Size {
17777            width: em_width,
17778            height: line_height,
17779        } = self.character_size(window);
17780
17781        let snapshot = self.snapshot(window, cx);
17782        let scroll_position = snapshot.scroll_position();
17783        let scroll_left = scroll_position.x * em_width;
17784
17785        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17786        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17787            + self.gutter_dimensions.width
17788            + self.gutter_dimensions.margin;
17789        let y = line_height * (start.row().as_f32() - scroll_position.y);
17790
17791        Some(Bounds {
17792            origin: element_bounds.origin + point(x, y),
17793            size: size(em_width, line_height),
17794        })
17795    }
17796
17797    fn character_index_for_point(
17798        &mut self,
17799        point: gpui::Point<Pixels>,
17800        _window: &mut Window,
17801        _cx: &mut Context<Self>,
17802    ) -> Option<usize> {
17803        let position_map = self.last_position_map.as_ref()?;
17804        if !position_map.text_hitbox.contains(&point) {
17805            return None;
17806        }
17807        let display_point = position_map.point_for_position(point).previous_valid;
17808        let anchor = position_map
17809            .snapshot
17810            .display_point_to_anchor(display_point, Bias::Left);
17811        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17812        Some(utf16_offset.0)
17813    }
17814}
17815
17816trait SelectionExt {
17817    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17818    fn spanned_rows(
17819        &self,
17820        include_end_if_at_line_start: bool,
17821        map: &DisplaySnapshot,
17822    ) -> Range<MultiBufferRow>;
17823}
17824
17825impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17826    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17827        let start = self
17828            .start
17829            .to_point(&map.buffer_snapshot)
17830            .to_display_point(map);
17831        let end = self
17832            .end
17833            .to_point(&map.buffer_snapshot)
17834            .to_display_point(map);
17835        if self.reversed {
17836            end..start
17837        } else {
17838            start..end
17839        }
17840    }
17841
17842    fn spanned_rows(
17843        &self,
17844        include_end_if_at_line_start: bool,
17845        map: &DisplaySnapshot,
17846    ) -> Range<MultiBufferRow> {
17847        let start = self.start.to_point(&map.buffer_snapshot);
17848        let mut end = self.end.to_point(&map.buffer_snapshot);
17849        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17850            end.row -= 1;
17851        }
17852
17853        let buffer_start = map.prev_line_boundary(start).0;
17854        let buffer_end = map.next_line_boundary(end).0;
17855        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17856    }
17857}
17858
17859impl<T: InvalidationRegion> InvalidationStack<T> {
17860    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17861    where
17862        S: Clone + ToOffset,
17863    {
17864        while let Some(region) = self.last() {
17865            let all_selections_inside_invalidation_ranges =
17866                if selections.len() == region.ranges().len() {
17867                    selections
17868                        .iter()
17869                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17870                        .all(|(selection, invalidation_range)| {
17871                            let head = selection.head().to_offset(buffer);
17872                            invalidation_range.start <= head && invalidation_range.end >= head
17873                        })
17874                } else {
17875                    false
17876                };
17877
17878            if all_selections_inside_invalidation_ranges {
17879                break;
17880            } else {
17881                self.pop();
17882            }
17883        }
17884    }
17885}
17886
17887impl<T> Default for InvalidationStack<T> {
17888    fn default() -> Self {
17889        Self(Default::default())
17890    }
17891}
17892
17893impl<T> Deref for InvalidationStack<T> {
17894    type Target = Vec<T>;
17895
17896    fn deref(&self) -> &Self::Target {
17897        &self.0
17898    }
17899}
17900
17901impl<T> DerefMut for InvalidationStack<T> {
17902    fn deref_mut(&mut self) -> &mut Self::Target {
17903        &mut self.0
17904    }
17905}
17906
17907impl InvalidationRegion for SnippetState {
17908    fn ranges(&self) -> &[Range<Anchor>] {
17909        &self.ranges[self.active_index]
17910    }
17911}
17912
17913pub fn diagnostic_block_renderer(
17914    diagnostic: Diagnostic,
17915    max_message_rows: Option<u8>,
17916    allow_closing: bool,
17917) -> RenderBlock {
17918    let (text_without_backticks, code_ranges) =
17919        highlight_diagnostic_message(&diagnostic, max_message_rows);
17920
17921    Arc::new(move |cx: &mut BlockContext| {
17922        let group_id: SharedString = cx.block_id.to_string().into();
17923
17924        let mut text_style = cx.window.text_style().clone();
17925        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17926        let theme_settings = ThemeSettings::get_global(cx);
17927        text_style.font_family = theme_settings.buffer_font.family.clone();
17928        text_style.font_style = theme_settings.buffer_font.style;
17929        text_style.font_features = theme_settings.buffer_font.features.clone();
17930        text_style.font_weight = theme_settings.buffer_font.weight;
17931
17932        let multi_line_diagnostic = diagnostic.message.contains('\n');
17933
17934        let buttons = |diagnostic: &Diagnostic| {
17935            if multi_line_diagnostic {
17936                v_flex()
17937            } else {
17938                h_flex()
17939            }
17940            .when(allow_closing, |div| {
17941                div.children(diagnostic.is_primary.then(|| {
17942                    IconButton::new("close-block", IconName::XCircle)
17943                        .icon_color(Color::Muted)
17944                        .size(ButtonSize::Compact)
17945                        .style(ButtonStyle::Transparent)
17946                        .visible_on_hover(group_id.clone())
17947                        .on_click(move |_click, window, cx| {
17948                            window.dispatch_action(Box::new(Cancel), cx)
17949                        })
17950                        .tooltip(|window, cx| {
17951                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
17952                        })
17953                }))
17954            })
17955            .child(
17956                IconButton::new("copy-block", IconName::Copy)
17957                    .icon_color(Color::Muted)
17958                    .size(ButtonSize::Compact)
17959                    .style(ButtonStyle::Transparent)
17960                    .visible_on_hover(group_id.clone())
17961                    .on_click({
17962                        let message = diagnostic.message.clone();
17963                        move |_click, _, cx| {
17964                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
17965                        }
17966                    })
17967                    .tooltip(Tooltip::text("Copy diagnostic message")),
17968            )
17969        };
17970
17971        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
17972            AvailableSpace::min_size(),
17973            cx.window,
17974            cx.app,
17975        );
17976
17977        h_flex()
17978            .id(cx.block_id)
17979            .group(group_id.clone())
17980            .relative()
17981            .size_full()
17982            .block_mouse_down()
17983            .pl(cx.gutter_dimensions.width)
17984            .w(cx.max_width - cx.gutter_dimensions.full_width())
17985            .child(
17986                div()
17987                    .flex()
17988                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
17989                    .flex_shrink(),
17990            )
17991            .child(buttons(&diagnostic))
17992            .child(div().flex().flex_shrink_0().child(
17993                StyledText::new(text_without_backticks.clone()).with_default_highlights(
17994                    &text_style,
17995                    code_ranges.iter().map(|range| {
17996                        (
17997                            range.clone(),
17998                            HighlightStyle {
17999                                font_weight: Some(FontWeight::BOLD),
18000                                ..Default::default()
18001                            },
18002                        )
18003                    }),
18004                ),
18005            ))
18006            .into_any_element()
18007    })
18008}
18009
18010fn inline_completion_edit_text(
18011    current_snapshot: &BufferSnapshot,
18012    edits: &[(Range<Anchor>, String)],
18013    edit_preview: &EditPreview,
18014    include_deletions: bool,
18015    cx: &App,
18016) -> HighlightedText {
18017    let edits = edits
18018        .iter()
18019        .map(|(anchor, text)| {
18020            (
18021                anchor.start.text_anchor..anchor.end.text_anchor,
18022                text.clone(),
18023            )
18024        })
18025        .collect::<Vec<_>>();
18026
18027    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18028}
18029
18030pub fn highlight_diagnostic_message(
18031    diagnostic: &Diagnostic,
18032    mut max_message_rows: Option<u8>,
18033) -> (SharedString, Vec<Range<usize>>) {
18034    let mut text_without_backticks = String::new();
18035    let mut code_ranges = Vec::new();
18036
18037    if let Some(source) = &diagnostic.source {
18038        text_without_backticks.push_str(source);
18039        code_ranges.push(0..source.len());
18040        text_without_backticks.push_str(": ");
18041    }
18042
18043    let mut prev_offset = 0;
18044    let mut in_code_block = false;
18045    let has_row_limit = max_message_rows.is_some();
18046    let mut newline_indices = diagnostic
18047        .message
18048        .match_indices('\n')
18049        .filter(|_| has_row_limit)
18050        .map(|(ix, _)| ix)
18051        .fuse()
18052        .peekable();
18053
18054    for (quote_ix, _) in diagnostic
18055        .message
18056        .match_indices('`')
18057        .chain([(diagnostic.message.len(), "")])
18058    {
18059        let mut first_newline_ix = None;
18060        let mut last_newline_ix = None;
18061        while let Some(newline_ix) = newline_indices.peek() {
18062            if *newline_ix < quote_ix {
18063                if first_newline_ix.is_none() {
18064                    first_newline_ix = Some(*newline_ix);
18065                }
18066                last_newline_ix = Some(*newline_ix);
18067
18068                if let Some(rows_left) = &mut max_message_rows {
18069                    if *rows_left == 0 {
18070                        break;
18071                    } else {
18072                        *rows_left -= 1;
18073                    }
18074                }
18075                let _ = newline_indices.next();
18076            } else {
18077                break;
18078            }
18079        }
18080        let prev_len = text_without_backticks.len();
18081        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18082        text_without_backticks.push_str(new_text);
18083        if in_code_block {
18084            code_ranges.push(prev_len..text_without_backticks.len());
18085        }
18086        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18087        in_code_block = !in_code_block;
18088        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18089            text_without_backticks.push_str("...");
18090            break;
18091        }
18092    }
18093
18094    (text_without_backticks.into(), code_ranges)
18095}
18096
18097fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18098    match severity {
18099        DiagnosticSeverity::ERROR => colors.error,
18100        DiagnosticSeverity::WARNING => colors.warning,
18101        DiagnosticSeverity::INFORMATION => colors.info,
18102        DiagnosticSeverity::HINT => colors.info,
18103        _ => colors.ignored,
18104    }
18105}
18106
18107pub fn styled_runs_for_code_label<'a>(
18108    label: &'a CodeLabel,
18109    syntax_theme: &'a theme::SyntaxTheme,
18110) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18111    let fade_out = HighlightStyle {
18112        fade_out: Some(0.35),
18113        ..Default::default()
18114    };
18115
18116    let mut prev_end = label.filter_range.end;
18117    label
18118        .runs
18119        .iter()
18120        .enumerate()
18121        .flat_map(move |(ix, (range, highlight_id))| {
18122            let style = if let Some(style) = highlight_id.style(syntax_theme) {
18123                style
18124            } else {
18125                return Default::default();
18126            };
18127            let mut muted_style = style;
18128            muted_style.highlight(fade_out);
18129
18130            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18131            if range.start >= label.filter_range.end {
18132                if range.start > prev_end {
18133                    runs.push((prev_end..range.start, fade_out));
18134                }
18135                runs.push((range.clone(), muted_style));
18136            } else if range.end <= label.filter_range.end {
18137                runs.push((range.clone(), style));
18138            } else {
18139                runs.push((range.start..label.filter_range.end, style));
18140                runs.push((label.filter_range.end..range.end, muted_style));
18141            }
18142            prev_end = cmp::max(prev_end, range.end);
18143
18144            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18145                runs.push((prev_end..label.text.len(), fade_out));
18146            }
18147
18148            runs
18149        })
18150}
18151
18152pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18153    let mut prev_index = 0;
18154    let mut prev_codepoint: Option<char> = None;
18155    text.char_indices()
18156        .chain([(text.len(), '\0')])
18157        .filter_map(move |(index, codepoint)| {
18158            let prev_codepoint = prev_codepoint.replace(codepoint)?;
18159            let is_boundary = index == text.len()
18160                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18161                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18162            if is_boundary {
18163                let chunk = &text[prev_index..index];
18164                prev_index = index;
18165                Some(chunk)
18166            } else {
18167                None
18168            }
18169        })
18170}
18171
18172pub trait RangeToAnchorExt: Sized {
18173    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18174
18175    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18176        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18177        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18178    }
18179}
18180
18181impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18182    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18183        let start_offset = self.start.to_offset(snapshot);
18184        let end_offset = self.end.to_offset(snapshot);
18185        if start_offset == end_offset {
18186            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18187        } else {
18188            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18189        }
18190    }
18191}
18192
18193pub trait RowExt {
18194    fn as_f32(&self) -> f32;
18195
18196    fn next_row(&self) -> Self;
18197
18198    fn previous_row(&self) -> Self;
18199
18200    fn minus(&self, other: Self) -> u32;
18201}
18202
18203impl RowExt for DisplayRow {
18204    fn as_f32(&self) -> f32 {
18205        self.0 as f32
18206    }
18207
18208    fn next_row(&self) -> Self {
18209        Self(self.0 + 1)
18210    }
18211
18212    fn previous_row(&self) -> Self {
18213        Self(self.0.saturating_sub(1))
18214    }
18215
18216    fn minus(&self, other: Self) -> u32 {
18217        self.0 - other.0
18218    }
18219}
18220
18221impl RowExt for MultiBufferRow {
18222    fn as_f32(&self) -> f32 {
18223        self.0 as f32
18224    }
18225
18226    fn next_row(&self) -> Self {
18227        Self(self.0 + 1)
18228    }
18229
18230    fn previous_row(&self) -> Self {
18231        Self(self.0.saturating_sub(1))
18232    }
18233
18234    fn minus(&self, other: Self) -> u32 {
18235        self.0 - other.0
18236    }
18237}
18238
18239trait RowRangeExt {
18240    type Row;
18241
18242    fn len(&self) -> usize;
18243
18244    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18245}
18246
18247impl RowRangeExt for Range<MultiBufferRow> {
18248    type Row = MultiBufferRow;
18249
18250    fn len(&self) -> usize {
18251        (self.end.0 - self.start.0) as usize
18252    }
18253
18254    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18255        (self.start.0..self.end.0).map(MultiBufferRow)
18256    }
18257}
18258
18259impl RowRangeExt for Range<DisplayRow> {
18260    type Row = DisplayRow;
18261
18262    fn len(&self) -> usize {
18263        (self.end.0 - self.start.0) as usize
18264    }
18265
18266    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18267        (self.start.0..self.end.0).map(DisplayRow)
18268    }
18269}
18270
18271/// If select range has more than one line, we
18272/// just point the cursor to range.start.
18273fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18274    if range.start.row == range.end.row {
18275        range
18276    } else {
18277        range.start..range.start
18278    }
18279}
18280pub struct KillRing(ClipboardItem);
18281impl Global for KillRing {}
18282
18283const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18284
18285fn all_edits_insertions_or_deletions(
18286    edits: &Vec<(Range<Anchor>, String)>,
18287    snapshot: &MultiBufferSnapshot,
18288) -> bool {
18289    let mut all_insertions = true;
18290    let mut all_deletions = true;
18291
18292    for (range, new_text) in edits.iter() {
18293        let range_is_empty = range.to_offset(&snapshot).is_empty();
18294        let text_is_empty = new_text.is_empty();
18295
18296        if range_is_empty != text_is_empty {
18297            if range_is_empty {
18298                all_deletions = false;
18299            } else {
18300                all_insertions = false;
18301            }
18302        } else {
18303            return false;
18304        }
18305
18306        if !all_insertions && !all_deletions {
18307            return false;
18308        }
18309    }
18310    all_insertions || all_deletions
18311}