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        diff_base_byte_range: Range<usize>,
  264        display_row_range: Range<DisplayRow>,
  265        multi_buffer_range: Range<Anchor>,
  266        status: DiffHunkStatus,
  267    },
  268}
  269
  270pub fn init_settings(cx: &mut App) {
  271    EditorSettings::register(cx);
  272}
  273
  274pub fn init(cx: &mut App) {
  275    init_settings(cx);
  276
  277    workspace::register_project_item::<Editor>(cx);
  278    workspace::FollowableViewRegistry::register::<Editor>(cx);
  279    workspace::register_serializable_item::<Editor>(cx);
  280
  281    cx.observe_new(
  282        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  283            workspace.register_action(Editor::new_file);
  284            workspace.register_action(Editor::new_file_vertical);
  285            workspace.register_action(Editor::new_file_horizontal);
  286            workspace.register_action(Editor::cancel_language_server_work);
  287        },
  288    )
  289    .detach();
  290
  291    cx.on_action(move |_: &workspace::NewFile, cx| {
  292        let app_state = workspace::AppState::global(cx);
  293        if let Some(app_state) = app_state.upgrade() {
  294            workspace::open_new(
  295                Default::default(),
  296                app_state,
  297                cx,
  298                |workspace, window, cx| {
  299                    Editor::new_file(workspace, &Default::default(), window, cx)
  300                },
  301            )
  302            .detach();
  303        }
  304    });
  305    cx.on_action(move |_: &workspace::NewWindow, cx| {
  306        let app_state = workspace::AppState::global(cx);
  307        if let Some(app_state) = app_state.upgrade() {
  308            workspace::open_new(
  309                Default::default(),
  310                app_state,
  311                cx,
  312                |workspace, window, cx| {
  313                    cx.activate(true);
  314                    Editor::new_file(workspace, &Default::default(), window, cx)
  315                },
  316            )
  317            .detach();
  318        }
  319    });
  320}
  321
  322pub struct SearchWithinRange;
  323
  324trait InvalidationRegion {
  325    fn ranges(&self) -> &[Range<Anchor>];
  326}
  327
  328#[derive(Clone, Debug, PartialEq)]
  329pub enum SelectPhase {
  330    Begin {
  331        position: DisplayPoint,
  332        add: bool,
  333        click_count: usize,
  334    },
  335    BeginColumnar {
  336        position: DisplayPoint,
  337        reset: bool,
  338        goal_column: u32,
  339    },
  340    Extend {
  341        position: DisplayPoint,
  342        click_count: usize,
  343    },
  344    Update {
  345        position: DisplayPoint,
  346        goal_column: u32,
  347        scroll_delta: gpui::Point<f32>,
  348    },
  349    End,
  350}
  351
  352#[derive(Clone, Debug)]
  353pub enum SelectMode {
  354    Character,
  355    Word(Range<Anchor>),
  356    Line(Range<Anchor>),
  357    All,
  358}
  359
  360#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  361pub enum EditorMode {
  362    SingleLine { auto_width: bool },
  363    AutoHeight { max_lines: usize },
  364    Full,
  365}
  366
  367#[derive(Copy, Clone, Debug)]
  368pub enum SoftWrap {
  369    /// Prefer not to wrap at all.
  370    ///
  371    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  372    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  373    GitDiff,
  374    /// Prefer a single line generally, unless an overly long line is encountered.
  375    None,
  376    /// Soft wrap lines that exceed the editor width.
  377    EditorWidth,
  378    /// Soft wrap lines at the preferred line length.
  379    Column(u32),
  380    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  381    Bounded(u32),
  382}
  383
  384#[derive(Clone)]
  385pub struct EditorStyle {
  386    pub background: Hsla,
  387    pub local_player: PlayerColor,
  388    pub text: TextStyle,
  389    pub scrollbar_width: Pixels,
  390    pub syntax: Arc<SyntaxTheme>,
  391    pub status: StatusColors,
  392    pub inlay_hints_style: HighlightStyle,
  393    pub inline_completion_styles: InlineCompletionStyles,
  394    pub unnecessary_code_fade: f32,
  395}
  396
  397impl Default for EditorStyle {
  398    fn default() -> Self {
  399        Self {
  400            background: Hsla::default(),
  401            local_player: PlayerColor::default(),
  402            text: TextStyle::default(),
  403            scrollbar_width: Pixels::default(),
  404            syntax: Default::default(),
  405            // HACK: Status colors don't have a real default.
  406            // We should look into removing the status colors from the editor
  407            // style and retrieve them directly from the theme.
  408            status: StatusColors::dark(),
  409            inlay_hints_style: HighlightStyle::default(),
  410            inline_completion_styles: InlineCompletionStyles {
  411                insertion: HighlightStyle::default(),
  412                whitespace: HighlightStyle::default(),
  413            },
  414            unnecessary_code_fade: Default::default(),
  415        }
  416    }
  417}
  418
  419pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  420    let show_background = language_settings::language_settings(None, None, cx)
  421        .inlay_hints
  422        .show_background;
  423
  424    HighlightStyle {
  425        color: Some(cx.theme().status().hint),
  426        background_color: show_background.then(|| cx.theme().status().hint_background),
  427        ..HighlightStyle::default()
  428    }
  429}
  430
  431pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  432    InlineCompletionStyles {
  433        insertion: HighlightStyle {
  434            color: Some(cx.theme().status().predictive),
  435            ..HighlightStyle::default()
  436        },
  437        whitespace: HighlightStyle {
  438            background_color: Some(cx.theme().status().created_background),
  439            ..HighlightStyle::default()
  440        },
  441    }
  442}
  443
  444type CompletionId = usize;
  445
  446pub(crate) enum EditDisplayMode {
  447    TabAccept,
  448    DiffPopover,
  449    Inline,
  450}
  451
  452enum InlineCompletion {
  453    Edit {
  454        edits: Vec<(Range<Anchor>, String)>,
  455        edit_preview: Option<EditPreview>,
  456        display_mode: EditDisplayMode,
  457        snapshot: BufferSnapshot,
  458    },
  459    Move {
  460        target: Anchor,
  461        snapshot: BufferSnapshot,
  462    },
  463}
  464
  465struct InlineCompletionState {
  466    inlay_ids: Vec<InlayId>,
  467    completion: InlineCompletion,
  468    completion_id: Option<SharedString>,
  469    invalidation_range: Range<Anchor>,
  470}
  471
  472enum EditPredictionSettings {
  473    Disabled,
  474    Enabled {
  475        show_in_menu: bool,
  476        preview_requires_modifier: bool,
  477    },
  478}
  479
  480enum InlineCompletionHighlight {}
  481
  482#[derive(Debug, Clone)]
  483struct InlineDiagnostic {
  484    message: SharedString,
  485    group_id: usize,
  486    is_primary: bool,
  487    start: Point,
  488    severity: DiagnosticSeverity,
  489}
  490
  491pub enum MenuInlineCompletionsPolicy {
  492    Never,
  493    ByProvider,
  494}
  495
  496pub enum EditPredictionPreview {
  497    /// Modifier is not pressed
  498    Inactive { released_too_fast: bool },
  499    /// Modifier pressed
  500    Active {
  501        since: Instant,
  502        previous_scroll_position: Option<ScrollAnchor>,
  503    },
  504}
  505
  506impl EditPredictionPreview {
  507    pub fn released_too_fast(&self) -> bool {
  508        match self {
  509            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  510            EditPredictionPreview::Active { .. } => false,
  511        }
  512    }
  513
  514    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  515        if let EditPredictionPreview::Active {
  516            previous_scroll_position,
  517            ..
  518        } = self
  519        {
  520            *previous_scroll_position = scroll_position;
  521        }
  522    }
  523}
  524
  525#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  526struct EditorActionId(usize);
  527
  528impl EditorActionId {
  529    pub fn post_inc(&mut self) -> Self {
  530        let answer = self.0;
  531
  532        *self = Self(answer + 1);
  533
  534        Self(answer)
  535    }
  536}
  537
  538// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  539// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  540
  541type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  542type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  543
  544#[derive(Default)]
  545struct ScrollbarMarkerState {
  546    scrollbar_size: Size<Pixels>,
  547    dirty: bool,
  548    markers: Arc<[PaintQuad]>,
  549    pending_refresh: Option<Task<Result<()>>>,
  550}
  551
  552impl ScrollbarMarkerState {
  553    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  554        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  555    }
  556}
  557
  558#[derive(Clone, Debug)]
  559struct RunnableTasks {
  560    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  561    offset: multi_buffer::Anchor,
  562    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  563    column: u32,
  564    // Values of all named captures, including those starting with '_'
  565    extra_variables: HashMap<String, String>,
  566    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  567    context_range: Range<BufferOffset>,
  568}
  569
  570impl RunnableTasks {
  571    fn resolve<'a>(
  572        &'a self,
  573        cx: &'a task::TaskContext,
  574    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  575        self.templates.iter().filter_map(|(kind, template)| {
  576            template
  577                .resolve_task(&kind.to_id_base(), cx)
  578                .map(|task| (kind.clone(), task))
  579        })
  580    }
  581}
  582
  583#[derive(Clone)]
  584struct ResolvedTasks {
  585    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  586    position: Anchor,
  587}
  588#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  589struct BufferOffset(usize);
  590
  591// Addons allow storing per-editor state in other crates (e.g. Vim)
  592pub trait Addon: 'static {
  593    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  594
  595    fn render_buffer_header_controls(
  596        &self,
  597        _: &ExcerptInfo,
  598        _: &Window,
  599        _: &App,
  600    ) -> Option<AnyElement> {
  601        None
  602    }
  603
  604    fn to_any(&self) -> &dyn std::any::Any;
  605}
  606
  607#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  608pub enum IsVimMode {
  609    Yes,
  610    No,
  611}
  612
  613/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  614///
  615/// See the [module level documentation](self) for more information.
  616pub struct Editor {
  617    focus_handle: FocusHandle,
  618    last_focused_descendant: Option<WeakFocusHandle>,
  619    /// The text buffer being edited
  620    buffer: Entity<MultiBuffer>,
  621    /// Map of how text in the buffer should be displayed.
  622    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  623    pub display_map: Entity<DisplayMap>,
  624    pub selections: SelectionsCollection,
  625    pub scroll_manager: ScrollManager,
  626    /// When inline assist editors are linked, they all render cursors because
  627    /// typing enters text into each of them, even the ones that aren't focused.
  628    pub(crate) show_cursor_when_unfocused: bool,
  629    columnar_selection_tail: Option<Anchor>,
  630    add_selections_state: Option<AddSelectionsState>,
  631    select_next_state: Option<SelectNextState>,
  632    select_prev_state: Option<SelectNextState>,
  633    selection_history: SelectionHistory,
  634    autoclose_regions: Vec<AutocloseRegion>,
  635    snippet_stack: InvalidationStack<SnippetState>,
  636    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  637    ime_transaction: Option<TransactionId>,
  638    active_diagnostics: Option<ActiveDiagnosticGroup>,
  639    show_inline_diagnostics: bool,
  640    inline_diagnostics_update: Task<()>,
  641    inline_diagnostics_enabled: bool,
  642    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  643    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  644
  645    // TODO: make this a access method
  646    pub project: Option<Entity<Project>>,
  647    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  648    completion_provider: Option<Box<dyn CompletionProvider>>,
  649    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  650    blink_manager: Entity<BlinkManager>,
  651    show_cursor_names: bool,
  652    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  653    pub show_local_selections: bool,
  654    mode: EditorMode,
  655    show_breadcrumbs: bool,
  656    show_gutter: bool,
  657    show_scrollbars: bool,
  658    show_line_numbers: Option<bool>,
  659    use_relative_line_numbers: Option<bool>,
  660    show_git_diff_gutter: Option<bool>,
  661    show_code_actions: Option<bool>,
  662    show_runnables: Option<bool>,
  663    show_wrap_guides: Option<bool>,
  664    show_indent_guides: Option<bool>,
  665    placeholder_text: Option<Arc<str>>,
  666    highlight_order: usize,
  667    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  668    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  669    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  670    scrollbar_marker_state: ScrollbarMarkerState,
  671    active_indent_guides_state: ActiveIndentGuidesState,
  672    nav_history: Option<ItemNavHistory>,
  673    context_menu: RefCell<Option<CodeContextMenu>>,
  674    mouse_context_menu: Option<MouseContextMenu>,
  675    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  676    signature_help_state: SignatureHelpState,
  677    auto_signature_help: Option<bool>,
  678    find_all_references_task_sources: Vec<Anchor>,
  679    next_completion_id: CompletionId,
  680    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  681    code_actions_task: Option<Task<Result<()>>>,
  682    selection_highlight_task: Option<Task<()>>,
  683    document_highlights_task: Option<Task<()>>,
  684    linked_editing_range_task: Option<Task<Option<()>>>,
  685    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  686    pending_rename: Option<RenameState>,
  687    searchable: bool,
  688    cursor_shape: CursorShape,
  689    current_line_highlight: Option<CurrentLineHighlight>,
  690    collapse_matches: bool,
  691    autoindent_mode: Option<AutoindentMode>,
  692    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  693    input_enabled: bool,
  694    use_modal_editing: bool,
  695    read_only: bool,
  696    leader_peer_id: Option<PeerId>,
  697    remote_id: Option<ViewId>,
  698    hover_state: HoverState,
  699    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  700    gutter_hovered: bool,
  701    hovered_link_state: Option<HoveredLinkState>,
  702    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  703    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  704    active_inline_completion: Option<InlineCompletionState>,
  705    /// Used to prevent flickering as the user types while the menu is open
  706    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  707    edit_prediction_settings: EditPredictionSettings,
  708    inline_completions_hidden_for_vim_mode: bool,
  709    show_inline_completions_override: Option<bool>,
  710    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  711    edit_prediction_preview: EditPredictionPreview,
  712    edit_prediction_indent_conflict: bool,
  713    edit_prediction_requires_modifier_in_indent_conflict: bool,
  714    inlay_hint_cache: InlayHintCache,
  715    next_inlay_id: usize,
  716    _subscriptions: Vec<Subscription>,
  717    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  718    gutter_dimensions: GutterDimensions,
  719    style: Option<EditorStyle>,
  720    text_style_refinement: Option<TextStyleRefinement>,
  721    next_editor_action_id: EditorActionId,
  722    editor_actions:
  723        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  724    use_autoclose: bool,
  725    use_auto_surround: bool,
  726    auto_replace_emoji_shortcode: bool,
  727    show_git_blame_gutter: bool,
  728    show_git_blame_inline: bool,
  729    show_git_blame_inline_delay_task: Option<Task<()>>,
  730    git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
  731    git_blame_inline_enabled: bool,
  732    serialize_dirty_buffers: bool,
  733    show_selection_menu: Option<bool>,
  734    blame: Option<Entity<GitBlame>>,
  735    blame_subscription: Option<Subscription>,
  736    custom_context_menu: Option<
  737        Box<
  738            dyn 'static
  739                + Fn(
  740                    &mut Self,
  741                    DisplayPoint,
  742                    &mut Window,
  743                    &mut Context<Self>,
  744                ) -> Option<Entity<ui::ContextMenu>>,
  745        >,
  746    >,
  747    last_bounds: Option<Bounds<Pixels>>,
  748    last_position_map: Option<Rc<PositionMap>>,
  749    expect_bounds_change: Option<Bounds<Pixels>>,
  750    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  751    tasks_update_task: Option<Task<()>>,
  752    in_project_search: bool,
  753    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  754    breadcrumb_header: Option<String>,
  755    focused_block: Option<FocusedBlock>,
  756    next_scroll_position: NextScrollCursorCenterTopBottom,
  757    addons: HashMap<TypeId, Box<dyn Addon>>,
  758    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  759    load_diff_task: Option<Shared<Task<()>>>,
  760    selection_mark_mode: bool,
  761    toggle_fold_multiple_buffers: Task<()>,
  762    _scroll_cursor_center_top_bottom_task: Task<()>,
  763    serialize_selections: Task<()>,
  764}
  765
  766#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  767enum NextScrollCursorCenterTopBottom {
  768    #[default]
  769    Center,
  770    Top,
  771    Bottom,
  772}
  773
  774impl NextScrollCursorCenterTopBottom {
  775    fn next(&self) -> Self {
  776        match self {
  777            Self::Center => Self::Top,
  778            Self::Top => Self::Bottom,
  779            Self::Bottom => Self::Center,
  780        }
  781    }
  782}
  783
  784#[derive(Clone)]
  785pub struct EditorSnapshot {
  786    pub mode: EditorMode,
  787    show_gutter: bool,
  788    show_line_numbers: Option<bool>,
  789    show_git_diff_gutter: Option<bool>,
  790    show_code_actions: Option<bool>,
  791    show_runnables: Option<bool>,
  792    git_blame_gutter_max_author_length: Option<usize>,
  793    pub display_snapshot: DisplaySnapshot,
  794    pub placeholder_text: Option<Arc<str>>,
  795    is_focused: bool,
  796    scroll_anchor: ScrollAnchor,
  797    ongoing_scroll: OngoingScroll,
  798    current_line_highlight: CurrentLineHighlight,
  799    gutter_hovered: bool,
  800}
  801
  802const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  803
  804#[derive(Default, Debug, Clone, Copy)]
  805pub struct GutterDimensions {
  806    pub left_padding: Pixels,
  807    pub right_padding: Pixels,
  808    pub width: Pixels,
  809    pub margin: Pixels,
  810    pub git_blame_entries_width: Option<Pixels>,
  811}
  812
  813impl GutterDimensions {
  814    /// The full width of the space taken up by the gutter.
  815    pub fn full_width(&self) -> Pixels {
  816        self.margin + self.width
  817    }
  818
  819    /// The width of the space reserved for the fold indicators,
  820    /// use alongside 'justify_end' and `gutter_width` to
  821    /// right align content with the line numbers
  822    pub fn fold_area_width(&self) -> Pixels {
  823        self.margin + self.right_padding
  824    }
  825}
  826
  827#[derive(Debug)]
  828pub struct RemoteSelection {
  829    pub replica_id: ReplicaId,
  830    pub selection: Selection<Anchor>,
  831    pub cursor_shape: CursorShape,
  832    pub peer_id: PeerId,
  833    pub line_mode: bool,
  834    pub participant_index: Option<ParticipantIndex>,
  835    pub user_name: Option<SharedString>,
  836}
  837
  838#[derive(Clone, Debug)]
  839struct SelectionHistoryEntry {
  840    selections: Arc<[Selection<Anchor>]>,
  841    select_next_state: Option<SelectNextState>,
  842    select_prev_state: Option<SelectNextState>,
  843    add_selections_state: Option<AddSelectionsState>,
  844}
  845
  846enum SelectionHistoryMode {
  847    Normal,
  848    Undoing,
  849    Redoing,
  850}
  851
  852#[derive(Clone, PartialEq, Eq, Hash)]
  853struct HoveredCursor {
  854    replica_id: u16,
  855    selection_id: usize,
  856}
  857
  858impl Default for SelectionHistoryMode {
  859    fn default() -> Self {
  860        Self::Normal
  861    }
  862}
  863
  864#[derive(Default)]
  865struct SelectionHistory {
  866    #[allow(clippy::type_complexity)]
  867    selections_by_transaction:
  868        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  869    mode: SelectionHistoryMode,
  870    undo_stack: VecDeque<SelectionHistoryEntry>,
  871    redo_stack: VecDeque<SelectionHistoryEntry>,
  872}
  873
  874impl SelectionHistory {
  875    fn insert_transaction(
  876        &mut self,
  877        transaction_id: TransactionId,
  878        selections: Arc<[Selection<Anchor>]>,
  879    ) {
  880        self.selections_by_transaction
  881            .insert(transaction_id, (selections, None));
  882    }
  883
  884    #[allow(clippy::type_complexity)]
  885    fn transaction(
  886        &self,
  887        transaction_id: TransactionId,
  888    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  889        self.selections_by_transaction.get(&transaction_id)
  890    }
  891
  892    #[allow(clippy::type_complexity)]
  893    fn transaction_mut(
  894        &mut self,
  895        transaction_id: TransactionId,
  896    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  897        self.selections_by_transaction.get_mut(&transaction_id)
  898    }
  899
  900    fn push(&mut self, entry: SelectionHistoryEntry) {
  901        if !entry.selections.is_empty() {
  902            match self.mode {
  903                SelectionHistoryMode::Normal => {
  904                    self.push_undo(entry);
  905                    self.redo_stack.clear();
  906                }
  907                SelectionHistoryMode::Undoing => self.push_redo(entry),
  908                SelectionHistoryMode::Redoing => self.push_undo(entry),
  909            }
  910        }
  911    }
  912
  913    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  914        if self
  915            .undo_stack
  916            .back()
  917            .map_or(true, |e| e.selections != entry.selections)
  918        {
  919            self.undo_stack.push_back(entry);
  920            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  921                self.undo_stack.pop_front();
  922            }
  923        }
  924    }
  925
  926    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  927        if self
  928            .redo_stack
  929            .back()
  930            .map_or(true, |e| e.selections != entry.selections)
  931        {
  932            self.redo_stack.push_back(entry);
  933            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  934                self.redo_stack.pop_front();
  935            }
  936        }
  937    }
  938}
  939
  940struct RowHighlight {
  941    index: usize,
  942    range: Range<Anchor>,
  943    color: Hsla,
  944    should_autoscroll: bool,
  945}
  946
  947#[derive(Clone, Debug)]
  948struct AddSelectionsState {
  949    above: bool,
  950    stack: Vec<usize>,
  951}
  952
  953#[derive(Clone)]
  954struct SelectNextState {
  955    query: AhoCorasick,
  956    wordwise: bool,
  957    done: bool,
  958}
  959
  960impl std::fmt::Debug for SelectNextState {
  961    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  962        f.debug_struct(std::any::type_name::<Self>())
  963            .field("wordwise", &self.wordwise)
  964            .field("done", &self.done)
  965            .finish()
  966    }
  967}
  968
  969#[derive(Debug)]
  970struct AutocloseRegion {
  971    selection_id: usize,
  972    range: Range<Anchor>,
  973    pair: BracketPair,
  974}
  975
  976#[derive(Debug)]
  977struct SnippetState {
  978    ranges: Vec<Vec<Range<Anchor>>>,
  979    active_index: usize,
  980    choices: Vec<Option<Vec<String>>>,
  981}
  982
  983#[doc(hidden)]
  984pub struct RenameState {
  985    pub range: Range<Anchor>,
  986    pub old_name: Arc<str>,
  987    pub editor: Entity<Editor>,
  988    block_id: CustomBlockId,
  989}
  990
  991struct InvalidationStack<T>(Vec<T>);
  992
  993struct RegisteredInlineCompletionProvider {
  994    provider: Arc<dyn InlineCompletionProviderHandle>,
  995    _subscription: Subscription,
  996}
  997
  998#[derive(Debug, PartialEq, Eq)]
  999struct ActiveDiagnosticGroup {
 1000    primary_range: Range<Anchor>,
 1001    primary_message: String,
 1002    group_id: usize,
 1003    blocks: HashMap<CustomBlockId, Diagnostic>,
 1004    is_valid: bool,
 1005}
 1006
 1007#[derive(Serialize, Deserialize, Clone, Debug)]
 1008pub struct ClipboardSelection {
 1009    /// The number of bytes in this selection.
 1010    pub len: usize,
 1011    /// Whether this was a full-line selection.
 1012    pub is_entire_line: bool,
 1013    /// The column where this selection originally started.
 1014    pub start_column: u32,
 1015}
 1016
 1017#[derive(Debug)]
 1018pub(crate) struct NavigationData {
 1019    cursor_anchor: Anchor,
 1020    cursor_position: Point,
 1021    scroll_anchor: ScrollAnchor,
 1022    scroll_top_row: u32,
 1023}
 1024
 1025#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1026pub enum GotoDefinitionKind {
 1027    Symbol,
 1028    Declaration,
 1029    Type,
 1030    Implementation,
 1031}
 1032
 1033#[derive(Debug, Clone)]
 1034enum InlayHintRefreshReason {
 1035    ModifiersChanged(bool),
 1036    Toggle(bool),
 1037    SettingsChange(InlayHintSettings),
 1038    NewLinesShown,
 1039    BufferEdited(HashSet<Arc<Language>>),
 1040    RefreshRequested,
 1041    ExcerptsRemoved(Vec<ExcerptId>),
 1042}
 1043
 1044impl InlayHintRefreshReason {
 1045    fn description(&self) -> &'static str {
 1046        match self {
 1047            Self::ModifiersChanged(_) => "modifiers changed",
 1048            Self::Toggle(_) => "toggle",
 1049            Self::SettingsChange(_) => "settings change",
 1050            Self::NewLinesShown => "new lines shown",
 1051            Self::BufferEdited(_) => "buffer edited",
 1052            Self::RefreshRequested => "refresh requested",
 1053            Self::ExcerptsRemoved(_) => "excerpts removed",
 1054        }
 1055    }
 1056}
 1057
 1058pub enum FormatTarget {
 1059    Buffers,
 1060    Ranges(Vec<Range<MultiBufferPoint>>),
 1061}
 1062
 1063pub(crate) struct FocusedBlock {
 1064    id: BlockId,
 1065    focus_handle: WeakFocusHandle,
 1066}
 1067
 1068#[derive(Clone)]
 1069enum JumpData {
 1070    MultiBufferRow {
 1071        row: MultiBufferRow,
 1072        line_offset_from_top: u32,
 1073    },
 1074    MultiBufferPoint {
 1075        excerpt_id: ExcerptId,
 1076        position: Point,
 1077        anchor: text::Anchor,
 1078        line_offset_from_top: u32,
 1079    },
 1080}
 1081
 1082pub enum MultibufferSelectionMode {
 1083    First,
 1084    All,
 1085}
 1086
 1087impl Editor {
 1088    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1089        let buffer = cx.new(|cx| Buffer::local("", cx));
 1090        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1091        Self::new(
 1092            EditorMode::SingleLine { auto_width: false },
 1093            buffer,
 1094            None,
 1095            false,
 1096            window,
 1097            cx,
 1098        )
 1099    }
 1100
 1101    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1102        let buffer = cx.new(|cx| Buffer::local("", cx));
 1103        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1104        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1105    }
 1106
 1107    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1108        let buffer = cx.new(|cx| Buffer::local("", cx));
 1109        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1110        Self::new(
 1111            EditorMode::SingleLine { auto_width: true },
 1112            buffer,
 1113            None,
 1114            false,
 1115            window,
 1116            cx,
 1117        )
 1118    }
 1119
 1120    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1121        let buffer = cx.new(|cx| Buffer::local("", cx));
 1122        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1123        Self::new(
 1124            EditorMode::AutoHeight { max_lines },
 1125            buffer,
 1126            None,
 1127            false,
 1128            window,
 1129            cx,
 1130        )
 1131    }
 1132
 1133    pub fn for_buffer(
 1134        buffer: Entity<Buffer>,
 1135        project: Option<Entity<Project>>,
 1136        window: &mut Window,
 1137        cx: &mut Context<Self>,
 1138    ) -> Self {
 1139        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1140        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1141    }
 1142
 1143    pub fn for_multibuffer(
 1144        buffer: Entity<MultiBuffer>,
 1145        project: Option<Entity<Project>>,
 1146        show_excerpt_controls: bool,
 1147        window: &mut Window,
 1148        cx: &mut Context<Self>,
 1149    ) -> Self {
 1150        Self::new(
 1151            EditorMode::Full,
 1152            buffer,
 1153            project,
 1154            show_excerpt_controls,
 1155            window,
 1156            cx,
 1157        )
 1158    }
 1159
 1160    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1161        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1162        let mut clone = Self::new(
 1163            self.mode,
 1164            self.buffer.clone(),
 1165            self.project.clone(),
 1166            show_excerpt_controls,
 1167            window,
 1168            cx,
 1169        );
 1170        self.display_map.update(cx, |display_map, cx| {
 1171            let snapshot = display_map.snapshot(cx);
 1172            clone.display_map.update(cx, |display_map, cx| {
 1173                display_map.set_state(&snapshot, cx);
 1174            });
 1175        });
 1176        clone.selections.clone_state(&self.selections);
 1177        clone.scroll_manager.clone_state(&self.scroll_manager);
 1178        clone.searchable = self.searchable;
 1179        clone
 1180    }
 1181
 1182    pub fn new(
 1183        mode: EditorMode,
 1184        buffer: Entity<MultiBuffer>,
 1185        project: Option<Entity<Project>>,
 1186        show_excerpt_controls: bool,
 1187        window: &mut Window,
 1188        cx: &mut Context<Self>,
 1189    ) -> Self {
 1190        let style = window.text_style();
 1191        let font_size = style.font_size.to_pixels(window.rem_size());
 1192        let editor = cx.entity().downgrade();
 1193        let fold_placeholder = FoldPlaceholder {
 1194            constrain_width: true,
 1195            render: Arc::new(move |fold_id, fold_range, cx| {
 1196                let editor = editor.clone();
 1197                div()
 1198                    .id(fold_id)
 1199                    .bg(cx.theme().colors().ghost_element_background)
 1200                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1201                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1202                    .rounded_sm()
 1203                    .size_full()
 1204                    .cursor_pointer()
 1205                    .child("")
 1206                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1207                    .on_click(move |_, _window, cx| {
 1208                        editor
 1209                            .update(cx, |editor, cx| {
 1210                                editor.unfold_ranges(
 1211                                    &[fold_range.start..fold_range.end],
 1212                                    true,
 1213                                    false,
 1214                                    cx,
 1215                                );
 1216                                cx.stop_propagation();
 1217                            })
 1218                            .ok();
 1219                    })
 1220                    .into_any()
 1221            }),
 1222            merge_adjacent: true,
 1223            ..Default::default()
 1224        };
 1225        let display_map = cx.new(|cx| {
 1226            DisplayMap::new(
 1227                buffer.clone(),
 1228                style.font(),
 1229                font_size,
 1230                None,
 1231                show_excerpt_controls,
 1232                FILE_HEADER_HEIGHT,
 1233                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1234                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1235                fold_placeholder,
 1236                cx,
 1237            )
 1238        });
 1239
 1240        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1241
 1242        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1243
 1244        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1245            .then(|| language_settings::SoftWrap::None);
 1246
 1247        let mut project_subscriptions = Vec::new();
 1248        if mode == EditorMode::Full {
 1249            if let Some(project) = project.as_ref() {
 1250                if buffer.read(cx).is_singleton() {
 1251                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1252                        cx.emit(EditorEvent::TitleChanged);
 1253                    }));
 1254                }
 1255                project_subscriptions.push(cx.subscribe_in(
 1256                    project,
 1257                    window,
 1258                    |editor, _, event, window, cx| {
 1259                        if let project::Event::RefreshInlayHints = event {
 1260                            editor
 1261                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1262                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1263                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1264                                let focus_handle = editor.focus_handle(cx);
 1265                                if focus_handle.is_focused(window) {
 1266                                    let snapshot = buffer.read(cx).snapshot();
 1267                                    for (range, snippet) in snippet_edits {
 1268                                        let editor_range =
 1269                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1270                                        editor
 1271                                            .insert_snippet(
 1272                                                &[editor_range],
 1273                                                snippet.clone(),
 1274                                                window,
 1275                                                cx,
 1276                                            )
 1277                                            .ok();
 1278                                    }
 1279                                }
 1280                            }
 1281                        }
 1282                    },
 1283                ));
 1284                if let Some(task_inventory) = project
 1285                    .read(cx)
 1286                    .task_store()
 1287                    .read(cx)
 1288                    .task_inventory()
 1289                    .cloned()
 1290                {
 1291                    project_subscriptions.push(cx.observe_in(
 1292                        &task_inventory,
 1293                        window,
 1294                        |editor, _, window, cx| {
 1295                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1296                        },
 1297                    ));
 1298                }
 1299            }
 1300        }
 1301
 1302        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1303
 1304        let inlay_hint_settings =
 1305            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1306        let focus_handle = cx.focus_handle();
 1307        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1308            .detach();
 1309        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1310            .detach();
 1311        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1312            .detach();
 1313        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1314            .detach();
 1315
 1316        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1317            Some(false)
 1318        } else {
 1319            None
 1320        };
 1321
 1322        let mut code_action_providers = Vec::new();
 1323        let mut load_uncommitted_diff = None;
 1324        if let Some(project) = project.clone() {
 1325            load_uncommitted_diff = Some(
 1326                get_uncommitted_diff_for_buffer(
 1327                    &project,
 1328                    buffer.read(cx).all_buffers(),
 1329                    buffer.clone(),
 1330                    cx,
 1331                )
 1332                .shared(),
 1333            );
 1334            code_action_providers.push(Rc::new(project) as Rc<_>);
 1335        }
 1336
 1337        let mut this = Self {
 1338            focus_handle,
 1339            show_cursor_when_unfocused: false,
 1340            last_focused_descendant: None,
 1341            buffer: buffer.clone(),
 1342            display_map: display_map.clone(),
 1343            selections,
 1344            scroll_manager: ScrollManager::new(cx),
 1345            columnar_selection_tail: None,
 1346            add_selections_state: None,
 1347            select_next_state: None,
 1348            select_prev_state: None,
 1349            selection_history: Default::default(),
 1350            autoclose_regions: Default::default(),
 1351            snippet_stack: Default::default(),
 1352            select_larger_syntax_node_stack: Vec::new(),
 1353            ime_transaction: Default::default(),
 1354            active_diagnostics: None,
 1355            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1356            inline_diagnostics_update: Task::ready(()),
 1357            inline_diagnostics: Vec::new(),
 1358            soft_wrap_mode_override,
 1359            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1360            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1361            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1362            project,
 1363            blink_manager: blink_manager.clone(),
 1364            show_local_selections: true,
 1365            show_scrollbars: true,
 1366            mode,
 1367            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1368            show_gutter: mode == EditorMode::Full,
 1369            show_line_numbers: None,
 1370            use_relative_line_numbers: None,
 1371            show_git_diff_gutter: None,
 1372            show_code_actions: None,
 1373            show_runnables: None,
 1374            show_wrap_guides: None,
 1375            show_indent_guides,
 1376            placeholder_text: None,
 1377            highlight_order: 0,
 1378            highlighted_rows: HashMap::default(),
 1379            background_highlights: Default::default(),
 1380            gutter_highlights: TreeMap::default(),
 1381            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1382            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1383            nav_history: None,
 1384            context_menu: RefCell::new(None),
 1385            mouse_context_menu: None,
 1386            completion_tasks: Default::default(),
 1387            signature_help_state: SignatureHelpState::default(),
 1388            auto_signature_help: None,
 1389            find_all_references_task_sources: Vec::new(),
 1390            next_completion_id: 0,
 1391            next_inlay_id: 0,
 1392            code_action_providers,
 1393            available_code_actions: Default::default(),
 1394            code_actions_task: Default::default(),
 1395            selection_highlight_task: Default::default(),
 1396            document_highlights_task: Default::default(),
 1397            linked_editing_range_task: Default::default(),
 1398            pending_rename: Default::default(),
 1399            searchable: true,
 1400            cursor_shape: EditorSettings::get_global(cx)
 1401                .cursor_shape
 1402                .unwrap_or_default(),
 1403            current_line_highlight: None,
 1404            autoindent_mode: Some(AutoindentMode::EachLine),
 1405            collapse_matches: false,
 1406            workspace: None,
 1407            input_enabled: true,
 1408            use_modal_editing: mode == EditorMode::Full,
 1409            read_only: false,
 1410            use_autoclose: true,
 1411            use_auto_surround: true,
 1412            auto_replace_emoji_shortcode: false,
 1413            leader_peer_id: None,
 1414            remote_id: None,
 1415            hover_state: Default::default(),
 1416            pending_mouse_down: None,
 1417            hovered_link_state: Default::default(),
 1418            edit_prediction_provider: None,
 1419            active_inline_completion: None,
 1420            stale_inline_completion_in_menu: None,
 1421            edit_prediction_preview: EditPredictionPreview::Inactive {
 1422                released_too_fast: false,
 1423            },
 1424            inline_diagnostics_enabled: mode == EditorMode::Full,
 1425            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1426
 1427            gutter_hovered: false,
 1428            pixel_position_of_newest_cursor: None,
 1429            last_bounds: None,
 1430            last_position_map: None,
 1431            expect_bounds_change: None,
 1432            gutter_dimensions: GutterDimensions::default(),
 1433            style: None,
 1434            show_cursor_names: false,
 1435            hovered_cursors: Default::default(),
 1436            next_editor_action_id: EditorActionId::default(),
 1437            editor_actions: Rc::default(),
 1438            inline_completions_hidden_for_vim_mode: false,
 1439            show_inline_completions_override: None,
 1440            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1441            edit_prediction_settings: EditPredictionSettings::Disabled,
 1442            edit_prediction_indent_conflict: false,
 1443            edit_prediction_requires_modifier_in_indent_conflict: true,
 1444            custom_context_menu: None,
 1445            show_git_blame_gutter: false,
 1446            show_git_blame_inline: false,
 1447            show_selection_menu: None,
 1448            show_git_blame_inline_delay_task: None,
 1449            git_blame_inline_tooltip: None,
 1450            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1451            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1452                .session
 1453                .restore_unsaved_buffers,
 1454            blame: None,
 1455            blame_subscription: None,
 1456            tasks: Default::default(),
 1457            _subscriptions: vec![
 1458                cx.observe(&buffer, Self::on_buffer_changed),
 1459                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1460                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1461                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1462                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1463                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1464                cx.observe_window_activation(window, |editor, window, cx| {
 1465                    let active = window.is_window_active();
 1466                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1467                        if active {
 1468                            blink_manager.enable(cx);
 1469                        } else {
 1470                            blink_manager.disable(cx);
 1471                        }
 1472                    });
 1473                }),
 1474            ],
 1475            tasks_update_task: None,
 1476            linked_edit_ranges: Default::default(),
 1477            in_project_search: false,
 1478            previous_search_ranges: None,
 1479            breadcrumb_header: None,
 1480            focused_block: None,
 1481            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1482            addons: HashMap::default(),
 1483            registered_buffers: HashMap::default(),
 1484            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1485            selection_mark_mode: false,
 1486            toggle_fold_multiple_buffers: Task::ready(()),
 1487            serialize_selections: Task::ready(()),
 1488            text_style_refinement: None,
 1489            load_diff_task: load_uncommitted_diff,
 1490        };
 1491        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1492        this._subscriptions.extend(project_subscriptions);
 1493
 1494        this.end_selection(window, cx);
 1495        this.scroll_manager.show_scrollbar(window, cx);
 1496
 1497        if mode == EditorMode::Full {
 1498            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1499            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1500
 1501            if this.git_blame_inline_enabled {
 1502                this.git_blame_inline_enabled = true;
 1503                this.start_git_blame_inline(false, window, cx);
 1504            }
 1505
 1506            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1507                if let Some(project) = this.project.as_ref() {
 1508                    let handle = project.update(cx, |project, cx| {
 1509                        project.register_buffer_with_language_servers(&buffer, cx)
 1510                    });
 1511                    this.registered_buffers
 1512                        .insert(buffer.read(cx).remote_id(), handle);
 1513                }
 1514            }
 1515        }
 1516
 1517        this.report_editor_event("Editor Opened", None, cx);
 1518        this
 1519    }
 1520
 1521    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1522        self.mouse_context_menu
 1523            .as_ref()
 1524            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1525    }
 1526
 1527    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1528        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1529    }
 1530
 1531    fn key_context_internal(
 1532        &self,
 1533        has_active_edit_prediction: bool,
 1534        window: &Window,
 1535        cx: &App,
 1536    ) -> KeyContext {
 1537        let mut key_context = KeyContext::new_with_defaults();
 1538        key_context.add("Editor");
 1539        let mode = match self.mode {
 1540            EditorMode::SingleLine { .. } => "single_line",
 1541            EditorMode::AutoHeight { .. } => "auto_height",
 1542            EditorMode::Full => "full",
 1543        };
 1544
 1545        if EditorSettings::jupyter_enabled(cx) {
 1546            key_context.add("jupyter");
 1547        }
 1548
 1549        key_context.set("mode", mode);
 1550        if self.pending_rename.is_some() {
 1551            key_context.add("renaming");
 1552        }
 1553
 1554        match self.context_menu.borrow().as_ref() {
 1555            Some(CodeContextMenu::Completions(_)) => {
 1556                key_context.add("menu");
 1557                key_context.add("showing_completions");
 1558            }
 1559            Some(CodeContextMenu::CodeActions(_)) => {
 1560                key_context.add("menu");
 1561                key_context.add("showing_code_actions")
 1562            }
 1563            None => {}
 1564        }
 1565
 1566        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1567        if !self.focus_handle(cx).contains_focused(window, cx)
 1568            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1569        {
 1570            for addon in self.addons.values() {
 1571                addon.extend_key_context(&mut key_context, cx)
 1572            }
 1573        }
 1574
 1575        if let Some(extension) = self
 1576            .buffer
 1577            .read(cx)
 1578            .as_singleton()
 1579            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1580        {
 1581            key_context.set("extension", extension.to_string());
 1582        }
 1583
 1584        if has_active_edit_prediction {
 1585            if self.edit_prediction_in_conflict() {
 1586                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1587            } else {
 1588                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1589                key_context.add("copilot_suggestion");
 1590            }
 1591        }
 1592
 1593        if self.selection_mark_mode {
 1594            key_context.add("selection_mode");
 1595        }
 1596
 1597        key_context
 1598    }
 1599
 1600    pub fn edit_prediction_in_conflict(&self) -> bool {
 1601        if !self.show_edit_predictions_in_menu() {
 1602            return false;
 1603        }
 1604
 1605        let showing_completions = self
 1606            .context_menu
 1607            .borrow()
 1608            .as_ref()
 1609            .map_or(false, |context| {
 1610                matches!(context, CodeContextMenu::Completions(_))
 1611            });
 1612
 1613        showing_completions
 1614            || self.edit_prediction_requires_modifier()
 1615            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1616            // bindings to insert tab characters.
 1617            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1618    }
 1619
 1620    pub fn accept_edit_prediction_keybind(
 1621        &self,
 1622        window: &Window,
 1623        cx: &App,
 1624    ) -> AcceptEditPredictionBinding {
 1625        let key_context = self.key_context_internal(true, window, cx);
 1626        let in_conflict = self.edit_prediction_in_conflict();
 1627
 1628        AcceptEditPredictionBinding(
 1629            window
 1630                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1631                .into_iter()
 1632                .filter(|binding| {
 1633                    !in_conflict
 1634                        || binding
 1635                            .keystrokes()
 1636                            .first()
 1637                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1638                })
 1639                .rev()
 1640                .min_by_key(|binding| {
 1641                    binding
 1642                        .keystrokes()
 1643                        .first()
 1644                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1645                }),
 1646        )
 1647    }
 1648
 1649    pub fn new_file(
 1650        workspace: &mut Workspace,
 1651        _: &workspace::NewFile,
 1652        window: &mut Window,
 1653        cx: &mut Context<Workspace>,
 1654    ) {
 1655        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1656            "Failed to create buffer",
 1657            window,
 1658            cx,
 1659            |e, _, _| match e.error_code() {
 1660                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1661                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1662                e.error_tag("required").unwrap_or("the latest version")
 1663            )),
 1664                _ => None,
 1665            },
 1666        );
 1667    }
 1668
 1669    pub fn new_in_workspace(
 1670        workspace: &mut Workspace,
 1671        window: &mut Window,
 1672        cx: &mut Context<Workspace>,
 1673    ) -> Task<Result<Entity<Editor>>> {
 1674        let project = workspace.project().clone();
 1675        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1676
 1677        cx.spawn_in(window, |workspace, mut cx| async move {
 1678            let buffer = create.await?;
 1679            workspace.update_in(&mut cx, |workspace, window, cx| {
 1680                let editor =
 1681                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1682                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1683                editor
 1684            })
 1685        })
 1686    }
 1687
 1688    fn new_file_vertical(
 1689        workspace: &mut Workspace,
 1690        _: &workspace::NewFileSplitVertical,
 1691        window: &mut Window,
 1692        cx: &mut Context<Workspace>,
 1693    ) {
 1694        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1695    }
 1696
 1697    fn new_file_horizontal(
 1698        workspace: &mut Workspace,
 1699        _: &workspace::NewFileSplitHorizontal,
 1700        window: &mut Window,
 1701        cx: &mut Context<Workspace>,
 1702    ) {
 1703        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1704    }
 1705
 1706    fn new_file_in_direction(
 1707        workspace: &mut Workspace,
 1708        direction: SplitDirection,
 1709        window: &mut Window,
 1710        cx: &mut Context<Workspace>,
 1711    ) {
 1712        let project = workspace.project().clone();
 1713        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1714
 1715        cx.spawn_in(window, |workspace, mut cx| async move {
 1716            let buffer = create.await?;
 1717            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1718                workspace.split_item(
 1719                    direction,
 1720                    Box::new(
 1721                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1722                    ),
 1723                    window,
 1724                    cx,
 1725                )
 1726            })?;
 1727            anyhow::Ok(())
 1728        })
 1729        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1730            match e.error_code() {
 1731                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1732                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1733                e.error_tag("required").unwrap_or("the latest version")
 1734            )),
 1735                _ => None,
 1736            }
 1737        });
 1738    }
 1739
 1740    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1741        self.leader_peer_id
 1742    }
 1743
 1744    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1745        &self.buffer
 1746    }
 1747
 1748    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1749        self.workspace.as_ref()?.0.upgrade()
 1750    }
 1751
 1752    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1753        self.buffer().read(cx).title(cx)
 1754    }
 1755
 1756    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1757        let git_blame_gutter_max_author_length = self
 1758            .render_git_blame_gutter(cx)
 1759            .then(|| {
 1760                if let Some(blame) = self.blame.as_ref() {
 1761                    let max_author_length =
 1762                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1763                    Some(max_author_length)
 1764                } else {
 1765                    None
 1766                }
 1767            })
 1768            .flatten();
 1769
 1770        EditorSnapshot {
 1771            mode: self.mode,
 1772            show_gutter: self.show_gutter,
 1773            show_line_numbers: self.show_line_numbers,
 1774            show_git_diff_gutter: self.show_git_diff_gutter,
 1775            show_code_actions: self.show_code_actions,
 1776            show_runnables: self.show_runnables,
 1777            git_blame_gutter_max_author_length,
 1778            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1779            scroll_anchor: self.scroll_manager.anchor(),
 1780            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1781            placeholder_text: self.placeholder_text.clone(),
 1782            is_focused: self.focus_handle.is_focused(window),
 1783            current_line_highlight: self
 1784                .current_line_highlight
 1785                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1786            gutter_hovered: self.gutter_hovered,
 1787        }
 1788    }
 1789
 1790    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1791        self.buffer.read(cx).language_at(point, cx)
 1792    }
 1793
 1794    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1795        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1796    }
 1797
 1798    pub fn active_excerpt(
 1799        &self,
 1800        cx: &App,
 1801    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1802        self.buffer
 1803            .read(cx)
 1804            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1805    }
 1806
 1807    pub fn mode(&self) -> EditorMode {
 1808        self.mode
 1809    }
 1810
 1811    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1812        self.collaboration_hub.as_deref()
 1813    }
 1814
 1815    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1816        self.collaboration_hub = Some(hub);
 1817    }
 1818
 1819    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1820        self.in_project_search = in_project_search;
 1821    }
 1822
 1823    pub fn set_custom_context_menu(
 1824        &mut self,
 1825        f: impl 'static
 1826            + Fn(
 1827                &mut Self,
 1828                DisplayPoint,
 1829                &mut Window,
 1830                &mut Context<Self>,
 1831            ) -> Option<Entity<ui::ContextMenu>>,
 1832    ) {
 1833        self.custom_context_menu = Some(Box::new(f))
 1834    }
 1835
 1836    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1837        self.completion_provider = provider;
 1838    }
 1839
 1840    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1841        self.semantics_provider.clone()
 1842    }
 1843
 1844    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1845        self.semantics_provider = provider;
 1846    }
 1847
 1848    pub fn set_edit_prediction_provider<T>(
 1849        &mut self,
 1850        provider: Option<Entity<T>>,
 1851        window: &mut Window,
 1852        cx: &mut Context<Self>,
 1853    ) where
 1854        T: EditPredictionProvider,
 1855    {
 1856        self.edit_prediction_provider =
 1857            provider.map(|provider| RegisteredInlineCompletionProvider {
 1858                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1859                    if this.focus_handle.is_focused(window) {
 1860                        this.update_visible_inline_completion(window, cx);
 1861                    }
 1862                }),
 1863                provider: Arc::new(provider),
 1864            });
 1865        self.update_edit_prediction_settings(cx);
 1866        self.refresh_inline_completion(false, false, window, cx);
 1867    }
 1868
 1869    pub fn placeholder_text(&self) -> Option<&str> {
 1870        self.placeholder_text.as_deref()
 1871    }
 1872
 1873    pub fn set_placeholder_text(
 1874        &mut self,
 1875        placeholder_text: impl Into<Arc<str>>,
 1876        cx: &mut Context<Self>,
 1877    ) {
 1878        let placeholder_text = Some(placeholder_text.into());
 1879        if self.placeholder_text != placeholder_text {
 1880            self.placeholder_text = placeholder_text;
 1881            cx.notify();
 1882        }
 1883    }
 1884
 1885    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1886        self.cursor_shape = cursor_shape;
 1887
 1888        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1889        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1890
 1891        cx.notify();
 1892    }
 1893
 1894    pub fn set_current_line_highlight(
 1895        &mut self,
 1896        current_line_highlight: Option<CurrentLineHighlight>,
 1897    ) {
 1898        self.current_line_highlight = current_line_highlight;
 1899    }
 1900
 1901    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1902        self.collapse_matches = collapse_matches;
 1903    }
 1904
 1905    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1906        let buffers = self.buffer.read(cx).all_buffers();
 1907        let Some(project) = self.project.as_ref() else {
 1908            return;
 1909        };
 1910        project.update(cx, |project, cx| {
 1911            for buffer in buffers {
 1912                self.registered_buffers
 1913                    .entry(buffer.read(cx).remote_id())
 1914                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1915            }
 1916        })
 1917    }
 1918
 1919    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1920        if self.collapse_matches {
 1921            return range.start..range.start;
 1922        }
 1923        range.clone()
 1924    }
 1925
 1926    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1927        if self.display_map.read(cx).clip_at_line_ends != clip {
 1928            self.display_map
 1929                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1930        }
 1931    }
 1932
 1933    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1934        self.input_enabled = input_enabled;
 1935    }
 1936
 1937    pub fn set_inline_completions_hidden_for_vim_mode(
 1938        &mut self,
 1939        hidden: bool,
 1940        window: &mut Window,
 1941        cx: &mut Context<Self>,
 1942    ) {
 1943        if hidden != self.inline_completions_hidden_for_vim_mode {
 1944            self.inline_completions_hidden_for_vim_mode = hidden;
 1945            if hidden {
 1946                self.update_visible_inline_completion(window, cx);
 1947            } else {
 1948                self.refresh_inline_completion(true, false, window, cx);
 1949            }
 1950        }
 1951    }
 1952
 1953    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1954        self.menu_inline_completions_policy = value;
 1955    }
 1956
 1957    pub fn set_autoindent(&mut self, autoindent: bool) {
 1958        if autoindent {
 1959            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1960        } else {
 1961            self.autoindent_mode = None;
 1962        }
 1963    }
 1964
 1965    pub fn read_only(&self, cx: &App) -> bool {
 1966        self.read_only || self.buffer.read(cx).read_only()
 1967    }
 1968
 1969    pub fn set_read_only(&mut self, read_only: bool) {
 1970        self.read_only = read_only;
 1971    }
 1972
 1973    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1974        self.use_autoclose = autoclose;
 1975    }
 1976
 1977    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1978        self.use_auto_surround = auto_surround;
 1979    }
 1980
 1981    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1982        self.auto_replace_emoji_shortcode = auto_replace;
 1983    }
 1984
 1985    pub fn toggle_edit_predictions(
 1986        &mut self,
 1987        _: &ToggleEditPrediction,
 1988        window: &mut Window,
 1989        cx: &mut Context<Self>,
 1990    ) {
 1991        if self.show_inline_completions_override.is_some() {
 1992            self.set_show_edit_predictions(None, window, cx);
 1993        } else {
 1994            let show_edit_predictions = !self.edit_predictions_enabled();
 1995            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1996        }
 1997    }
 1998
 1999    pub fn set_show_edit_predictions(
 2000        &mut self,
 2001        show_edit_predictions: Option<bool>,
 2002        window: &mut Window,
 2003        cx: &mut Context<Self>,
 2004    ) {
 2005        self.show_inline_completions_override = show_edit_predictions;
 2006        self.update_edit_prediction_settings(cx);
 2007
 2008        if let Some(false) = show_edit_predictions {
 2009            self.discard_inline_completion(false, cx);
 2010        } else {
 2011            self.refresh_inline_completion(false, true, window, cx);
 2012        }
 2013    }
 2014
 2015    fn inline_completions_disabled_in_scope(
 2016        &self,
 2017        buffer: &Entity<Buffer>,
 2018        buffer_position: language::Anchor,
 2019        cx: &App,
 2020    ) -> bool {
 2021        let snapshot = buffer.read(cx).snapshot();
 2022        let settings = snapshot.settings_at(buffer_position, cx);
 2023
 2024        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2025            return false;
 2026        };
 2027
 2028        scope.override_name().map_or(false, |scope_name| {
 2029            settings
 2030                .edit_predictions_disabled_in
 2031                .iter()
 2032                .any(|s| s == scope_name)
 2033        })
 2034    }
 2035
 2036    pub fn set_use_modal_editing(&mut self, to: bool) {
 2037        self.use_modal_editing = to;
 2038    }
 2039
 2040    pub fn use_modal_editing(&self) -> bool {
 2041        self.use_modal_editing
 2042    }
 2043
 2044    fn selections_did_change(
 2045        &mut self,
 2046        local: bool,
 2047        old_cursor_position: &Anchor,
 2048        show_completions: bool,
 2049        window: &mut Window,
 2050        cx: &mut Context<Self>,
 2051    ) {
 2052        window.invalidate_character_coordinates();
 2053
 2054        // Copy selections to primary selection buffer
 2055        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2056        if local {
 2057            let selections = self.selections.all::<usize>(cx);
 2058            let buffer_handle = self.buffer.read(cx).read(cx);
 2059
 2060            let mut text = String::new();
 2061            for (index, selection) in selections.iter().enumerate() {
 2062                let text_for_selection = buffer_handle
 2063                    .text_for_range(selection.start..selection.end)
 2064                    .collect::<String>();
 2065
 2066                text.push_str(&text_for_selection);
 2067                if index != selections.len() - 1 {
 2068                    text.push('\n');
 2069                }
 2070            }
 2071
 2072            if !text.is_empty() {
 2073                cx.write_to_primary(ClipboardItem::new_string(text));
 2074            }
 2075        }
 2076
 2077        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2078            self.buffer.update(cx, |buffer, cx| {
 2079                buffer.set_active_selections(
 2080                    &self.selections.disjoint_anchors(),
 2081                    self.selections.line_mode,
 2082                    self.cursor_shape,
 2083                    cx,
 2084                )
 2085            });
 2086        }
 2087        let display_map = self
 2088            .display_map
 2089            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2090        let buffer = &display_map.buffer_snapshot;
 2091        self.add_selections_state = None;
 2092        self.select_next_state = None;
 2093        self.select_prev_state = None;
 2094        self.select_larger_syntax_node_stack.clear();
 2095        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2096        self.snippet_stack
 2097            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2098        self.take_rename(false, window, cx);
 2099
 2100        let new_cursor_position = self.selections.newest_anchor().head();
 2101
 2102        self.push_to_nav_history(
 2103            *old_cursor_position,
 2104            Some(new_cursor_position.to_point(buffer)),
 2105            cx,
 2106        );
 2107
 2108        if local {
 2109            let new_cursor_position = self.selections.newest_anchor().head();
 2110            let mut context_menu = self.context_menu.borrow_mut();
 2111            let completion_menu = match context_menu.as_ref() {
 2112                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2113                _ => {
 2114                    *context_menu = None;
 2115                    None
 2116                }
 2117            };
 2118            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2119                if !self.registered_buffers.contains_key(&buffer_id) {
 2120                    if let Some(project) = self.project.as_ref() {
 2121                        project.update(cx, |project, cx| {
 2122                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2123                                return;
 2124                            };
 2125                            self.registered_buffers.insert(
 2126                                buffer_id,
 2127                                project.register_buffer_with_language_servers(&buffer, cx),
 2128                            );
 2129                        })
 2130                    }
 2131                }
 2132            }
 2133
 2134            if let Some(completion_menu) = completion_menu {
 2135                let cursor_position = new_cursor_position.to_offset(buffer);
 2136                let (word_range, kind) =
 2137                    buffer.surrounding_word(completion_menu.initial_position, true);
 2138                if kind == Some(CharKind::Word)
 2139                    && word_range.to_inclusive().contains(&cursor_position)
 2140                {
 2141                    let mut completion_menu = completion_menu.clone();
 2142                    drop(context_menu);
 2143
 2144                    let query = Self::completion_query(buffer, cursor_position);
 2145                    cx.spawn(move |this, mut cx| async move {
 2146                        completion_menu
 2147                            .filter(query.as_deref(), cx.background_executor().clone())
 2148                            .await;
 2149
 2150                        this.update(&mut cx, |this, cx| {
 2151                            let mut context_menu = this.context_menu.borrow_mut();
 2152                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2153                            else {
 2154                                return;
 2155                            };
 2156
 2157                            if menu.id > completion_menu.id {
 2158                                return;
 2159                            }
 2160
 2161                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2162                            drop(context_menu);
 2163                            cx.notify();
 2164                        })
 2165                    })
 2166                    .detach();
 2167
 2168                    if show_completions {
 2169                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2170                    }
 2171                } else {
 2172                    drop(context_menu);
 2173                    self.hide_context_menu(window, cx);
 2174                }
 2175            } else {
 2176                drop(context_menu);
 2177            }
 2178
 2179            hide_hover(self, cx);
 2180
 2181            if old_cursor_position.to_display_point(&display_map).row()
 2182                != new_cursor_position.to_display_point(&display_map).row()
 2183            {
 2184                self.available_code_actions.take();
 2185            }
 2186            self.refresh_code_actions(window, cx);
 2187            self.refresh_document_highlights(cx);
 2188            self.refresh_selected_text_highlights(window, cx);
 2189            refresh_matching_bracket_highlights(self, window, cx);
 2190            self.update_visible_inline_completion(window, cx);
 2191            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2192            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2193            if self.git_blame_inline_enabled {
 2194                self.start_inline_blame_timer(window, cx);
 2195            }
 2196        }
 2197
 2198        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2199        cx.emit(EditorEvent::SelectionsChanged { local });
 2200
 2201        let selections = &self.selections.disjoint;
 2202        if selections.len() == 1 {
 2203            cx.emit(SearchEvent::ActiveMatchChanged)
 2204        }
 2205        if local
 2206            && self.is_singleton(cx)
 2207            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2208        {
 2209            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2210                let background_executor = cx.background_executor().clone();
 2211                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2212                let snapshot = self.buffer().read(cx).snapshot(cx);
 2213                let selections = selections.clone();
 2214                self.serialize_selections = cx.background_spawn(async move {
 2215                    background_executor.timer(Duration::from_millis(100)).await;
 2216                    let selections = selections
 2217                        .iter()
 2218                        .map(|selection| {
 2219                            (
 2220                                selection.start.to_offset(&snapshot),
 2221                                selection.end.to_offset(&snapshot),
 2222                            )
 2223                        })
 2224                        .collect();
 2225                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2226                        .await
 2227                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2228                        .log_err();
 2229                });
 2230            }
 2231        }
 2232
 2233        cx.notify();
 2234    }
 2235
 2236    pub fn sync_selections(
 2237        &mut self,
 2238        other: Entity<Editor>,
 2239        cx: &mut Context<Self>,
 2240    ) -> gpui::Subscription {
 2241        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2242        self.selections.change_with(cx, |selections| {
 2243            selections.select_anchors(other_selections);
 2244        });
 2245
 2246        let other_subscription =
 2247            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2248                EditorEvent::SelectionsChanged { local: true } => {
 2249                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2250                    this.selections.change_with(cx, |selections| {
 2251                        selections.select_anchors(other_selections);
 2252                    });
 2253                }
 2254                _ => {}
 2255            });
 2256
 2257        let this_subscription =
 2258            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2259                EditorEvent::SelectionsChanged { local: true } => {
 2260                    let these_selections = this.selections.disjoint.to_vec();
 2261                    other.update(cx, |other_editor, cx| {
 2262                        other_editor.selections.change_with(cx, |selections| {
 2263                            selections.select_anchors(these_selections);
 2264                        })
 2265                    });
 2266                }
 2267                _ => {}
 2268            });
 2269
 2270        Subscription::join(other_subscription, this_subscription)
 2271    }
 2272
 2273    pub fn change_selections<R>(
 2274        &mut self,
 2275        autoscroll: Option<Autoscroll>,
 2276        window: &mut Window,
 2277        cx: &mut Context<Self>,
 2278        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2279    ) -> R {
 2280        self.change_selections_inner(autoscroll, true, window, cx, change)
 2281    }
 2282
 2283    fn change_selections_inner<R>(
 2284        &mut self,
 2285        autoscroll: Option<Autoscroll>,
 2286        request_completions: bool,
 2287        window: &mut Window,
 2288        cx: &mut Context<Self>,
 2289        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2290    ) -> R {
 2291        let old_cursor_position = self.selections.newest_anchor().head();
 2292        self.push_to_selection_history();
 2293
 2294        let (changed, result) = self.selections.change_with(cx, change);
 2295
 2296        if changed {
 2297            if let Some(autoscroll) = autoscroll {
 2298                self.request_autoscroll(autoscroll, cx);
 2299            }
 2300            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2301
 2302            if self.should_open_signature_help_automatically(
 2303                &old_cursor_position,
 2304                self.signature_help_state.backspace_pressed(),
 2305                cx,
 2306            ) {
 2307                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2308            }
 2309            self.signature_help_state.set_backspace_pressed(false);
 2310        }
 2311
 2312        result
 2313    }
 2314
 2315    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2316    where
 2317        I: IntoIterator<Item = (Range<S>, T)>,
 2318        S: ToOffset,
 2319        T: Into<Arc<str>>,
 2320    {
 2321        if self.read_only(cx) {
 2322            return;
 2323        }
 2324
 2325        self.buffer
 2326            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2327    }
 2328
 2329    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2330    where
 2331        I: IntoIterator<Item = (Range<S>, T)>,
 2332        S: ToOffset,
 2333        T: Into<Arc<str>>,
 2334    {
 2335        if self.read_only(cx) {
 2336            return;
 2337        }
 2338
 2339        self.buffer.update(cx, |buffer, cx| {
 2340            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2341        });
 2342    }
 2343
 2344    pub fn edit_with_block_indent<I, S, T>(
 2345        &mut self,
 2346        edits: I,
 2347        original_start_columns: Vec<u32>,
 2348        cx: &mut Context<Self>,
 2349    ) where
 2350        I: IntoIterator<Item = (Range<S>, T)>,
 2351        S: ToOffset,
 2352        T: Into<Arc<str>>,
 2353    {
 2354        if self.read_only(cx) {
 2355            return;
 2356        }
 2357
 2358        self.buffer.update(cx, |buffer, cx| {
 2359            buffer.edit(
 2360                edits,
 2361                Some(AutoindentMode::Block {
 2362                    original_start_columns,
 2363                }),
 2364                cx,
 2365            )
 2366        });
 2367    }
 2368
 2369    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2370        self.hide_context_menu(window, cx);
 2371
 2372        match phase {
 2373            SelectPhase::Begin {
 2374                position,
 2375                add,
 2376                click_count,
 2377            } => self.begin_selection(position, add, click_count, window, cx),
 2378            SelectPhase::BeginColumnar {
 2379                position,
 2380                goal_column,
 2381                reset,
 2382            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2383            SelectPhase::Extend {
 2384                position,
 2385                click_count,
 2386            } => self.extend_selection(position, click_count, window, cx),
 2387            SelectPhase::Update {
 2388                position,
 2389                goal_column,
 2390                scroll_delta,
 2391            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2392            SelectPhase::End => self.end_selection(window, cx),
 2393        }
 2394    }
 2395
 2396    fn extend_selection(
 2397        &mut self,
 2398        position: DisplayPoint,
 2399        click_count: usize,
 2400        window: &mut Window,
 2401        cx: &mut Context<Self>,
 2402    ) {
 2403        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2404        let tail = self.selections.newest::<usize>(cx).tail();
 2405        self.begin_selection(position, false, click_count, window, cx);
 2406
 2407        let position = position.to_offset(&display_map, Bias::Left);
 2408        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2409
 2410        let mut pending_selection = self
 2411            .selections
 2412            .pending_anchor()
 2413            .expect("extend_selection not called with pending selection");
 2414        if position >= tail {
 2415            pending_selection.start = tail_anchor;
 2416        } else {
 2417            pending_selection.end = tail_anchor;
 2418            pending_selection.reversed = true;
 2419        }
 2420
 2421        let mut pending_mode = self.selections.pending_mode().unwrap();
 2422        match &mut pending_mode {
 2423            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2424            _ => {}
 2425        }
 2426
 2427        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2428            s.set_pending(pending_selection, pending_mode)
 2429        });
 2430    }
 2431
 2432    fn begin_selection(
 2433        &mut self,
 2434        position: DisplayPoint,
 2435        add: bool,
 2436        click_count: usize,
 2437        window: &mut Window,
 2438        cx: &mut Context<Self>,
 2439    ) {
 2440        if !self.focus_handle.is_focused(window) {
 2441            self.last_focused_descendant = None;
 2442            window.focus(&self.focus_handle);
 2443        }
 2444
 2445        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2446        let buffer = &display_map.buffer_snapshot;
 2447        let newest_selection = self.selections.newest_anchor().clone();
 2448        let position = display_map.clip_point(position, Bias::Left);
 2449
 2450        let start;
 2451        let end;
 2452        let mode;
 2453        let mut auto_scroll;
 2454        match click_count {
 2455            1 => {
 2456                start = buffer.anchor_before(position.to_point(&display_map));
 2457                end = start;
 2458                mode = SelectMode::Character;
 2459                auto_scroll = true;
 2460            }
 2461            2 => {
 2462                let range = movement::surrounding_word(&display_map, position);
 2463                start = buffer.anchor_before(range.start.to_point(&display_map));
 2464                end = buffer.anchor_before(range.end.to_point(&display_map));
 2465                mode = SelectMode::Word(start..end);
 2466                auto_scroll = true;
 2467            }
 2468            3 => {
 2469                let position = display_map
 2470                    .clip_point(position, Bias::Left)
 2471                    .to_point(&display_map);
 2472                let line_start = display_map.prev_line_boundary(position).0;
 2473                let next_line_start = buffer.clip_point(
 2474                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2475                    Bias::Left,
 2476                );
 2477                start = buffer.anchor_before(line_start);
 2478                end = buffer.anchor_before(next_line_start);
 2479                mode = SelectMode::Line(start..end);
 2480                auto_scroll = true;
 2481            }
 2482            _ => {
 2483                start = buffer.anchor_before(0);
 2484                end = buffer.anchor_before(buffer.len());
 2485                mode = SelectMode::All;
 2486                auto_scroll = false;
 2487            }
 2488        }
 2489        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2490
 2491        let point_to_delete: Option<usize> = {
 2492            let selected_points: Vec<Selection<Point>> =
 2493                self.selections.disjoint_in_range(start..end, cx);
 2494
 2495            if !add || click_count > 1 {
 2496                None
 2497            } else if !selected_points.is_empty() {
 2498                Some(selected_points[0].id)
 2499            } else {
 2500                let clicked_point_already_selected =
 2501                    self.selections.disjoint.iter().find(|selection| {
 2502                        selection.start.to_point(buffer) == start.to_point(buffer)
 2503                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2504                    });
 2505
 2506                clicked_point_already_selected.map(|selection| selection.id)
 2507            }
 2508        };
 2509
 2510        let selections_count = self.selections.count();
 2511
 2512        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2513            if let Some(point_to_delete) = point_to_delete {
 2514                s.delete(point_to_delete);
 2515
 2516                if selections_count == 1 {
 2517                    s.set_pending_anchor_range(start..end, mode);
 2518                }
 2519            } else {
 2520                if !add {
 2521                    s.clear_disjoint();
 2522                } else if click_count > 1 {
 2523                    s.delete(newest_selection.id)
 2524                }
 2525
 2526                s.set_pending_anchor_range(start..end, mode);
 2527            }
 2528        });
 2529    }
 2530
 2531    fn begin_columnar_selection(
 2532        &mut self,
 2533        position: DisplayPoint,
 2534        goal_column: u32,
 2535        reset: bool,
 2536        window: &mut Window,
 2537        cx: &mut Context<Self>,
 2538    ) {
 2539        if !self.focus_handle.is_focused(window) {
 2540            self.last_focused_descendant = None;
 2541            window.focus(&self.focus_handle);
 2542        }
 2543
 2544        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2545
 2546        if reset {
 2547            let pointer_position = display_map
 2548                .buffer_snapshot
 2549                .anchor_before(position.to_point(&display_map));
 2550
 2551            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2552                s.clear_disjoint();
 2553                s.set_pending_anchor_range(
 2554                    pointer_position..pointer_position,
 2555                    SelectMode::Character,
 2556                );
 2557            });
 2558        }
 2559
 2560        let tail = self.selections.newest::<Point>(cx).tail();
 2561        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2562
 2563        if !reset {
 2564            self.select_columns(
 2565                tail.to_display_point(&display_map),
 2566                position,
 2567                goal_column,
 2568                &display_map,
 2569                window,
 2570                cx,
 2571            );
 2572        }
 2573    }
 2574
 2575    fn update_selection(
 2576        &mut self,
 2577        position: DisplayPoint,
 2578        goal_column: u32,
 2579        scroll_delta: gpui::Point<f32>,
 2580        window: &mut Window,
 2581        cx: &mut Context<Self>,
 2582    ) {
 2583        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2584
 2585        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2586            let tail = tail.to_display_point(&display_map);
 2587            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2588        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2589            let buffer = self.buffer.read(cx).snapshot(cx);
 2590            let head;
 2591            let tail;
 2592            let mode = self.selections.pending_mode().unwrap();
 2593            match &mode {
 2594                SelectMode::Character => {
 2595                    head = position.to_point(&display_map);
 2596                    tail = pending.tail().to_point(&buffer);
 2597                }
 2598                SelectMode::Word(original_range) => {
 2599                    let original_display_range = original_range.start.to_display_point(&display_map)
 2600                        ..original_range.end.to_display_point(&display_map);
 2601                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2602                        ..original_display_range.end.to_point(&display_map);
 2603                    if movement::is_inside_word(&display_map, position)
 2604                        || original_display_range.contains(&position)
 2605                    {
 2606                        let word_range = movement::surrounding_word(&display_map, position);
 2607                        if word_range.start < original_display_range.start {
 2608                            head = word_range.start.to_point(&display_map);
 2609                        } else {
 2610                            head = word_range.end.to_point(&display_map);
 2611                        }
 2612                    } else {
 2613                        head = position.to_point(&display_map);
 2614                    }
 2615
 2616                    if head <= original_buffer_range.start {
 2617                        tail = original_buffer_range.end;
 2618                    } else {
 2619                        tail = original_buffer_range.start;
 2620                    }
 2621                }
 2622                SelectMode::Line(original_range) => {
 2623                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2624
 2625                    let position = display_map
 2626                        .clip_point(position, Bias::Left)
 2627                        .to_point(&display_map);
 2628                    let line_start = display_map.prev_line_boundary(position).0;
 2629                    let next_line_start = buffer.clip_point(
 2630                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2631                        Bias::Left,
 2632                    );
 2633
 2634                    if line_start < original_range.start {
 2635                        head = line_start
 2636                    } else {
 2637                        head = next_line_start
 2638                    }
 2639
 2640                    if head <= original_range.start {
 2641                        tail = original_range.end;
 2642                    } else {
 2643                        tail = original_range.start;
 2644                    }
 2645                }
 2646                SelectMode::All => {
 2647                    return;
 2648                }
 2649            };
 2650
 2651            if head < tail {
 2652                pending.start = buffer.anchor_before(head);
 2653                pending.end = buffer.anchor_before(tail);
 2654                pending.reversed = true;
 2655            } else {
 2656                pending.start = buffer.anchor_before(tail);
 2657                pending.end = buffer.anchor_before(head);
 2658                pending.reversed = false;
 2659            }
 2660
 2661            self.change_selections(None, window, cx, |s| {
 2662                s.set_pending(pending, mode);
 2663            });
 2664        } else {
 2665            log::error!("update_selection dispatched with no pending selection");
 2666            return;
 2667        }
 2668
 2669        self.apply_scroll_delta(scroll_delta, window, cx);
 2670        cx.notify();
 2671    }
 2672
 2673    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2674        self.columnar_selection_tail.take();
 2675        if self.selections.pending_anchor().is_some() {
 2676            let selections = self.selections.all::<usize>(cx);
 2677            self.change_selections(None, window, cx, |s| {
 2678                s.select(selections);
 2679                s.clear_pending();
 2680            });
 2681        }
 2682    }
 2683
 2684    fn select_columns(
 2685        &mut self,
 2686        tail: DisplayPoint,
 2687        head: DisplayPoint,
 2688        goal_column: u32,
 2689        display_map: &DisplaySnapshot,
 2690        window: &mut Window,
 2691        cx: &mut Context<Self>,
 2692    ) {
 2693        let start_row = cmp::min(tail.row(), head.row());
 2694        let end_row = cmp::max(tail.row(), head.row());
 2695        let start_column = cmp::min(tail.column(), goal_column);
 2696        let end_column = cmp::max(tail.column(), goal_column);
 2697        let reversed = start_column < tail.column();
 2698
 2699        let selection_ranges = (start_row.0..=end_row.0)
 2700            .map(DisplayRow)
 2701            .filter_map(|row| {
 2702                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2703                    let start = display_map
 2704                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2705                        .to_point(display_map);
 2706                    let end = display_map
 2707                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2708                        .to_point(display_map);
 2709                    if reversed {
 2710                        Some(end..start)
 2711                    } else {
 2712                        Some(start..end)
 2713                    }
 2714                } else {
 2715                    None
 2716                }
 2717            })
 2718            .collect::<Vec<_>>();
 2719
 2720        self.change_selections(None, window, cx, |s| {
 2721            s.select_ranges(selection_ranges);
 2722        });
 2723        cx.notify();
 2724    }
 2725
 2726    pub fn has_pending_nonempty_selection(&self) -> bool {
 2727        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2728            Some(Selection { start, end, .. }) => start != end,
 2729            None => false,
 2730        };
 2731
 2732        pending_nonempty_selection
 2733            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2734    }
 2735
 2736    pub fn has_pending_selection(&self) -> bool {
 2737        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2738    }
 2739
 2740    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2741        self.selection_mark_mode = false;
 2742
 2743        if self.clear_expanded_diff_hunks(cx) {
 2744            cx.notify();
 2745            return;
 2746        }
 2747        if self.dismiss_menus_and_popups(true, window, cx) {
 2748            return;
 2749        }
 2750
 2751        if self.mode == EditorMode::Full
 2752            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2753        {
 2754            return;
 2755        }
 2756
 2757        cx.propagate();
 2758    }
 2759
 2760    pub fn dismiss_menus_and_popups(
 2761        &mut self,
 2762        is_user_requested: bool,
 2763        window: &mut Window,
 2764        cx: &mut Context<Self>,
 2765    ) -> bool {
 2766        if self.take_rename(false, window, cx).is_some() {
 2767            return true;
 2768        }
 2769
 2770        if hide_hover(self, cx) {
 2771            return true;
 2772        }
 2773
 2774        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2775            return true;
 2776        }
 2777
 2778        if self.hide_context_menu(window, cx).is_some() {
 2779            return true;
 2780        }
 2781
 2782        if self.mouse_context_menu.take().is_some() {
 2783            return true;
 2784        }
 2785
 2786        if is_user_requested && self.discard_inline_completion(true, cx) {
 2787            return true;
 2788        }
 2789
 2790        if self.snippet_stack.pop().is_some() {
 2791            return true;
 2792        }
 2793
 2794        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2795            self.dismiss_diagnostics(cx);
 2796            return true;
 2797        }
 2798
 2799        false
 2800    }
 2801
 2802    fn linked_editing_ranges_for(
 2803        &self,
 2804        selection: Range<text::Anchor>,
 2805        cx: &App,
 2806    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2807        if self.linked_edit_ranges.is_empty() {
 2808            return None;
 2809        }
 2810        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2811            selection.end.buffer_id.and_then(|end_buffer_id| {
 2812                if selection.start.buffer_id != Some(end_buffer_id) {
 2813                    return None;
 2814                }
 2815                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2816                let snapshot = buffer.read(cx).snapshot();
 2817                self.linked_edit_ranges
 2818                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2819                    .map(|ranges| (ranges, snapshot, buffer))
 2820            })?;
 2821        use text::ToOffset as TO;
 2822        // find offset from the start of current range to current cursor position
 2823        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2824
 2825        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2826        let start_difference = start_offset - start_byte_offset;
 2827        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2828        let end_difference = end_offset - start_byte_offset;
 2829        // Current range has associated linked ranges.
 2830        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2831        for range in linked_ranges.iter() {
 2832            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2833            let end_offset = start_offset + end_difference;
 2834            let start_offset = start_offset + start_difference;
 2835            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2836                continue;
 2837            }
 2838            if self.selections.disjoint_anchor_ranges().any(|s| {
 2839                if s.start.buffer_id != selection.start.buffer_id
 2840                    || s.end.buffer_id != selection.end.buffer_id
 2841                {
 2842                    return false;
 2843                }
 2844                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2845                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2846            }) {
 2847                continue;
 2848            }
 2849            let start = buffer_snapshot.anchor_after(start_offset);
 2850            let end = buffer_snapshot.anchor_after(end_offset);
 2851            linked_edits
 2852                .entry(buffer.clone())
 2853                .or_default()
 2854                .push(start..end);
 2855        }
 2856        Some(linked_edits)
 2857    }
 2858
 2859    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2860        let text: Arc<str> = text.into();
 2861
 2862        if self.read_only(cx) {
 2863            return;
 2864        }
 2865
 2866        let selections = self.selections.all_adjusted(cx);
 2867        let mut bracket_inserted = false;
 2868        let mut edits = Vec::new();
 2869        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2870        let mut new_selections = Vec::with_capacity(selections.len());
 2871        let mut new_autoclose_regions = Vec::new();
 2872        let snapshot = self.buffer.read(cx).read(cx);
 2873
 2874        for (selection, autoclose_region) in
 2875            self.selections_with_autoclose_regions(selections, &snapshot)
 2876        {
 2877            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2878                // Determine if the inserted text matches the opening or closing
 2879                // bracket of any of this language's bracket pairs.
 2880                let mut bracket_pair = None;
 2881                let mut is_bracket_pair_start = false;
 2882                let mut is_bracket_pair_end = false;
 2883                if !text.is_empty() {
 2884                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2885                    //  and they are removing the character that triggered IME popup.
 2886                    for (pair, enabled) in scope.brackets() {
 2887                        if !pair.close && !pair.surround {
 2888                            continue;
 2889                        }
 2890
 2891                        if enabled && pair.start.ends_with(text.as_ref()) {
 2892                            let prefix_len = pair.start.len() - text.len();
 2893                            let preceding_text_matches_prefix = prefix_len == 0
 2894                                || (selection.start.column >= (prefix_len as u32)
 2895                                    && snapshot.contains_str_at(
 2896                                        Point::new(
 2897                                            selection.start.row,
 2898                                            selection.start.column - (prefix_len as u32),
 2899                                        ),
 2900                                        &pair.start[..prefix_len],
 2901                                    ));
 2902                            if preceding_text_matches_prefix {
 2903                                bracket_pair = Some(pair.clone());
 2904                                is_bracket_pair_start = true;
 2905                                break;
 2906                            }
 2907                        }
 2908                        if pair.end.as_str() == text.as_ref() {
 2909                            bracket_pair = Some(pair.clone());
 2910                            is_bracket_pair_end = true;
 2911                            break;
 2912                        }
 2913                    }
 2914                }
 2915
 2916                if let Some(bracket_pair) = bracket_pair {
 2917                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2918                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2919                    let auto_surround =
 2920                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2921                    if selection.is_empty() {
 2922                        if is_bracket_pair_start {
 2923                            // If the inserted text is a suffix of an opening bracket and the
 2924                            // selection is preceded by the rest of the opening bracket, then
 2925                            // insert the closing bracket.
 2926                            let following_text_allows_autoclose = snapshot
 2927                                .chars_at(selection.start)
 2928                                .next()
 2929                                .map_or(true, |c| scope.should_autoclose_before(c));
 2930
 2931                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2932                                && bracket_pair.start.len() == 1
 2933                            {
 2934                                let target = bracket_pair.start.chars().next().unwrap();
 2935                                let current_line_count = snapshot
 2936                                    .reversed_chars_at(selection.start)
 2937                                    .take_while(|&c| c != '\n')
 2938                                    .filter(|&c| c == target)
 2939                                    .count();
 2940                                current_line_count % 2 == 1
 2941                            } else {
 2942                                false
 2943                            };
 2944
 2945                            if autoclose
 2946                                && bracket_pair.close
 2947                                && following_text_allows_autoclose
 2948                                && !is_closing_quote
 2949                            {
 2950                                let anchor = snapshot.anchor_before(selection.end);
 2951                                new_selections.push((selection.map(|_| anchor), text.len()));
 2952                                new_autoclose_regions.push((
 2953                                    anchor,
 2954                                    text.len(),
 2955                                    selection.id,
 2956                                    bracket_pair.clone(),
 2957                                ));
 2958                                edits.push((
 2959                                    selection.range(),
 2960                                    format!("{}{}", text, bracket_pair.end).into(),
 2961                                ));
 2962                                bracket_inserted = true;
 2963                                continue;
 2964                            }
 2965                        }
 2966
 2967                        if let Some(region) = autoclose_region {
 2968                            // If the selection is followed by an auto-inserted closing bracket,
 2969                            // then don't insert that closing bracket again; just move the selection
 2970                            // past the closing bracket.
 2971                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2972                                && text.as_ref() == region.pair.end.as_str();
 2973                            if should_skip {
 2974                                let anchor = snapshot.anchor_after(selection.end);
 2975                                new_selections
 2976                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2977                                continue;
 2978                            }
 2979                        }
 2980
 2981                        let always_treat_brackets_as_autoclosed = snapshot
 2982                            .settings_at(selection.start, cx)
 2983                            .always_treat_brackets_as_autoclosed;
 2984                        if always_treat_brackets_as_autoclosed
 2985                            && is_bracket_pair_end
 2986                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2987                        {
 2988                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2989                            // and the inserted text is a closing bracket and the selection is followed
 2990                            // by the closing bracket then move the selection past the closing bracket.
 2991                            let anchor = snapshot.anchor_after(selection.end);
 2992                            new_selections.push((selection.map(|_| anchor), text.len()));
 2993                            continue;
 2994                        }
 2995                    }
 2996                    // If an opening bracket is 1 character long and is typed while
 2997                    // text is selected, then surround that text with the bracket pair.
 2998                    else if auto_surround
 2999                        && bracket_pair.surround
 3000                        && is_bracket_pair_start
 3001                        && bracket_pair.start.chars().count() == 1
 3002                    {
 3003                        edits.push((selection.start..selection.start, text.clone()));
 3004                        edits.push((
 3005                            selection.end..selection.end,
 3006                            bracket_pair.end.as_str().into(),
 3007                        ));
 3008                        bracket_inserted = true;
 3009                        new_selections.push((
 3010                            Selection {
 3011                                id: selection.id,
 3012                                start: snapshot.anchor_after(selection.start),
 3013                                end: snapshot.anchor_before(selection.end),
 3014                                reversed: selection.reversed,
 3015                                goal: selection.goal,
 3016                            },
 3017                            0,
 3018                        ));
 3019                        continue;
 3020                    }
 3021                }
 3022            }
 3023
 3024            if self.auto_replace_emoji_shortcode
 3025                && selection.is_empty()
 3026                && text.as_ref().ends_with(':')
 3027            {
 3028                if let Some(possible_emoji_short_code) =
 3029                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3030                {
 3031                    if !possible_emoji_short_code.is_empty() {
 3032                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3033                            let emoji_shortcode_start = Point::new(
 3034                                selection.start.row,
 3035                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3036                            );
 3037
 3038                            // Remove shortcode from buffer
 3039                            edits.push((
 3040                                emoji_shortcode_start..selection.start,
 3041                                "".to_string().into(),
 3042                            ));
 3043                            new_selections.push((
 3044                                Selection {
 3045                                    id: selection.id,
 3046                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3047                                    end: snapshot.anchor_before(selection.start),
 3048                                    reversed: selection.reversed,
 3049                                    goal: selection.goal,
 3050                                },
 3051                                0,
 3052                            ));
 3053
 3054                            // Insert emoji
 3055                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3056                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3057                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3058
 3059                            continue;
 3060                        }
 3061                    }
 3062                }
 3063            }
 3064
 3065            // If not handling any auto-close operation, then just replace the selected
 3066            // text with the given input and move the selection to the end of the
 3067            // newly inserted text.
 3068            let anchor = snapshot.anchor_after(selection.end);
 3069            if !self.linked_edit_ranges.is_empty() {
 3070                let start_anchor = snapshot.anchor_before(selection.start);
 3071
 3072                let is_word_char = text.chars().next().map_or(true, |char| {
 3073                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3074                    classifier.is_word(char)
 3075                });
 3076
 3077                if is_word_char {
 3078                    if let Some(ranges) = self
 3079                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3080                    {
 3081                        for (buffer, edits) in ranges {
 3082                            linked_edits
 3083                                .entry(buffer.clone())
 3084                                .or_default()
 3085                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3086                        }
 3087                    }
 3088                }
 3089            }
 3090
 3091            new_selections.push((selection.map(|_| anchor), 0));
 3092            edits.push((selection.start..selection.end, text.clone()));
 3093        }
 3094
 3095        drop(snapshot);
 3096
 3097        self.transact(window, cx, |this, window, cx| {
 3098            this.buffer.update(cx, |buffer, cx| {
 3099                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3100            });
 3101            for (buffer, edits) in linked_edits {
 3102                buffer.update(cx, |buffer, cx| {
 3103                    let snapshot = buffer.snapshot();
 3104                    let edits = edits
 3105                        .into_iter()
 3106                        .map(|(range, text)| {
 3107                            use text::ToPoint as TP;
 3108                            let end_point = TP::to_point(&range.end, &snapshot);
 3109                            let start_point = TP::to_point(&range.start, &snapshot);
 3110                            (start_point..end_point, text)
 3111                        })
 3112                        .sorted_by_key(|(range, _)| range.start)
 3113                        .collect::<Vec<_>>();
 3114                    buffer.edit(edits, None, cx);
 3115                })
 3116            }
 3117            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3118            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3119            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3120            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3121                .zip(new_selection_deltas)
 3122                .map(|(selection, delta)| Selection {
 3123                    id: selection.id,
 3124                    start: selection.start + delta,
 3125                    end: selection.end + delta,
 3126                    reversed: selection.reversed,
 3127                    goal: SelectionGoal::None,
 3128                })
 3129                .collect::<Vec<_>>();
 3130
 3131            let mut i = 0;
 3132            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3133                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3134                let start = map.buffer_snapshot.anchor_before(position);
 3135                let end = map.buffer_snapshot.anchor_after(position);
 3136                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3137                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3138                        Ordering::Less => i += 1,
 3139                        Ordering::Greater => break,
 3140                        Ordering::Equal => {
 3141                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3142                                Ordering::Less => i += 1,
 3143                                Ordering::Equal => break,
 3144                                Ordering::Greater => break,
 3145                            }
 3146                        }
 3147                    }
 3148                }
 3149                this.autoclose_regions.insert(
 3150                    i,
 3151                    AutocloseRegion {
 3152                        selection_id,
 3153                        range: start..end,
 3154                        pair,
 3155                    },
 3156                );
 3157            }
 3158
 3159            let had_active_inline_completion = this.has_active_inline_completion();
 3160            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3161                s.select(new_selections)
 3162            });
 3163
 3164            if !bracket_inserted {
 3165                if let Some(on_type_format_task) =
 3166                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3167                {
 3168                    on_type_format_task.detach_and_log_err(cx);
 3169                }
 3170            }
 3171
 3172            let editor_settings = EditorSettings::get_global(cx);
 3173            if bracket_inserted
 3174                && (editor_settings.auto_signature_help
 3175                    || editor_settings.show_signature_help_after_edits)
 3176            {
 3177                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3178            }
 3179
 3180            let trigger_in_words =
 3181                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3182            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3183            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3184            this.refresh_inline_completion(true, false, window, cx);
 3185        });
 3186    }
 3187
 3188    fn find_possible_emoji_shortcode_at_position(
 3189        snapshot: &MultiBufferSnapshot,
 3190        position: Point,
 3191    ) -> Option<String> {
 3192        let mut chars = Vec::new();
 3193        let mut found_colon = false;
 3194        for char in snapshot.reversed_chars_at(position).take(100) {
 3195            // Found a possible emoji shortcode in the middle of the buffer
 3196            if found_colon {
 3197                if char.is_whitespace() {
 3198                    chars.reverse();
 3199                    return Some(chars.iter().collect());
 3200                }
 3201                // If the previous character is not a whitespace, we are in the middle of a word
 3202                // and we only want to complete the shortcode if the word is made up of other emojis
 3203                let mut containing_word = String::new();
 3204                for ch in snapshot
 3205                    .reversed_chars_at(position)
 3206                    .skip(chars.len() + 1)
 3207                    .take(100)
 3208                {
 3209                    if ch.is_whitespace() {
 3210                        break;
 3211                    }
 3212                    containing_word.push(ch);
 3213                }
 3214                let containing_word = containing_word.chars().rev().collect::<String>();
 3215                if util::word_consists_of_emojis(containing_word.as_str()) {
 3216                    chars.reverse();
 3217                    return Some(chars.iter().collect());
 3218                }
 3219            }
 3220
 3221            if char.is_whitespace() || !char.is_ascii() {
 3222                return None;
 3223            }
 3224            if char == ':' {
 3225                found_colon = true;
 3226            } else {
 3227                chars.push(char);
 3228            }
 3229        }
 3230        // Found a possible emoji shortcode at the beginning of the buffer
 3231        chars.reverse();
 3232        Some(chars.iter().collect())
 3233    }
 3234
 3235    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3236        self.transact(window, cx, |this, window, cx| {
 3237            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3238                let selections = this.selections.all::<usize>(cx);
 3239                let multi_buffer = this.buffer.read(cx);
 3240                let buffer = multi_buffer.snapshot(cx);
 3241                selections
 3242                    .iter()
 3243                    .map(|selection| {
 3244                        let start_point = selection.start.to_point(&buffer);
 3245                        let mut indent =
 3246                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3247                        indent.len = cmp::min(indent.len, start_point.column);
 3248                        let start = selection.start;
 3249                        let end = selection.end;
 3250                        let selection_is_empty = start == end;
 3251                        let language_scope = buffer.language_scope_at(start);
 3252                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3253                            &language_scope
 3254                        {
 3255                            let insert_extra_newline =
 3256                                insert_extra_newline_brackets(&buffer, start..end, language)
 3257                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3258
 3259                            // Comment extension on newline is allowed only for cursor selections
 3260                            let comment_delimiter = maybe!({
 3261                                if !selection_is_empty {
 3262                                    return None;
 3263                                }
 3264
 3265                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3266                                    return None;
 3267                                }
 3268
 3269                                let delimiters = language.line_comment_prefixes();
 3270                                let max_len_of_delimiter =
 3271                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3272                                let (snapshot, range) =
 3273                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3274
 3275                                let mut index_of_first_non_whitespace = 0;
 3276                                let comment_candidate = snapshot
 3277                                    .chars_for_range(range)
 3278                                    .skip_while(|c| {
 3279                                        let should_skip = c.is_whitespace();
 3280                                        if should_skip {
 3281                                            index_of_first_non_whitespace += 1;
 3282                                        }
 3283                                        should_skip
 3284                                    })
 3285                                    .take(max_len_of_delimiter)
 3286                                    .collect::<String>();
 3287                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3288                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3289                                })?;
 3290                                let cursor_is_placed_after_comment_marker =
 3291                                    index_of_first_non_whitespace + comment_prefix.len()
 3292                                        <= start_point.column as usize;
 3293                                if cursor_is_placed_after_comment_marker {
 3294                                    Some(comment_prefix.clone())
 3295                                } else {
 3296                                    None
 3297                                }
 3298                            });
 3299                            (comment_delimiter, insert_extra_newline)
 3300                        } else {
 3301                            (None, false)
 3302                        };
 3303
 3304                        let capacity_for_delimiter = comment_delimiter
 3305                            .as_deref()
 3306                            .map(str::len)
 3307                            .unwrap_or_default();
 3308                        let mut new_text =
 3309                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3310                        new_text.push('\n');
 3311                        new_text.extend(indent.chars());
 3312                        if let Some(delimiter) = &comment_delimiter {
 3313                            new_text.push_str(delimiter);
 3314                        }
 3315                        if insert_extra_newline {
 3316                            new_text = new_text.repeat(2);
 3317                        }
 3318
 3319                        let anchor = buffer.anchor_after(end);
 3320                        let new_selection = selection.map(|_| anchor);
 3321                        (
 3322                            (start..end, new_text),
 3323                            (insert_extra_newline, new_selection),
 3324                        )
 3325                    })
 3326                    .unzip()
 3327            };
 3328
 3329            this.edit_with_autoindent(edits, cx);
 3330            let buffer = this.buffer.read(cx).snapshot(cx);
 3331            let new_selections = selection_fixup_info
 3332                .into_iter()
 3333                .map(|(extra_newline_inserted, new_selection)| {
 3334                    let mut cursor = new_selection.end.to_point(&buffer);
 3335                    if extra_newline_inserted {
 3336                        cursor.row -= 1;
 3337                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3338                    }
 3339                    new_selection.map(|_| cursor)
 3340                })
 3341                .collect();
 3342
 3343            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3344                s.select(new_selections)
 3345            });
 3346            this.refresh_inline_completion(true, false, window, cx);
 3347        });
 3348    }
 3349
 3350    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3351        let buffer = self.buffer.read(cx);
 3352        let snapshot = buffer.snapshot(cx);
 3353
 3354        let mut edits = Vec::new();
 3355        let mut rows = Vec::new();
 3356
 3357        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3358            let cursor = selection.head();
 3359            let row = cursor.row;
 3360
 3361            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3362
 3363            let newline = "\n".to_string();
 3364            edits.push((start_of_line..start_of_line, newline));
 3365
 3366            rows.push(row + rows_inserted as u32);
 3367        }
 3368
 3369        self.transact(window, cx, |editor, window, cx| {
 3370            editor.edit(edits, cx);
 3371
 3372            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3373                let mut index = 0;
 3374                s.move_cursors_with(|map, _, _| {
 3375                    let row = rows[index];
 3376                    index += 1;
 3377
 3378                    let point = Point::new(row, 0);
 3379                    let boundary = map.next_line_boundary(point).1;
 3380                    let clipped = map.clip_point(boundary, Bias::Left);
 3381
 3382                    (clipped, SelectionGoal::None)
 3383                });
 3384            });
 3385
 3386            let mut indent_edits = Vec::new();
 3387            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3388            for row in rows {
 3389                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3390                for (row, indent) in indents {
 3391                    if indent.len == 0 {
 3392                        continue;
 3393                    }
 3394
 3395                    let text = match indent.kind {
 3396                        IndentKind::Space => " ".repeat(indent.len as usize),
 3397                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3398                    };
 3399                    let point = Point::new(row.0, 0);
 3400                    indent_edits.push((point..point, text));
 3401                }
 3402            }
 3403            editor.edit(indent_edits, cx);
 3404        });
 3405    }
 3406
 3407    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3408        let buffer = self.buffer.read(cx);
 3409        let snapshot = buffer.snapshot(cx);
 3410
 3411        let mut edits = Vec::new();
 3412        let mut rows = Vec::new();
 3413        let mut rows_inserted = 0;
 3414
 3415        for selection in self.selections.all_adjusted(cx) {
 3416            let cursor = selection.head();
 3417            let row = cursor.row;
 3418
 3419            let point = Point::new(row + 1, 0);
 3420            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3421
 3422            let newline = "\n".to_string();
 3423            edits.push((start_of_line..start_of_line, newline));
 3424
 3425            rows_inserted += 1;
 3426            rows.push(row + rows_inserted);
 3427        }
 3428
 3429        self.transact(window, cx, |editor, window, cx| {
 3430            editor.edit(edits, cx);
 3431
 3432            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3433                let mut index = 0;
 3434                s.move_cursors_with(|map, _, _| {
 3435                    let row = rows[index];
 3436                    index += 1;
 3437
 3438                    let point = Point::new(row, 0);
 3439                    let boundary = map.next_line_boundary(point).1;
 3440                    let clipped = map.clip_point(boundary, Bias::Left);
 3441
 3442                    (clipped, SelectionGoal::None)
 3443                });
 3444            });
 3445
 3446            let mut indent_edits = Vec::new();
 3447            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3448            for row in rows {
 3449                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3450                for (row, indent) in indents {
 3451                    if indent.len == 0 {
 3452                        continue;
 3453                    }
 3454
 3455                    let text = match indent.kind {
 3456                        IndentKind::Space => " ".repeat(indent.len as usize),
 3457                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3458                    };
 3459                    let point = Point::new(row.0, 0);
 3460                    indent_edits.push((point..point, text));
 3461                }
 3462            }
 3463            editor.edit(indent_edits, cx);
 3464        });
 3465    }
 3466
 3467    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3468        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3469            original_start_columns: Vec::new(),
 3470        });
 3471        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3472    }
 3473
 3474    fn insert_with_autoindent_mode(
 3475        &mut self,
 3476        text: &str,
 3477        autoindent_mode: Option<AutoindentMode>,
 3478        window: &mut Window,
 3479        cx: &mut Context<Self>,
 3480    ) {
 3481        if self.read_only(cx) {
 3482            return;
 3483        }
 3484
 3485        let text: Arc<str> = text.into();
 3486        self.transact(window, cx, |this, window, cx| {
 3487            let old_selections = this.selections.all_adjusted(cx);
 3488            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3489                let anchors = {
 3490                    let snapshot = buffer.read(cx);
 3491                    old_selections
 3492                        .iter()
 3493                        .map(|s| {
 3494                            let anchor = snapshot.anchor_after(s.head());
 3495                            s.map(|_| anchor)
 3496                        })
 3497                        .collect::<Vec<_>>()
 3498                };
 3499                buffer.edit(
 3500                    old_selections
 3501                        .iter()
 3502                        .map(|s| (s.start..s.end, text.clone())),
 3503                    autoindent_mode,
 3504                    cx,
 3505                );
 3506                anchors
 3507            });
 3508
 3509            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3510                s.select_anchors(selection_anchors);
 3511            });
 3512
 3513            cx.notify();
 3514        });
 3515    }
 3516
 3517    fn trigger_completion_on_input(
 3518        &mut self,
 3519        text: &str,
 3520        trigger_in_words: bool,
 3521        window: &mut Window,
 3522        cx: &mut Context<Self>,
 3523    ) {
 3524        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3525            self.show_completions(
 3526                &ShowCompletions {
 3527                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3528                },
 3529                window,
 3530                cx,
 3531            );
 3532        } else {
 3533            self.hide_context_menu(window, cx);
 3534        }
 3535    }
 3536
 3537    fn is_completion_trigger(
 3538        &self,
 3539        text: &str,
 3540        trigger_in_words: bool,
 3541        cx: &mut Context<Self>,
 3542    ) -> bool {
 3543        let position = self.selections.newest_anchor().head();
 3544        let multibuffer = self.buffer.read(cx);
 3545        let Some(buffer) = position
 3546            .buffer_id
 3547            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3548        else {
 3549            return false;
 3550        };
 3551
 3552        if let Some(completion_provider) = &self.completion_provider {
 3553            completion_provider.is_completion_trigger(
 3554                &buffer,
 3555                position.text_anchor,
 3556                text,
 3557                trigger_in_words,
 3558                cx,
 3559            )
 3560        } else {
 3561            false
 3562        }
 3563    }
 3564
 3565    /// If any empty selections is touching the start of its innermost containing autoclose
 3566    /// region, expand it to select the brackets.
 3567    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3568        let selections = self.selections.all::<usize>(cx);
 3569        let buffer = self.buffer.read(cx).read(cx);
 3570        let new_selections = self
 3571            .selections_with_autoclose_regions(selections, &buffer)
 3572            .map(|(mut selection, region)| {
 3573                if !selection.is_empty() {
 3574                    return selection;
 3575                }
 3576
 3577                if let Some(region) = region {
 3578                    let mut range = region.range.to_offset(&buffer);
 3579                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3580                        range.start -= region.pair.start.len();
 3581                        if buffer.contains_str_at(range.start, &region.pair.start)
 3582                            && buffer.contains_str_at(range.end, &region.pair.end)
 3583                        {
 3584                            range.end += region.pair.end.len();
 3585                            selection.start = range.start;
 3586                            selection.end = range.end;
 3587
 3588                            return selection;
 3589                        }
 3590                    }
 3591                }
 3592
 3593                let always_treat_brackets_as_autoclosed = buffer
 3594                    .settings_at(selection.start, cx)
 3595                    .always_treat_brackets_as_autoclosed;
 3596
 3597                if !always_treat_brackets_as_autoclosed {
 3598                    return selection;
 3599                }
 3600
 3601                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3602                    for (pair, enabled) in scope.brackets() {
 3603                        if !enabled || !pair.close {
 3604                            continue;
 3605                        }
 3606
 3607                        if buffer.contains_str_at(selection.start, &pair.end) {
 3608                            let pair_start_len = pair.start.len();
 3609                            if buffer.contains_str_at(
 3610                                selection.start.saturating_sub(pair_start_len),
 3611                                &pair.start,
 3612                            ) {
 3613                                selection.start -= pair_start_len;
 3614                                selection.end += pair.end.len();
 3615
 3616                                return selection;
 3617                            }
 3618                        }
 3619                    }
 3620                }
 3621
 3622                selection
 3623            })
 3624            .collect();
 3625
 3626        drop(buffer);
 3627        self.change_selections(None, window, cx, |selections| {
 3628            selections.select(new_selections)
 3629        });
 3630    }
 3631
 3632    /// Iterate the given selections, and for each one, find the smallest surrounding
 3633    /// autoclose region. This uses the ordering of the selections and the autoclose
 3634    /// regions to avoid repeated comparisons.
 3635    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3636        &'a self,
 3637        selections: impl IntoIterator<Item = Selection<D>>,
 3638        buffer: &'a MultiBufferSnapshot,
 3639    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3640        let mut i = 0;
 3641        let mut regions = self.autoclose_regions.as_slice();
 3642        selections.into_iter().map(move |selection| {
 3643            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3644
 3645            let mut enclosing = None;
 3646            while let Some(pair_state) = regions.get(i) {
 3647                if pair_state.range.end.to_offset(buffer) < range.start {
 3648                    regions = &regions[i + 1..];
 3649                    i = 0;
 3650                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3651                    break;
 3652                } else {
 3653                    if pair_state.selection_id == selection.id {
 3654                        enclosing = Some(pair_state);
 3655                    }
 3656                    i += 1;
 3657                }
 3658            }
 3659
 3660            (selection, enclosing)
 3661        })
 3662    }
 3663
 3664    /// Remove any autoclose regions that no longer contain their selection.
 3665    fn invalidate_autoclose_regions(
 3666        &mut self,
 3667        mut selections: &[Selection<Anchor>],
 3668        buffer: &MultiBufferSnapshot,
 3669    ) {
 3670        self.autoclose_regions.retain(|state| {
 3671            let mut i = 0;
 3672            while let Some(selection) = selections.get(i) {
 3673                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3674                    selections = &selections[1..];
 3675                    continue;
 3676                }
 3677                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3678                    break;
 3679                }
 3680                if selection.id == state.selection_id {
 3681                    return true;
 3682                } else {
 3683                    i += 1;
 3684                }
 3685            }
 3686            false
 3687        });
 3688    }
 3689
 3690    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3691        let offset = position.to_offset(buffer);
 3692        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3693        if offset > word_range.start && kind == Some(CharKind::Word) {
 3694            Some(
 3695                buffer
 3696                    .text_for_range(word_range.start..offset)
 3697                    .collect::<String>(),
 3698            )
 3699        } else {
 3700            None
 3701        }
 3702    }
 3703
 3704    pub fn toggle_inlay_hints(
 3705        &mut self,
 3706        _: &ToggleInlayHints,
 3707        _: &mut Window,
 3708        cx: &mut Context<Self>,
 3709    ) {
 3710        self.refresh_inlay_hints(
 3711            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 3712            cx,
 3713        );
 3714    }
 3715
 3716    pub fn inlay_hints_enabled(&self) -> bool {
 3717        self.inlay_hint_cache.enabled
 3718    }
 3719
 3720    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3721        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3722            return;
 3723        }
 3724
 3725        let reason_description = reason.description();
 3726        let ignore_debounce = matches!(
 3727            reason,
 3728            InlayHintRefreshReason::SettingsChange(_)
 3729                | InlayHintRefreshReason::Toggle(_)
 3730                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3731                | InlayHintRefreshReason::ModifiersChanged(_)
 3732        );
 3733        let (invalidate_cache, required_languages) = match reason {
 3734            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 3735                match self.inlay_hint_cache.modifiers_override(enabled) {
 3736                    Some(enabled) => {
 3737                        if enabled {
 3738                            (InvalidationStrategy::RefreshRequested, None)
 3739                        } else {
 3740                            self.splice_inlays(
 3741                                &self
 3742                                    .visible_inlay_hints(cx)
 3743                                    .iter()
 3744                                    .map(|inlay| inlay.id)
 3745                                    .collect::<Vec<InlayId>>(),
 3746                                Vec::new(),
 3747                                cx,
 3748                            );
 3749                            return;
 3750                        }
 3751                    }
 3752                    None => return,
 3753                }
 3754            }
 3755            InlayHintRefreshReason::Toggle(enabled) => {
 3756                if self.inlay_hint_cache.toggle(enabled) {
 3757                    if enabled {
 3758                        (InvalidationStrategy::RefreshRequested, None)
 3759                    } else {
 3760                        self.splice_inlays(
 3761                            &self
 3762                                .visible_inlay_hints(cx)
 3763                                .iter()
 3764                                .map(|inlay| inlay.id)
 3765                                .collect::<Vec<InlayId>>(),
 3766                            Vec::new(),
 3767                            cx,
 3768                        );
 3769                        return;
 3770                    }
 3771                } else {
 3772                    return;
 3773                }
 3774            }
 3775            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3776                match self.inlay_hint_cache.update_settings(
 3777                    &self.buffer,
 3778                    new_settings,
 3779                    self.visible_inlay_hints(cx),
 3780                    cx,
 3781                ) {
 3782                    ControlFlow::Break(Some(InlaySplice {
 3783                        to_remove,
 3784                        to_insert,
 3785                    })) => {
 3786                        self.splice_inlays(&to_remove, to_insert, cx);
 3787                        return;
 3788                    }
 3789                    ControlFlow::Break(None) => return,
 3790                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3791                }
 3792            }
 3793            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3794                if let Some(InlaySplice {
 3795                    to_remove,
 3796                    to_insert,
 3797                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3798                {
 3799                    self.splice_inlays(&to_remove, to_insert, cx);
 3800                }
 3801                return;
 3802            }
 3803            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3804            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3805                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3806            }
 3807            InlayHintRefreshReason::RefreshRequested => {
 3808                (InvalidationStrategy::RefreshRequested, None)
 3809            }
 3810        };
 3811
 3812        if let Some(InlaySplice {
 3813            to_remove,
 3814            to_insert,
 3815        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3816            reason_description,
 3817            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3818            invalidate_cache,
 3819            ignore_debounce,
 3820            cx,
 3821        ) {
 3822            self.splice_inlays(&to_remove, to_insert, cx);
 3823        }
 3824    }
 3825
 3826    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3827        self.display_map
 3828            .read(cx)
 3829            .current_inlays()
 3830            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3831            .cloned()
 3832            .collect()
 3833    }
 3834
 3835    pub fn excerpts_for_inlay_hints_query(
 3836        &self,
 3837        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3838        cx: &mut Context<Editor>,
 3839    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3840        let Some(project) = self.project.as_ref() else {
 3841            return HashMap::default();
 3842        };
 3843        let project = project.read(cx);
 3844        let multi_buffer = self.buffer().read(cx);
 3845        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3846        let multi_buffer_visible_start = self
 3847            .scroll_manager
 3848            .anchor()
 3849            .anchor
 3850            .to_point(&multi_buffer_snapshot);
 3851        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3852            multi_buffer_visible_start
 3853                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3854            Bias::Left,
 3855        );
 3856        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3857        multi_buffer_snapshot
 3858            .range_to_buffer_ranges(multi_buffer_visible_range)
 3859            .into_iter()
 3860            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3861            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3862                let buffer_file = project::File::from_dyn(buffer.file())?;
 3863                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3864                let worktree_entry = buffer_worktree
 3865                    .read(cx)
 3866                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3867                if worktree_entry.is_ignored {
 3868                    return None;
 3869                }
 3870
 3871                let language = buffer.language()?;
 3872                if let Some(restrict_to_languages) = restrict_to_languages {
 3873                    if !restrict_to_languages.contains(language) {
 3874                        return None;
 3875                    }
 3876                }
 3877                Some((
 3878                    excerpt_id,
 3879                    (
 3880                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3881                        buffer.version().clone(),
 3882                        excerpt_visible_range,
 3883                    ),
 3884                ))
 3885            })
 3886            .collect()
 3887    }
 3888
 3889    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3890        TextLayoutDetails {
 3891            text_system: window.text_system().clone(),
 3892            editor_style: self.style.clone().unwrap(),
 3893            rem_size: window.rem_size(),
 3894            scroll_anchor: self.scroll_manager.anchor(),
 3895            visible_rows: self.visible_line_count(),
 3896            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3897        }
 3898    }
 3899
 3900    pub fn splice_inlays(
 3901        &self,
 3902        to_remove: &[InlayId],
 3903        to_insert: Vec<Inlay>,
 3904        cx: &mut Context<Self>,
 3905    ) {
 3906        self.display_map.update(cx, |display_map, cx| {
 3907            display_map.splice_inlays(to_remove, to_insert, cx)
 3908        });
 3909        cx.notify();
 3910    }
 3911
 3912    fn trigger_on_type_formatting(
 3913        &self,
 3914        input: String,
 3915        window: &mut Window,
 3916        cx: &mut Context<Self>,
 3917    ) -> Option<Task<Result<()>>> {
 3918        if input.len() != 1 {
 3919            return None;
 3920        }
 3921
 3922        let project = self.project.as_ref()?;
 3923        let position = self.selections.newest_anchor().head();
 3924        let (buffer, buffer_position) = self
 3925            .buffer
 3926            .read(cx)
 3927            .text_anchor_for_position(position, cx)?;
 3928
 3929        let settings = language_settings::language_settings(
 3930            buffer
 3931                .read(cx)
 3932                .language_at(buffer_position)
 3933                .map(|l| l.name()),
 3934            buffer.read(cx).file(),
 3935            cx,
 3936        );
 3937        if !settings.use_on_type_format {
 3938            return None;
 3939        }
 3940
 3941        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3942        // hence we do LSP request & edit on host side only — add formats to host's history.
 3943        let push_to_lsp_host_history = true;
 3944        // If this is not the host, append its history with new edits.
 3945        let push_to_client_history = project.read(cx).is_via_collab();
 3946
 3947        let on_type_formatting = project.update(cx, |project, cx| {
 3948            project.on_type_format(
 3949                buffer.clone(),
 3950                buffer_position,
 3951                input,
 3952                push_to_lsp_host_history,
 3953                cx,
 3954            )
 3955        });
 3956        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3957            if let Some(transaction) = on_type_formatting.await? {
 3958                if push_to_client_history {
 3959                    buffer
 3960                        .update(&mut cx, |buffer, _| {
 3961                            buffer.push_transaction(transaction, Instant::now());
 3962                        })
 3963                        .ok();
 3964                }
 3965                editor.update(&mut cx, |editor, cx| {
 3966                    editor.refresh_document_highlights(cx);
 3967                })?;
 3968            }
 3969            Ok(())
 3970        }))
 3971    }
 3972
 3973    pub fn show_completions(
 3974        &mut self,
 3975        options: &ShowCompletions,
 3976        window: &mut Window,
 3977        cx: &mut Context<Self>,
 3978    ) {
 3979        if self.pending_rename.is_some() {
 3980            return;
 3981        }
 3982
 3983        let Some(provider) = self.completion_provider.as_ref() else {
 3984            return;
 3985        };
 3986
 3987        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3988            return;
 3989        }
 3990
 3991        let position = self.selections.newest_anchor().head();
 3992        if position.diff_base_anchor.is_some() {
 3993            return;
 3994        }
 3995        let (buffer, buffer_position) =
 3996            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3997                output
 3998            } else {
 3999                return;
 4000            };
 4001        let show_completion_documentation = buffer
 4002            .read(cx)
 4003            .snapshot()
 4004            .settings_at(buffer_position, cx)
 4005            .show_completion_documentation;
 4006
 4007        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4008
 4009        let trigger_kind = match &options.trigger {
 4010            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4011                CompletionTriggerKind::TRIGGER_CHARACTER
 4012            }
 4013            _ => CompletionTriggerKind::INVOKED,
 4014        };
 4015        let completion_context = CompletionContext {
 4016            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4017                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4018                    Some(String::from(trigger))
 4019                } else {
 4020                    None
 4021                }
 4022            }),
 4023            trigger_kind,
 4024        };
 4025        let completions =
 4026            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 4027        let sort_completions = provider.sort_completions();
 4028
 4029        let id = post_inc(&mut self.next_completion_id);
 4030        let task = cx.spawn_in(window, |editor, mut cx| {
 4031            async move {
 4032                editor.update(&mut cx, |this, _| {
 4033                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4034                })?;
 4035                let completions = completions.await.log_err();
 4036                let menu = if let Some(completions) = completions {
 4037                    let mut menu = CompletionsMenu::new(
 4038                        id,
 4039                        sort_completions,
 4040                        show_completion_documentation,
 4041                        position,
 4042                        buffer.clone(),
 4043                        completions.into(),
 4044                    );
 4045
 4046                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4047                        .await;
 4048
 4049                    menu.visible().then_some(menu)
 4050                } else {
 4051                    None
 4052                };
 4053
 4054                editor.update_in(&mut cx, |editor, window, cx| {
 4055                    match editor.context_menu.borrow().as_ref() {
 4056                        None => {}
 4057                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4058                            if prev_menu.id > id {
 4059                                return;
 4060                            }
 4061                        }
 4062                        _ => return,
 4063                    }
 4064
 4065                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4066                        let mut menu = menu.unwrap();
 4067                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4068
 4069                        *editor.context_menu.borrow_mut() =
 4070                            Some(CodeContextMenu::Completions(menu));
 4071
 4072                        if editor.show_edit_predictions_in_menu() {
 4073                            editor.update_visible_inline_completion(window, cx);
 4074                        } else {
 4075                            editor.discard_inline_completion(false, cx);
 4076                        }
 4077
 4078                        cx.notify();
 4079                    } else if editor.completion_tasks.len() <= 1 {
 4080                        // If there are no more completion tasks and the last menu was
 4081                        // empty, we should hide it.
 4082                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4083                        // If it was already hidden and we don't show inline
 4084                        // completions in the menu, we should also show the
 4085                        // inline-completion when available.
 4086                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4087                            editor.update_visible_inline_completion(window, cx);
 4088                        }
 4089                    }
 4090                })?;
 4091
 4092                Ok::<_, anyhow::Error>(())
 4093            }
 4094            .log_err()
 4095        });
 4096
 4097        self.completion_tasks.push((id, task));
 4098    }
 4099
 4100    pub fn confirm_completion(
 4101        &mut self,
 4102        action: &ConfirmCompletion,
 4103        window: &mut Window,
 4104        cx: &mut Context<Self>,
 4105    ) -> Option<Task<Result<()>>> {
 4106        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4107    }
 4108
 4109    pub fn compose_completion(
 4110        &mut self,
 4111        action: &ComposeCompletion,
 4112        window: &mut Window,
 4113        cx: &mut Context<Self>,
 4114    ) -> Option<Task<Result<()>>> {
 4115        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4116    }
 4117
 4118    fn do_completion(
 4119        &mut self,
 4120        item_ix: Option<usize>,
 4121        intent: CompletionIntent,
 4122        window: &mut Window,
 4123        cx: &mut Context<Editor>,
 4124    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4125        use language::ToOffset as _;
 4126
 4127        let completions_menu =
 4128            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4129                menu
 4130            } else {
 4131                return None;
 4132            };
 4133
 4134        let entries = completions_menu.entries.borrow();
 4135        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4136        if self.show_edit_predictions_in_menu() {
 4137            self.discard_inline_completion(true, cx);
 4138        }
 4139        let candidate_id = mat.candidate_id;
 4140        drop(entries);
 4141
 4142        let buffer_handle = completions_menu.buffer;
 4143        let completion = completions_menu
 4144            .completions
 4145            .borrow()
 4146            .get(candidate_id)?
 4147            .clone();
 4148        cx.stop_propagation();
 4149
 4150        let snippet;
 4151        let text;
 4152
 4153        if completion.is_snippet() {
 4154            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4155            text = snippet.as_ref().unwrap().text.clone();
 4156        } else {
 4157            snippet = None;
 4158            text = completion.new_text.clone();
 4159        };
 4160        let selections = self.selections.all::<usize>(cx);
 4161        let buffer = buffer_handle.read(cx);
 4162        let old_range = completion.old_range.to_offset(buffer);
 4163        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4164
 4165        let newest_selection = self.selections.newest_anchor();
 4166        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4167            return None;
 4168        }
 4169
 4170        let lookbehind = newest_selection
 4171            .start
 4172            .text_anchor
 4173            .to_offset(buffer)
 4174            .saturating_sub(old_range.start);
 4175        let lookahead = old_range
 4176            .end
 4177            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4178        let mut common_prefix_len = old_text
 4179            .bytes()
 4180            .zip(text.bytes())
 4181            .take_while(|(a, b)| a == b)
 4182            .count();
 4183
 4184        let snapshot = self.buffer.read(cx).snapshot(cx);
 4185        let mut range_to_replace: Option<Range<isize>> = None;
 4186        let mut ranges = Vec::new();
 4187        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4188        for selection in &selections {
 4189            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4190                let start = selection.start.saturating_sub(lookbehind);
 4191                let end = selection.end + lookahead;
 4192                if selection.id == newest_selection.id {
 4193                    range_to_replace = Some(
 4194                        ((start + common_prefix_len) as isize - selection.start as isize)
 4195                            ..(end as isize - selection.start as isize),
 4196                    );
 4197                }
 4198                ranges.push(start + common_prefix_len..end);
 4199            } else {
 4200                common_prefix_len = 0;
 4201                ranges.clear();
 4202                ranges.extend(selections.iter().map(|s| {
 4203                    if s.id == newest_selection.id {
 4204                        range_to_replace = Some(
 4205                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4206                                - selection.start as isize
 4207                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4208                                    - selection.start as isize,
 4209                        );
 4210                        old_range.clone()
 4211                    } else {
 4212                        s.start..s.end
 4213                    }
 4214                }));
 4215                break;
 4216            }
 4217            if !self.linked_edit_ranges.is_empty() {
 4218                let start_anchor = snapshot.anchor_before(selection.head());
 4219                let end_anchor = snapshot.anchor_after(selection.tail());
 4220                if let Some(ranges) = self
 4221                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4222                {
 4223                    for (buffer, edits) in ranges {
 4224                        linked_edits.entry(buffer.clone()).or_default().extend(
 4225                            edits
 4226                                .into_iter()
 4227                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4228                        );
 4229                    }
 4230                }
 4231            }
 4232        }
 4233        let text = &text[common_prefix_len..];
 4234
 4235        cx.emit(EditorEvent::InputHandled {
 4236            utf16_range_to_replace: range_to_replace,
 4237            text: text.into(),
 4238        });
 4239
 4240        self.transact(window, cx, |this, window, cx| {
 4241            if let Some(mut snippet) = snippet {
 4242                snippet.text = text.to_string();
 4243                for tabstop in snippet
 4244                    .tabstops
 4245                    .iter_mut()
 4246                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4247                {
 4248                    tabstop.start -= common_prefix_len as isize;
 4249                    tabstop.end -= common_prefix_len as isize;
 4250                }
 4251
 4252                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4253            } else {
 4254                this.buffer.update(cx, |buffer, cx| {
 4255                    buffer.edit(
 4256                        ranges.iter().map(|range| (range.clone(), text)),
 4257                        this.autoindent_mode.clone(),
 4258                        cx,
 4259                    );
 4260                });
 4261            }
 4262            for (buffer, edits) in linked_edits {
 4263                buffer.update(cx, |buffer, cx| {
 4264                    let snapshot = buffer.snapshot();
 4265                    let edits = edits
 4266                        .into_iter()
 4267                        .map(|(range, text)| {
 4268                            use text::ToPoint as TP;
 4269                            let end_point = TP::to_point(&range.end, &snapshot);
 4270                            let start_point = TP::to_point(&range.start, &snapshot);
 4271                            (start_point..end_point, text)
 4272                        })
 4273                        .sorted_by_key(|(range, _)| range.start)
 4274                        .collect::<Vec<_>>();
 4275                    buffer.edit(edits, None, cx);
 4276                })
 4277            }
 4278
 4279            this.refresh_inline_completion(true, false, window, cx);
 4280        });
 4281
 4282        let show_new_completions_on_confirm = completion
 4283            .confirm
 4284            .as_ref()
 4285            .map_or(false, |confirm| confirm(intent, window, cx));
 4286        if show_new_completions_on_confirm {
 4287            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4288        }
 4289
 4290        let provider = self.completion_provider.as_ref()?;
 4291        drop(completion);
 4292        let apply_edits = provider.apply_additional_edits_for_completion(
 4293            buffer_handle,
 4294            completions_menu.completions.clone(),
 4295            candidate_id,
 4296            true,
 4297            cx,
 4298        );
 4299
 4300        let editor_settings = EditorSettings::get_global(cx);
 4301        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4302            // After the code completion is finished, users often want to know what signatures are needed.
 4303            // so we should automatically call signature_help
 4304            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4305        }
 4306
 4307        Some(cx.foreground_executor().spawn(async move {
 4308            apply_edits.await?;
 4309            Ok(())
 4310        }))
 4311    }
 4312
 4313    pub fn toggle_code_actions(
 4314        &mut self,
 4315        action: &ToggleCodeActions,
 4316        window: &mut Window,
 4317        cx: &mut Context<Self>,
 4318    ) {
 4319        let mut context_menu = self.context_menu.borrow_mut();
 4320        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4321            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4322                // Toggle if we're selecting the same one
 4323                *context_menu = None;
 4324                cx.notify();
 4325                return;
 4326            } else {
 4327                // Otherwise, clear it and start a new one
 4328                *context_menu = None;
 4329                cx.notify();
 4330            }
 4331        }
 4332        drop(context_menu);
 4333        let snapshot = self.snapshot(window, cx);
 4334        let deployed_from_indicator = action.deployed_from_indicator;
 4335        let mut task = self.code_actions_task.take();
 4336        let action = action.clone();
 4337        cx.spawn_in(window, |editor, mut cx| async move {
 4338            while let Some(prev_task) = task {
 4339                prev_task.await.log_err();
 4340                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4341            }
 4342
 4343            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4344                if editor.focus_handle.is_focused(window) {
 4345                    let multibuffer_point = action
 4346                        .deployed_from_indicator
 4347                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4348                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4349                    let (buffer, buffer_row) = snapshot
 4350                        .buffer_snapshot
 4351                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4352                        .and_then(|(buffer_snapshot, range)| {
 4353                            editor
 4354                                .buffer
 4355                                .read(cx)
 4356                                .buffer(buffer_snapshot.remote_id())
 4357                                .map(|buffer| (buffer, range.start.row))
 4358                        })?;
 4359                    let (_, code_actions) = editor
 4360                        .available_code_actions
 4361                        .clone()
 4362                        .and_then(|(location, code_actions)| {
 4363                            let snapshot = location.buffer.read(cx).snapshot();
 4364                            let point_range = location.range.to_point(&snapshot);
 4365                            let point_range = point_range.start.row..=point_range.end.row;
 4366                            if point_range.contains(&buffer_row) {
 4367                                Some((location, code_actions))
 4368                            } else {
 4369                                None
 4370                            }
 4371                        })
 4372                        .unzip();
 4373                    let buffer_id = buffer.read(cx).remote_id();
 4374                    let tasks = editor
 4375                        .tasks
 4376                        .get(&(buffer_id, buffer_row))
 4377                        .map(|t| Arc::new(t.to_owned()));
 4378                    if tasks.is_none() && code_actions.is_none() {
 4379                        return None;
 4380                    }
 4381
 4382                    editor.completion_tasks.clear();
 4383                    editor.discard_inline_completion(false, cx);
 4384                    let task_context =
 4385                        tasks
 4386                            .as_ref()
 4387                            .zip(editor.project.clone())
 4388                            .map(|(tasks, project)| {
 4389                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4390                            });
 4391
 4392                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4393                        let task_context = match task_context {
 4394                            Some(task_context) => task_context.await,
 4395                            None => None,
 4396                        };
 4397                        let resolved_tasks =
 4398                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4399                                Rc::new(ResolvedTasks {
 4400                                    templates: tasks.resolve(&task_context).collect(),
 4401                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4402                                        multibuffer_point.row,
 4403                                        tasks.column,
 4404                                    )),
 4405                                })
 4406                            });
 4407                        let spawn_straight_away = resolved_tasks
 4408                            .as_ref()
 4409                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4410                            && code_actions
 4411                                .as_ref()
 4412                                .map_or(true, |actions| actions.is_empty());
 4413                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4414                            *editor.context_menu.borrow_mut() =
 4415                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4416                                    buffer,
 4417                                    actions: CodeActionContents {
 4418                                        tasks: resolved_tasks,
 4419                                        actions: code_actions,
 4420                                    },
 4421                                    selected_item: Default::default(),
 4422                                    scroll_handle: UniformListScrollHandle::default(),
 4423                                    deployed_from_indicator,
 4424                                }));
 4425                            if spawn_straight_away {
 4426                                if let Some(task) = editor.confirm_code_action(
 4427                                    &ConfirmCodeAction { item_ix: Some(0) },
 4428                                    window,
 4429                                    cx,
 4430                                ) {
 4431                                    cx.notify();
 4432                                    return task;
 4433                                }
 4434                            }
 4435                            cx.notify();
 4436                            Task::ready(Ok(()))
 4437                        }) {
 4438                            task.await
 4439                        } else {
 4440                            Ok(())
 4441                        }
 4442                    }))
 4443                } else {
 4444                    Some(Task::ready(Ok(())))
 4445                }
 4446            })?;
 4447            if let Some(task) = spawned_test_task {
 4448                task.await?;
 4449            }
 4450
 4451            Ok::<_, anyhow::Error>(())
 4452        })
 4453        .detach_and_log_err(cx);
 4454    }
 4455
 4456    pub fn confirm_code_action(
 4457        &mut self,
 4458        action: &ConfirmCodeAction,
 4459        window: &mut Window,
 4460        cx: &mut Context<Self>,
 4461    ) -> Option<Task<Result<()>>> {
 4462        let actions_menu =
 4463            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4464                menu
 4465            } else {
 4466                return None;
 4467            };
 4468        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4469        let action = actions_menu.actions.get(action_ix)?;
 4470        let title = action.label();
 4471        let buffer = actions_menu.buffer;
 4472        let workspace = self.workspace()?;
 4473
 4474        match action {
 4475            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4476                workspace.update(cx, |workspace, cx| {
 4477                    workspace::tasks::schedule_resolved_task(
 4478                        workspace,
 4479                        task_source_kind,
 4480                        resolved_task,
 4481                        false,
 4482                        cx,
 4483                    );
 4484
 4485                    Some(Task::ready(Ok(())))
 4486                })
 4487            }
 4488            CodeActionsItem::CodeAction {
 4489                excerpt_id,
 4490                action,
 4491                provider,
 4492            } => {
 4493                let apply_code_action =
 4494                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4495                let workspace = workspace.downgrade();
 4496                Some(cx.spawn_in(window, |editor, cx| async move {
 4497                    let project_transaction = apply_code_action.await?;
 4498                    Self::open_project_transaction(
 4499                        &editor,
 4500                        workspace,
 4501                        project_transaction,
 4502                        title,
 4503                        cx,
 4504                    )
 4505                    .await
 4506                }))
 4507            }
 4508        }
 4509    }
 4510
 4511    pub async fn open_project_transaction(
 4512        this: &WeakEntity<Editor>,
 4513        workspace: WeakEntity<Workspace>,
 4514        transaction: ProjectTransaction,
 4515        title: String,
 4516        mut cx: AsyncWindowContext,
 4517    ) -> Result<()> {
 4518        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4519        cx.update(|_, cx| {
 4520            entries.sort_unstable_by_key(|(buffer, _)| {
 4521                buffer.read(cx).file().map(|f| f.path().clone())
 4522            });
 4523        })?;
 4524
 4525        // If the project transaction's edits are all contained within this editor, then
 4526        // avoid opening a new editor to display them.
 4527
 4528        if let Some((buffer, transaction)) = entries.first() {
 4529            if entries.len() == 1 {
 4530                let excerpt = this.update(&mut cx, |editor, cx| {
 4531                    editor
 4532                        .buffer()
 4533                        .read(cx)
 4534                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4535                })?;
 4536                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4537                    if excerpted_buffer == *buffer {
 4538                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4539                            let excerpt_range = excerpt_range.to_offset(buffer);
 4540                            buffer
 4541                                .edited_ranges_for_transaction::<usize>(transaction)
 4542                                .all(|range| {
 4543                                    excerpt_range.start <= range.start
 4544                                        && excerpt_range.end >= range.end
 4545                                })
 4546                        })?;
 4547
 4548                        if all_edits_within_excerpt {
 4549                            return Ok(());
 4550                        }
 4551                    }
 4552                }
 4553            }
 4554        } else {
 4555            return Ok(());
 4556        }
 4557
 4558        let mut ranges_to_highlight = Vec::new();
 4559        let excerpt_buffer = cx.new(|cx| {
 4560            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4561            for (buffer_handle, transaction) in &entries {
 4562                let buffer = buffer_handle.read(cx);
 4563                ranges_to_highlight.extend(
 4564                    multibuffer.push_excerpts_with_context_lines(
 4565                        buffer_handle.clone(),
 4566                        buffer
 4567                            .edited_ranges_for_transaction::<usize>(transaction)
 4568                            .collect(),
 4569                        DEFAULT_MULTIBUFFER_CONTEXT,
 4570                        cx,
 4571                    ),
 4572                );
 4573            }
 4574            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4575            multibuffer
 4576        })?;
 4577
 4578        workspace.update_in(&mut cx, |workspace, window, cx| {
 4579            let project = workspace.project().clone();
 4580            let editor = cx
 4581                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4582            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4583            editor.update(cx, |editor, cx| {
 4584                editor.highlight_background::<Self>(
 4585                    &ranges_to_highlight,
 4586                    |theme| theme.editor_highlighted_line_background,
 4587                    cx,
 4588                );
 4589            });
 4590        })?;
 4591
 4592        Ok(())
 4593    }
 4594
 4595    pub fn clear_code_action_providers(&mut self) {
 4596        self.code_action_providers.clear();
 4597        self.available_code_actions.take();
 4598    }
 4599
 4600    pub fn add_code_action_provider(
 4601        &mut self,
 4602        provider: Rc<dyn CodeActionProvider>,
 4603        window: &mut Window,
 4604        cx: &mut Context<Self>,
 4605    ) {
 4606        if self
 4607            .code_action_providers
 4608            .iter()
 4609            .any(|existing_provider| existing_provider.id() == provider.id())
 4610        {
 4611            return;
 4612        }
 4613
 4614        self.code_action_providers.push(provider);
 4615        self.refresh_code_actions(window, cx);
 4616    }
 4617
 4618    pub fn remove_code_action_provider(
 4619        &mut self,
 4620        id: Arc<str>,
 4621        window: &mut Window,
 4622        cx: &mut Context<Self>,
 4623    ) {
 4624        self.code_action_providers
 4625            .retain(|provider| provider.id() != id);
 4626        self.refresh_code_actions(window, cx);
 4627    }
 4628
 4629    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4630        let buffer = self.buffer.read(cx);
 4631        let newest_selection = self.selections.newest_anchor().clone();
 4632        if newest_selection.head().diff_base_anchor.is_some() {
 4633            return None;
 4634        }
 4635        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4636        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4637        if start_buffer != end_buffer {
 4638            return None;
 4639        }
 4640
 4641        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4642            cx.background_executor()
 4643                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4644                .await;
 4645
 4646            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4647                let providers = this.code_action_providers.clone();
 4648                let tasks = this
 4649                    .code_action_providers
 4650                    .iter()
 4651                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4652                    .collect::<Vec<_>>();
 4653                (providers, tasks)
 4654            })?;
 4655
 4656            let mut actions = Vec::new();
 4657            for (provider, provider_actions) in
 4658                providers.into_iter().zip(future::join_all(tasks).await)
 4659            {
 4660                if let Some(provider_actions) = provider_actions.log_err() {
 4661                    actions.extend(provider_actions.into_iter().map(|action| {
 4662                        AvailableCodeAction {
 4663                            excerpt_id: newest_selection.start.excerpt_id,
 4664                            action,
 4665                            provider: provider.clone(),
 4666                        }
 4667                    }));
 4668                }
 4669            }
 4670
 4671            this.update(&mut cx, |this, cx| {
 4672                this.available_code_actions = if actions.is_empty() {
 4673                    None
 4674                } else {
 4675                    Some((
 4676                        Location {
 4677                            buffer: start_buffer,
 4678                            range: start..end,
 4679                        },
 4680                        actions.into(),
 4681                    ))
 4682                };
 4683                cx.notify();
 4684            })
 4685        }));
 4686        None
 4687    }
 4688
 4689    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4690        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4691            self.show_git_blame_inline = false;
 4692
 4693            self.show_git_blame_inline_delay_task =
 4694                Some(cx.spawn_in(window, |this, mut cx| async move {
 4695                    cx.background_executor().timer(delay).await;
 4696
 4697                    this.update(&mut cx, |this, cx| {
 4698                        this.show_git_blame_inline = true;
 4699                        cx.notify();
 4700                    })
 4701                    .log_err();
 4702                }));
 4703        }
 4704    }
 4705
 4706    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4707        if self.pending_rename.is_some() {
 4708            return None;
 4709        }
 4710
 4711        let provider = self.semantics_provider.clone()?;
 4712        let buffer = self.buffer.read(cx);
 4713        let newest_selection = self.selections.newest_anchor().clone();
 4714        let cursor_position = newest_selection.head();
 4715        let (cursor_buffer, cursor_buffer_position) =
 4716            buffer.text_anchor_for_position(cursor_position, cx)?;
 4717        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4718        if cursor_buffer != tail_buffer {
 4719            return None;
 4720        }
 4721        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4722        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4723            cx.background_executor()
 4724                .timer(Duration::from_millis(debounce))
 4725                .await;
 4726
 4727            let highlights = if let Some(highlights) = cx
 4728                .update(|cx| {
 4729                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4730                })
 4731                .ok()
 4732                .flatten()
 4733            {
 4734                highlights.await.log_err()
 4735            } else {
 4736                None
 4737            };
 4738
 4739            if let Some(highlights) = highlights {
 4740                this.update(&mut cx, |this, cx| {
 4741                    if this.pending_rename.is_some() {
 4742                        return;
 4743                    }
 4744
 4745                    let buffer_id = cursor_position.buffer_id;
 4746                    let buffer = this.buffer.read(cx);
 4747                    if !buffer
 4748                        .text_anchor_for_position(cursor_position, cx)
 4749                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4750                    {
 4751                        return;
 4752                    }
 4753
 4754                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4755                    let mut write_ranges = Vec::new();
 4756                    let mut read_ranges = Vec::new();
 4757                    for highlight in highlights {
 4758                        for (excerpt_id, excerpt_range) in
 4759                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4760                        {
 4761                            let start = highlight
 4762                                .range
 4763                                .start
 4764                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4765                            let end = highlight
 4766                                .range
 4767                                .end
 4768                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4769                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4770                                continue;
 4771                            }
 4772
 4773                            let range = Anchor {
 4774                                buffer_id,
 4775                                excerpt_id,
 4776                                text_anchor: start,
 4777                                diff_base_anchor: None,
 4778                            }..Anchor {
 4779                                buffer_id,
 4780                                excerpt_id,
 4781                                text_anchor: end,
 4782                                diff_base_anchor: None,
 4783                            };
 4784                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4785                                write_ranges.push(range);
 4786                            } else {
 4787                                read_ranges.push(range);
 4788                            }
 4789                        }
 4790                    }
 4791
 4792                    this.highlight_background::<DocumentHighlightRead>(
 4793                        &read_ranges,
 4794                        |theme| theme.editor_document_highlight_read_background,
 4795                        cx,
 4796                    );
 4797                    this.highlight_background::<DocumentHighlightWrite>(
 4798                        &write_ranges,
 4799                        |theme| theme.editor_document_highlight_write_background,
 4800                        cx,
 4801                    );
 4802                    cx.notify();
 4803                })
 4804                .log_err();
 4805            }
 4806        }));
 4807        None
 4808    }
 4809
 4810    pub fn refresh_selected_text_highlights(
 4811        &mut self,
 4812        window: &mut Window,
 4813        cx: &mut Context<Editor>,
 4814    ) {
 4815        self.selection_highlight_task.take();
 4816        if !EditorSettings::get_global(cx).selection_highlight {
 4817            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4818            return;
 4819        }
 4820        if self.selections.count() != 1 || self.selections.line_mode {
 4821            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4822            return;
 4823        }
 4824        let selection = self.selections.newest::<Point>(cx);
 4825        if selection.is_empty() || selection.start.row != selection.end.row {
 4826            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4827            return;
 4828        }
 4829        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4830        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4831            cx.background_executor()
 4832                .timer(Duration::from_millis(debounce))
 4833                .await;
 4834            let Some(Some(matches_task)) = editor
 4835                .update_in(&mut cx, |editor, _, cx| {
 4836                    if editor.selections.count() != 1 || editor.selections.line_mode {
 4837                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4838                        return None;
 4839                    }
 4840                    let selection = editor.selections.newest::<Point>(cx);
 4841                    if selection.is_empty() || selection.start.row != selection.end.row {
 4842                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4843                        return None;
 4844                    }
 4845                    let buffer = editor.buffer().read(cx).snapshot(cx);
 4846                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 4847                    if query.trim().is_empty() {
 4848                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4849                        return None;
 4850                    }
 4851                    Some(cx.background_spawn(async move {
 4852                        let mut ranges = Vec::new();
 4853                        let selection_anchors = selection.range().to_anchors(&buffer);
 4854                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 4855                            for (search_buffer, search_range, excerpt_id) in
 4856                                buffer.range_to_buffer_ranges(range)
 4857                            {
 4858                                ranges.extend(
 4859                                    project::search::SearchQuery::text(
 4860                                        query.clone(),
 4861                                        false,
 4862                                        false,
 4863                                        false,
 4864                                        Default::default(),
 4865                                        Default::default(),
 4866                                        None,
 4867                                    )
 4868                                    .unwrap()
 4869                                    .search(search_buffer, Some(search_range.clone()))
 4870                                    .await
 4871                                    .into_iter()
 4872                                    .filter_map(
 4873                                        |match_range| {
 4874                                            let start = search_buffer.anchor_after(
 4875                                                search_range.start + match_range.start,
 4876                                            );
 4877                                            let end = search_buffer.anchor_before(
 4878                                                search_range.start + match_range.end,
 4879                                            );
 4880                                            let range = Anchor::range_in_buffer(
 4881                                                excerpt_id,
 4882                                                search_buffer.remote_id(),
 4883                                                start..end,
 4884                                            );
 4885                                            (range != selection_anchors).then_some(range)
 4886                                        },
 4887                                    ),
 4888                                );
 4889                            }
 4890                        }
 4891                        ranges
 4892                    }))
 4893                })
 4894                .log_err()
 4895            else {
 4896                return;
 4897            };
 4898            let matches = matches_task.await;
 4899            editor
 4900                .update_in(&mut cx, |editor, _, cx| {
 4901                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4902                    if !matches.is_empty() {
 4903                        editor.highlight_background::<SelectedTextHighlight>(
 4904                            &matches,
 4905                            |theme| theme.editor_document_highlight_bracket_background,
 4906                            cx,
 4907                        )
 4908                    }
 4909                })
 4910                .log_err();
 4911        }));
 4912    }
 4913
 4914    pub fn refresh_inline_completion(
 4915        &mut self,
 4916        debounce: bool,
 4917        user_requested: bool,
 4918        window: &mut Window,
 4919        cx: &mut Context<Self>,
 4920    ) -> Option<()> {
 4921        let provider = self.edit_prediction_provider()?;
 4922        let cursor = self.selections.newest_anchor().head();
 4923        let (buffer, cursor_buffer_position) =
 4924            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4925
 4926        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4927            self.discard_inline_completion(false, cx);
 4928            return None;
 4929        }
 4930
 4931        if !user_requested
 4932            && (!self.should_show_edit_predictions()
 4933                || !self.is_focused(window)
 4934                || buffer.read(cx).is_empty())
 4935        {
 4936            self.discard_inline_completion(false, cx);
 4937            return None;
 4938        }
 4939
 4940        self.update_visible_inline_completion(window, cx);
 4941        provider.refresh(
 4942            self.project.clone(),
 4943            buffer,
 4944            cursor_buffer_position,
 4945            debounce,
 4946            cx,
 4947        );
 4948        Some(())
 4949    }
 4950
 4951    fn show_edit_predictions_in_menu(&self) -> bool {
 4952        match self.edit_prediction_settings {
 4953            EditPredictionSettings::Disabled => false,
 4954            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4955        }
 4956    }
 4957
 4958    pub fn edit_predictions_enabled(&self) -> bool {
 4959        match self.edit_prediction_settings {
 4960            EditPredictionSettings::Disabled => false,
 4961            EditPredictionSettings::Enabled { .. } => true,
 4962        }
 4963    }
 4964
 4965    fn edit_prediction_requires_modifier(&self) -> bool {
 4966        match self.edit_prediction_settings {
 4967            EditPredictionSettings::Disabled => false,
 4968            EditPredictionSettings::Enabled {
 4969                preview_requires_modifier,
 4970                ..
 4971            } => preview_requires_modifier,
 4972        }
 4973    }
 4974
 4975    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 4976        if self.edit_prediction_provider.is_none() {
 4977            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 4978        } else {
 4979            let selection = self.selections.newest_anchor();
 4980            let cursor = selection.head();
 4981
 4982            if let Some((buffer, cursor_buffer_position)) =
 4983                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4984            {
 4985                self.edit_prediction_settings =
 4986                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 4987            }
 4988        }
 4989    }
 4990
 4991    fn edit_prediction_settings_at_position(
 4992        &self,
 4993        buffer: &Entity<Buffer>,
 4994        buffer_position: language::Anchor,
 4995        cx: &App,
 4996    ) -> EditPredictionSettings {
 4997        if self.mode != EditorMode::Full
 4998            || !self.show_inline_completions_override.unwrap_or(true)
 4999            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5000        {
 5001            return EditPredictionSettings::Disabled;
 5002        }
 5003
 5004        let buffer = buffer.read(cx);
 5005
 5006        let file = buffer.file();
 5007
 5008        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5009            return EditPredictionSettings::Disabled;
 5010        };
 5011
 5012        let by_provider = matches!(
 5013            self.menu_inline_completions_policy,
 5014            MenuInlineCompletionsPolicy::ByProvider
 5015        );
 5016
 5017        let show_in_menu = by_provider
 5018            && self
 5019                .edit_prediction_provider
 5020                .as_ref()
 5021                .map_or(false, |provider| {
 5022                    provider.provider.show_completions_in_menu()
 5023                });
 5024
 5025        let preview_requires_modifier =
 5026            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5027
 5028        EditPredictionSettings::Enabled {
 5029            show_in_menu,
 5030            preview_requires_modifier,
 5031        }
 5032    }
 5033
 5034    fn should_show_edit_predictions(&self) -> bool {
 5035        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5036    }
 5037
 5038    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5039        matches!(
 5040            self.edit_prediction_preview,
 5041            EditPredictionPreview::Active { .. }
 5042        )
 5043    }
 5044
 5045    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5046        let cursor = self.selections.newest_anchor().head();
 5047        if let Some((buffer, cursor_position)) =
 5048            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5049        {
 5050            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5051        } else {
 5052            false
 5053        }
 5054    }
 5055
 5056    fn edit_predictions_enabled_in_buffer(
 5057        &self,
 5058        buffer: &Entity<Buffer>,
 5059        buffer_position: language::Anchor,
 5060        cx: &App,
 5061    ) -> bool {
 5062        maybe!({
 5063            let provider = self.edit_prediction_provider()?;
 5064            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5065                return Some(false);
 5066            }
 5067            let buffer = buffer.read(cx);
 5068            let Some(file) = buffer.file() else {
 5069                return Some(true);
 5070            };
 5071            let settings = all_language_settings(Some(file), cx);
 5072            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5073        })
 5074        .unwrap_or(false)
 5075    }
 5076
 5077    fn cycle_inline_completion(
 5078        &mut self,
 5079        direction: Direction,
 5080        window: &mut Window,
 5081        cx: &mut Context<Self>,
 5082    ) -> Option<()> {
 5083        let provider = self.edit_prediction_provider()?;
 5084        let cursor = self.selections.newest_anchor().head();
 5085        let (buffer, cursor_buffer_position) =
 5086            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5087        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5088            return None;
 5089        }
 5090
 5091        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5092        self.update_visible_inline_completion(window, cx);
 5093
 5094        Some(())
 5095    }
 5096
 5097    pub fn show_inline_completion(
 5098        &mut self,
 5099        _: &ShowEditPrediction,
 5100        window: &mut Window,
 5101        cx: &mut Context<Self>,
 5102    ) {
 5103        if !self.has_active_inline_completion() {
 5104            self.refresh_inline_completion(false, true, window, cx);
 5105            return;
 5106        }
 5107
 5108        self.update_visible_inline_completion(window, cx);
 5109    }
 5110
 5111    pub fn display_cursor_names(
 5112        &mut self,
 5113        _: &DisplayCursorNames,
 5114        window: &mut Window,
 5115        cx: &mut Context<Self>,
 5116    ) {
 5117        self.show_cursor_names(window, cx);
 5118    }
 5119
 5120    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5121        self.show_cursor_names = true;
 5122        cx.notify();
 5123        cx.spawn_in(window, |this, mut cx| async move {
 5124            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5125            this.update(&mut cx, |this, cx| {
 5126                this.show_cursor_names = false;
 5127                cx.notify()
 5128            })
 5129            .ok()
 5130        })
 5131        .detach();
 5132    }
 5133
 5134    pub fn next_edit_prediction(
 5135        &mut self,
 5136        _: &NextEditPrediction,
 5137        window: &mut Window,
 5138        cx: &mut Context<Self>,
 5139    ) {
 5140        if self.has_active_inline_completion() {
 5141            self.cycle_inline_completion(Direction::Next, window, cx);
 5142        } else {
 5143            let is_copilot_disabled = self
 5144                .refresh_inline_completion(false, true, window, cx)
 5145                .is_none();
 5146            if is_copilot_disabled {
 5147                cx.propagate();
 5148            }
 5149        }
 5150    }
 5151
 5152    pub fn previous_edit_prediction(
 5153        &mut self,
 5154        _: &PreviousEditPrediction,
 5155        window: &mut Window,
 5156        cx: &mut Context<Self>,
 5157    ) {
 5158        if self.has_active_inline_completion() {
 5159            self.cycle_inline_completion(Direction::Prev, window, cx);
 5160        } else {
 5161            let is_copilot_disabled = self
 5162                .refresh_inline_completion(false, true, window, cx)
 5163                .is_none();
 5164            if is_copilot_disabled {
 5165                cx.propagate();
 5166            }
 5167        }
 5168    }
 5169
 5170    pub fn accept_edit_prediction(
 5171        &mut self,
 5172        _: &AcceptEditPrediction,
 5173        window: &mut Window,
 5174        cx: &mut Context<Self>,
 5175    ) {
 5176        if self.show_edit_predictions_in_menu() {
 5177            self.hide_context_menu(window, cx);
 5178        }
 5179
 5180        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5181            return;
 5182        };
 5183
 5184        self.report_inline_completion_event(
 5185            active_inline_completion.completion_id.clone(),
 5186            true,
 5187            cx,
 5188        );
 5189
 5190        match &active_inline_completion.completion {
 5191            InlineCompletion::Move { target, .. } => {
 5192                let target = *target;
 5193
 5194                if let Some(position_map) = &self.last_position_map {
 5195                    if position_map
 5196                        .visible_row_range
 5197                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5198                        || !self.edit_prediction_requires_modifier()
 5199                    {
 5200                        self.unfold_ranges(&[target..target], true, false, cx);
 5201                        // Note that this is also done in vim's handler of the Tab action.
 5202                        self.change_selections(
 5203                            Some(Autoscroll::newest()),
 5204                            window,
 5205                            cx,
 5206                            |selections| {
 5207                                selections.select_anchor_ranges([target..target]);
 5208                            },
 5209                        );
 5210                        self.clear_row_highlights::<EditPredictionPreview>();
 5211
 5212                        self.edit_prediction_preview
 5213                            .set_previous_scroll_position(None);
 5214                    } else {
 5215                        self.edit_prediction_preview
 5216                            .set_previous_scroll_position(Some(
 5217                                position_map.snapshot.scroll_anchor,
 5218                            ));
 5219
 5220                        self.highlight_rows::<EditPredictionPreview>(
 5221                            target..target,
 5222                            cx.theme().colors().editor_highlighted_line_background,
 5223                            true,
 5224                            cx,
 5225                        );
 5226                        self.request_autoscroll(Autoscroll::fit(), cx);
 5227                    }
 5228                }
 5229            }
 5230            InlineCompletion::Edit { edits, .. } => {
 5231                if let Some(provider) = self.edit_prediction_provider() {
 5232                    provider.accept(cx);
 5233                }
 5234
 5235                let snapshot = self.buffer.read(cx).snapshot(cx);
 5236                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5237
 5238                self.buffer.update(cx, |buffer, cx| {
 5239                    buffer.edit(edits.iter().cloned(), None, cx)
 5240                });
 5241
 5242                self.change_selections(None, window, cx, |s| {
 5243                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5244                });
 5245
 5246                self.update_visible_inline_completion(window, cx);
 5247                if self.active_inline_completion.is_none() {
 5248                    self.refresh_inline_completion(true, true, window, cx);
 5249                }
 5250
 5251                cx.notify();
 5252            }
 5253        }
 5254
 5255        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5256    }
 5257
 5258    pub fn accept_partial_inline_completion(
 5259        &mut self,
 5260        _: &AcceptPartialEditPrediction,
 5261        window: &mut Window,
 5262        cx: &mut Context<Self>,
 5263    ) {
 5264        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5265            return;
 5266        };
 5267        if self.selections.count() != 1 {
 5268            return;
 5269        }
 5270
 5271        self.report_inline_completion_event(
 5272            active_inline_completion.completion_id.clone(),
 5273            true,
 5274            cx,
 5275        );
 5276
 5277        match &active_inline_completion.completion {
 5278            InlineCompletion::Move { target, .. } => {
 5279                let target = *target;
 5280                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5281                    selections.select_anchor_ranges([target..target]);
 5282                });
 5283            }
 5284            InlineCompletion::Edit { edits, .. } => {
 5285                // Find an insertion that starts at the cursor position.
 5286                let snapshot = self.buffer.read(cx).snapshot(cx);
 5287                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5288                let insertion = edits.iter().find_map(|(range, text)| {
 5289                    let range = range.to_offset(&snapshot);
 5290                    if range.is_empty() && range.start == cursor_offset {
 5291                        Some(text)
 5292                    } else {
 5293                        None
 5294                    }
 5295                });
 5296
 5297                if let Some(text) = insertion {
 5298                    let mut partial_completion = text
 5299                        .chars()
 5300                        .by_ref()
 5301                        .take_while(|c| c.is_alphabetic())
 5302                        .collect::<String>();
 5303                    if partial_completion.is_empty() {
 5304                        partial_completion = text
 5305                            .chars()
 5306                            .by_ref()
 5307                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5308                            .collect::<String>();
 5309                    }
 5310
 5311                    cx.emit(EditorEvent::InputHandled {
 5312                        utf16_range_to_replace: None,
 5313                        text: partial_completion.clone().into(),
 5314                    });
 5315
 5316                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5317
 5318                    self.refresh_inline_completion(true, true, window, cx);
 5319                    cx.notify();
 5320                } else {
 5321                    self.accept_edit_prediction(&Default::default(), window, cx);
 5322                }
 5323            }
 5324        }
 5325    }
 5326
 5327    fn discard_inline_completion(
 5328        &mut self,
 5329        should_report_inline_completion_event: bool,
 5330        cx: &mut Context<Self>,
 5331    ) -> bool {
 5332        if should_report_inline_completion_event {
 5333            let completion_id = self
 5334                .active_inline_completion
 5335                .as_ref()
 5336                .and_then(|active_completion| active_completion.completion_id.clone());
 5337
 5338            self.report_inline_completion_event(completion_id, false, cx);
 5339        }
 5340
 5341        if let Some(provider) = self.edit_prediction_provider() {
 5342            provider.discard(cx);
 5343        }
 5344
 5345        self.take_active_inline_completion(cx)
 5346    }
 5347
 5348    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5349        let Some(provider) = self.edit_prediction_provider() else {
 5350            return;
 5351        };
 5352
 5353        let Some((_, buffer, _)) = self
 5354            .buffer
 5355            .read(cx)
 5356            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5357        else {
 5358            return;
 5359        };
 5360
 5361        let extension = buffer
 5362            .read(cx)
 5363            .file()
 5364            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5365
 5366        let event_type = match accepted {
 5367            true => "Edit Prediction Accepted",
 5368            false => "Edit Prediction Discarded",
 5369        };
 5370        telemetry::event!(
 5371            event_type,
 5372            provider = provider.name(),
 5373            prediction_id = id,
 5374            suggestion_accepted = accepted,
 5375            file_extension = extension,
 5376        );
 5377    }
 5378
 5379    pub fn has_active_inline_completion(&self) -> bool {
 5380        self.active_inline_completion.is_some()
 5381    }
 5382
 5383    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5384        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5385            return false;
 5386        };
 5387
 5388        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5389        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5390        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5391        true
 5392    }
 5393
 5394    /// Returns true when we're displaying the edit prediction popover below the cursor
 5395    /// like we are not previewing and the LSP autocomplete menu is visible
 5396    /// or we are in `when_holding_modifier` mode.
 5397    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5398        if self.edit_prediction_preview_is_active()
 5399            || !self.show_edit_predictions_in_menu()
 5400            || !self.edit_predictions_enabled()
 5401        {
 5402            return false;
 5403        }
 5404
 5405        if self.has_visible_completions_menu() {
 5406            return true;
 5407        }
 5408
 5409        has_completion && self.edit_prediction_requires_modifier()
 5410    }
 5411
 5412    fn handle_modifiers_changed(
 5413        &mut self,
 5414        modifiers: Modifiers,
 5415        position_map: &PositionMap,
 5416        window: &mut Window,
 5417        cx: &mut Context<Self>,
 5418    ) {
 5419        if self.show_edit_predictions_in_menu() {
 5420            self.update_edit_prediction_preview(&modifiers, window, cx);
 5421        }
 5422
 5423        self.update_selection_mode(&modifiers, position_map, window, cx);
 5424
 5425        let mouse_position = window.mouse_position();
 5426        if !position_map.text_hitbox.is_hovered(window) {
 5427            return;
 5428        }
 5429
 5430        self.update_hovered_link(
 5431            position_map.point_for_position(mouse_position),
 5432            &position_map.snapshot,
 5433            modifiers,
 5434            window,
 5435            cx,
 5436        )
 5437    }
 5438
 5439    fn update_selection_mode(
 5440        &mut self,
 5441        modifiers: &Modifiers,
 5442        position_map: &PositionMap,
 5443        window: &mut Window,
 5444        cx: &mut Context<Self>,
 5445    ) {
 5446        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5447            return;
 5448        }
 5449
 5450        let mouse_position = window.mouse_position();
 5451        let point_for_position = position_map.point_for_position(mouse_position);
 5452        let position = point_for_position.previous_valid;
 5453
 5454        self.select(
 5455            SelectPhase::BeginColumnar {
 5456                position,
 5457                reset: false,
 5458                goal_column: point_for_position.exact_unclipped.column(),
 5459            },
 5460            window,
 5461            cx,
 5462        );
 5463    }
 5464
 5465    fn update_edit_prediction_preview(
 5466        &mut self,
 5467        modifiers: &Modifiers,
 5468        window: &mut Window,
 5469        cx: &mut Context<Self>,
 5470    ) {
 5471        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5472        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5473            return;
 5474        };
 5475
 5476        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5477            if matches!(
 5478                self.edit_prediction_preview,
 5479                EditPredictionPreview::Inactive { .. }
 5480            ) {
 5481                self.edit_prediction_preview = EditPredictionPreview::Active {
 5482                    previous_scroll_position: None,
 5483                    since: Instant::now(),
 5484                };
 5485
 5486                self.update_visible_inline_completion(window, cx);
 5487                cx.notify();
 5488            }
 5489        } else if let EditPredictionPreview::Active {
 5490            previous_scroll_position,
 5491            since,
 5492        } = self.edit_prediction_preview
 5493        {
 5494            if let (Some(previous_scroll_position), Some(position_map)) =
 5495                (previous_scroll_position, self.last_position_map.as_ref())
 5496            {
 5497                self.set_scroll_position(
 5498                    previous_scroll_position
 5499                        .scroll_position(&position_map.snapshot.display_snapshot),
 5500                    window,
 5501                    cx,
 5502                );
 5503            }
 5504
 5505            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 5506                released_too_fast: since.elapsed() < Duration::from_millis(200),
 5507            };
 5508            self.clear_row_highlights::<EditPredictionPreview>();
 5509            self.update_visible_inline_completion(window, cx);
 5510            cx.notify();
 5511        }
 5512    }
 5513
 5514    fn update_visible_inline_completion(
 5515        &mut self,
 5516        _window: &mut Window,
 5517        cx: &mut Context<Self>,
 5518    ) -> Option<()> {
 5519        let selection = self.selections.newest_anchor();
 5520        let cursor = selection.head();
 5521        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5522        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5523        let excerpt_id = cursor.excerpt_id;
 5524
 5525        let show_in_menu = self.show_edit_predictions_in_menu();
 5526        let completions_menu_has_precedence = !show_in_menu
 5527            && (self.context_menu.borrow().is_some()
 5528                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5529
 5530        if completions_menu_has_precedence
 5531            || !offset_selection.is_empty()
 5532            || self
 5533                .active_inline_completion
 5534                .as_ref()
 5535                .map_or(false, |completion| {
 5536                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5537                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5538                    !invalidation_range.contains(&offset_selection.head())
 5539                })
 5540        {
 5541            self.discard_inline_completion(false, cx);
 5542            return None;
 5543        }
 5544
 5545        self.take_active_inline_completion(cx);
 5546        let Some(provider) = self.edit_prediction_provider() else {
 5547            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5548            return None;
 5549        };
 5550
 5551        let (buffer, cursor_buffer_position) =
 5552            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5553
 5554        self.edit_prediction_settings =
 5555            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5556
 5557        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 5558
 5559        if self.edit_prediction_indent_conflict {
 5560            let cursor_point = cursor.to_point(&multibuffer);
 5561
 5562            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 5563
 5564            if let Some((_, indent)) = indents.iter().next() {
 5565                if indent.len == cursor_point.column {
 5566                    self.edit_prediction_indent_conflict = false;
 5567                }
 5568            }
 5569        }
 5570
 5571        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5572        let edits = inline_completion
 5573            .edits
 5574            .into_iter()
 5575            .flat_map(|(range, new_text)| {
 5576                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5577                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5578                Some((start..end, new_text))
 5579            })
 5580            .collect::<Vec<_>>();
 5581        if edits.is_empty() {
 5582            return None;
 5583        }
 5584
 5585        let first_edit_start = edits.first().unwrap().0.start;
 5586        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5587        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5588
 5589        let last_edit_end = edits.last().unwrap().0.end;
 5590        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5591        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5592
 5593        let cursor_row = cursor.to_point(&multibuffer).row;
 5594
 5595        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5596
 5597        let mut inlay_ids = Vec::new();
 5598        let invalidation_row_range;
 5599        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5600            Some(cursor_row..edit_end_row)
 5601        } else if cursor_row > edit_end_row {
 5602            Some(edit_start_row..cursor_row)
 5603        } else {
 5604            None
 5605        };
 5606        let is_move =
 5607            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5608        let completion = if is_move {
 5609            invalidation_row_range =
 5610                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5611            let target = first_edit_start;
 5612            InlineCompletion::Move { target, snapshot }
 5613        } else {
 5614            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5615                && !self.inline_completions_hidden_for_vim_mode;
 5616
 5617            if show_completions_in_buffer {
 5618                if edits
 5619                    .iter()
 5620                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5621                {
 5622                    let mut inlays = Vec::new();
 5623                    for (range, new_text) in &edits {
 5624                        let inlay = Inlay::inline_completion(
 5625                            post_inc(&mut self.next_inlay_id),
 5626                            range.start,
 5627                            new_text.as_str(),
 5628                        );
 5629                        inlay_ids.push(inlay.id);
 5630                        inlays.push(inlay);
 5631                    }
 5632
 5633                    self.splice_inlays(&[], inlays, cx);
 5634                } else {
 5635                    let background_color = cx.theme().status().deleted_background;
 5636                    self.highlight_text::<InlineCompletionHighlight>(
 5637                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5638                        HighlightStyle {
 5639                            background_color: Some(background_color),
 5640                            ..Default::default()
 5641                        },
 5642                        cx,
 5643                    );
 5644                }
 5645            }
 5646
 5647            invalidation_row_range = edit_start_row..edit_end_row;
 5648
 5649            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5650                if provider.show_tab_accept_marker() {
 5651                    EditDisplayMode::TabAccept
 5652                } else {
 5653                    EditDisplayMode::Inline
 5654                }
 5655            } else {
 5656                EditDisplayMode::DiffPopover
 5657            };
 5658
 5659            InlineCompletion::Edit {
 5660                edits,
 5661                edit_preview: inline_completion.edit_preview,
 5662                display_mode,
 5663                snapshot,
 5664            }
 5665        };
 5666
 5667        let invalidation_range = multibuffer
 5668            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5669            ..multibuffer.anchor_after(Point::new(
 5670                invalidation_row_range.end,
 5671                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5672            ));
 5673
 5674        self.stale_inline_completion_in_menu = None;
 5675        self.active_inline_completion = Some(InlineCompletionState {
 5676            inlay_ids,
 5677            completion,
 5678            completion_id: inline_completion.id,
 5679            invalidation_range,
 5680        });
 5681
 5682        cx.notify();
 5683
 5684        Some(())
 5685    }
 5686
 5687    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5688        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5689    }
 5690
 5691    fn render_code_actions_indicator(
 5692        &self,
 5693        _style: &EditorStyle,
 5694        row: DisplayRow,
 5695        is_active: bool,
 5696        cx: &mut Context<Self>,
 5697    ) -> Option<IconButton> {
 5698        if self.available_code_actions.is_some() {
 5699            Some(
 5700                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5701                    .shape(ui::IconButtonShape::Square)
 5702                    .icon_size(IconSize::XSmall)
 5703                    .icon_color(Color::Muted)
 5704                    .toggle_state(is_active)
 5705                    .tooltip({
 5706                        let focus_handle = self.focus_handle.clone();
 5707                        move |window, cx| {
 5708                            Tooltip::for_action_in(
 5709                                "Toggle Code Actions",
 5710                                &ToggleCodeActions {
 5711                                    deployed_from_indicator: None,
 5712                                },
 5713                                &focus_handle,
 5714                                window,
 5715                                cx,
 5716                            )
 5717                        }
 5718                    })
 5719                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5720                        window.focus(&editor.focus_handle(cx));
 5721                        editor.toggle_code_actions(
 5722                            &ToggleCodeActions {
 5723                                deployed_from_indicator: Some(row),
 5724                            },
 5725                            window,
 5726                            cx,
 5727                        );
 5728                    })),
 5729            )
 5730        } else {
 5731            None
 5732        }
 5733    }
 5734
 5735    fn clear_tasks(&mut self) {
 5736        self.tasks.clear()
 5737    }
 5738
 5739    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5740        if self.tasks.insert(key, value).is_some() {
 5741            // This case should hopefully be rare, but just in case...
 5742            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5743        }
 5744    }
 5745
 5746    fn build_tasks_context(
 5747        project: &Entity<Project>,
 5748        buffer: &Entity<Buffer>,
 5749        buffer_row: u32,
 5750        tasks: &Arc<RunnableTasks>,
 5751        cx: &mut Context<Self>,
 5752    ) -> Task<Option<task::TaskContext>> {
 5753        let position = Point::new(buffer_row, tasks.column);
 5754        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5755        let location = Location {
 5756            buffer: buffer.clone(),
 5757            range: range_start..range_start,
 5758        };
 5759        // Fill in the environmental variables from the tree-sitter captures
 5760        let mut captured_task_variables = TaskVariables::default();
 5761        for (capture_name, value) in tasks.extra_variables.clone() {
 5762            captured_task_variables.insert(
 5763                task::VariableName::Custom(capture_name.into()),
 5764                value.clone(),
 5765            );
 5766        }
 5767        project.update(cx, |project, cx| {
 5768            project.task_store().update(cx, |task_store, cx| {
 5769                task_store.task_context_for_location(captured_task_variables, location, cx)
 5770            })
 5771        })
 5772    }
 5773
 5774    pub fn spawn_nearest_task(
 5775        &mut self,
 5776        action: &SpawnNearestTask,
 5777        window: &mut Window,
 5778        cx: &mut Context<Self>,
 5779    ) {
 5780        let Some((workspace, _)) = self.workspace.clone() else {
 5781            return;
 5782        };
 5783        let Some(project) = self.project.clone() else {
 5784            return;
 5785        };
 5786
 5787        // Try to find a closest, enclosing node using tree-sitter that has a
 5788        // task
 5789        let Some((buffer, buffer_row, tasks)) = self
 5790            .find_enclosing_node_task(cx)
 5791            // Or find the task that's closest in row-distance.
 5792            .or_else(|| self.find_closest_task(cx))
 5793        else {
 5794            return;
 5795        };
 5796
 5797        let reveal_strategy = action.reveal;
 5798        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5799        cx.spawn_in(window, |_, mut cx| async move {
 5800            let context = task_context.await?;
 5801            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5802
 5803            let resolved = resolved_task.resolved.as_mut()?;
 5804            resolved.reveal = reveal_strategy;
 5805
 5806            workspace
 5807                .update(&mut cx, |workspace, cx| {
 5808                    workspace::tasks::schedule_resolved_task(
 5809                        workspace,
 5810                        task_source_kind,
 5811                        resolved_task,
 5812                        false,
 5813                        cx,
 5814                    );
 5815                })
 5816                .ok()
 5817        })
 5818        .detach();
 5819    }
 5820
 5821    fn find_closest_task(
 5822        &mut self,
 5823        cx: &mut Context<Self>,
 5824    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5825        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5826
 5827        let ((buffer_id, row), tasks) = self
 5828            .tasks
 5829            .iter()
 5830            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5831
 5832        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5833        let tasks = Arc::new(tasks.to_owned());
 5834        Some((buffer, *row, tasks))
 5835    }
 5836
 5837    fn find_enclosing_node_task(
 5838        &mut self,
 5839        cx: &mut Context<Self>,
 5840    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5841        let snapshot = self.buffer.read(cx).snapshot(cx);
 5842        let offset = self.selections.newest::<usize>(cx).head();
 5843        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5844        let buffer_id = excerpt.buffer().remote_id();
 5845
 5846        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5847        let mut cursor = layer.node().walk();
 5848
 5849        while cursor.goto_first_child_for_byte(offset).is_some() {
 5850            if cursor.node().end_byte() == offset {
 5851                cursor.goto_next_sibling();
 5852            }
 5853        }
 5854
 5855        // Ascend to the smallest ancestor that contains the range and has a task.
 5856        loop {
 5857            let node = cursor.node();
 5858            let node_range = node.byte_range();
 5859            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5860
 5861            // Check if this node contains our offset
 5862            if node_range.start <= offset && node_range.end >= offset {
 5863                // If it contains offset, check for task
 5864                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5865                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5866                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5867                }
 5868            }
 5869
 5870            if !cursor.goto_parent() {
 5871                break;
 5872            }
 5873        }
 5874        None
 5875    }
 5876
 5877    fn render_run_indicator(
 5878        &self,
 5879        _style: &EditorStyle,
 5880        is_active: bool,
 5881        row: DisplayRow,
 5882        cx: &mut Context<Self>,
 5883    ) -> IconButton {
 5884        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5885            .shape(ui::IconButtonShape::Square)
 5886            .icon_size(IconSize::XSmall)
 5887            .icon_color(Color::Muted)
 5888            .toggle_state(is_active)
 5889            .on_click(cx.listener(move |editor, _e, window, cx| {
 5890                window.focus(&editor.focus_handle(cx));
 5891                editor.toggle_code_actions(
 5892                    &ToggleCodeActions {
 5893                        deployed_from_indicator: Some(row),
 5894                    },
 5895                    window,
 5896                    cx,
 5897                );
 5898            }))
 5899    }
 5900
 5901    pub fn context_menu_visible(&self) -> bool {
 5902        !self.edit_prediction_preview_is_active()
 5903            && self
 5904                .context_menu
 5905                .borrow()
 5906                .as_ref()
 5907                .map_or(false, |menu| menu.visible())
 5908    }
 5909
 5910    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5911        self.context_menu
 5912            .borrow()
 5913            .as_ref()
 5914            .map(|menu| menu.origin())
 5915    }
 5916
 5917    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 5918    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 5919
 5920    #[allow(clippy::too_many_arguments)]
 5921    fn render_edit_prediction_popover(
 5922        &mut self,
 5923        text_bounds: &Bounds<Pixels>,
 5924        content_origin: gpui::Point<Pixels>,
 5925        editor_snapshot: &EditorSnapshot,
 5926        visible_row_range: Range<DisplayRow>,
 5927        scroll_top: f32,
 5928        scroll_bottom: f32,
 5929        line_layouts: &[LineWithInvisibles],
 5930        line_height: Pixels,
 5931        scroll_pixel_position: gpui::Point<Pixels>,
 5932        newest_selection_head: Option<DisplayPoint>,
 5933        editor_width: Pixels,
 5934        style: &EditorStyle,
 5935        window: &mut Window,
 5936        cx: &mut App,
 5937    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5938        let active_inline_completion = self.active_inline_completion.as_ref()?;
 5939
 5940        if self.edit_prediction_visible_in_cursor_popover(true) {
 5941            return None;
 5942        }
 5943
 5944        match &active_inline_completion.completion {
 5945            InlineCompletion::Move { target, .. } => {
 5946                let target_display_point = target.to_display_point(editor_snapshot);
 5947
 5948                if self.edit_prediction_requires_modifier() {
 5949                    if !self.edit_prediction_preview_is_active() {
 5950                        return None;
 5951                    }
 5952
 5953                    self.render_edit_prediction_modifier_jump_popover(
 5954                        text_bounds,
 5955                        content_origin,
 5956                        visible_row_range,
 5957                        line_layouts,
 5958                        line_height,
 5959                        scroll_pixel_position,
 5960                        newest_selection_head,
 5961                        target_display_point,
 5962                        window,
 5963                        cx,
 5964                    )
 5965                } else {
 5966                    self.render_edit_prediction_eager_jump_popover(
 5967                        text_bounds,
 5968                        content_origin,
 5969                        editor_snapshot,
 5970                        visible_row_range,
 5971                        scroll_top,
 5972                        scroll_bottom,
 5973                        line_height,
 5974                        scroll_pixel_position,
 5975                        target_display_point,
 5976                        editor_width,
 5977                        window,
 5978                        cx,
 5979                    )
 5980                }
 5981            }
 5982            InlineCompletion::Edit {
 5983                display_mode: EditDisplayMode::Inline,
 5984                ..
 5985            } => None,
 5986            InlineCompletion::Edit {
 5987                display_mode: EditDisplayMode::TabAccept,
 5988                edits,
 5989                ..
 5990            } => {
 5991                let range = &edits.first()?.0;
 5992                let target_display_point = range.end.to_display_point(editor_snapshot);
 5993
 5994                self.render_edit_prediction_end_of_line_popover(
 5995                    "Accept",
 5996                    editor_snapshot,
 5997                    visible_row_range,
 5998                    target_display_point,
 5999                    line_height,
 6000                    scroll_pixel_position,
 6001                    content_origin,
 6002                    editor_width,
 6003                    window,
 6004                    cx,
 6005                )
 6006            }
 6007            InlineCompletion::Edit {
 6008                edits,
 6009                edit_preview,
 6010                display_mode: EditDisplayMode::DiffPopover,
 6011                snapshot,
 6012            } => self.render_edit_prediction_diff_popover(
 6013                text_bounds,
 6014                content_origin,
 6015                editor_snapshot,
 6016                visible_row_range,
 6017                line_layouts,
 6018                line_height,
 6019                scroll_pixel_position,
 6020                newest_selection_head,
 6021                editor_width,
 6022                style,
 6023                edits,
 6024                edit_preview,
 6025                snapshot,
 6026                window,
 6027                cx,
 6028            ),
 6029        }
 6030    }
 6031
 6032    #[allow(clippy::too_many_arguments)]
 6033    fn render_edit_prediction_modifier_jump_popover(
 6034        &mut self,
 6035        text_bounds: &Bounds<Pixels>,
 6036        content_origin: gpui::Point<Pixels>,
 6037        visible_row_range: Range<DisplayRow>,
 6038        line_layouts: &[LineWithInvisibles],
 6039        line_height: Pixels,
 6040        scroll_pixel_position: gpui::Point<Pixels>,
 6041        newest_selection_head: Option<DisplayPoint>,
 6042        target_display_point: DisplayPoint,
 6043        window: &mut Window,
 6044        cx: &mut App,
 6045    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6046        let scrolled_content_origin =
 6047            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 6048
 6049        const SCROLL_PADDING_Y: Pixels = px(12.);
 6050
 6051        if target_display_point.row() < visible_row_range.start {
 6052            return self.render_edit_prediction_scroll_popover(
 6053                |_| SCROLL_PADDING_Y,
 6054                IconName::ArrowUp,
 6055                visible_row_range,
 6056                line_layouts,
 6057                newest_selection_head,
 6058                scrolled_content_origin,
 6059                window,
 6060                cx,
 6061            );
 6062        } else if target_display_point.row() >= visible_row_range.end {
 6063            return self.render_edit_prediction_scroll_popover(
 6064                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 6065                IconName::ArrowDown,
 6066                visible_row_range,
 6067                line_layouts,
 6068                newest_selection_head,
 6069                scrolled_content_origin,
 6070                window,
 6071                cx,
 6072            );
 6073        }
 6074
 6075        const POLE_WIDTH: Pixels = px(2.);
 6076
 6077        let line_layout =
 6078            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 6079        let target_column = target_display_point.column() as usize;
 6080
 6081        let target_x = line_layout.x_for_index(target_column);
 6082        let target_y =
 6083            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 6084
 6085        let flag_on_right = target_x < text_bounds.size.width / 2.;
 6086
 6087        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 6088        border_color.l += 0.001;
 6089
 6090        let mut element = v_flex()
 6091            .items_end()
 6092            .when(flag_on_right, |el| el.items_start())
 6093            .child(if flag_on_right {
 6094                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6095                    .rounded_bl(px(0.))
 6096                    .rounded_tl(px(0.))
 6097                    .border_l_2()
 6098                    .border_color(border_color)
 6099            } else {
 6100                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6101                    .rounded_br(px(0.))
 6102                    .rounded_tr(px(0.))
 6103                    .border_r_2()
 6104                    .border_color(border_color)
 6105            })
 6106            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 6107            .into_any();
 6108
 6109        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6110
 6111        let mut origin = scrolled_content_origin + point(target_x, target_y)
 6112            - point(
 6113                if flag_on_right {
 6114                    POLE_WIDTH
 6115                } else {
 6116                    size.width - POLE_WIDTH
 6117                },
 6118                size.height - line_height,
 6119            );
 6120
 6121        origin.x = origin.x.max(content_origin.x);
 6122
 6123        element.prepaint_at(origin, window, cx);
 6124
 6125        Some((element, origin))
 6126    }
 6127
 6128    #[allow(clippy::too_many_arguments)]
 6129    fn render_edit_prediction_scroll_popover(
 6130        &mut self,
 6131        to_y: impl Fn(Size<Pixels>) -> Pixels,
 6132        scroll_icon: IconName,
 6133        visible_row_range: Range<DisplayRow>,
 6134        line_layouts: &[LineWithInvisibles],
 6135        newest_selection_head: Option<DisplayPoint>,
 6136        scrolled_content_origin: gpui::Point<Pixels>,
 6137        window: &mut Window,
 6138        cx: &mut App,
 6139    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6140        let mut element = self
 6141            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 6142            .into_any();
 6143
 6144        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6145
 6146        let cursor = newest_selection_head?;
 6147        let cursor_row_layout =
 6148            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6149        let cursor_column = cursor.column() as usize;
 6150
 6151        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6152
 6153        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6154
 6155        element.prepaint_at(origin, window, cx);
 6156        Some((element, origin))
 6157    }
 6158
 6159    #[allow(clippy::too_many_arguments)]
 6160    fn render_edit_prediction_eager_jump_popover(
 6161        &mut self,
 6162        text_bounds: &Bounds<Pixels>,
 6163        content_origin: gpui::Point<Pixels>,
 6164        editor_snapshot: &EditorSnapshot,
 6165        visible_row_range: Range<DisplayRow>,
 6166        scroll_top: f32,
 6167        scroll_bottom: f32,
 6168        line_height: Pixels,
 6169        scroll_pixel_position: gpui::Point<Pixels>,
 6170        target_display_point: DisplayPoint,
 6171        editor_width: Pixels,
 6172        window: &mut Window,
 6173        cx: &mut App,
 6174    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6175        if target_display_point.row().as_f32() < scroll_top {
 6176            let mut element = self
 6177                .render_edit_prediction_line_popover(
 6178                    "Jump to Edit",
 6179                    Some(IconName::ArrowUp),
 6180                    window,
 6181                    cx,
 6182                )?
 6183                .into_any();
 6184
 6185            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6186            let offset = point(
 6187                (text_bounds.size.width - size.width) / 2.,
 6188                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6189            );
 6190
 6191            let origin = text_bounds.origin + offset;
 6192            element.prepaint_at(origin, window, cx);
 6193            Some((element, origin))
 6194        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6195            let mut element = self
 6196                .render_edit_prediction_line_popover(
 6197                    "Jump to Edit",
 6198                    Some(IconName::ArrowDown),
 6199                    window,
 6200                    cx,
 6201                )?
 6202                .into_any();
 6203
 6204            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6205            let offset = point(
 6206                (text_bounds.size.width - size.width) / 2.,
 6207                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6208            );
 6209
 6210            let origin = text_bounds.origin + offset;
 6211            element.prepaint_at(origin, window, cx);
 6212            Some((element, origin))
 6213        } else {
 6214            self.render_edit_prediction_end_of_line_popover(
 6215                "Jump to Edit",
 6216                editor_snapshot,
 6217                visible_row_range,
 6218                target_display_point,
 6219                line_height,
 6220                scroll_pixel_position,
 6221                content_origin,
 6222                editor_width,
 6223                window,
 6224                cx,
 6225            )
 6226        }
 6227    }
 6228
 6229    #[allow(clippy::too_many_arguments)]
 6230    fn render_edit_prediction_end_of_line_popover(
 6231        self: &mut Editor,
 6232        label: &'static str,
 6233        editor_snapshot: &EditorSnapshot,
 6234        visible_row_range: Range<DisplayRow>,
 6235        target_display_point: DisplayPoint,
 6236        line_height: Pixels,
 6237        scroll_pixel_position: gpui::Point<Pixels>,
 6238        content_origin: gpui::Point<Pixels>,
 6239        editor_width: Pixels,
 6240        window: &mut Window,
 6241        cx: &mut App,
 6242    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6243        let target_line_end = DisplayPoint::new(
 6244            target_display_point.row(),
 6245            editor_snapshot.line_len(target_display_point.row()),
 6246        );
 6247
 6248        let mut element = self
 6249            .render_edit_prediction_line_popover(label, None, window, cx)?
 6250            .into_any();
 6251
 6252        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6253
 6254        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 6255
 6256        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 6257        let mut origin = start_point
 6258            + line_origin
 6259            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 6260        origin.x = origin.x.max(content_origin.x);
 6261
 6262        let max_x = content_origin.x + editor_width - size.width;
 6263
 6264        if origin.x > max_x {
 6265            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 6266
 6267            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 6268                origin.y += offset;
 6269                IconName::ArrowUp
 6270            } else {
 6271                origin.y -= offset;
 6272                IconName::ArrowDown
 6273            };
 6274
 6275            element = self
 6276                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 6277                .into_any();
 6278
 6279            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6280
 6281            origin.x = content_origin.x + editor_width - size.width - px(2.);
 6282        }
 6283
 6284        element.prepaint_at(origin, window, cx);
 6285        Some((element, origin))
 6286    }
 6287
 6288    #[allow(clippy::too_many_arguments)]
 6289    fn render_edit_prediction_diff_popover(
 6290        self: &Editor,
 6291        text_bounds: &Bounds<Pixels>,
 6292        content_origin: gpui::Point<Pixels>,
 6293        editor_snapshot: &EditorSnapshot,
 6294        visible_row_range: Range<DisplayRow>,
 6295        line_layouts: &[LineWithInvisibles],
 6296        line_height: Pixels,
 6297        scroll_pixel_position: gpui::Point<Pixels>,
 6298        newest_selection_head: Option<DisplayPoint>,
 6299        editor_width: Pixels,
 6300        style: &EditorStyle,
 6301        edits: &Vec<(Range<Anchor>, String)>,
 6302        edit_preview: &Option<language::EditPreview>,
 6303        snapshot: &language::BufferSnapshot,
 6304        window: &mut Window,
 6305        cx: &mut App,
 6306    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6307        let edit_start = edits
 6308            .first()
 6309            .unwrap()
 6310            .0
 6311            .start
 6312            .to_display_point(editor_snapshot);
 6313        let edit_end = edits
 6314            .last()
 6315            .unwrap()
 6316            .0
 6317            .end
 6318            .to_display_point(editor_snapshot);
 6319
 6320        let is_visible = visible_row_range.contains(&edit_start.row())
 6321            || visible_row_range.contains(&edit_end.row());
 6322        if !is_visible {
 6323            return None;
 6324        }
 6325
 6326        let highlighted_edits =
 6327            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 6328
 6329        let styled_text = highlighted_edits.to_styled_text(&style.text);
 6330        let line_count = highlighted_edits.text.lines().count();
 6331
 6332        const BORDER_WIDTH: Pixels = px(1.);
 6333
 6334        let mut element = h_flex()
 6335            .items_start()
 6336            .child(
 6337                h_flex()
 6338                    .bg(cx.theme().colors().editor_background)
 6339                    .border(BORDER_WIDTH)
 6340                    .shadow_sm()
 6341                    .border_color(cx.theme().colors().border)
 6342                    .rounded_l_lg()
 6343                    .when(line_count > 1, |el| el.rounded_br_lg())
 6344                    .pr_1()
 6345                    .child(styled_text),
 6346            )
 6347            .child(
 6348                h_flex()
 6349                    .h(line_height + BORDER_WIDTH * px(2.))
 6350                    .px_1p5()
 6351                    .gap_1()
 6352                    // Workaround: For some reason, there's a gap if we don't do this
 6353                    .ml(-BORDER_WIDTH)
 6354                    .shadow(smallvec![gpui::BoxShadow {
 6355                        color: gpui::black().opacity(0.05),
 6356                        offset: point(px(1.), px(1.)),
 6357                        blur_radius: px(2.),
 6358                        spread_radius: px(0.),
 6359                    }])
 6360                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 6361                    .border(BORDER_WIDTH)
 6362                    .border_color(cx.theme().colors().border)
 6363                    .rounded_r_lg()
 6364                    .children(self.render_edit_prediction_accept_keybind(window, cx)),
 6365            )
 6366            .into_any();
 6367
 6368        let longest_row =
 6369            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 6370        let longest_line_width = if visible_row_range.contains(&longest_row) {
 6371            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 6372        } else {
 6373            layout_line(
 6374                longest_row,
 6375                editor_snapshot,
 6376                style,
 6377                editor_width,
 6378                |_| false,
 6379                window,
 6380                cx,
 6381            )
 6382            .width
 6383        };
 6384
 6385        let viewport_bounds =
 6386            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 6387                right: -EditorElement::SCROLLBAR_WIDTH,
 6388                ..Default::default()
 6389            });
 6390
 6391        let x_after_longest =
 6392            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 6393                - scroll_pixel_position.x;
 6394
 6395        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6396
 6397        // Fully visible if it can be displayed within the window (allow overlapping other
 6398        // panes). However, this is only allowed if the popover starts within text_bounds.
 6399        let can_position_to_the_right = x_after_longest < text_bounds.right()
 6400            && x_after_longest + element_bounds.width < viewport_bounds.right();
 6401
 6402        let mut origin = if can_position_to_the_right {
 6403            point(
 6404                x_after_longest,
 6405                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 6406                    - scroll_pixel_position.y,
 6407            )
 6408        } else {
 6409            let cursor_row = newest_selection_head.map(|head| head.row());
 6410            let above_edit = edit_start
 6411                .row()
 6412                .0
 6413                .checked_sub(line_count as u32)
 6414                .map(DisplayRow);
 6415            let below_edit = Some(edit_end.row() + 1);
 6416            let above_cursor =
 6417                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 6418            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 6419
 6420            // Place the edit popover adjacent to the edit if there is a location
 6421            // available that is onscreen and does not obscure the cursor. Otherwise,
 6422            // place it adjacent to the cursor.
 6423            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 6424                .into_iter()
 6425                .flatten()
 6426                .find(|&start_row| {
 6427                    let end_row = start_row + line_count as u32;
 6428                    visible_row_range.contains(&start_row)
 6429                        && visible_row_range.contains(&end_row)
 6430                        && cursor_row.map_or(true, |cursor_row| {
 6431                            !((start_row..end_row).contains(&cursor_row))
 6432                        })
 6433                })?;
 6434
 6435            content_origin
 6436                + point(
 6437                    -scroll_pixel_position.x,
 6438                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 6439                )
 6440        };
 6441
 6442        origin.x -= BORDER_WIDTH;
 6443
 6444        window.defer_draw(element, origin, 1);
 6445
 6446        // Do not return an element, since it will already be drawn due to defer_draw.
 6447        None
 6448    }
 6449
 6450    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 6451        px(30.)
 6452    }
 6453
 6454    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 6455        if self.read_only(cx) {
 6456            cx.theme().players().read_only()
 6457        } else {
 6458            self.style.as_ref().unwrap().local_player
 6459        }
 6460    }
 6461
 6462    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 6463        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 6464        let accept_keystroke = accept_binding.keystroke()?;
 6465
 6466        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6467
 6468        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 6469            Color::Accent
 6470        } else {
 6471            Color::Muted
 6472        };
 6473
 6474        h_flex()
 6475            .px_0p5()
 6476            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 6477            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6478            .text_size(TextSize::XSmall.rems(cx))
 6479            .child(h_flex().children(ui::render_modifiers(
 6480                &accept_keystroke.modifiers,
 6481                PlatformStyle::platform(),
 6482                Some(modifiers_color),
 6483                Some(IconSize::XSmall.rems().into()),
 6484                true,
 6485            )))
 6486            .when(is_platform_style_mac, |parent| {
 6487                parent.child(accept_keystroke.key.clone())
 6488            })
 6489            .when(!is_platform_style_mac, |parent| {
 6490                parent.child(
 6491                    Key::new(
 6492                        util::capitalize(&accept_keystroke.key),
 6493                        Some(Color::Default),
 6494                    )
 6495                    .size(Some(IconSize::XSmall.rems().into())),
 6496                )
 6497            })
 6498            .into()
 6499    }
 6500
 6501    fn render_edit_prediction_line_popover(
 6502        &self,
 6503        label: impl Into<SharedString>,
 6504        icon: Option<IconName>,
 6505        window: &mut Window,
 6506        cx: &App,
 6507    ) -> Option<Div> {
 6508        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 6509
 6510        let result = h_flex()
 6511            .py_0p5()
 6512            .pl_1()
 6513            .pr(padding_right)
 6514            .gap_1()
 6515            .rounded(px(6.))
 6516            .border_1()
 6517            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6518            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 6519            .shadow_sm()
 6520            .children(self.render_edit_prediction_accept_keybind(window, cx))
 6521            .child(Label::new(label).size(LabelSize::Small))
 6522            .when_some(icon, |element, icon| {
 6523                element.child(
 6524                    div()
 6525                        .mt(px(1.5))
 6526                        .child(Icon::new(icon).size(IconSize::Small)),
 6527                )
 6528            });
 6529
 6530        Some(result)
 6531    }
 6532
 6533    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 6534        let accent_color = cx.theme().colors().text_accent;
 6535        let editor_bg_color = cx.theme().colors().editor_background;
 6536        editor_bg_color.blend(accent_color.opacity(0.1))
 6537    }
 6538
 6539    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 6540        let accent_color = cx.theme().colors().text_accent;
 6541        let editor_bg_color = cx.theme().colors().editor_background;
 6542        editor_bg_color.blend(accent_color.opacity(0.6))
 6543    }
 6544
 6545    #[allow(clippy::too_many_arguments)]
 6546    fn render_edit_prediction_cursor_popover(
 6547        &self,
 6548        min_width: Pixels,
 6549        max_width: Pixels,
 6550        cursor_point: Point,
 6551        style: &EditorStyle,
 6552        accept_keystroke: Option<&gpui::Keystroke>,
 6553        _window: &Window,
 6554        cx: &mut Context<Editor>,
 6555    ) -> Option<AnyElement> {
 6556        let provider = self.edit_prediction_provider.as_ref()?;
 6557
 6558        if provider.provider.needs_terms_acceptance(cx) {
 6559            return Some(
 6560                h_flex()
 6561                    .min_w(min_width)
 6562                    .flex_1()
 6563                    .px_2()
 6564                    .py_1()
 6565                    .gap_3()
 6566                    .elevation_2(cx)
 6567                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 6568                    .id("accept-terms")
 6569                    .cursor_pointer()
 6570                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 6571                    .on_click(cx.listener(|this, _event, window, cx| {
 6572                        cx.stop_propagation();
 6573                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 6574                        window.dispatch_action(
 6575                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 6576                            cx,
 6577                        );
 6578                    }))
 6579                    .child(
 6580                        h_flex()
 6581                            .flex_1()
 6582                            .gap_2()
 6583                            .child(Icon::new(IconName::ZedPredict))
 6584                            .child(Label::new("Accept Terms of Service"))
 6585                            .child(div().w_full())
 6586                            .child(
 6587                                Icon::new(IconName::ArrowUpRight)
 6588                                    .color(Color::Muted)
 6589                                    .size(IconSize::Small),
 6590                            )
 6591                            .into_any_element(),
 6592                    )
 6593                    .into_any(),
 6594            );
 6595        }
 6596
 6597        let is_refreshing = provider.provider.is_refreshing(cx);
 6598
 6599        fn pending_completion_container() -> Div {
 6600            h_flex()
 6601                .h_full()
 6602                .flex_1()
 6603                .gap_2()
 6604                .child(Icon::new(IconName::ZedPredict))
 6605        }
 6606
 6607        let completion = match &self.active_inline_completion {
 6608            Some(prediction) => {
 6609                if !self.has_visible_completions_menu() {
 6610                    const RADIUS: Pixels = px(6.);
 6611                    const BORDER_WIDTH: Pixels = px(1.);
 6612
 6613                    return Some(
 6614                        h_flex()
 6615                            .elevation_2(cx)
 6616                            .border(BORDER_WIDTH)
 6617                            .border_color(cx.theme().colors().border)
 6618                            .rounded(RADIUS)
 6619                            .rounded_tl(px(0.))
 6620                            .overflow_hidden()
 6621                            .child(div().px_1p5().child(match &prediction.completion {
 6622                                InlineCompletion::Move { target, snapshot } => {
 6623                                    use text::ToPoint as _;
 6624                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 6625                                    {
 6626                                        Icon::new(IconName::ZedPredictDown)
 6627                                    } else {
 6628                                        Icon::new(IconName::ZedPredictUp)
 6629                                    }
 6630                                }
 6631                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 6632                            }))
 6633                            .child(
 6634                                h_flex()
 6635                                    .gap_1()
 6636                                    .py_1()
 6637                                    .px_2()
 6638                                    .rounded_r(RADIUS - BORDER_WIDTH)
 6639                                    .border_l_1()
 6640                                    .border_color(cx.theme().colors().border)
 6641                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6642                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 6643                                        el.child(
 6644                                            Label::new("Hold")
 6645                                                .size(LabelSize::Small)
 6646                                                .line_height_style(LineHeightStyle::UiLabel),
 6647                                        )
 6648                                    })
 6649                                    .child(h_flex().children(ui::render_modifiers(
 6650                                        &accept_keystroke?.modifiers,
 6651                                        PlatformStyle::platform(),
 6652                                        Some(Color::Default),
 6653                                        Some(IconSize::XSmall.rems().into()),
 6654                                        false,
 6655                                    ))),
 6656                            )
 6657                            .into_any(),
 6658                    );
 6659                }
 6660
 6661                self.render_edit_prediction_cursor_popover_preview(
 6662                    prediction,
 6663                    cursor_point,
 6664                    style,
 6665                    cx,
 6666                )?
 6667            }
 6668
 6669            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 6670                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 6671                    stale_completion,
 6672                    cursor_point,
 6673                    style,
 6674                    cx,
 6675                )?,
 6676
 6677                None => {
 6678                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6679                }
 6680            },
 6681
 6682            None => pending_completion_container().child(Label::new("No Prediction")),
 6683        };
 6684
 6685        let completion = if is_refreshing {
 6686            completion
 6687                .with_animation(
 6688                    "loading-completion",
 6689                    Animation::new(Duration::from_secs(2))
 6690                        .repeat()
 6691                        .with_easing(pulsating_between(0.4, 0.8)),
 6692                    |label, delta| label.opacity(delta),
 6693                )
 6694                .into_any_element()
 6695        } else {
 6696            completion.into_any_element()
 6697        };
 6698
 6699        let has_completion = self.active_inline_completion.is_some();
 6700
 6701        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6702        Some(
 6703            h_flex()
 6704                .min_w(min_width)
 6705                .max_w(max_width)
 6706                .flex_1()
 6707                .elevation_2(cx)
 6708                .border_color(cx.theme().colors().border)
 6709                .child(
 6710                    div()
 6711                        .flex_1()
 6712                        .py_1()
 6713                        .px_2()
 6714                        .overflow_hidden()
 6715                        .child(completion),
 6716                )
 6717                .when_some(accept_keystroke, |el, accept_keystroke| {
 6718                    if !accept_keystroke.modifiers.modified() {
 6719                        return el;
 6720                    }
 6721
 6722                    el.child(
 6723                        h_flex()
 6724                            .h_full()
 6725                            .border_l_1()
 6726                            .rounded_r_lg()
 6727                            .border_color(cx.theme().colors().border)
 6728                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6729                            .gap_1()
 6730                            .py_1()
 6731                            .px_2()
 6732                            .child(
 6733                                h_flex()
 6734                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6735                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6736                                    .child(h_flex().children(ui::render_modifiers(
 6737                                        &accept_keystroke.modifiers,
 6738                                        PlatformStyle::platform(),
 6739                                        Some(if !has_completion {
 6740                                            Color::Muted
 6741                                        } else {
 6742                                            Color::Default
 6743                                        }),
 6744                                        None,
 6745                                        false,
 6746                                    ))),
 6747                            )
 6748                            .child(Label::new("Preview").into_any_element())
 6749                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6750                    )
 6751                })
 6752                .into_any(),
 6753        )
 6754    }
 6755
 6756    fn render_edit_prediction_cursor_popover_preview(
 6757        &self,
 6758        completion: &InlineCompletionState,
 6759        cursor_point: Point,
 6760        style: &EditorStyle,
 6761        cx: &mut Context<Editor>,
 6762    ) -> Option<Div> {
 6763        use text::ToPoint as _;
 6764
 6765        fn render_relative_row_jump(
 6766            prefix: impl Into<String>,
 6767            current_row: u32,
 6768            target_row: u32,
 6769        ) -> Div {
 6770            let (row_diff, arrow) = if target_row < current_row {
 6771                (current_row - target_row, IconName::ArrowUp)
 6772            } else {
 6773                (target_row - current_row, IconName::ArrowDown)
 6774            };
 6775
 6776            h_flex()
 6777                .child(
 6778                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6779                        .color(Color::Muted)
 6780                        .size(LabelSize::Small),
 6781                )
 6782                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6783        }
 6784
 6785        match &completion.completion {
 6786            InlineCompletion::Move {
 6787                target, snapshot, ..
 6788            } => Some(
 6789                h_flex()
 6790                    .px_2()
 6791                    .gap_2()
 6792                    .flex_1()
 6793                    .child(
 6794                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6795                            Icon::new(IconName::ZedPredictDown)
 6796                        } else {
 6797                            Icon::new(IconName::ZedPredictUp)
 6798                        },
 6799                    )
 6800                    .child(Label::new("Jump to Edit")),
 6801            ),
 6802
 6803            InlineCompletion::Edit {
 6804                edits,
 6805                edit_preview,
 6806                snapshot,
 6807                display_mode: _,
 6808            } => {
 6809                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6810
 6811                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6812                    &snapshot,
 6813                    &edits,
 6814                    edit_preview.as_ref()?,
 6815                    true,
 6816                    cx,
 6817                )
 6818                .first_line_preview();
 6819
 6820                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6821                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 6822
 6823                let preview = h_flex()
 6824                    .gap_1()
 6825                    .min_w_16()
 6826                    .child(styled_text)
 6827                    .when(has_more_lines, |parent| parent.child(""));
 6828
 6829                let left = if first_edit_row != cursor_point.row {
 6830                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6831                        .into_any_element()
 6832                } else {
 6833                    Icon::new(IconName::ZedPredict).into_any_element()
 6834                };
 6835
 6836                Some(
 6837                    h_flex()
 6838                        .h_full()
 6839                        .flex_1()
 6840                        .gap_2()
 6841                        .pr_1()
 6842                        .overflow_x_hidden()
 6843                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6844                        .child(left)
 6845                        .child(preview),
 6846                )
 6847            }
 6848        }
 6849    }
 6850
 6851    fn render_context_menu(
 6852        &self,
 6853        style: &EditorStyle,
 6854        max_height_in_lines: u32,
 6855        y_flipped: bool,
 6856        window: &mut Window,
 6857        cx: &mut Context<Editor>,
 6858    ) -> Option<AnyElement> {
 6859        let menu = self.context_menu.borrow();
 6860        let menu = menu.as_ref()?;
 6861        if !menu.visible() {
 6862            return None;
 6863        };
 6864        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6865    }
 6866
 6867    fn render_context_menu_aside(
 6868        &mut self,
 6869        max_size: Size<Pixels>,
 6870        window: &mut Window,
 6871        cx: &mut Context<Editor>,
 6872    ) -> Option<AnyElement> {
 6873        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 6874            if menu.visible() {
 6875                menu.render_aside(self, max_size, window, cx)
 6876            } else {
 6877                None
 6878            }
 6879        })
 6880    }
 6881
 6882    fn hide_context_menu(
 6883        &mut self,
 6884        window: &mut Window,
 6885        cx: &mut Context<Self>,
 6886    ) -> Option<CodeContextMenu> {
 6887        cx.notify();
 6888        self.completion_tasks.clear();
 6889        let context_menu = self.context_menu.borrow_mut().take();
 6890        self.stale_inline_completion_in_menu.take();
 6891        self.update_visible_inline_completion(window, cx);
 6892        context_menu
 6893    }
 6894
 6895    fn show_snippet_choices(
 6896        &mut self,
 6897        choices: &Vec<String>,
 6898        selection: Range<Anchor>,
 6899        cx: &mut Context<Self>,
 6900    ) {
 6901        if selection.start.buffer_id.is_none() {
 6902            return;
 6903        }
 6904        let buffer_id = selection.start.buffer_id.unwrap();
 6905        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6906        let id = post_inc(&mut self.next_completion_id);
 6907
 6908        if let Some(buffer) = buffer {
 6909            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6910                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6911            ));
 6912        }
 6913    }
 6914
 6915    pub fn insert_snippet(
 6916        &mut self,
 6917        insertion_ranges: &[Range<usize>],
 6918        snippet: Snippet,
 6919        window: &mut Window,
 6920        cx: &mut Context<Self>,
 6921    ) -> Result<()> {
 6922        struct Tabstop<T> {
 6923            is_end_tabstop: bool,
 6924            ranges: Vec<Range<T>>,
 6925            choices: Option<Vec<String>>,
 6926        }
 6927
 6928        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6929            let snippet_text: Arc<str> = snippet.text.clone().into();
 6930            buffer.edit(
 6931                insertion_ranges
 6932                    .iter()
 6933                    .cloned()
 6934                    .map(|range| (range, snippet_text.clone())),
 6935                Some(AutoindentMode::EachLine),
 6936                cx,
 6937            );
 6938
 6939            let snapshot = &*buffer.read(cx);
 6940            let snippet = &snippet;
 6941            snippet
 6942                .tabstops
 6943                .iter()
 6944                .map(|tabstop| {
 6945                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6946                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6947                    });
 6948                    let mut tabstop_ranges = tabstop
 6949                        .ranges
 6950                        .iter()
 6951                        .flat_map(|tabstop_range| {
 6952                            let mut delta = 0_isize;
 6953                            insertion_ranges.iter().map(move |insertion_range| {
 6954                                let insertion_start = insertion_range.start as isize + delta;
 6955                                delta +=
 6956                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6957
 6958                                let start = ((insertion_start + tabstop_range.start) as usize)
 6959                                    .min(snapshot.len());
 6960                                let end = ((insertion_start + tabstop_range.end) as usize)
 6961                                    .min(snapshot.len());
 6962                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6963                            })
 6964                        })
 6965                        .collect::<Vec<_>>();
 6966                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6967
 6968                    Tabstop {
 6969                        is_end_tabstop,
 6970                        ranges: tabstop_ranges,
 6971                        choices: tabstop.choices.clone(),
 6972                    }
 6973                })
 6974                .collect::<Vec<_>>()
 6975        });
 6976        if let Some(tabstop) = tabstops.first() {
 6977            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6978                s.select_ranges(tabstop.ranges.iter().cloned());
 6979            });
 6980
 6981            if let Some(choices) = &tabstop.choices {
 6982                if let Some(selection) = tabstop.ranges.first() {
 6983                    self.show_snippet_choices(choices, selection.clone(), cx)
 6984                }
 6985            }
 6986
 6987            // If we're already at the last tabstop and it's at the end of the snippet,
 6988            // we're done, we don't need to keep the state around.
 6989            if !tabstop.is_end_tabstop {
 6990                let choices = tabstops
 6991                    .iter()
 6992                    .map(|tabstop| tabstop.choices.clone())
 6993                    .collect();
 6994
 6995                let ranges = tabstops
 6996                    .into_iter()
 6997                    .map(|tabstop| tabstop.ranges)
 6998                    .collect::<Vec<_>>();
 6999
 7000                self.snippet_stack.push(SnippetState {
 7001                    active_index: 0,
 7002                    ranges,
 7003                    choices,
 7004                });
 7005            }
 7006
 7007            // Check whether the just-entered snippet ends with an auto-closable bracket.
 7008            if self.autoclose_regions.is_empty() {
 7009                let snapshot = self.buffer.read(cx).snapshot(cx);
 7010                for selection in &mut self.selections.all::<Point>(cx) {
 7011                    let selection_head = selection.head();
 7012                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 7013                        continue;
 7014                    };
 7015
 7016                    let mut bracket_pair = None;
 7017                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 7018                    let prev_chars = snapshot
 7019                        .reversed_chars_at(selection_head)
 7020                        .collect::<String>();
 7021                    for (pair, enabled) in scope.brackets() {
 7022                        if enabled
 7023                            && pair.close
 7024                            && prev_chars.starts_with(pair.start.as_str())
 7025                            && next_chars.starts_with(pair.end.as_str())
 7026                        {
 7027                            bracket_pair = Some(pair.clone());
 7028                            break;
 7029                        }
 7030                    }
 7031                    if let Some(pair) = bracket_pair {
 7032                        let start = snapshot.anchor_after(selection_head);
 7033                        let end = snapshot.anchor_after(selection_head);
 7034                        self.autoclose_regions.push(AutocloseRegion {
 7035                            selection_id: selection.id,
 7036                            range: start..end,
 7037                            pair,
 7038                        });
 7039                    }
 7040                }
 7041            }
 7042        }
 7043        Ok(())
 7044    }
 7045
 7046    pub fn move_to_next_snippet_tabstop(
 7047        &mut self,
 7048        window: &mut Window,
 7049        cx: &mut Context<Self>,
 7050    ) -> bool {
 7051        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 7052    }
 7053
 7054    pub fn move_to_prev_snippet_tabstop(
 7055        &mut self,
 7056        window: &mut Window,
 7057        cx: &mut Context<Self>,
 7058    ) -> bool {
 7059        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 7060    }
 7061
 7062    pub fn move_to_snippet_tabstop(
 7063        &mut self,
 7064        bias: Bias,
 7065        window: &mut Window,
 7066        cx: &mut Context<Self>,
 7067    ) -> bool {
 7068        if let Some(mut snippet) = self.snippet_stack.pop() {
 7069            match bias {
 7070                Bias::Left => {
 7071                    if snippet.active_index > 0 {
 7072                        snippet.active_index -= 1;
 7073                    } else {
 7074                        self.snippet_stack.push(snippet);
 7075                        return false;
 7076                    }
 7077                }
 7078                Bias::Right => {
 7079                    if snippet.active_index + 1 < snippet.ranges.len() {
 7080                        snippet.active_index += 1;
 7081                    } else {
 7082                        self.snippet_stack.push(snippet);
 7083                        return false;
 7084                    }
 7085                }
 7086            }
 7087            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 7088                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7089                    s.select_anchor_ranges(current_ranges.iter().cloned())
 7090                });
 7091
 7092                if let Some(choices) = &snippet.choices[snippet.active_index] {
 7093                    if let Some(selection) = current_ranges.first() {
 7094                        self.show_snippet_choices(&choices, selection.clone(), cx);
 7095                    }
 7096                }
 7097
 7098                // If snippet state is not at the last tabstop, push it back on the stack
 7099                if snippet.active_index + 1 < snippet.ranges.len() {
 7100                    self.snippet_stack.push(snippet);
 7101                }
 7102                return true;
 7103            }
 7104        }
 7105
 7106        false
 7107    }
 7108
 7109    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 7110        self.transact(window, cx, |this, window, cx| {
 7111            this.select_all(&SelectAll, window, cx);
 7112            this.insert("", window, cx);
 7113        });
 7114    }
 7115
 7116    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 7117        self.transact(window, cx, |this, window, cx| {
 7118            this.select_autoclose_pair(window, cx);
 7119            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 7120            if !this.linked_edit_ranges.is_empty() {
 7121                let selections = this.selections.all::<MultiBufferPoint>(cx);
 7122                let snapshot = this.buffer.read(cx).snapshot(cx);
 7123
 7124                for selection in selections.iter() {
 7125                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 7126                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 7127                    if selection_start.buffer_id != selection_end.buffer_id {
 7128                        continue;
 7129                    }
 7130                    if let Some(ranges) =
 7131                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 7132                    {
 7133                        for (buffer, entries) in ranges {
 7134                            linked_ranges.entry(buffer).or_default().extend(entries);
 7135                        }
 7136                    }
 7137                }
 7138            }
 7139
 7140            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7141            if !this.selections.line_mode {
 7142                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 7143                for selection in &mut selections {
 7144                    if selection.is_empty() {
 7145                        let old_head = selection.head();
 7146                        let mut new_head =
 7147                            movement::left(&display_map, old_head.to_display_point(&display_map))
 7148                                .to_point(&display_map);
 7149                        if let Some((buffer, line_buffer_range)) = display_map
 7150                            .buffer_snapshot
 7151                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 7152                        {
 7153                            let indent_size =
 7154                                buffer.indent_size_for_line(line_buffer_range.start.row);
 7155                            let indent_len = match indent_size.kind {
 7156                                IndentKind::Space => {
 7157                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 7158                                }
 7159                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 7160                            };
 7161                            if old_head.column <= indent_size.len && old_head.column > 0 {
 7162                                let indent_len = indent_len.get();
 7163                                new_head = cmp::min(
 7164                                    new_head,
 7165                                    MultiBufferPoint::new(
 7166                                        old_head.row,
 7167                                        ((old_head.column - 1) / indent_len) * indent_len,
 7168                                    ),
 7169                                );
 7170                            }
 7171                        }
 7172
 7173                        selection.set_head(new_head, SelectionGoal::None);
 7174                    }
 7175                }
 7176            }
 7177
 7178            this.signature_help_state.set_backspace_pressed(true);
 7179            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7180                s.select(selections)
 7181            });
 7182            this.insert("", window, cx);
 7183            let empty_str: Arc<str> = Arc::from("");
 7184            for (buffer, edits) in linked_ranges {
 7185                let snapshot = buffer.read(cx).snapshot();
 7186                use text::ToPoint as TP;
 7187
 7188                let edits = edits
 7189                    .into_iter()
 7190                    .map(|range| {
 7191                        let end_point = TP::to_point(&range.end, &snapshot);
 7192                        let mut start_point = TP::to_point(&range.start, &snapshot);
 7193
 7194                        if end_point == start_point {
 7195                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 7196                                .saturating_sub(1);
 7197                            start_point =
 7198                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 7199                        };
 7200
 7201                        (start_point..end_point, empty_str.clone())
 7202                    })
 7203                    .sorted_by_key(|(range, _)| range.start)
 7204                    .collect::<Vec<_>>();
 7205                buffer.update(cx, |this, cx| {
 7206                    this.edit(edits, None, cx);
 7207                })
 7208            }
 7209            this.refresh_inline_completion(true, false, window, cx);
 7210            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 7211        });
 7212    }
 7213
 7214    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 7215        self.transact(window, cx, |this, window, cx| {
 7216            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7217                let line_mode = s.line_mode;
 7218                s.move_with(|map, selection| {
 7219                    if selection.is_empty() && !line_mode {
 7220                        let cursor = movement::right(map, selection.head());
 7221                        selection.end = cursor;
 7222                        selection.reversed = true;
 7223                        selection.goal = SelectionGoal::None;
 7224                    }
 7225                })
 7226            });
 7227            this.insert("", window, cx);
 7228            this.refresh_inline_completion(true, false, window, cx);
 7229        });
 7230    }
 7231
 7232    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 7233        if self.move_to_prev_snippet_tabstop(window, cx) {
 7234            return;
 7235        }
 7236
 7237        self.outdent(&Outdent, window, cx);
 7238    }
 7239
 7240    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 7241        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 7242            return;
 7243        }
 7244
 7245        let mut selections = self.selections.all_adjusted(cx);
 7246        let buffer = self.buffer.read(cx);
 7247        let snapshot = buffer.snapshot(cx);
 7248        let rows_iter = selections.iter().map(|s| s.head().row);
 7249        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 7250
 7251        let mut edits = Vec::new();
 7252        let mut prev_edited_row = 0;
 7253        let mut row_delta = 0;
 7254        for selection in &mut selections {
 7255            if selection.start.row != prev_edited_row {
 7256                row_delta = 0;
 7257            }
 7258            prev_edited_row = selection.end.row;
 7259
 7260            // If the selection is non-empty, then increase the indentation of the selected lines.
 7261            if !selection.is_empty() {
 7262                row_delta =
 7263                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7264                continue;
 7265            }
 7266
 7267            // If the selection is empty and the cursor is in the leading whitespace before the
 7268            // suggested indentation, then auto-indent the line.
 7269            let cursor = selection.head();
 7270            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 7271            if let Some(suggested_indent) =
 7272                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 7273            {
 7274                if cursor.column < suggested_indent.len
 7275                    && cursor.column <= current_indent.len
 7276                    && current_indent.len <= suggested_indent.len
 7277                {
 7278                    selection.start = Point::new(cursor.row, suggested_indent.len);
 7279                    selection.end = selection.start;
 7280                    if row_delta == 0 {
 7281                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 7282                            cursor.row,
 7283                            current_indent,
 7284                            suggested_indent,
 7285                        ));
 7286                        row_delta = suggested_indent.len - current_indent.len;
 7287                    }
 7288                    continue;
 7289                }
 7290            }
 7291
 7292            // Otherwise, insert a hard or soft tab.
 7293            let settings = buffer.settings_at(cursor, cx);
 7294            let tab_size = if settings.hard_tabs {
 7295                IndentSize::tab()
 7296            } else {
 7297                let tab_size = settings.tab_size.get();
 7298                let char_column = snapshot
 7299                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 7300                    .flat_map(str::chars)
 7301                    .count()
 7302                    + row_delta as usize;
 7303                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 7304                IndentSize::spaces(chars_to_next_tab_stop)
 7305            };
 7306            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 7307            selection.end = selection.start;
 7308            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 7309            row_delta += tab_size.len;
 7310        }
 7311
 7312        self.transact(window, cx, |this, window, cx| {
 7313            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7314            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7315                s.select(selections)
 7316            });
 7317            this.refresh_inline_completion(true, false, window, cx);
 7318        });
 7319    }
 7320
 7321    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 7322        if self.read_only(cx) {
 7323            return;
 7324        }
 7325        let mut selections = self.selections.all::<Point>(cx);
 7326        let mut prev_edited_row = 0;
 7327        let mut row_delta = 0;
 7328        let mut edits = Vec::new();
 7329        let buffer = self.buffer.read(cx);
 7330        let snapshot = buffer.snapshot(cx);
 7331        for selection in &mut selections {
 7332            if selection.start.row != prev_edited_row {
 7333                row_delta = 0;
 7334            }
 7335            prev_edited_row = selection.end.row;
 7336
 7337            row_delta =
 7338                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7339        }
 7340
 7341        self.transact(window, cx, |this, window, cx| {
 7342            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7343            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7344                s.select(selections)
 7345            });
 7346        });
 7347    }
 7348
 7349    fn indent_selection(
 7350        buffer: &MultiBuffer,
 7351        snapshot: &MultiBufferSnapshot,
 7352        selection: &mut Selection<Point>,
 7353        edits: &mut Vec<(Range<Point>, String)>,
 7354        delta_for_start_row: u32,
 7355        cx: &App,
 7356    ) -> u32 {
 7357        let settings = buffer.settings_at(selection.start, cx);
 7358        let tab_size = settings.tab_size.get();
 7359        let indent_kind = if settings.hard_tabs {
 7360            IndentKind::Tab
 7361        } else {
 7362            IndentKind::Space
 7363        };
 7364        let mut start_row = selection.start.row;
 7365        let mut end_row = selection.end.row + 1;
 7366
 7367        // If a selection ends at the beginning of a line, don't indent
 7368        // that last line.
 7369        if selection.end.column == 0 && selection.end.row > selection.start.row {
 7370            end_row -= 1;
 7371        }
 7372
 7373        // Avoid re-indenting a row that has already been indented by a
 7374        // previous selection, but still update this selection's column
 7375        // to reflect that indentation.
 7376        if delta_for_start_row > 0 {
 7377            start_row += 1;
 7378            selection.start.column += delta_for_start_row;
 7379            if selection.end.row == selection.start.row {
 7380                selection.end.column += delta_for_start_row;
 7381            }
 7382        }
 7383
 7384        let mut delta_for_end_row = 0;
 7385        let has_multiple_rows = start_row + 1 != end_row;
 7386        for row in start_row..end_row {
 7387            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 7388            let indent_delta = match (current_indent.kind, indent_kind) {
 7389                (IndentKind::Space, IndentKind::Space) => {
 7390                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 7391                    IndentSize::spaces(columns_to_next_tab_stop)
 7392                }
 7393                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 7394                (_, IndentKind::Tab) => IndentSize::tab(),
 7395            };
 7396
 7397            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 7398                0
 7399            } else {
 7400                selection.start.column
 7401            };
 7402            let row_start = Point::new(row, start);
 7403            edits.push((
 7404                row_start..row_start,
 7405                indent_delta.chars().collect::<String>(),
 7406            ));
 7407
 7408            // Update this selection's endpoints to reflect the indentation.
 7409            if row == selection.start.row {
 7410                selection.start.column += indent_delta.len;
 7411            }
 7412            if row == selection.end.row {
 7413                selection.end.column += indent_delta.len;
 7414                delta_for_end_row = indent_delta.len;
 7415            }
 7416        }
 7417
 7418        if selection.start.row == selection.end.row {
 7419            delta_for_start_row + delta_for_end_row
 7420        } else {
 7421            delta_for_end_row
 7422        }
 7423    }
 7424
 7425    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 7426        if self.read_only(cx) {
 7427            return;
 7428        }
 7429        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7430        let selections = self.selections.all::<Point>(cx);
 7431        let mut deletion_ranges = Vec::new();
 7432        let mut last_outdent = None;
 7433        {
 7434            let buffer = self.buffer.read(cx);
 7435            let snapshot = buffer.snapshot(cx);
 7436            for selection in &selections {
 7437                let settings = buffer.settings_at(selection.start, cx);
 7438                let tab_size = settings.tab_size.get();
 7439                let mut rows = selection.spanned_rows(false, &display_map);
 7440
 7441                // Avoid re-outdenting a row that has already been outdented by a
 7442                // previous selection.
 7443                if let Some(last_row) = last_outdent {
 7444                    if last_row == rows.start {
 7445                        rows.start = rows.start.next_row();
 7446                    }
 7447                }
 7448                let has_multiple_rows = rows.len() > 1;
 7449                for row in rows.iter_rows() {
 7450                    let indent_size = snapshot.indent_size_for_line(row);
 7451                    if indent_size.len > 0 {
 7452                        let deletion_len = match indent_size.kind {
 7453                            IndentKind::Space => {
 7454                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 7455                                if columns_to_prev_tab_stop == 0 {
 7456                                    tab_size
 7457                                } else {
 7458                                    columns_to_prev_tab_stop
 7459                                }
 7460                            }
 7461                            IndentKind::Tab => 1,
 7462                        };
 7463                        let start = if has_multiple_rows
 7464                            || deletion_len > selection.start.column
 7465                            || indent_size.len < selection.start.column
 7466                        {
 7467                            0
 7468                        } else {
 7469                            selection.start.column - deletion_len
 7470                        };
 7471                        deletion_ranges.push(
 7472                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 7473                        );
 7474                        last_outdent = Some(row);
 7475                    }
 7476                }
 7477            }
 7478        }
 7479
 7480        self.transact(window, cx, |this, window, cx| {
 7481            this.buffer.update(cx, |buffer, cx| {
 7482                let empty_str: Arc<str> = Arc::default();
 7483                buffer.edit(
 7484                    deletion_ranges
 7485                        .into_iter()
 7486                        .map(|range| (range, empty_str.clone())),
 7487                    None,
 7488                    cx,
 7489                );
 7490            });
 7491            let selections = this.selections.all::<usize>(cx);
 7492            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7493                s.select(selections)
 7494            });
 7495        });
 7496    }
 7497
 7498    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 7499        if self.read_only(cx) {
 7500            return;
 7501        }
 7502        let selections = self
 7503            .selections
 7504            .all::<usize>(cx)
 7505            .into_iter()
 7506            .map(|s| s.range());
 7507
 7508        self.transact(window, cx, |this, window, cx| {
 7509            this.buffer.update(cx, |buffer, cx| {
 7510                buffer.autoindent_ranges(selections, cx);
 7511            });
 7512            let selections = this.selections.all::<usize>(cx);
 7513            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7514                s.select(selections)
 7515            });
 7516        });
 7517    }
 7518
 7519    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 7520        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7521        let selections = self.selections.all::<Point>(cx);
 7522
 7523        let mut new_cursors = Vec::new();
 7524        let mut edit_ranges = Vec::new();
 7525        let mut selections = selections.iter().peekable();
 7526        while let Some(selection) = selections.next() {
 7527            let mut rows = selection.spanned_rows(false, &display_map);
 7528            let goal_display_column = selection.head().to_display_point(&display_map).column();
 7529
 7530            // Accumulate contiguous regions of rows that we want to delete.
 7531            while let Some(next_selection) = selections.peek() {
 7532                let next_rows = next_selection.spanned_rows(false, &display_map);
 7533                if next_rows.start <= rows.end {
 7534                    rows.end = next_rows.end;
 7535                    selections.next().unwrap();
 7536                } else {
 7537                    break;
 7538                }
 7539            }
 7540
 7541            let buffer = &display_map.buffer_snapshot;
 7542            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 7543            let edit_end;
 7544            let cursor_buffer_row;
 7545            if buffer.max_point().row >= rows.end.0 {
 7546                // If there's a line after the range, delete the \n from the end of the row range
 7547                // and position the cursor on the next line.
 7548                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 7549                cursor_buffer_row = rows.end;
 7550            } else {
 7551                // If there isn't a line after the range, delete the \n from the line before the
 7552                // start of the row range and position the cursor there.
 7553                edit_start = edit_start.saturating_sub(1);
 7554                edit_end = buffer.len();
 7555                cursor_buffer_row = rows.start.previous_row();
 7556            }
 7557
 7558            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 7559            *cursor.column_mut() =
 7560                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 7561
 7562            new_cursors.push((
 7563                selection.id,
 7564                buffer.anchor_after(cursor.to_point(&display_map)),
 7565            ));
 7566            edit_ranges.push(edit_start..edit_end);
 7567        }
 7568
 7569        self.transact(window, cx, |this, window, cx| {
 7570            let buffer = this.buffer.update(cx, |buffer, cx| {
 7571                let empty_str: Arc<str> = Arc::default();
 7572                buffer.edit(
 7573                    edit_ranges
 7574                        .into_iter()
 7575                        .map(|range| (range, empty_str.clone())),
 7576                    None,
 7577                    cx,
 7578                );
 7579                buffer.snapshot(cx)
 7580            });
 7581            let new_selections = new_cursors
 7582                .into_iter()
 7583                .map(|(id, cursor)| {
 7584                    let cursor = cursor.to_point(&buffer);
 7585                    Selection {
 7586                        id,
 7587                        start: cursor,
 7588                        end: cursor,
 7589                        reversed: false,
 7590                        goal: SelectionGoal::None,
 7591                    }
 7592                })
 7593                .collect();
 7594
 7595            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7596                s.select(new_selections);
 7597            });
 7598        });
 7599    }
 7600
 7601    pub fn join_lines_impl(
 7602        &mut self,
 7603        insert_whitespace: bool,
 7604        window: &mut Window,
 7605        cx: &mut Context<Self>,
 7606    ) {
 7607        if self.read_only(cx) {
 7608            return;
 7609        }
 7610        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 7611        for selection in self.selections.all::<Point>(cx) {
 7612            let start = MultiBufferRow(selection.start.row);
 7613            // Treat single line selections as if they include the next line. Otherwise this action
 7614            // would do nothing for single line selections individual cursors.
 7615            let end = if selection.start.row == selection.end.row {
 7616                MultiBufferRow(selection.start.row + 1)
 7617            } else {
 7618                MultiBufferRow(selection.end.row)
 7619            };
 7620
 7621            if let Some(last_row_range) = row_ranges.last_mut() {
 7622                if start <= last_row_range.end {
 7623                    last_row_range.end = end;
 7624                    continue;
 7625                }
 7626            }
 7627            row_ranges.push(start..end);
 7628        }
 7629
 7630        let snapshot = self.buffer.read(cx).snapshot(cx);
 7631        let mut cursor_positions = Vec::new();
 7632        for row_range in &row_ranges {
 7633            let anchor = snapshot.anchor_before(Point::new(
 7634                row_range.end.previous_row().0,
 7635                snapshot.line_len(row_range.end.previous_row()),
 7636            ));
 7637            cursor_positions.push(anchor..anchor);
 7638        }
 7639
 7640        self.transact(window, cx, |this, window, cx| {
 7641            for row_range in row_ranges.into_iter().rev() {
 7642                for row in row_range.iter_rows().rev() {
 7643                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 7644                    let next_line_row = row.next_row();
 7645                    let indent = snapshot.indent_size_for_line(next_line_row);
 7646                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7647
 7648                    let replace =
 7649                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7650                            " "
 7651                        } else {
 7652                            ""
 7653                        };
 7654
 7655                    this.buffer.update(cx, |buffer, cx| {
 7656                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7657                    });
 7658                }
 7659            }
 7660
 7661            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7662                s.select_anchor_ranges(cursor_positions)
 7663            });
 7664        });
 7665    }
 7666
 7667    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7668        self.join_lines_impl(true, window, cx);
 7669    }
 7670
 7671    pub fn sort_lines_case_sensitive(
 7672        &mut self,
 7673        _: &SortLinesCaseSensitive,
 7674        window: &mut Window,
 7675        cx: &mut Context<Self>,
 7676    ) {
 7677        self.manipulate_lines(window, cx, |lines| lines.sort())
 7678    }
 7679
 7680    pub fn sort_lines_case_insensitive(
 7681        &mut self,
 7682        _: &SortLinesCaseInsensitive,
 7683        window: &mut Window,
 7684        cx: &mut Context<Self>,
 7685    ) {
 7686        self.manipulate_lines(window, cx, |lines| {
 7687            lines.sort_by_key(|line| line.to_lowercase())
 7688        })
 7689    }
 7690
 7691    pub fn unique_lines_case_insensitive(
 7692        &mut self,
 7693        _: &UniqueLinesCaseInsensitive,
 7694        window: &mut Window,
 7695        cx: &mut Context<Self>,
 7696    ) {
 7697        self.manipulate_lines(window, cx, |lines| {
 7698            let mut seen = HashSet::default();
 7699            lines.retain(|line| seen.insert(line.to_lowercase()));
 7700        })
 7701    }
 7702
 7703    pub fn unique_lines_case_sensitive(
 7704        &mut self,
 7705        _: &UniqueLinesCaseSensitive,
 7706        window: &mut Window,
 7707        cx: &mut Context<Self>,
 7708    ) {
 7709        self.manipulate_lines(window, cx, |lines| {
 7710            let mut seen = HashSet::default();
 7711            lines.retain(|line| seen.insert(*line));
 7712        })
 7713    }
 7714
 7715    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7716        let Some(project) = self.project.clone() else {
 7717            return;
 7718        };
 7719        self.reload(project, window, cx)
 7720            .detach_and_notify_err(window, cx);
 7721    }
 7722
 7723    pub fn restore_file(
 7724        &mut self,
 7725        _: &::git::RestoreFile,
 7726        window: &mut Window,
 7727        cx: &mut Context<Self>,
 7728    ) {
 7729        let mut buffer_ids = HashSet::default();
 7730        let snapshot = self.buffer().read(cx).snapshot(cx);
 7731        for selection in self.selections.all::<usize>(cx) {
 7732            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 7733        }
 7734
 7735        let buffer = self.buffer().read(cx);
 7736        let ranges = buffer_ids
 7737            .into_iter()
 7738            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 7739            .collect::<Vec<_>>();
 7740
 7741        self.restore_hunks_in_ranges(ranges, window, cx);
 7742    }
 7743
 7744    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 7745        let selections = self
 7746            .selections
 7747            .all(cx)
 7748            .into_iter()
 7749            .map(|s| s.range())
 7750            .collect();
 7751        self.restore_hunks_in_ranges(selections, window, cx);
 7752    }
 7753
 7754    fn restore_hunks_in_ranges(
 7755        &mut self,
 7756        ranges: Vec<Range<Point>>,
 7757        window: &mut Window,
 7758        cx: &mut Context<Editor>,
 7759    ) {
 7760        let mut revert_changes = HashMap::default();
 7761        let chunk_by = self
 7762            .snapshot(window, cx)
 7763            .hunks_for_ranges(ranges)
 7764            .into_iter()
 7765            .chunk_by(|hunk| hunk.buffer_id);
 7766        for (buffer_id, hunks) in &chunk_by {
 7767            let hunks = hunks.collect::<Vec<_>>();
 7768            for hunk in &hunks {
 7769                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 7770            }
 7771            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), window, cx);
 7772        }
 7773        drop(chunk_by);
 7774        if !revert_changes.is_empty() {
 7775            self.transact(window, cx, |editor, window, cx| {
 7776                editor.restore(revert_changes, window, cx);
 7777            });
 7778        }
 7779    }
 7780
 7781    pub fn open_active_item_in_terminal(
 7782        &mut self,
 7783        _: &OpenInTerminal,
 7784        window: &mut Window,
 7785        cx: &mut Context<Self>,
 7786    ) {
 7787        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7788            let project_path = buffer.read(cx).project_path(cx)?;
 7789            let project = self.project.as_ref()?.read(cx);
 7790            let entry = project.entry_for_path(&project_path, cx)?;
 7791            let parent = match &entry.canonical_path {
 7792                Some(canonical_path) => canonical_path.to_path_buf(),
 7793                None => project.absolute_path(&project_path, cx)?,
 7794            }
 7795            .parent()?
 7796            .to_path_buf();
 7797            Some(parent)
 7798        }) {
 7799            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7800        }
 7801    }
 7802
 7803    pub fn prepare_restore_change(
 7804        &self,
 7805        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7806        hunk: &MultiBufferDiffHunk,
 7807        cx: &mut App,
 7808    ) -> Option<()> {
 7809        let buffer = self.buffer.read(cx);
 7810        let diff = buffer.diff_for(hunk.buffer_id)?;
 7811        let buffer = buffer.buffer(hunk.buffer_id)?;
 7812        let buffer = buffer.read(cx);
 7813        let original_text = diff
 7814            .read(cx)
 7815            .base_text()
 7816            .as_rope()
 7817            .slice(hunk.diff_base_byte_range.clone());
 7818        let buffer_snapshot = buffer.snapshot();
 7819        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7820        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7821            probe
 7822                .0
 7823                .start
 7824                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7825                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7826        }) {
 7827            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7828            Some(())
 7829        } else {
 7830            None
 7831        }
 7832    }
 7833
 7834    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7835        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7836    }
 7837
 7838    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7839        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7840    }
 7841
 7842    fn manipulate_lines<Fn>(
 7843        &mut self,
 7844        window: &mut Window,
 7845        cx: &mut Context<Self>,
 7846        mut callback: Fn,
 7847    ) where
 7848        Fn: FnMut(&mut Vec<&str>),
 7849    {
 7850        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7851        let buffer = self.buffer.read(cx).snapshot(cx);
 7852
 7853        let mut edits = Vec::new();
 7854
 7855        let selections = self.selections.all::<Point>(cx);
 7856        let mut selections = selections.iter().peekable();
 7857        let mut contiguous_row_selections = Vec::new();
 7858        let mut new_selections = Vec::new();
 7859        let mut added_lines = 0;
 7860        let mut removed_lines = 0;
 7861
 7862        while let Some(selection) = selections.next() {
 7863            let (start_row, end_row) = consume_contiguous_rows(
 7864                &mut contiguous_row_selections,
 7865                selection,
 7866                &display_map,
 7867                &mut selections,
 7868            );
 7869
 7870            let start_point = Point::new(start_row.0, 0);
 7871            let end_point = Point::new(
 7872                end_row.previous_row().0,
 7873                buffer.line_len(end_row.previous_row()),
 7874            );
 7875            let text = buffer
 7876                .text_for_range(start_point..end_point)
 7877                .collect::<String>();
 7878
 7879            let mut lines = text.split('\n').collect_vec();
 7880
 7881            let lines_before = lines.len();
 7882            callback(&mut lines);
 7883            let lines_after = lines.len();
 7884
 7885            edits.push((start_point..end_point, lines.join("\n")));
 7886
 7887            // Selections must change based on added and removed line count
 7888            let start_row =
 7889                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7890            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7891            new_selections.push(Selection {
 7892                id: selection.id,
 7893                start: start_row,
 7894                end: end_row,
 7895                goal: SelectionGoal::None,
 7896                reversed: selection.reversed,
 7897            });
 7898
 7899            if lines_after > lines_before {
 7900                added_lines += lines_after - lines_before;
 7901            } else if lines_before > lines_after {
 7902                removed_lines += lines_before - lines_after;
 7903            }
 7904        }
 7905
 7906        self.transact(window, cx, |this, window, cx| {
 7907            let buffer = this.buffer.update(cx, |buffer, cx| {
 7908                buffer.edit(edits, None, cx);
 7909                buffer.snapshot(cx)
 7910            });
 7911
 7912            // Recalculate offsets on newly edited buffer
 7913            let new_selections = new_selections
 7914                .iter()
 7915                .map(|s| {
 7916                    let start_point = Point::new(s.start.0, 0);
 7917                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7918                    Selection {
 7919                        id: s.id,
 7920                        start: buffer.point_to_offset(start_point),
 7921                        end: buffer.point_to_offset(end_point),
 7922                        goal: s.goal,
 7923                        reversed: s.reversed,
 7924                    }
 7925                })
 7926                .collect();
 7927
 7928            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7929                s.select(new_selections);
 7930            });
 7931
 7932            this.request_autoscroll(Autoscroll::fit(), cx);
 7933        });
 7934    }
 7935
 7936    pub fn convert_to_upper_case(
 7937        &mut self,
 7938        _: &ConvertToUpperCase,
 7939        window: &mut Window,
 7940        cx: &mut Context<Self>,
 7941    ) {
 7942        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7943    }
 7944
 7945    pub fn convert_to_lower_case(
 7946        &mut self,
 7947        _: &ConvertToLowerCase,
 7948        window: &mut Window,
 7949        cx: &mut Context<Self>,
 7950    ) {
 7951        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7952    }
 7953
 7954    pub fn convert_to_title_case(
 7955        &mut self,
 7956        _: &ConvertToTitleCase,
 7957        window: &mut Window,
 7958        cx: &mut Context<Self>,
 7959    ) {
 7960        self.manipulate_text(window, cx, |text| {
 7961            text.split('\n')
 7962                .map(|line| line.to_case(Case::Title))
 7963                .join("\n")
 7964        })
 7965    }
 7966
 7967    pub fn convert_to_snake_case(
 7968        &mut self,
 7969        _: &ConvertToSnakeCase,
 7970        window: &mut Window,
 7971        cx: &mut Context<Self>,
 7972    ) {
 7973        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7974    }
 7975
 7976    pub fn convert_to_kebab_case(
 7977        &mut self,
 7978        _: &ConvertToKebabCase,
 7979        window: &mut Window,
 7980        cx: &mut Context<Self>,
 7981    ) {
 7982        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7983    }
 7984
 7985    pub fn convert_to_upper_camel_case(
 7986        &mut self,
 7987        _: &ConvertToUpperCamelCase,
 7988        window: &mut Window,
 7989        cx: &mut Context<Self>,
 7990    ) {
 7991        self.manipulate_text(window, cx, |text| {
 7992            text.split('\n')
 7993                .map(|line| line.to_case(Case::UpperCamel))
 7994                .join("\n")
 7995        })
 7996    }
 7997
 7998    pub fn convert_to_lower_camel_case(
 7999        &mut self,
 8000        _: &ConvertToLowerCamelCase,
 8001        window: &mut Window,
 8002        cx: &mut Context<Self>,
 8003    ) {
 8004        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 8005    }
 8006
 8007    pub fn convert_to_opposite_case(
 8008        &mut self,
 8009        _: &ConvertToOppositeCase,
 8010        window: &mut Window,
 8011        cx: &mut Context<Self>,
 8012    ) {
 8013        self.manipulate_text(window, cx, |text| {
 8014            text.chars()
 8015                .fold(String::with_capacity(text.len()), |mut t, c| {
 8016                    if c.is_uppercase() {
 8017                        t.extend(c.to_lowercase());
 8018                    } else {
 8019                        t.extend(c.to_uppercase());
 8020                    }
 8021                    t
 8022                })
 8023        })
 8024    }
 8025
 8026    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 8027    where
 8028        Fn: FnMut(&str) -> String,
 8029    {
 8030        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8031        let buffer = self.buffer.read(cx).snapshot(cx);
 8032
 8033        let mut new_selections = Vec::new();
 8034        let mut edits = Vec::new();
 8035        let mut selection_adjustment = 0i32;
 8036
 8037        for selection in self.selections.all::<usize>(cx) {
 8038            let selection_is_empty = selection.is_empty();
 8039
 8040            let (start, end) = if selection_is_empty {
 8041                let word_range = movement::surrounding_word(
 8042                    &display_map,
 8043                    selection.start.to_display_point(&display_map),
 8044                );
 8045                let start = word_range.start.to_offset(&display_map, Bias::Left);
 8046                let end = word_range.end.to_offset(&display_map, Bias::Left);
 8047                (start, end)
 8048            } else {
 8049                (selection.start, selection.end)
 8050            };
 8051
 8052            let text = buffer.text_for_range(start..end).collect::<String>();
 8053            let old_length = text.len() as i32;
 8054            let text = callback(&text);
 8055
 8056            new_selections.push(Selection {
 8057                start: (start as i32 - selection_adjustment) as usize,
 8058                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 8059                goal: SelectionGoal::None,
 8060                ..selection
 8061            });
 8062
 8063            selection_adjustment += old_length - text.len() as i32;
 8064
 8065            edits.push((start..end, text));
 8066        }
 8067
 8068        self.transact(window, cx, |this, window, cx| {
 8069            this.buffer.update(cx, |buffer, cx| {
 8070                buffer.edit(edits, None, cx);
 8071            });
 8072
 8073            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8074                s.select(new_selections);
 8075            });
 8076
 8077            this.request_autoscroll(Autoscroll::fit(), cx);
 8078        });
 8079    }
 8080
 8081    pub fn duplicate(
 8082        &mut self,
 8083        upwards: bool,
 8084        whole_lines: bool,
 8085        window: &mut Window,
 8086        cx: &mut Context<Self>,
 8087    ) {
 8088        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8089        let buffer = &display_map.buffer_snapshot;
 8090        let selections = self.selections.all::<Point>(cx);
 8091
 8092        let mut edits = Vec::new();
 8093        let mut selections_iter = selections.iter().peekable();
 8094        while let Some(selection) = selections_iter.next() {
 8095            let mut rows = selection.spanned_rows(false, &display_map);
 8096            // duplicate line-wise
 8097            if whole_lines || selection.start == selection.end {
 8098                // Avoid duplicating the same lines twice.
 8099                while let Some(next_selection) = selections_iter.peek() {
 8100                    let next_rows = next_selection.spanned_rows(false, &display_map);
 8101                    if next_rows.start < rows.end {
 8102                        rows.end = next_rows.end;
 8103                        selections_iter.next().unwrap();
 8104                    } else {
 8105                        break;
 8106                    }
 8107                }
 8108
 8109                // Copy the text from the selected row region and splice it either at the start
 8110                // or end of the region.
 8111                let start = Point::new(rows.start.0, 0);
 8112                let end = Point::new(
 8113                    rows.end.previous_row().0,
 8114                    buffer.line_len(rows.end.previous_row()),
 8115                );
 8116                let text = buffer
 8117                    .text_for_range(start..end)
 8118                    .chain(Some("\n"))
 8119                    .collect::<String>();
 8120                let insert_location = if upwards {
 8121                    Point::new(rows.end.0, 0)
 8122                } else {
 8123                    start
 8124                };
 8125                edits.push((insert_location..insert_location, text));
 8126            } else {
 8127                // duplicate character-wise
 8128                let start = selection.start;
 8129                let end = selection.end;
 8130                let text = buffer.text_for_range(start..end).collect::<String>();
 8131                edits.push((selection.end..selection.end, text));
 8132            }
 8133        }
 8134
 8135        self.transact(window, cx, |this, _, cx| {
 8136            this.buffer.update(cx, |buffer, cx| {
 8137                buffer.edit(edits, None, cx);
 8138            });
 8139
 8140            this.request_autoscroll(Autoscroll::fit(), cx);
 8141        });
 8142    }
 8143
 8144    pub fn duplicate_line_up(
 8145        &mut self,
 8146        _: &DuplicateLineUp,
 8147        window: &mut Window,
 8148        cx: &mut Context<Self>,
 8149    ) {
 8150        self.duplicate(true, true, window, cx);
 8151    }
 8152
 8153    pub fn duplicate_line_down(
 8154        &mut self,
 8155        _: &DuplicateLineDown,
 8156        window: &mut Window,
 8157        cx: &mut Context<Self>,
 8158    ) {
 8159        self.duplicate(false, true, window, cx);
 8160    }
 8161
 8162    pub fn duplicate_selection(
 8163        &mut self,
 8164        _: &DuplicateSelection,
 8165        window: &mut Window,
 8166        cx: &mut Context<Self>,
 8167    ) {
 8168        self.duplicate(false, false, window, cx);
 8169    }
 8170
 8171    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 8172        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8173        let buffer = self.buffer.read(cx).snapshot(cx);
 8174
 8175        let mut edits = Vec::new();
 8176        let mut unfold_ranges = Vec::new();
 8177        let mut refold_creases = Vec::new();
 8178
 8179        let selections = self.selections.all::<Point>(cx);
 8180        let mut selections = selections.iter().peekable();
 8181        let mut contiguous_row_selections = Vec::new();
 8182        let mut new_selections = Vec::new();
 8183
 8184        while let Some(selection) = selections.next() {
 8185            // Find all the selections that span a contiguous row range
 8186            let (start_row, end_row) = consume_contiguous_rows(
 8187                &mut contiguous_row_selections,
 8188                selection,
 8189                &display_map,
 8190                &mut selections,
 8191            );
 8192
 8193            // Move the text spanned by the row range to be before the line preceding the row range
 8194            if start_row.0 > 0 {
 8195                let range_to_move = Point::new(
 8196                    start_row.previous_row().0,
 8197                    buffer.line_len(start_row.previous_row()),
 8198                )
 8199                    ..Point::new(
 8200                        end_row.previous_row().0,
 8201                        buffer.line_len(end_row.previous_row()),
 8202                    );
 8203                let insertion_point = display_map
 8204                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 8205                    .0;
 8206
 8207                // Don't move lines across excerpts
 8208                if buffer
 8209                    .excerpt_containing(insertion_point..range_to_move.end)
 8210                    .is_some()
 8211                {
 8212                    let text = buffer
 8213                        .text_for_range(range_to_move.clone())
 8214                        .flat_map(|s| s.chars())
 8215                        .skip(1)
 8216                        .chain(['\n'])
 8217                        .collect::<String>();
 8218
 8219                    edits.push((
 8220                        buffer.anchor_after(range_to_move.start)
 8221                            ..buffer.anchor_before(range_to_move.end),
 8222                        String::new(),
 8223                    ));
 8224                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8225                    edits.push((insertion_anchor..insertion_anchor, text));
 8226
 8227                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 8228
 8229                    // Move selections up
 8230                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8231                        |mut selection| {
 8232                            selection.start.row -= row_delta;
 8233                            selection.end.row -= row_delta;
 8234                            selection
 8235                        },
 8236                    ));
 8237
 8238                    // Move folds up
 8239                    unfold_ranges.push(range_to_move.clone());
 8240                    for fold in display_map.folds_in_range(
 8241                        buffer.anchor_before(range_to_move.start)
 8242                            ..buffer.anchor_after(range_to_move.end),
 8243                    ) {
 8244                        let mut start = fold.range.start.to_point(&buffer);
 8245                        let mut end = fold.range.end.to_point(&buffer);
 8246                        start.row -= row_delta;
 8247                        end.row -= row_delta;
 8248                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8249                    }
 8250                }
 8251            }
 8252
 8253            // If we didn't move line(s), preserve the existing selections
 8254            new_selections.append(&mut contiguous_row_selections);
 8255        }
 8256
 8257        self.transact(window, cx, |this, window, cx| {
 8258            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8259            this.buffer.update(cx, |buffer, cx| {
 8260                for (range, text) in edits {
 8261                    buffer.edit([(range, text)], None, cx);
 8262                }
 8263            });
 8264            this.fold_creases(refold_creases, true, window, cx);
 8265            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8266                s.select(new_selections);
 8267            })
 8268        });
 8269    }
 8270
 8271    pub fn move_line_down(
 8272        &mut self,
 8273        _: &MoveLineDown,
 8274        window: &mut Window,
 8275        cx: &mut Context<Self>,
 8276    ) {
 8277        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8278        let buffer = self.buffer.read(cx).snapshot(cx);
 8279
 8280        let mut edits = Vec::new();
 8281        let mut unfold_ranges = Vec::new();
 8282        let mut refold_creases = Vec::new();
 8283
 8284        let selections = self.selections.all::<Point>(cx);
 8285        let mut selections = selections.iter().peekable();
 8286        let mut contiguous_row_selections = Vec::new();
 8287        let mut new_selections = Vec::new();
 8288
 8289        while let Some(selection) = selections.next() {
 8290            // Find all the selections that span a contiguous row range
 8291            let (start_row, end_row) = consume_contiguous_rows(
 8292                &mut contiguous_row_selections,
 8293                selection,
 8294                &display_map,
 8295                &mut selections,
 8296            );
 8297
 8298            // Move the text spanned by the row range to be after the last line of the row range
 8299            if end_row.0 <= buffer.max_point().row {
 8300                let range_to_move =
 8301                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 8302                let insertion_point = display_map
 8303                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 8304                    .0;
 8305
 8306                // Don't move lines across excerpt boundaries
 8307                if buffer
 8308                    .excerpt_containing(range_to_move.start..insertion_point)
 8309                    .is_some()
 8310                {
 8311                    let mut text = String::from("\n");
 8312                    text.extend(buffer.text_for_range(range_to_move.clone()));
 8313                    text.pop(); // Drop trailing newline
 8314                    edits.push((
 8315                        buffer.anchor_after(range_to_move.start)
 8316                            ..buffer.anchor_before(range_to_move.end),
 8317                        String::new(),
 8318                    ));
 8319                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8320                    edits.push((insertion_anchor..insertion_anchor, text));
 8321
 8322                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 8323
 8324                    // Move selections down
 8325                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8326                        |mut selection| {
 8327                            selection.start.row += row_delta;
 8328                            selection.end.row += row_delta;
 8329                            selection
 8330                        },
 8331                    ));
 8332
 8333                    // Move folds down
 8334                    unfold_ranges.push(range_to_move.clone());
 8335                    for fold in display_map.folds_in_range(
 8336                        buffer.anchor_before(range_to_move.start)
 8337                            ..buffer.anchor_after(range_to_move.end),
 8338                    ) {
 8339                        let mut start = fold.range.start.to_point(&buffer);
 8340                        let mut end = fold.range.end.to_point(&buffer);
 8341                        start.row += row_delta;
 8342                        end.row += row_delta;
 8343                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8344                    }
 8345                }
 8346            }
 8347
 8348            // If we didn't move line(s), preserve the existing selections
 8349            new_selections.append(&mut contiguous_row_selections);
 8350        }
 8351
 8352        self.transact(window, cx, |this, window, cx| {
 8353            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8354            this.buffer.update(cx, |buffer, cx| {
 8355                for (range, text) in edits {
 8356                    buffer.edit([(range, text)], None, cx);
 8357                }
 8358            });
 8359            this.fold_creases(refold_creases, true, window, cx);
 8360            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8361                s.select(new_selections)
 8362            });
 8363        });
 8364    }
 8365
 8366    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 8367        let text_layout_details = &self.text_layout_details(window);
 8368        self.transact(window, cx, |this, window, cx| {
 8369            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8370                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 8371                let line_mode = s.line_mode;
 8372                s.move_with(|display_map, selection| {
 8373                    if !selection.is_empty() || line_mode {
 8374                        return;
 8375                    }
 8376
 8377                    let mut head = selection.head();
 8378                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 8379                    if head.column() == display_map.line_len(head.row()) {
 8380                        transpose_offset = display_map
 8381                            .buffer_snapshot
 8382                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8383                    }
 8384
 8385                    if transpose_offset == 0 {
 8386                        return;
 8387                    }
 8388
 8389                    *head.column_mut() += 1;
 8390                    head = display_map.clip_point(head, Bias::Right);
 8391                    let goal = SelectionGoal::HorizontalPosition(
 8392                        display_map
 8393                            .x_for_display_point(head, text_layout_details)
 8394                            .into(),
 8395                    );
 8396                    selection.collapse_to(head, goal);
 8397
 8398                    let transpose_start = display_map
 8399                        .buffer_snapshot
 8400                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8401                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 8402                        let transpose_end = display_map
 8403                            .buffer_snapshot
 8404                            .clip_offset(transpose_offset + 1, Bias::Right);
 8405                        if let Some(ch) =
 8406                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 8407                        {
 8408                            edits.push((transpose_start..transpose_offset, String::new()));
 8409                            edits.push((transpose_end..transpose_end, ch.to_string()));
 8410                        }
 8411                    }
 8412                });
 8413                edits
 8414            });
 8415            this.buffer
 8416                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8417            let selections = this.selections.all::<usize>(cx);
 8418            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8419                s.select(selections);
 8420            });
 8421        });
 8422    }
 8423
 8424    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 8425        self.rewrap_impl(IsVimMode::No, cx)
 8426    }
 8427
 8428    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 8429        let buffer = self.buffer.read(cx).snapshot(cx);
 8430        let selections = self.selections.all::<Point>(cx);
 8431        let mut selections = selections.iter().peekable();
 8432
 8433        let mut edits = Vec::new();
 8434        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 8435
 8436        while let Some(selection) = selections.next() {
 8437            let mut start_row = selection.start.row;
 8438            let mut end_row = selection.end.row;
 8439
 8440            // Skip selections that overlap with a range that has already been rewrapped.
 8441            let selection_range = start_row..end_row;
 8442            if rewrapped_row_ranges
 8443                .iter()
 8444                .any(|range| range.overlaps(&selection_range))
 8445            {
 8446                continue;
 8447            }
 8448
 8449            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 8450
 8451            // Since not all lines in the selection may be at the same indent
 8452            // level, choose the indent size that is the most common between all
 8453            // of the lines.
 8454            //
 8455            // If there is a tie, we use the deepest indent.
 8456            let (indent_size, indent_end) = {
 8457                let mut indent_size_occurrences = HashMap::default();
 8458                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 8459
 8460                for row in start_row..=end_row {
 8461                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 8462                    rows_by_indent_size.entry(indent).or_default().push(row);
 8463                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 8464                }
 8465
 8466                let indent_size = indent_size_occurrences
 8467                    .into_iter()
 8468                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 8469                    .map(|(indent, _)| indent)
 8470                    .unwrap_or_default();
 8471                let row = rows_by_indent_size[&indent_size][0];
 8472                let indent_end = Point::new(row, indent_size.len);
 8473
 8474                (indent_size, indent_end)
 8475            };
 8476
 8477            let mut line_prefix = indent_size.chars().collect::<String>();
 8478
 8479            let mut inside_comment = false;
 8480            if let Some(comment_prefix) =
 8481                buffer
 8482                    .language_scope_at(selection.head())
 8483                    .and_then(|language| {
 8484                        language
 8485                            .line_comment_prefixes()
 8486                            .iter()
 8487                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 8488                            .cloned()
 8489                    })
 8490            {
 8491                line_prefix.push_str(&comment_prefix);
 8492                inside_comment = true;
 8493            }
 8494
 8495            let language_settings = buffer.settings_at(selection.head(), cx);
 8496            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 8497                RewrapBehavior::InComments => inside_comment,
 8498                RewrapBehavior::InSelections => !selection.is_empty(),
 8499                RewrapBehavior::Anywhere => true,
 8500            };
 8501
 8502            let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
 8503            if !should_rewrap {
 8504                continue;
 8505            }
 8506
 8507            if selection.is_empty() {
 8508                'expand_upwards: while start_row > 0 {
 8509                    let prev_row = start_row - 1;
 8510                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 8511                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 8512                    {
 8513                        start_row = prev_row;
 8514                    } else {
 8515                        break 'expand_upwards;
 8516                    }
 8517                }
 8518
 8519                'expand_downwards: while end_row < buffer.max_point().row {
 8520                    let next_row = end_row + 1;
 8521                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 8522                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 8523                    {
 8524                        end_row = next_row;
 8525                    } else {
 8526                        break 'expand_downwards;
 8527                    }
 8528                }
 8529            }
 8530
 8531            let start = Point::new(start_row, 0);
 8532            let start_offset = start.to_offset(&buffer);
 8533            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 8534            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 8535            let Some(lines_without_prefixes) = selection_text
 8536                .lines()
 8537                .map(|line| {
 8538                    line.strip_prefix(&line_prefix)
 8539                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 8540                        .ok_or_else(|| {
 8541                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 8542                        })
 8543                })
 8544                .collect::<Result<Vec<_>, _>>()
 8545                .log_err()
 8546            else {
 8547                continue;
 8548            };
 8549
 8550            let wrap_column = buffer
 8551                .settings_at(Point::new(start_row, 0), cx)
 8552                .preferred_line_length as usize;
 8553            let wrapped_text = wrap_with_prefix(
 8554                line_prefix,
 8555                lines_without_prefixes.join(" "),
 8556                wrap_column,
 8557                tab_size,
 8558            );
 8559
 8560            // TODO: should always use char-based diff while still supporting cursor behavior that
 8561            // matches vim.
 8562            let mut diff_options = DiffOptions::default();
 8563            if is_vim_mode == IsVimMode::Yes {
 8564                diff_options.max_word_diff_len = 0;
 8565                diff_options.max_word_diff_line_count = 0;
 8566            } else {
 8567                diff_options.max_word_diff_len = usize::MAX;
 8568                diff_options.max_word_diff_line_count = usize::MAX;
 8569            }
 8570
 8571            for (old_range, new_text) in
 8572                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 8573            {
 8574                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 8575                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 8576                edits.push((edit_start..edit_end, new_text));
 8577            }
 8578
 8579            rewrapped_row_ranges.push(start_row..=end_row);
 8580        }
 8581
 8582        self.buffer
 8583            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8584    }
 8585
 8586    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 8587        let mut text = String::new();
 8588        let buffer = self.buffer.read(cx).snapshot(cx);
 8589        let mut selections = self.selections.all::<Point>(cx);
 8590        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8591        {
 8592            let max_point = buffer.max_point();
 8593            let mut is_first = true;
 8594            for selection in &mut selections {
 8595                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8596                if is_entire_line {
 8597                    selection.start = Point::new(selection.start.row, 0);
 8598                    if !selection.is_empty() && selection.end.column == 0 {
 8599                        selection.end = cmp::min(max_point, selection.end);
 8600                    } else {
 8601                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 8602                    }
 8603                    selection.goal = SelectionGoal::None;
 8604                }
 8605                if is_first {
 8606                    is_first = false;
 8607                } else {
 8608                    text += "\n";
 8609                }
 8610                let mut len = 0;
 8611                for chunk in buffer.text_for_range(selection.start..selection.end) {
 8612                    text.push_str(chunk);
 8613                    len += chunk.len();
 8614                }
 8615                clipboard_selections.push(ClipboardSelection {
 8616                    len,
 8617                    is_entire_line,
 8618                    start_column: selection.start.column,
 8619                });
 8620            }
 8621        }
 8622
 8623        self.transact(window, cx, |this, window, cx| {
 8624            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8625                s.select(selections);
 8626            });
 8627            this.insert("", window, cx);
 8628        });
 8629        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 8630    }
 8631
 8632    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8633        let item = self.cut_common(window, cx);
 8634        cx.write_to_clipboard(item);
 8635    }
 8636
 8637    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8638        self.change_selections(None, window, cx, |s| {
 8639            s.move_with(|snapshot, sel| {
 8640                if sel.is_empty() {
 8641                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8642                }
 8643            });
 8644        });
 8645        let item = self.cut_common(window, cx);
 8646        cx.set_global(KillRing(item))
 8647    }
 8648
 8649    pub fn kill_ring_yank(
 8650        &mut self,
 8651        _: &KillRingYank,
 8652        window: &mut Window,
 8653        cx: &mut Context<Self>,
 8654    ) {
 8655        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8656            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8657                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8658            } else {
 8659                return;
 8660            }
 8661        } else {
 8662            return;
 8663        };
 8664        self.do_paste(&text, metadata, false, window, cx);
 8665    }
 8666
 8667    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8668        let selections = self.selections.all::<Point>(cx);
 8669        let buffer = self.buffer.read(cx).read(cx);
 8670        let mut text = String::new();
 8671
 8672        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8673        {
 8674            let max_point = buffer.max_point();
 8675            let mut is_first = true;
 8676            for selection in selections.iter() {
 8677                let mut start = selection.start;
 8678                let mut end = selection.end;
 8679                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8680                if is_entire_line {
 8681                    start = Point::new(start.row, 0);
 8682                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8683                }
 8684                if is_first {
 8685                    is_first = false;
 8686                } else {
 8687                    text += "\n";
 8688                }
 8689                let mut len = 0;
 8690                for chunk in buffer.text_for_range(start..end) {
 8691                    text.push_str(chunk);
 8692                    len += chunk.len();
 8693                }
 8694                clipboard_selections.push(ClipboardSelection {
 8695                    len,
 8696                    is_entire_line,
 8697                    start_column: start.column,
 8698                });
 8699            }
 8700        }
 8701
 8702        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8703            text,
 8704            clipboard_selections,
 8705        ));
 8706    }
 8707
 8708    pub fn do_paste(
 8709        &mut self,
 8710        text: &String,
 8711        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8712        handle_entire_lines: bool,
 8713        window: &mut Window,
 8714        cx: &mut Context<Self>,
 8715    ) {
 8716        if self.read_only(cx) {
 8717            return;
 8718        }
 8719
 8720        let clipboard_text = Cow::Borrowed(text);
 8721
 8722        self.transact(window, cx, |this, window, cx| {
 8723            if let Some(mut clipboard_selections) = clipboard_selections {
 8724                let old_selections = this.selections.all::<usize>(cx);
 8725                let all_selections_were_entire_line =
 8726                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8727                let first_selection_start_column =
 8728                    clipboard_selections.first().map(|s| s.start_column);
 8729                if clipboard_selections.len() != old_selections.len() {
 8730                    clipboard_selections.drain(..);
 8731                }
 8732                let cursor_offset = this.selections.last::<usize>(cx).head();
 8733                let mut auto_indent_on_paste = true;
 8734
 8735                this.buffer.update(cx, |buffer, cx| {
 8736                    let snapshot = buffer.read(cx);
 8737                    auto_indent_on_paste =
 8738                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 8739
 8740                    let mut start_offset = 0;
 8741                    let mut edits = Vec::new();
 8742                    let mut original_start_columns = Vec::new();
 8743                    for (ix, selection) in old_selections.iter().enumerate() {
 8744                        let to_insert;
 8745                        let entire_line;
 8746                        let original_start_column;
 8747                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8748                            let end_offset = start_offset + clipboard_selection.len;
 8749                            to_insert = &clipboard_text[start_offset..end_offset];
 8750                            entire_line = clipboard_selection.is_entire_line;
 8751                            start_offset = end_offset + 1;
 8752                            original_start_column = Some(clipboard_selection.start_column);
 8753                        } else {
 8754                            to_insert = clipboard_text.as_str();
 8755                            entire_line = all_selections_were_entire_line;
 8756                            original_start_column = first_selection_start_column
 8757                        }
 8758
 8759                        // If the corresponding selection was empty when this slice of the
 8760                        // clipboard text was written, then the entire line containing the
 8761                        // selection was copied. If this selection is also currently empty,
 8762                        // then paste the line before the current line of the buffer.
 8763                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8764                            let column = selection.start.to_point(&snapshot).column as usize;
 8765                            let line_start = selection.start - column;
 8766                            line_start..line_start
 8767                        } else {
 8768                            selection.range()
 8769                        };
 8770
 8771                        edits.push((range, to_insert));
 8772                        original_start_columns.extend(original_start_column);
 8773                    }
 8774                    drop(snapshot);
 8775
 8776                    buffer.edit(
 8777                        edits,
 8778                        if auto_indent_on_paste {
 8779                            Some(AutoindentMode::Block {
 8780                                original_start_columns,
 8781                            })
 8782                        } else {
 8783                            None
 8784                        },
 8785                        cx,
 8786                    );
 8787                });
 8788
 8789                let selections = this.selections.all::<usize>(cx);
 8790                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8791                    s.select(selections)
 8792                });
 8793            } else {
 8794                this.insert(&clipboard_text, window, cx);
 8795            }
 8796        });
 8797    }
 8798
 8799    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8800        if let Some(item) = cx.read_from_clipboard() {
 8801            let entries = item.entries();
 8802
 8803            match entries.first() {
 8804                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8805                // of all the pasted entries.
 8806                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8807                    .do_paste(
 8808                        clipboard_string.text(),
 8809                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8810                        true,
 8811                        window,
 8812                        cx,
 8813                    ),
 8814                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8815            }
 8816        }
 8817    }
 8818
 8819    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8820        if self.read_only(cx) {
 8821            return;
 8822        }
 8823
 8824        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8825            if let Some((selections, _)) =
 8826                self.selection_history.transaction(transaction_id).cloned()
 8827            {
 8828                self.change_selections(None, window, cx, |s| {
 8829                    s.select_anchors(selections.to_vec());
 8830                });
 8831            } else {
 8832                log::error!(
 8833                    "No entry in selection_history found for undo. \
 8834                     This may correspond to a bug where undo does not update the selection. \
 8835                     If this is occurring, please add details to \
 8836                     https://github.com/zed-industries/zed/issues/22692"
 8837                );
 8838            }
 8839            self.request_autoscroll(Autoscroll::fit(), cx);
 8840            self.unmark_text(window, cx);
 8841            self.refresh_inline_completion(true, false, window, cx);
 8842            cx.emit(EditorEvent::Edited { transaction_id });
 8843            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8844        }
 8845    }
 8846
 8847    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8848        if self.read_only(cx) {
 8849            return;
 8850        }
 8851
 8852        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8853            if let Some((_, Some(selections))) =
 8854                self.selection_history.transaction(transaction_id).cloned()
 8855            {
 8856                self.change_selections(None, window, cx, |s| {
 8857                    s.select_anchors(selections.to_vec());
 8858                });
 8859            } else {
 8860                log::error!(
 8861                    "No entry in selection_history found for redo. \
 8862                     This may correspond to a bug where undo does not update the selection. \
 8863                     If this is occurring, please add details to \
 8864                     https://github.com/zed-industries/zed/issues/22692"
 8865                );
 8866            }
 8867            self.request_autoscroll(Autoscroll::fit(), cx);
 8868            self.unmark_text(window, cx);
 8869            self.refresh_inline_completion(true, false, window, cx);
 8870            cx.emit(EditorEvent::Edited { transaction_id });
 8871        }
 8872    }
 8873
 8874    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8875        self.buffer
 8876            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8877    }
 8878
 8879    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8880        self.buffer
 8881            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8882    }
 8883
 8884    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8885        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8886            let line_mode = s.line_mode;
 8887            s.move_with(|map, selection| {
 8888                let cursor = if selection.is_empty() && !line_mode {
 8889                    movement::left(map, selection.start)
 8890                } else {
 8891                    selection.start
 8892                };
 8893                selection.collapse_to(cursor, SelectionGoal::None);
 8894            });
 8895        })
 8896    }
 8897
 8898    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8899        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8900            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8901        })
 8902    }
 8903
 8904    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8905        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8906            let line_mode = s.line_mode;
 8907            s.move_with(|map, selection| {
 8908                let cursor = if selection.is_empty() && !line_mode {
 8909                    movement::right(map, selection.end)
 8910                } else {
 8911                    selection.end
 8912                };
 8913                selection.collapse_to(cursor, SelectionGoal::None)
 8914            });
 8915        })
 8916    }
 8917
 8918    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8919        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8920            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8921        })
 8922    }
 8923
 8924    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8925        if self.take_rename(true, window, cx).is_some() {
 8926            return;
 8927        }
 8928
 8929        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8930            cx.propagate();
 8931            return;
 8932        }
 8933
 8934        let text_layout_details = &self.text_layout_details(window);
 8935        let selection_count = self.selections.count();
 8936        let first_selection = self.selections.first_anchor();
 8937
 8938        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8939            let line_mode = s.line_mode;
 8940            s.move_with(|map, selection| {
 8941                if !selection.is_empty() && !line_mode {
 8942                    selection.goal = SelectionGoal::None;
 8943                }
 8944                let (cursor, goal) = movement::up(
 8945                    map,
 8946                    selection.start,
 8947                    selection.goal,
 8948                    false,
 8949                    text_layout_details,
 8950                );
 8951                selection.collapse_to(cursor, goal);
 8952            });
 8953        });
 8954
 8955        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8956        {
 8957            cx.propagate();
 8958        }
 8959    }
 8960
 8961    pub fn move_up_by_lines(
 8962        &mut self,
 8963        action: &MoveUpByLines,
 8964        window: &mut Window,
 8965        cx: &mut Context<Self>,
 8966    ) {
 8967        if self.take_rename(true, window, cx).is_some() {
 8968            return;
 8969        }
 8970
 8971        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8972            cx.propagate();
 8973            return;
 8974        }
 8975
 8976        let text_layout_details = &self.text_layout_details(window);
 8977
 8978        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8979            let line_mode = s.line_mode;
 8980            s.move_with(|map, selection| {
 8981                if !selection.is_empty() && !line_mode {
 8982                    selection.goal = SelectionGoal::None;
 8983                }
 8984                let (cursor, goal) = movement::up_by_rows(
 8985                    map,
 8986                    selection.start,
 8987                    action.lines,
 8988                    selection.goal,
 8989                    false,
 8990                    text_layout_details,
 8991                );
 8992                selection.collapse_to(cursor, goal);
 8993            });
 8994        })
 8995    }
 8996
 8997    pub fn move_down_by_lines(
 8998        &mut self,
 8999        action: &MoveDownByLines,
 9000        window: &mut Window,
 9001        cx: &mut Context<Self>,
 9002    ) {
 9003        if self.take_rename(true, window, cx).is_some() {
 9004            return;
 9005        }
 9006
 9007        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9008            cx.propagate();
 9009            return;
 9010        }
 9011
 9012        let text_layout_details = &self.text_layout_details(window);
 9013
 9014        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9015            let line_mode = s.line_mode;
 9016            s.move_with(|map, selection| {
 9017                if !selection.is_empty() && !line_mode {
 9018                    selection.goal = SelectionGoal::None;
 9019                }
 9020                let (cursor, goal) = movement::down_by_rows(
 9021                    map,
 9022                    selection.start,
 9023                    action.lines,
 9024                    selection.goal,
 9025                    false,
 9026                    text_layout_details,
 9027                );
 9028                selection.collapse_to(cursor, goal);
 9029            });
 9030        })
 9031    }
 9032
 9033    pub fn select_down_by_lines(
 9034        &mut self,
 9035        action: &SelectDownByLines,
 9036        window: &mut Window,
 9037        cx: &mut Context<Self>,
 9038    ) {
 9039        let text_layout_details = &self.text_layout_details(window);
 9040        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9041            s.move_heads_with(|map, head, goal| {
 9042                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9043            })
 9044        })
 9045    }
 9046
 9047    pub fn select_up_by_lines(
 9048        &mut self,
 9049        action: &SelectUpByLines,
 9050        window: &mut Window,
 9051        cx: &mut Context<Self>,
 9052    ) {
 9053        let text_layout_details = &self.text_layout_details(window);
 9054        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9055            s.move_heads_with(|map, head, goal| {
 9056                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9057            })
 9058        })
 9059    }
 9060
 9061    pub fn select_page_up(
 9062        &mut self,
 9063        _: &SelectPageUp,
 9064        window: &mut Window,
 9065        cx: &mut Context<Self>,
 9066    ) {
 9067        let Some(row_count) = self.visible_row_count() else {
 9068            return;
 9069        };
 9070
 9071        let text_layout_details = &self.text_layout_details(window);
 9072
 9073        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9074            s.move_heads_with(|map, head, goal| {
 9075                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 9076            })
 9077        })
 9078    }
 9079
 9080    pub fn move_page_up(
 9081        &mut self,
 9082        action: &MovePageUp,
 9083        window: &mut Window,
 9084        cx: &mut Context<Self>,
 9085    ) {
 9086        if self.take_rename(true, window, cx).is_some() {
 9087            return;
 9088        }
 9089
 9090        if self
 9091            .context_menu
 9092            .borrow_mut()
 9093            .as_mut()
 9094            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 9095            .unwrap_or(false)
 9096        {
 9097            return;
 9098        }
 9099
 9100        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9101            cx.propagate();
 9102            return;
 9103        }
 9104
 9105        let Some(row_count) = self.visible_row_count() else {
 9106            return;
 9107        };
 9108
 9109        let autoscroll = if action.center_cursor {
 9110            Autoscroll::center()
 9111        } else {
 9112            Autoscroll::fit()
 9113        };
 9114
 9115        let text_layout_details = &self.text_layout_details(window);
 9116
 9117        self.change_selections(Some(autoscroll), window, cx, |s| {
 9118            let line_mode = s.line_mode;
 9119            s.move_with(|map, selection| {
 9120                if !selection.is_empty() && !line_mode {
 9121                    selection.goal = SelectionGoal::None;
 9122                }
 9123                let (cursor, goal) = movement::up_by_rows(
 9124                    map,
 9125                    selection.end,
 9126                    row_count,
 9127                    selection.goal,
 9128                    false,
 9129                    text_layout_details,
 9130                );
 9131                selection.collapse_to(cursor, goal);
 9132            });
 9133        });
 9134    }
 9135
 9136    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 9137        let text_layout_details = &self.text_layout_details(window);
 9138        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9139            s.move_heads_with(|map, head, goal| {
 9140                movement::up(map, head, goal, false, text_layout_details)
 9141            })
 9142        })
 9143    }
 9144
 9145    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 9146        self.take_rename(true, window, cx);
 9147
 9148        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9149            cx.propagate();
 9150            return;
 9151        }
 9152
 9153        let text_layout_details = &self.text_layout_details(window);
 9154        let selection_count = self.selections.count();
 9155        let first_selection = self.selections.first_anchor();
 9156
 9157        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9158            let line_mode = s.line_mode;
 9159            s.move_with(|map, selection| {
 9160                if !selection.is_empty() && !line_mode {
 9161                    selection.goal = SelectionGoal::None;
 9162                }
 9163                let (cursor, goal) = movement::down(
 9164                    map,
 9165                    selection.end,
 9166                    selection.goal,
 9167                    false,
 9168                    text_layout_details,
 9169                );
 9170                selection.collapse_to(cursor, goal);
 9171            });
 9172        });
 9173
 9174        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9175        {
 9176            cx.propagate();
 9177        }
 9178    }
 9179
 9180    pub fn select_page_down(
 9181        &mut self,
 9182        _: &SelectPageDown,
 9183        window: &mut Window,
 9184        cx: &mut Context<Self>,
 9185    ) {
 9186        let Some(row_count) = self.visible_row_count() else {
 9187            return;
 9188        };
 9189
 9190        let text_layout_details = &self.text_layout_details(window);
 9191
 9192        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9193            s.move_heads_with(|map, head, goal| {
 9194                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 9195            })
 9196        })
 9197    }
 9198
 9199    pub fn move_page_down(
 9200        &mut self,
 9201        action: &MovePageDown,
 9202        window: &mut Window,
 9203        cx: &mut Context<Self>,
 9204    ) {
 9205        if self.take_rename(true, window, cx).is_some() {
 9206            return;
 9207        }
 9208
 9209        if self
 9210            .context_menu
 9211            .borrow_mut()
 9212            .as_mut()
 9213            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 9214            .unwrap_or(false)
 9215        {
 9216            return;
 9217        }
 9218
 9219        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9220            cx.propagate();
 9221            return;
 9222        }
 9223
 9224        let Some(row_count) = self.visible_row_count() else {
 9225            return;
 9226        };
 9227
 9228        let autoscroll = if action.center_cursor {
 9229            Autoscroll::center()
 9230        } else {
 9231            Autoscroll::fit()
 9232        };
 9233
 9234        let text_layout_details = &self.text_layout_details(window);
 9235        self.change_selections(Some(autoscroll), window, cx, |s| {
 9236            let line_mode = s.line_mode;
 9237            s.move_with(|map, selection| {
 9238                if !selection.is_empty() && !line_mode {
 9239                    selection.goal = SelectionGoal::None;
 9240                }
 9241                let (cursor, goal) = movement::down_by_rows(
 9242                    map,
 9243                    selection.end,
 9244                    row_count,
 9245                    selection.goal,
 9246                    false,
 9247                    text_layout_details,
 9248                );
 9249                selection.collapse_to(cursor, goal);
 9250            });
 9251        });
 9252    }
 9253
 9254    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 9255        let text_layout_details = &self.text_layout_details(window);
 9256        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9257            s.move_heads_with(|map, head, goal| {
 9258                movement::down(map, head, goal, false, text_layout_details)
 9259            })
 9260        });
 9261    }
 9262
 9263    pub fn context_menu_first(
 9264        &mut self,
 9265        _: &ContextMenuFirst,
 9266        _window: &mut Window,
 9267        cx: &mut Context<Self>,
 9268    ) {
 9269        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9270            context_menu.select_first(self.completion_provider.as_deref(), cx);
 9271        }
 9272    }
 9273
 9274    pub fn context_menu_prev(
 9275        &mut self,
 9276        _: &ContextMenuPrevious,
 9277        _window: &mut Window,
 9278        cx: &mut Context<Self>,
 9279    ) {
 9280        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9281            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 9282        }
 9283    }
 9284
 9285    pub fn context_menu_next(
 9286        &mut self,
 9287        _: &ContextMenuNext,
 9288        _window: &mut Window,
 9289        cx: &mut Context<Self>,
 9290    ) {
 9291        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9292            context_menu.select_next(self.completion_provider.as_deref(), cx);
 9293        }
 9294    }
 9295
 9296    pub fn context_menu_last(
 9297        &mut self,
 9298        _: &ContextMenuLast,
 9299        _window: &mut Window,
 9300        cx: &mut Context<Self>,
 9301    ) {
 9302        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9303            context_menu.select_last(self.completion_provider.as_deref(), cx);
 9304        }
 9305    }
 9306
 9307    pub fn move_to_previous_word_start(
 9308        &mut self,
 9309        _: &MoveToPreviousWordStart,
 9310        window: &mut Window,
 9311        cx: &mut Context<Self>,
 9312    ) {
 9313        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9314            s.move_cursors_with(|map, head, _| {
 9315                (
 9316                    movement::previous_word_start(map, head),
 9317                    SelectionGoal::None,
 9318                )
 9319            });
 9320        })
 9321    }
 9322
 9323    pub fn move_to_previous_subword_start(
 9324        &mut self,
 9325        _: &MoveToPreviousSubwordStart,
 9326        window: &mut Window,
 9327        cx: &mut Context<Self>,
 9328    ) {
 9329        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9330            s.move_cursors_with(|map, head, _| {
 9331                (
 9332                    movement::previous_subword_start(map, head),
 9333                    SelectionGoal::None,
 9334                )
 9335            });
 9336        })
 9337    }
 9338
 9339    pub fn select_to_previous_word_start(
 9340        &mut self,
 9341        _: &SelectToPreviousWordStart,
 9342        window: &mut Window,
 9343        cx: &mut Context<Self>,
 9344    ) {
 9345        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9346            s.move_heads_with(|map, head, _| {
 9347                (
 9348                    movement::previous_word_start(map, head),
 9349                    SelectionGoal::None,
 9350                )
 9351            });
 9352        })
 9353    }
 9354
 9355    pub fn select_to_previous_subword_start(
 9356        &mut self,
 9357        _: &SelectToPreviousSubwordStart,
 9358        window: &mut Window,
 9359        cx: &mut Context<Self>,
 9360    ) {
 9361        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9362            s.move_heads_with(|map, head, _| {
 9363                (
 9364                    movement::previous_subword_start(map, head),
 9365                    SelectionGoal::None,
 9366                )
 9367            });
 9368        })
 9369    }
 9370
 9371    pub fn delete_to_previous_word_start(
 9372        &mut self,
 9373        action: &DeleteToPreviousWordStart,
 9374        window: &mut Window,
 9375        cx: &mut Context<Self>,
 9376    ) {
 9377        self.transact(window, cx, |this, window, cx| {
 9378            this.select_autoclose_pair(window, cx);
 9379            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9380                let line_mode = s.line_mode;
 9381                s.move_with(|map, selection| {
 9382                    if selection.is_empty() && !line_mode {
 9383                        let cursor = if action.ignore_newlines {
 9384                            movement::previous_word_start(map, selection.head())
 9385                        } else {
 9386                            movement::previous_word_start_or_newline(map, selection.head())
 9387                        };
 9388                        selection.set_head(cursor, SelectionGoal::None);
 9389                    }
 9390                });
 9391            });
 9392            this.insert("", window, cx);
 9393        });
 9394    }
 9395
 9396    pub fn delete_to_previous_subword_start(
 9397        &mut self,
 9398        _: &DeleteToPreviousSubwordStart,
 9399        window: &mut Window,
 9400        cx: &mut Context<Self>,
 9401    ) {
 9402        self.transact(window, cx, |this, window, cx| {
 9403            this.select_autoclose_pair(window, cx);
 9404            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9405                let line_mode = s.line_mode;
 9406                s.move_with(|map, selection| {
 9407                    if selection.is_empty() && !line_mode {
 9408                        let cursor = movement::previous_subword_start(map, selection.head());
 9409                        selection.set_head(cursor, SelectionGoal::None);
 9410                    }
 9411                });
 9412            });
 9413            this.insert("", window, cx);
 9414        });
 9415    }
 9416
 9417    pub fn move_to_next_word_end(
 9418        &mut self,
 9419        _: &MoveToNextWordEnd,
 9420        window: &mut Window,
 9421        cx: &mut Context<Self>,
 9422    ) {
 9423        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9424            s.move_cursors_with(|map, head, _| {
 9425                (movement::next_word_end(map, head), SelectionGoal::None)
 9426            });
 9427        })
 9428    }
 9429
 9430    pub fn move_to_next_subword_end(
 9431        &mut self,
 9432        _: &MoveToNextSubwordEnd,
 9433        window: &mut Window,
 9434        cx: &mut Context<Self>,
 9435    ) {
 9436        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9437            s.move_cursors_with(|map, head, _| {
 9438                (movement::next_subword_end(map, head), SelectionGoal::None)
 9439            });
 9440        })
 9441    }
 9442
 9443    pub fn select_to_next_word_end(
 9444        &mut self,
 9445        _: &SelectToNextWordEnd,
 9446        window: &mut Window,
 9447        cx: &mut Context<Self>,
 9448    ) {
 9449        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9450            s.move_heads_with(|map, head, _| {
 9451                (movement::next_word_end(map, head), SelectionGoal::None)
 9452            });
 9453        })
 9454    }
 9455
 9456    pub fn select_to_next_subword_end(
 9457        &mut self,
 9458        _: &SelectToNextSubwordEnd,
 9459        window: &mut Window,
 9460        cx: &mut Context<Self>,
 9461    ) {
 9462        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9463            s.move_heads_with(|map, head, _| {
 9464                (movement::next_subword_end(map, head), SelectionGoal::None)
 9465            });
 9466        })
 9467    }
 9468
 9469    pub fn delete_to_next_word_end(
 9470        &mut self,
 9471        action: &DeleteToNextWordEnd,
 9472        window: &mut Window,
 9473        cx: &mut Context<Self>,
 9474    ) {
 9475        self.transact(window, cx, |this, window, cx| {
 9476            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9477                let line_mode = s.line_mode;
 9478                s.move_with(|map, selection| {
 9479                    if selection.is_empty() && !line_mode {
 9480                        let cursor = if action.ignore_newlines {
 9481                            movement::next_word_end(map, selection.head())
 9482                        } else {
 9483                            movement::next_word_end_or_newline(map, selection.head())
 9484                        };
 9485                        selection.set_head(cursor, SelectionGoal::None);
 9486                    }
 9487                });
 9488            });
 9489            this.insert("", window, cx);
 9490        });
 9491    }
 9492
 9493    pub fn delete_to_next_subword_end(
 9494        &mut self,
 9495        _: &DeleteToNextSubwordEnd,
 9496        window: &mut Window,
 9497        cx: &mut Context<Self>,
 9498    ) {
 9499        self.transact(window, cx, |this, window, cx| {
 9500            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9501                s.move_with(|map, selection| {
 9502                    if selection.is_empty() {
 9503                        let cursor = movement::next_subword_end(map, selection.head());
 9504                        selection.set_head(cursor, SelectionGoal::None);
 9505                    }
 9506                });
 9507            });
 9508            this.insert("", window, cx);
 9509        });
 9510    }
 9511
 9512    pub fn move_to_beginning_of_line(
 9513        &mut self,
 9514        action: &MoveToBeginningOfLine,
 9515        window: &mut Window,
 9516        cx: &mut Context<Self>,
 9517    ) {
 9518        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9519            s.move_cursors_with(|map, head, _| {
 9520                (
 9521                    movement::indented_line_beginning(
 9522                        map,
 9523                        head,
 9524                        action.stop_at_soft_wraps,
 9525                        action.stop_at_indent,
 9526                    ),
 9527                    SelectionGoal::None,
 9528                )
 9529            });
 9530        })
 9531    }
 9532
 9533    pub fn select_to_beginning_of_line(
 9534        &mut self,
 9535        action: &SelectToBeginningOfLine,
 9536        window: &mut Window,
 9537        cx: &mut Context<Self>,
 9538    ) {
 9539        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9540            s.move_heads_with(|map, head, _| {
 9541                (
 9542                    movement::indented_line_beginning(
 9543                        map,
 9544                        head,
 9545                        action.stop_at_soft_wraps,
 9546                        action.stop_at_indent,
 9547                    ),
 9548                    SelectionGoal::None,
 9549                )
 9550            });
 9551        });
 9552    }
 9553
 9554    pub fn delete_to_beginning_of_line(
 9555        &mut self,
 9556        action: &DeleteToBeginningOfLine,
 9557        window: &mut Window,
 9558        cx: &mut Context<Self>,
 9559    ) {
 9560        self.transact(window, cx, |this, window, cx| {
 9561            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9562                s.move_with(|_, selection| {
 9563                    selection.reversed = true;
 9564                });
 9565            });
 9566
 9567            this.select_to_beginning_of_line(
 9568                &SelectToBeginningOfLine {
 9569                    stop_at_soft_wraps: false,
 9570                    stop_at_indent: action.stop_at_indent,
 9571                },
 9572                window,
 9573                cx,
 9574            );
 9575            this.backspace(&Backspace, window, cx);
 9576        });
 9577    }
 9578
 9579    pub fn move_to_end_of_line(
 9580        &mut self,
 9581        action: &MoveToEndOfLine,
 9582        window: &mut Window,
 9583        cx: &mut Context<Self>,
 9584    ) {
 9585        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9586            s.move_cursors_with(|map, head, _| {
 9587                (
 9588                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9589                    SelectionGoal::None,
 9590                )
 9591            });
 9592        })
 9593    }
 9594
 9595    pub fn select_to_end_of_line(
 9596        &mut self,
 9597        action: &SelectToEndOfLine,
 9598        window: &mut Window,
 9599        cx: &mut Context<Self>,
 9600    ) {
 9601        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9602            s.move_heads_with(|map, head, _| {
 9603                (
 9604                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9605                    SelectionGoal::None,
 9606                )
 9607            });
 9608        })
 9609    }
 9610
 9611    pub fn delete_to_end_of_line(
 9612        &mut self,
 9613        _: &DeleteToEndOfLine,
 9614        window: &mut Window,
 9615        cx: &mut Context<Self>,
 9616    ) {
 9617        self.transact(window, cx, |this, window, cx| {
 9618            this.select_to_end_of_line(
 9619                &SelectToEndOfLine {
 9620                    stop_at_soft_wraps: false,
 9621                },
 9622                window,
 9623                cx,
 9624            );
 9625            this.delete(&Delete, window, cx);
 9626        });
 9627    }
 9628
 9629    pub fn cut_to_end_of_line(
 9630        &mut self,
 9631        _: &CutToEndOfLine,
 9632        window: &mut Window,
 9633        cx: &mut Context<Self>,
 9634    ) {
 9635        self.transact(window, cx, |this, window, cx| {
 9636            this.select_to_end_of_line(
 9637                &SelectToEndOfLine {
 9638                    stop_at_soft_wraps: false,
 9639                },
 9640                window,
 9641                cx,
 9642            );
 9643            this.cut(&Cut, window, cx);
 9644        });
 9645    }
 9646
 9647    pub fn move_to_start_of_paragraph(
 9648        &mut self,
 9649        _: &MoveToStartOfParagraph,
 9650        window: &mut Window,
 9651        cx: &mut Context<Self>,
 9652    ) {
 9653        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9654            cx.propagate();
 9655            return;
 9656        }
 9657
 9658        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9659            s.move_with(|map, selection| {
 9660                selection.collapse_to(
 9661                    movement::start_of_paragraph(map, selection.head(), 1),
 9662                    SelectionGoal::None,
 9663                )
 9664            });
 9665        })
 9666    }
 9667
 9668    pub fn move_to_end_of_paragraph(
 9669        &mut self,
 9670        _: &MoveToEndOfParagraph,
 9671        window: &mut Window,
 9672        cx: &mut Context<Self>,
 9673    ) {
 9674        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9675            cx.propagate();
 9676            return;
 9677        }
 9678
 9679        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9680            s.move_with(|map, selection| {
 9681                selection.collapse_to(
 9682                    movement::end_of_paragraph(map, selection.head(), 1),
 9683                    SelectionGoal::None,
 9684                )
 9685            });
 9686        })
 9687    }
 9688
 9689    pub fn select_to_start_of_paragraph(
 9690        &mut self,
 9691        _: &SelectToStartOfParagraph,
 9692        window: &mut Window,
 9693        cx: &mut Context<Self>,
 9694    ) {
 9695        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9696            cx.propagate();
 9697            return;
 9698        }
 9699
 9700        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9701            s.move_heads_with(|map, head, _| {
 9702                (
 9703                    movement::start_of_paragraph(map, head, 1),
 9704                    SelectionGoal::None,
 9705                )
 9706            });
 9707        })
 9708    }
 9709
 9710    pub fn select_to_end_of_paragraph(
 9711        &mut self,
 9712        _: &SelectToEndOfParagraph,
 9713        window: &mut Window,
 9714        cx: &mut Context<Self>,
 9715    ) {
 9716        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9717            cx.propagate();
 9718            return;
 9719        }
 9720
 9721        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9722            s.move_heads_with(|map, head, _| {
 9723                (
 9724                    movement::end_of_paragraph(map, head, 1),
 9725                    SelectionGoal::None,
 9726                )
 9727            });
 9728        })
 9729    }
 9730
 9731    pub fn move_to_start_of_excerpt(
 9732        &mut self,
 9733        _: &MoveToStartOfExcerpt,
 9734        window: &mut Window,
 9735        cx: &mut Context<Self>,
 9736    ) {
 9737        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9738            cx.propagate();
 9739            return;
 9740        }
 9741
 9742        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9743            s.move_with(|map, selection| {
 9744                selection.collapse_to(
 9745                    movement::start_of_excerpt(
 9746                        map,
 9747                        selection.head(),
 9748                        workspace::searchable::Direction::Prev,
 9749                    ),
 9750                    SelectionGoal::None,
 9751                )
 9752            });
 9753        })
 9754    }
 9755
 9756    pub fn move_to_end_of_excerpt(
 9757        &mut self,
 9758        _: &MoveToEndOfExcerpt,
 9759        window: &mut Window,
 9760        cx: &mut Context<Self>,
 9761    ) {
 9762        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9763            cx.propagate();
 9764            return;
 9765        }
 9766
 9767        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9768            s.move_with(|map, selection| {
 9769                selection.collapse_to(
 9770                    movement::end_of_excerpt(
 9771                        map,
 9772                        selection.head(),
 9773                        workspace::searchable::Direction::Next,
 9774                    ),
 9775                    SelectionGoal::None,
 9776                )
 9777            });
 9778        })
 9779    }
 9780
 9781    pub fn select_to_start_of_excerpt(
 9782        &mut self,
 9783        _: &SelectToStartOfExcerpt,
 9784        window: &mut Window,
 9785        cx: &mut Context<Self>,
 9786    ) {
 9787        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9788            cx.propagate();
 9789            return;
 9790        }
 9791
 9792        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9793            s.move_heads_with(|map, head, _| {
 9794                (
 9795                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
 9796                    SelectionGoal::None,
 9797                )
 9798            });
 9799        })
 9800    }
 9801
 9802    pub fn select_to_end_of_excerpt(
 9803        &mut self,
 9804        _: &SelectToEndOfExcerpt,
 9805        window: &mut Window,
 9806        cx: &mut Context<Self>,
 9807    ) {
 9808        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9809            cx.propagate();
 9810            return;
 9811        }
 9812
 9813        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9814            s.move_heads_with(|map, head, _| {
 9815                (
 9816                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
 9817                    SelectionGoal::None,
 9818                )
 9819            });
 9820        })
 9821    }
 9822
 9823    pub fn move_to_beginning(
 9824        &mut self,
 9825        _: &MoveToBeginning,
 9826        window: &mut Window,
 9827        cx: &mut Context<Self>,
 9828    ) {
 9829        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9830            cx.propagate();
 9831            return;
 9832        }
 9833
 9834        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9835            s.select_ranges(vec![0..0]);
 9836        });
 9837    }
 9838
 9839    pub fn select_to_beginning(
 9840        &mut self,
 9841        _: &SelectToBeginning,
 9842        window: &mut Window,
 9843        cx: &mut Context<Self>,
 9844    ) {
 9845        let mut selection = self.selections.last::<Point>(cx);
 9846        selection.set_head(Point::zero(), SelectionGoal::None);
 9847
 9848        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9849            s.select(vec![selection]);
 9850        });
 9851    }
 9852
 9853    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9854        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9855            cx.propagate();
 9856            return;
 9857        }
 9858
 9859        let cursor = self.buffer.read(cx).read(cx).len();
 9860        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9861            s.select_ranges(vec![cursor..cursor])
 9862        });
 9863    }
 9864
 9865    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9866        self.nav_history = nav_history;
 9867    }
 9868
 9869    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9870        self.nav_history.as_ref()
 9871    }
 9872
 9873    fn push_to_nav_history(
 9874        &mut self,
 9875        cursor_anchor: Anchor,
 9876        new_position: Option<Point>,
 9877        cx: &mut Context<Self>,
 9878    ) {
 9879        if let Some(nav_history) = self.nav_history.as_mut() {
 9880            let buffer = self.buffer.read(cx).read(cx);
 9881            let cursor_position = cursor_anchor.to_point(&buffer);
 9882            let scroll_state = self.scroll_manager.anchor();
 9883            let scroll_top_row = scroll_state.top_row(&buffer);
 9884            drop(buffer);
 9885
 9886            if let Some(new_position) = new_position {
 9887                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9888                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9889                    return;
 9890                }
 9891            }
 9892
 9893            nav_history.push(
 9894                Some(NavigationData {
 9895                    cursor_anchor,
 9896                    cursor_position,
 9897                    scroll_anchor: scroll_state,
 9898                    scroll_top_row,
 9899                }),
 9900                cx,
 9901            );
 9902        }
 9903    }
 9904
 9905    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9906        let buffer = self.buffer.read(cx).snapshot(cx);
 9907        let mut selection = self.selections.first::<usize>(cx);
 9908        selection.set_head(buffer.len(), SelectionGoal::None);
 9909        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9910            s.select(vec![selection]);
 9911        });
 9912    }
 9913
 9914    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9915        let end = self.buffer.read(cx).read(cx).len();
 9916        self.change_selections(None, window, cx, |s| {
 9917            s.select_ranges(vec![0..end]);
 9918        });
 9919    }
 9920
 9921    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9922        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9923        let mut selections = self.selections.all::<Point>(cx);
 9924        let max_point = display_map.buffer_snapshot.max_point();
 9925        for selection in &mut selections {
 9926            let rows = selection.spanned_rows(true, &display_map);
 9927            selection.start = Point::new(rows.start.0, 0);
 9928            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9929            selection.reversed = false;
 9930        }
 9931        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9932            s.select(selections);
 9933        });
 9934    }
 9935
 9936    pub fn split_selection_into_lines(
 9937        &mut self,
 9938        _: &SplitSelectionIntoLines,
 9939        window: &mut Window,
 9940        cx: &mut Context<Self>,
 9941    ) {
 9942        let selections = self
 9943            .selections
 9944            .all::<Point>(cx)
 9945            .into_iter()
 9946            .map(|selection| selection.start..selection.end)
 9947            .collect::<Vec<_>>();
 9948        self.unfold_ranges(&selections, true, true, cx);
 9949
 9950        let mut new_selection_ranges = Vec::new();
 9951        {
 9952            let buffer = self.buffer.read(cx).read(cx);
 9953            for selection in selections {
 9954                for row in selection.start.row..selection.end.row {
 9955                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9956                    new_selection_ranges.push(cursor..cursor);
 9957                }
 9958
 9959                let is_multiline_selection = selection.start.row != selection.end.row;
 9960                // Don't insert last one if it's a multi-line selection ending at the start of a line,
 9961                // so this action feels more ergonomic when paired with other selection operations
 9962                let should_skip_last = is_multiline_selection && selection.end.column == 0;
 9963                if !should_skip_last {
 9964                    new_selection_ranges.push(selection.end..selection.end);
 9965                }
 9966            }
 9967        }
 9968        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9969            s.select_ranges(new_selection_ranges);
 9970        });
 9971    }
 9972
 9973    pub fn add_selection_above(
 9974        &mut self,
 9975        _: &AddSelectionAbove,
 9976        window: &mut Window,
 9977        cx: &mut Context<Self>,
 9978    ) {
 9979        self.add_selection(true, window, cx);
 9980    }
 9981
 9982    pub fn add_selection_below(
 9983        &mut self,
 9984        _: &AddSelectionBelow,
 9985        window: &mut Window,
 9986        cx: &mut Context<Self>,
 9987    ) {
 9988        self.add_selection(false, window, cx);
 9989    }
 9990
 9991    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9992        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9993        let mut selections = self.selections.all::<Point>(cx);
 9994        let text_layout_details = self.text_layout_details(window);
 9995        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9996            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9997            let range = oldest_selection.display_range(&display_map).sorted();
 9998
 9999            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10000            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10001            let positions = start_x.min(end_x)..start_x.max(end_x);
10002
10003            selections.clear();
10004            let mut stack = Vec::new();
10005            for row in range.start.row().0..=range.end.row().0 {
10006                if let Some(selection) = self.selections.build_columnar_selection(
10007                    &display_map,
10008                    DisplayRow(row),
10009                    &positions,
10010                    oldest_selection.reversed,
10011                    &text_layout_details,
10012                ) {
10013                    stack.push(selection.id);
10014                    selections.push(selection);
10015                }
10016            }
10017
10018            if above {
10019                stack.reverse();
10020            }
10021
10022            AddSelectionsState { above, stack }
10023        });
10024
10025        let last_added_selection = *state.stack.last().unwrap();
10026        let mut new_selections = Vec::new();
10027        if above == state.above {
10028            let end_row = if above {
10029                DisplayRow(0)
10030            } else {
10031                display_map.max_point().row()
10032            };
10033
10034            'outer: for selection in selections {
10035                if selection.id == last_added_selection {
10036                    let range = selection.display_range(&display_map).sorted();
10037                    debug_assert_eq!(range.start.row(), range.end.row());
10038                    let mut row = range.start.row();
10039                    let positions =
10040                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10041                            px(start)..px(end)
10042                        } else {
10043                            let start_x =
10044                                display_map.x_for_display_point(range.start, &text_layout_details);
10045                            let end_x =
10046                                display_map.x_for_display_point(range.end, &text_layout_details);
10047                            start_x.min(end_x)..start_x.max(end_x)
10048                        };
10049
10050                    while row != end_row {
10051                        if above {
10052                            row.0 -= 1;
10053                        } else {
10054                            row.0 += 1;
10055                        }
10056
10057                        if let Some(new_selection) = self.selections.build_columnar_selection(
10058                            &display_map,
10059                            row,
10060                            &positions,
10061                            selection.reversed,
10062                            &text_layout_details,
10063                        ) {
10064                            state.stack.push(new_selection.id);
10065                            if above {
10066                                new_selections.push(new_selection);
10067                                new_selections.push(selection);
10068                            } else {
10069                                new_selections.push(selection);
10070                                new_selections.push(new_selection);
10071                            }
10072
10073                            continue 'outer;
10074                        }
10075                    }
10076                }
10077
10078                new_selections.push(selection);
10079            }
10080        } else {
10081            new_selections = selections;
10082            new_selections.retain(|s| s.id != last_added_selection);
10083            state.stack.pop();
10084        }
10085
10086        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10087            s.select(new_selections);
10088        });
10089        if state.stack.len() > 1 {
10090            self.add_selections_state = Some(state);
10091        }
10092    }
10093
10094    pub fn select_next_match_internal(
10095        &mut self,
10096        display_map: &DisplaySnapshot,
10097        replace_newest: bool,
10098        autoscroll: Option<Autoscroll>,
10099        window: &mut Window,
10100        cx: &mut Context<Self>,
10101    ) -> Result<()> {
10102        fn select_next_match_ranges(
10103            this: &mut Editor,
10104            range: Range<usize>,
10105            replace_newest: bool,
10106            auto_scroll: Option<Autoscroll>,
10107            window: &mut Window,
10108            cx: &mut Context<Editor>,
10109        ) {
10110            this.unfold_ranges(&[range.clone()], false, true, cx);
10111            this.change_selections(auto_scroll, window, cx, |s| {
10112                if replace_newest {
10113                    s.delete(s.newest_anchor().id);
10114                }
10115                s.insert_range(range.clone());
10116            });
10117        }
10118
10119        let buffer = &display_map.buffer_snapshot;
10120        let mut selections = self.selections.all::<usize>(cx);
10121        if let Some(mut select_next_state) = self.select_next_state.take() {
10122            let query = &select_next_state.query;
10123            if !select_next_state.done {
10124                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10125                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10126                let mut next_selected_range = None;
10127
10128                let bytes_after_last_selection =
10129                    buffer.bytes_in_range(last_selection.end..buffer.len());
10130                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10131                let query_matches = query
10132                    .stream_find_iter(bytes_after_last_selection)
10133                    .map(|result| (last_selection.end, result))
10134                    .chain(
10135                        query
10136                            .stream_find_iter(bytes_before_first_selection)
10137                            .map(|result| (0, result)),
10138                    );
10139
10140                for (start_offset, query_match) in query_matches {
10141                    let query_match = query_match.unwrap(); // can only fail due to I/O
10142                    let offset_range =
10143                        start_offset + query_match.start()..start_offset + query_match.end();
10144                    let display_range = offset_range.start.to_display_point(display_map)
10145                        ..offset_range.end.to_display_point(display_map);
10146
10147                    if !select_next_state.wordwise
10148                        || (!movement::is_inside_word(display_map, display_range.start)
10149                            && !movement::is_inside_word(display_map, display_range.end))
10150                    {
10151                        // TODO: This is n^2, because we might check all the selections
10152                        if !selections
10153                            .iter()
10154                            .any(|selection| selection.range().overlaps(&offset_range))
10155                        {
10156                            next_selected_range = Some(offset_range);
10157                            break;
10158                        }
10159                    }
10160                }
10161
10162                if let Some(next_selected_range) = next_selected_range {
10163                    select_next_match_ranges(
10164                        self,
10165                        next_selected_range,
10166                        replace_newest,
10167                        autoscroll,
10168                        window,
10169                        cx,
10170                    );
10171                } else {
10172                    select_next_state.done = true;
10173                }
10174            }
10175
10176            self.select_next_state = Some(select_next_state);
10177        } else {
10178            let mut only_carets = true;
10179            let mut same_text_selected = true;
10180            let mut selected_text = None;
10181
10182            let mut selections_iter = selections.iter().peekable();
10183            while let Some(selection) = selections_iter.next() {
10184                if selection.start != selection.end {
10185                    only_carets = false;
10186                }
10187
10188                if same_text_selected {
10189                    if selected_text.is_none() {
10190                        selected_text =
10191                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10192                    }
10193
10194                    if let Some(next_selection) = selections_iter.peek() {
10195                        if next_selection.range().len() == selection.range().len() {
10196                            let next_selected_text = buffer
10197                                .text_for_range(next_selection.range())
10198                                .collect::<String>();
10199                            if Some(next_selected_text) != selected_text {
10200                                same_text_selected = false;
10201                                selected_text = None;
10202                            }
10203                        } else {
10204                            same_text_selected = false;
10205                            selected_text = None;
10206                        }
10207                    }
10208                }
10209            }
10210
10211            if only_carets {
10212                for selection in &mut selections {
10213                    let word_range = movement::surrounding_word(
10214                        display_map,
10215                        selection.start.to_display_point(display_map),
10216                    );
10217                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
10218                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
10219                    selection.goal = SelectionGoal::None;
10220                    selection.reversed = false;
10221                    select_next_match_ranges(
10222                        self,
10223                        selection.start..selection.end,
10224                        replace_newest,
10225                        autoscroll,
10226                        window,
10227                        cx,
10228                    );
10229                }
10230
10231                if selections.len() == 1 {
10232                    let selection = selections
10233                        .last()
10234                        .expect("ensured that there's only one selection");
10235                    let query = buffer
10236                        .text_for_range(selection.start..selection.end)
10237                        .collect::<String>();
10238                    let is_empty = query.is_empty();
10239                    let select_state = SelectNextState {
10240                        query: AhoCorasick::new(&[query])?,
10241                        wordwise: true,
10242                        done: is_empty,
10243                    };
10244                    self.select_next_state = Some(select_state);
10245                } else {
10246                    self.select_next_state = None;
10247                }
10248            } else if let Some(selected_text) = selected_text {
10249                self.select_next_state = Some(SelectNextState {
10250                    query: AhoCorasick::new(&[selected_text])?,
10251                    wordwise: false,
10252                    done: false,
10253                });
10254                self.select_next_match_internal(
10255                    display_map,
10256                    replace_newest,
10257                    autoscroll,
10258                    window,
10259                    cx,
10260                )?;
10261            }
10262        }
10263        Ok(())
10264    }
10265
10266    pub fn select_all_matches(
10267        &mut self,
10268        _action: &SelectAllMatches,
10269        window: &mut Window,
10270        cx: &mut Context<Self>,
10271    ) -> Result<()> {
10272        self.push_to_selection_history();
10273        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10274
10275        self.select_next_match_internal(&display_map, false, None, window, cx)?;
10276        let Some(select_next_state) = self.select_next_state.as_mut() else {
10277            return Ok(());
10278        };
10279        if select_next_state.done {
10280            return Ok(());
10281        }
10282
10283        let mut new_selections = self.selections.all::<usize>(cx);
10284
10285        let buffer = &display_map.buffer_snapshot;
10286        let query_matches = select_next_state
10287            .query
10288            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10289
10290        for query_match in query_matches {
10291            let query_match = query_match.unwrap(); // can only fail due to I/O
10292            let offset_range = query_match.start()..query_match.end();
10293            let display_range = offset_range.start.to_display_point(&display_map)
10294                ..offset_range.end.to_display_point(&display_map);
10295
10296            if !select_next_state.wordwise
10297                || (!movement::is_inside_word(&display_map, display_range.start)
10298                    && !movement::is_inside_word(&display_map, display_range.end))
10299            {
10300                self.selections.change_with(cx, |selections| {
10301                    new_selections.push(Selection {
10302                        id: selections.new_selection_id(),
10303                        start: offset_range.start,
10304                        end: offset_range.end,
10305                        reversed: false,
10306                        goal: SelectionGoal::None,
10307                    });
10308                });
10309            }
10310        }
10311
10312        new_selections.sort_by_key(|selection| selection.start);
10313        let mut ix = 0;
10314        while ix + 1 < new_selections.len() {
10315            let current_selection = &new_selections[ix];
10316            let next_selection = &new_selections[ix + 1];
10317            if current_selection.range().overlaps(&next_selection.range()) {
10318                if current_selection.id < next_selection.id {
10319                    new_selections.remove(ix + 1);
10320                } else {
10321                    new_selections.remove(ix);
10322                }
10323            } else {
10324                ix += 1;
10325            }
10326        }
10327
10328        let reversed = self.selections.oldest::<usize>(cx).reversed;
10329
10330        for selection in new_selections.iter_mut() {
10331            selection.reversed = reversed;
10332        }
10333
10334        select_next_state.done = true;
10335        self.unfold_ranges(
10336            &new_selections
10337                .iter()
10338                .map(|selection| selection.range())
10339                .collect::<Vec<_>>(),
10340            false,
10341            false,
10342            cx,
10343        );
10344        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10345            selections.select(new_selections)
10346        });
10347
10348        Ok(())
10349    }
10350
10351    pub fn select_next(
10352        &mut self,
10353        action: &SelectNext,
10354        window: &mut Window,
10355        cx: &mut Context<Self>,
10356    ) -> Result<()> {
10357        self.push_to_selection_history();
10358        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10359        self.select_next_match_internal(
10360            &display_map,
10361            action.replace_newest,
10362            Some(Autoscroll::newest()),
10363            window,
10364            cx,
10365        )?;
10366        Ok(())
10367    }
10368
10369    pub fn select_previous(
10370        &mut self,
10371        action: &SelectPrevious,
10372        window: &mut Window,
10373        cx: &mut Context<Self>,
10374    ) -> Result<()> {
10375        self.push_to_selection_history();
10376        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10377        let buffer = &display_map.buffer_snapshot;
10378        let mut selections = self.selections.all::<usize>(cx);
10379        if let Some(mut select_prev_state) = self.select_prev_state.take() {
10380            let query = &select_prev_state.query;
10381            if !select_prev_state.done {
10382                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10383                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10384                let mut next_selected_range = None;
10385                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10386                let bytes_before_last_selection =
10387                    buffer.reversed_bytes_in_range(0..last_selection.start);
10388                let bytes_after_first_selection =
10389                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10390                let query_matches = query
10391                    .stream_find_iter(bytes_before_last_selection)
10392                    .map(|result| (last_selection.start, result))
10393                    .chain(
10394                        query
10395                            .stream_find_iter(bytes_after_first_selection)
10396                            .map(|result| (buffer.len(), result)),
10397                    );
10398                for (end_offset, query_match) in query_matches {
10399                    let query_match = query_match.unwrap(); // can only fail due to I/O
10400                    let offset_range =
10401                        end_offset - query_match.end()..end_offset - query_match.start();
10402                    let display_range = offset_range.start.to_display_point(&display_map)
10403                        ..offset_range.end.to_display_point(&display_map);
10404
10405                    if !select_prev_state.wordwise
10406                        || (!movement::is_inside_word(&display_map, display_range.start)
10407                            && !movement::is_inside_word(&display_map, display_range.end))
10408                    {
10409                        next_selected_range = Some(offset_range);
10410                        break;
10411                    }
10412                }
10413
10414                if let Some(next_selected_range) = next_selected_range {
10415                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10416                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10417                        if action.replace_newest {
10418                            s.delete(s.newest_anchor().id);
10419                        }
10420                        s.insert_range(next_selected_range);
10421                    });
10422                } else {
10423                    select_prev_state.done = true;
10424                }
10425            }
10426
10427            self.select_prev_state = Some(select_prev_state);
10428        } else {
10429            let mut only_carets = true;
10430            let mut same_text_selected = true;
10431            let mut selected_text = None;
10432
10433            let mut selections_iter = selections.iter().peekable();
10434            while let Some(selection) = selections_iter.next() {
10435                if selection.start != selection.end {
10436                    only_carets = false;
10437                }
10438
10439                if same_text_selected {
10440                    if selected_text.is_none() {
10441                        selected_text =
10442                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10443                    }
10444
10445                    if let Some(next_selection) = selections_iter.peek() {
10446                        if next_selection.range().len() == selection.range().len() {
10447                            let next_selected_text = buffer
10448                                .text_for_range(next_selection.range())
10449                                .collect::<String>();
10450                            if Some(next_selected_text) != selected_text {
10451                                same_text_selected = false;
10452                                selected_text = None;
10453                            }
10454                        } else {
10455                            same_text_selected = false;
10456                            selected_text = None;
10457                        }
10458                    }
10459                }
10460            }
10461
10462            if only_carets {
10463                for selection in &mut selections {
10464                    let word_range = movement::surrounding_word(
10465                        &display_map,
10466                        selection.start.to_display_point(&display_map),
10467                    );
10468                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10469                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10470                    selection.goal = SelectionGoal::None;
10471                    selection.reversed = false;
10472                }
10473                if selections.len() == 1 {
10474                    let selection = selections
10475                        .last()
10476                        .expect("ensured that there's only one selection");
10477                    let query = buffer
10478                        .text_for_range(selection.start..selection.end)
10479                        .collect::<String>();
10480                    let is_empty = query.is_empty();
10481                    let select_state = SelectNextState {
10482                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10483                        wordwise: true,
10484                        done: is_empty,
10485                    };
10486                    self.select_prev_state = Some(select_state);
10487                } else {
10488                    self.select_prev_state = None;
10489                }
10490
10491                self.unfold_ranges(
10492                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10493                    false,
10494                    true,
10495                    cx,
10496                );
10497                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10498                    s.select(selections);
10499                });
10500            } else if let Some(selected_text) = selected_text {
10501                self.select_prev_state = Some(SelectNextState {
10502                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10503                    wordwise: false,
10504                    done: false,
10505                });
10506                self.select_previous(action, window, cx)?;
10507            }
10508        }
10509        Ok(())
10510    }
10511
10512    pub fn toggle_comments(
10513        &mut self,
10514        action: &ToggleComments,
10515        window: &mut Window,
10516        cx: &mut Context<Self>,
10517    ) {
10518        if self.read_only(cx) {
10519            return;
10520        }
10521        let text_layout_details = &self.text_layout_details(window);
10522        self.transact(window, cx, |this, window, cx| {
10523            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10524            let mut edits = Vec::new();
10525            let mut selection_edit_ranges = Vec::new();
10526            let mut last_toggled_row = None;
10527            let snapshot = this.buffer.read(cx).read(cx);
10528            let empty_str: Arc<str> = Arc::default();
10529            let mut suffixes_inserted = Vec::new();
10530            let ignore_indent = action.ignore_indent;
10531
10532            fn comment_prefix_range(
10533                snapshot: &MultiBufferSnapshot,
10534                row: MultiBufferRow,
10535                comment_prefix: &str,
10536                comment_prefix_whitespace: &str,
10537                ignore_indent: bool,
10538            ) -> Range<Point> {
10539                let indent_size = if ignore_indent {
10540                    0
10541                } else {
10542                    snapshot.indent_size_for_line(row).len
10543                };
10544
10545                let start = Point::new(row.0, indent_size);
10546
10547                let mut line_bytes = snapshot
10548                    .bytes_in_range(start..snapshot.max_point())
10549                    .flatten()
10550                    .copied();
10551
10552                // If this line currently begins with the line comment prefix, then record
10553                // the range containing the prefix.
10554                if line_bytes
10555                    .by_ref()
10556                    .take(comment_prefix.len())
10557                    .eq(comment_prefix.bytes())
10558                {
10559                    // Include any whitespace that matches the comment prefix.
10560                    let matching_whitespace_len = line_bytes
10561                        .zip(comment_prefix_whitespace.bytes())
10562                        .take_while(|(a, b)| a == b)
10563                        .count() as u32;
10564                    let end = Point::new(
10565                        start.row,
10566                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10567                    );
10568                    start..end
10569                } else {
10570                    start..start
10571                }
10572            }
10573
10574            fn comment_suffix_range(
10575                snapshot: &MultiBufferSnapshot,
10576                row: MultiBufferRow,
10577                comment_suffix: &str,
10578                comment_suffix_has_leading_space: bool,
10579            ) -> Range<Point> {
10580                let end = Point::new(row.0, snapshot.line_len(row));
10581                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10582
10583                let mut line_end_bytes = snapshot
10584                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10585                    .flatten()
10586                    .copied();
10587
10588                let leading_space_len = if suffix_start_column > 0
10589                    && line_end_bytes.next() == Some(b' ')
10590                    && comment_suffix_has_leading_space
10591                {
10592                    1
10593                } else {
10594                    0
10595                };
10596
10597                // If this line currently begins with the line comment prefix, then record
10598                // the range containing the prefix.
10599                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10600                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
10601                    start..end
10602                } else {
10603                    end..end
10604                }
10605            }
10606
10607            // TODO: Handle selections that cross excerpts
10608            for selection in &mut selections {
10609                let start_column = snapshot
10610                    .indent_size_for_line(MultiBufferRow(selection.start.row))
10611                    .len;
10612                let language = if let Some(language) =
10613                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10614                {
10615                    language
10616                } else {
10617                    continue;
10618                };
10619
10620                selection_edit_ranges.clear();
10621
10622                // If multiple selections contain a given row, avoid processing that
10623                // row more than once.
10624                let mut start_row = MultiBufferRow(selection.start.row);
10625                if last_toggled_row == Some(start_row) {
10626                    start_row = start_row.next_row();
10627                }
10628                let end_row =
10629                    if selection.end.row > selection.start.row && selection.end.column == 0 {
10630                        MultiBufferRow(selection.end.row - 1)
10631                    } else {
10632                        MultiBufferRow(selection.end.row)
10633                    };
10634                last_toggled_row = Some(end_row);
10635
10636                if start_row > end_row {
10637                    continue;
10638                }
10639
10640                // If the language has line comments, toggle those.
10641                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10642
10643                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10644                if ignore_indent {
10645                    full_comment_prefixes = full_comment_prefixes
10646                        .into_iter()
10647                        .map(|s| Arc::from(s.trim_end()))
10648                        .collect();
10649                }
10650
10651                if !full_comment_prefixes.is_empty() {
10652                    let first_prefix = full_comment_prefixes
10653                        .first()
10654                        .expect("prefixes is non-empty");
10655                    let prefix_trimmed_lengths = full_comment_prefixes
10656                        .iter()
10657                        .map(|p| p.trim_end_matches(' ').len())
10658                        .collect::<SmallVec<[usize; 4]>>();
10659
10660                    let mut all_selection_lines_are_comments = true;
10661
10662                    for row in start_row.0..=end_row.0 {
10663                        let row = MultiBufferRow(row);
10664                        if start_row < end_row && snapshot.is_line_blank(row) {
10665                            continue;
10666                        }
10667
10668                        let prefix_range = full_comment_prefixes
10669                            .iter()
10670                            .zip(prefix_trimmed_lengths.iter().copied())
10671                            .map(|(prefix, trimmed_prefix_len)| {
10672                                comment_prefix_range(
10673                                    snapshot.deref(),
10674                                    row,
10675                                    &prefix[..trimmed_prefix_len],
10676                                    &prefix[trimmed_prefix_len..],
10677                                    ignore_indent,
10678                                )
10679                            })
10680                            .max_by_key(|range| range.end.column - range.start.column)
10681                            .expect("prefixes is non-empty");
10682
10683                        if prefix_range.is_empty() {
10684                            all_selection_lines_are_comments = false;
10685                        }
10686
10687                        selection_edit_ranges.push(prefix_range);
10688                    }
10689
10690                    if all_selection_lines_are_comments {
10691                        edits.extend(
10692                            selection_edit_ranges
10693                                .iter()
10694                                .cloned()
10695                                .map(|range| (range, empty_str.clone())),
10696                        );
10697                    } else {
10698                        let min_column = selection_edit_ranges
10699                            .iter()
10700                            .map(|range| range.start.column)
10701                            .min()
10702                            .unwrap_or(0);
10703                        edits.extend(selection_edit_ranges.iter().map(|range| {
10704                            let position = Point::new(range.start.row, min_column);
10705                            (position..position, first_prefix.clone())
10706                        }));
10707                    }
10708                } else if let Some((full_comment_prefix, comment_suffix)) =
10709                    language.block_comment_delimiters()
10710                {
10711                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10712                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10713                    let prefix_range = comment_prefix_range(
10714                        snapshot.deref(),
10715                        start_row,
10716                        comment_prefix,
10717                        comment_prefix_whitespace,
10718                        ignore_indent,
10719                    );
10720                    let suffix_range = comment_suffix_range(
10721                        snapshot.deref(),
10722                        end_row,
10723                        comment_suffix.trim_start_matches(' '),
10724                        comment_suffix.starts_with(' '),
10725                    );
10726
10727                    if prefix_range.is_empty() || suffix_range.is_empty() {
10728                        edits.push((
10729                            prefix_range.start..prefix_range.start,
10730                            full_comment_prefix.clone(),
10731                        ));
10732                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10733                        suffixes_inserted.push((end_row, comment_suffix.len()));
10734                    } else {
10735                        edits.push((prefix_range, empty_str.clone()));
10736                        edits.push((suffix_range, empty_str.clone()));
10737                    }
10738                } else {
10739                    continue;
10740                }
10741            }
10742
10743            drop(snapshot);
10744            this.buffer.update(cx, |buffer, cx| {
10745                buffer.edit(edits, None, cx);
10746            });
10747
10748            // Adjust selections so that they end before any comment suffixes that
10749            // were inserted.
10750            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10751            let mut selections = this.selections.all::<Point>(cx);
10752            let snapshot = this.buffer.read(cx).read(cx);
10753            for selection in &mut selections {
10754                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10755                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10756                        Ordering::Less => {
10757                            suffixes_inserted.next();
10758                            continue;
10759                        }
10760                        Ordering::Greater => break,
10761                        Ordering::Equal => {
10762                            if selection.end.column == snapshot.line_len(row) {
10763                                if selection.is_empty() {
10764                                    selection.start.column -= suffix_len as u32;
10765                                }
10766                                selection.end.column -= suffix_len as u32;
10767                            }
10768                            break;
10769                        }
10770                    }
10771                }
10772            }
10773
10774            drop(snapshot);
10775            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10776                s.select(selections)
10777            });
10778
10779            let selections = this.selections.all::<Point>(cx);
10780            let selections_on_single_row = selections.windows(2).all(|selections| {
10781                selections[0].start.row == selections[1].start.row
10782                    && selections[0].end.row == selections[1].end.row
10783                    && selections[0].start.row == selections[0].end.row
10784            });
10785            let selections_selecting = selections
10786                .iter()
10787                .any(|selection| selection.start != selection.end);
10788            let advance_downwards = action.advance_downwards
10789                && selections_on_single_row
10790                && !selections_selecting
10791                && !matches!(this.mode, EditorMode::SingleLine { .. });
10792
10793            if advance_downwards {
10794                let snapshot = this.buffer.read(cx).snapshot(cx);
10795
10796                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10797                    s.move_cursors_with(|display_snapshot, display_point, _| {
10798                        let mut point = display_point.to_point(display_snapshot);
10799                        point.row += 1;
10800                        point = snapshot.clip_point(point, Bias::Left);
10801                        let display_point = point.to_display_point(display_snapshot);
10802                        let goal = SelectionGoal::HorizontalPosition(
10803                            display_snapshot
10804                                .x_for_display_point(display_point, text_layout_details)
10805                                .into(),
10806                        );
10807                        (display_point, goal)
10808                    })
10809                });
10810            }
10811        });
10812    }
10813
10814    pub fn select_enclosing_symbol(
10815        &mut self,
10816        _: &SelectEnclosingSymbol,
10817        window: &mut Window,
10818        cx: &mut Context<Self>,
10819    ) {
10820        let buffer = self.buffer.read(cx).snapshot(cx);
10821        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10822
10823        fn update_selection(
10824            selection: &Selection<usize>,
10825            buffer_snap: &MultiBufferSnapshot,
10826        ) -> Option<Selection<usize>> {
10827            let cursor = selection.head();
10828            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10829            for symbol in symbols.iter().rev() {
10830                let start = symbol.range.start.to_offset(buffer_snap);
10831                let end = symbol.range.end.to_offset(buffer_snap);
10832                let new_range = start..end;
10833                if start < selection.start || end > selection.end {
10834                    return Some(Selection {
10835                        id: selection.id,
10836                        start: new_range.start,
10837                        end: new_range.end,
10838                        goal: SelectionGoal::None,
10839                        reversed: selection.reversed,
10840                    });
10841                }
10842            }
10843            None
10844        }
10845
10846        let mut selected_larger_symbol = false;
10847        let new_selections = old_selections
10848            .iter()
10849            .map(|selection| match update_selection(selection, &buffer) {
10850                Some(new_selection) => {
10851                    if new_selection.range() != selection.range() {
10852                        selected_larger_symbol = true;
10853                    }
10854                    new_selection
10855                }
10856                None => selection.clone(),
10857            })
10858            .collect::<Vec<_>>();
10859
10860        if selected_larger_symbol {
10861            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10862                s.select(new_selections);
10863            });
10864        }
10865    }
10866
10867    pub fn select_larger_syntax_node(
10868        &mut self,
10869        _: &SelectLargerSyntaxNode,
10870        window: &mut Window,
10871        cx: &mut Context<Self>,
10872    ) {
10873        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10874        let buffer = self.buffer.read(cx).snapshot(cx);
10875        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10876
10877        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10878        let mut selected_larger_node = false;
10879        let new_selections = old_selections
10880            .iter()
10881            .map(|selection| {
10882                let old_range = selection.start..selection.end;
10883                let mut new_range = old_range.clone();
10884                let mut new_node = None;
10885                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10886                {
10887                    new_node = Some(node);
10888                    new_range = match containing_range {
10889                        MultiOrSingleBufferOffsetRange::Single(_) => break,
10890                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
10891                    };
10892                    if !display_map.intersects_fold(new_range.start)
10893                        && !display_map.intersects_fold(new_range.end)
10894                    {
10895                        break;
10896                    }
10897                }
10898
10899                if let Some(node) = new_node {
10900                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10901                    // nodes. Parent and grandparent are also logged because this operation will not
10902                    // visit nodes that have the same range as their parent.
10903                    log::info!("Node: {node:?}");
10904                    let parent = node.parent();
10905                    log::info!("Parent: {parent:?}");
10906                    let grandparent = parent.and_then(|x| x.parent());
10907                    log::info!("Grandparent: {grandparent:?}");
10908                }
10909
10910                selected_larger_node |= new_range != old_range;
10911                Selection {
10912                    id: selection.id,
10913                    start: new_range.start,
10914                    end: new_range.end,
10915                    goal: SelectionGoal::None,
10916                    reversed: selection.reversed,
10917                }
10918            })
10919            .collect::<Vec<_>>();
10920
10921        if selected_larger_node {
10922            stack.push(old_selections);
10923            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10924                s.select(new_selections);
10925            });
10926        }
10927        self.select_larger_syntax_node_stack = stack;
10928    }
10929
10930    pub fn select_smaller_syntax_node(
10931        &mut self,
10932        _: &SelectSmallerSyntaxNode,
10933        window: &mut Window,
10934        cx: &mut Context<Self>,
10935    ) {
10936        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10937        if let Some(selections) = stack.pop() {
10938            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10939                s.select(selections.to_vec());
10940            });
10941        }
10942        self.select_larger_syntax_node_stack = stack;
10943    }
10944
10945    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10946        if !EditorSettings::get_global(cx).gutter.runnables {
10947            self.clear_tasks();
10948            return Task::ready(());
10949        }
10950        let project = self.project.as_ref().map(Entity::downgrade);
10951        cx.spawn_in(window, |this, mut cx| async move {
10952            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10953            let Some(project) = project.and_then(|p| p.upgrade()) else {
10954                return;
10955            };
10956            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10957                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10958            }) else {
10959                return;
10960            };
10961
10962            let hide_runnables = project
10963                .update(&mut cx, |project, cx| {
10964                    // Do not display any test indicators in non-dev server remote projects.
10965                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10966                })
10967                .unwrap_or(true);
10968            if hide_runnables {
10969                return;
10970            }
10971            let new_rows =
10972                cx.background_spawn({
10973                    let snapshot = display_snapshot.clone();
10974                    async move {
10975                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10976                    }
10977                })
10978                    .await;
10979
10980            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10981            this.update(&mut cx, |this, _| {
10982                this.clear_tasks();
10983                for (key, value) in rows {
10984                    this.insert_tasks(key, value);
10985                }
10986            })
10987            .ok();
10988        })
10989    }
10990    fn fetch_runnable_ranges(
10991        snapshot: &DisplaySnapshot,
10992        range: Range<Anchor>,
10993    ) -> Vec<language::RunnableRange> {
10994        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10995    }
10996
10997    fn runnable_rows(
10998        project: Entity<Project>,
10999        snapshot: DisplaySnapshot,
11000        runnable_ranges: Vec<RunnableRange>,
11001        mut cx: AsyncWindowContext,
11002    ) -> Vec<((BufferId, u32), RunnableTasks)> {
11003        runnable_ranges
11004            .into_iter()
11005            .filter_map(|mut runnable| {
11006                let tasks = cx
11007                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11008                    .ok()?;
11009                if tasks.is_empty() {
11010                    return None;
11011                }
11012
11013                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11014
11015                let row = snapshot
11016                    .buffer_snapshot
11017                    .buffer_line_for_row(MultiBufferRow(point.row))?
11018                    .1
11019                    .start
11020                    .row;
11021
11022                let context_range =
11023                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11024                Some((
11025                    (runnable.buffer_id, row),
11026                    RunnableTasks {
11027                        templates: tasks,
11028                        offset: snapshot
11029                            .buffer_snapshot
11030                            .anchor_before(runnable.run_range.start),
11031                        context_range,
11032                        column: point.column,
11033                        extra_variables: runnable.extra_captures,
11034                    },
11035                ))
11036            })
11037            .collect()
11038    }
11039
11040    fn templates_with_tags(
11041        project: &Entity<Project>,
11042        runnable: &mut Runnable,
11043        cx: &mut App,
11044    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11045        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11046            let (worktree_id, file) = project
11047                .buffer_for_id(runnable.buffer, cx)
11048                .and_then(|buffer| buffer.read(cx).file())
11049                .map(|file| (file.worktree_id(cx), file.clone()))
11050                .unzip();
11051
11052            (
11053                project.task_store().read(cx).task_inventory().cloned(),
11054                worktree_id,
11055                file,
11056            )
11057        });
11058
11059        let tags = mem::take(&mut runnable.tags);
11060        let mut tags: Vec<_> = tags
11061            .into_iter()
11062            .flat_map(|tag| {
11063                let tag = tag.0.clone();
11064                inventory
11065                    .as_ref()
11066                    .into_iter()
11067                    .flat_map(|inventory| {
11068                        inventory.read(cx).list_tasks(
11069                            file.clone(),
11070                            Some(runnable.language.clone()),
11071                            worktree_id,
11072                            cx,
11073                        )
11074                    })
11075                    .filter(move |(_, template)| {
11076                        template.tags.iter().any(|source_tag| source_tag == &tag)
11077                    })
11078            })
11079            .sorted_by_key(|(kind, _)| kind.to_owned())
11080            .collect();
11081        if let Some((leading_tag_source, _)) = tags.first() {
11082            // Strongest source wins; if we have worktree tag binding, prefer that to
11083            // global and language bindings;
11084            // if we have a global binding, prefer that to language binding.
11085            let first_mismatch = tags
11086                .iter()
11087                .position(|(tag_source, _)| tag_source != leading_tag_source);
11088            if let Some(index) = first_mismatch {
11089                tags.truncate(index);
11090            }
11091        }
11092
11093        tags
11094    }
11095
11096    pub fn move_to_enclosing_bracket(
11097        &mut self,
11098        _: &MoveToEnclosingBracket,
11099        window: &mut Window,
11100        cx: &mut Context<Self>,
11101    ) {
11102        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11103            s.move_offsets_with(|snapshot, selection| {
11104                let Some(enclosing_bracket_ranges) =
11105                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11106                else {
11107                    return;
11108                };
11109
11110                let mut best_length = usize::MAX;
11111                let mut best_inside = false;
11112                let mut best_in_bracket_range = false;
11113                let mut best_destination = None;
11114                for (open, close) in enclosing_bracket_ranges {
11115                    let close = close.to_inclusive();
11116                    let length = close.end() - open.start;
11117                    let inside = selection.start >= open.end && selection.end <= *close.start();
11118                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
11119                        || close.contains(&selection.head());
11120
11121                    // If best is next to a bracket and current isn't, skip
11122                    if !in_bracket_range && best_in_bracket_range {
11123                        continue;
11124                    }
11125
11126                    // Prefer smaller lengths unless best is inside and current isn't
11127                    if length > best_length && (best_inside || !inside) {
11128                        continue;
11129                    }
11130
11131                    best_length = length;
11132                    best_inside = inside;
11133                    best_in_bracket_range = in_bracket_range;
11134                    best_destination = Some(
11135                        if close.contains(&selection.start) && close.contains(&selection.end) {
11136                            if inside {
11137                                open.end
11138                            } else {
11139                                open.start
11140                            }
11141                        } else if inside {
11142                            *close.start()
11143                        } else {
11144                            *close.end()
11145                        },
11146                    );
11147                }
11148
11149                if let Some(destination) = best_destination {
11150                    selection.collapse_to(destination, SelectionGoal::None);
11151                }
11152            })
11153        });
11154    }
11155
11156    pub fn undo_selection(
11157        &mut self,
11158        _: &UndoSelection,
11159        window: &mut Window,
11160        cx: &mut Context<Self>,
11161    ) {
11162        self.end_selection(window, cx);
11163        self.selection_history.mode = SelectionHistoryMode::Undoing;
11164        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11165            self.change_selections(None, window, cx, |s| {
11166                s.select_anchors(entry.selections.to_vec())
11167            });
11168            self.select_next_state = entry.select_next_state;
11169            self.select_prev_state = entry.select_prev_state;
11170            self.add_selections_state = entry.add_selections_state;
11171            self.request_autoscroll(Autoscroll::newest(), cx);
11172        }
11173        self.selection_history.mode = SelectionHistoryMode::Normal;
11174    }
11175
11176    pub fn redo_selection(
11177        &mut self,
11178        _: &RedoSelection,
11179        window: &mut Window,
11180        cx: &mut Context<Self>,
11181    ) {
11182        self.end_selection(window, cx);
11183        self.selection_history.mode = SelectionHistoryMode::Redoing;
11184        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11185            self.change_selections(None, window, cx, |s| {
11186                s.select_anchors(entry.selections.to_vec())
11187            });
11188            self.select_next_state = entry.select_next_state;
11189            self.select_prev_state = entry.select_prev_state;
11190            self.add_selections_state = entry.add_selections_state;
11191            self.request_autoscroll(Autoscroll::newest(), cx);
11192        }
11193        self.selection_history.mode = SelectionHistoryMode::Normal;
11194    }
11195
11196    pub fn expand_excerpts(
11197        &mut self,
11198        action: &ExpandExcerpts,
11199        _: &mut Window,
11200        cx: &mut Context<Self>,
11201    ) {
11202        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11203    }
11204
11205    pub fn expand_excerpts_down(
11206        &mut self,
11207        action: &ExpandExcerptsDown,
11208        _: &mut Window,
11209        cx: &mut Context<Self>,
11210    ) {
11211        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11212    }
11213
11214    pub fn expand_excerpts_up(
11215        &mut self,
11216        action: &ExpandExcerptsUp,
11217        _: &mut Window,
11218        cx: &mut Context<Self>,
11219    ) {
11220        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11221    }
11222
11223    pub fn expand_excerpts_for_direction(
11224        &mut self,
11225        lines: u32,
11226        direction: ExpandExcerptDirection,
11227
11228        cx: &mut Context<Self>,
11229    ) {
11230        let selections = self.selections.disjoint_anchors();
11231
11232        let lines = if lines == 0 {
11233            EditorSettings::get_global(cx).expand_excerpt_lines
11234        } else {
11235            lines
11236        };
11237
11238        self.buffer.update(cx, |buffer, cx| {
11239            let snapshot = buffer.snapshot(cx);
11240            let mut excerpt_ids = selections
11241                .iter()
11242                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11243                .collect::<Vec<_>>();
11244            excerpt_ids.sort();
11245            excerpt_ids.dedup();
11246            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11247        })
11248    }
11249
11250    pub fn expand_excerpt(
11251        &mut self,
11252        excerpt: ExcerptId,
11253        direction: ExpandExcerptDirection,
11254        cx: &mut Context<Self>,
11255    ) {
11256        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11257        self.buffer.update(cx, |buffer, cx| {
11258            buffer.expand_excerpts([excerpt], lines, direction, cx)
11259        })
11260    }
11261
11262    pub fn go_to_singleton_buffer_point(
11263        &mut self,
11264        point: Point,
11265        window: &mut Window,
11266        cx: &mut Context<Self>,
11267    ) {
11268        self.go_to_singleton_buffer_range(point..point, window, cx);
11269    }
11270
11271    pub fn go_to_singleton_buffer_range(
11272        &mut self,
11273        range: Range<Point>,
11274        window: &mut Window,
11275        cx: &mut Context<Self>,
11276    ) {
11277        let multibuffer = self.buffer().read(cx);
11278        let Some(buffer) = multibuffer.as_singleton() else {
11279            return;
11280        };
11281        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11282            return;
11283        };
11284        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11285            return;
11286        };
11287        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11288            s.select_anchor_ranges([start..end])
11289        });
11290    }
11291
11292    fn go_to_diagnostic(
11293        &mut self,
11294        _: &GoToDiagnostic,
11295        window: &mut Window,
11296        cx: &mut Context<Self>,
11297    ) {
11298        self.go_to_diagnostic_impl(Direction::Next, window, cx)
11299    }
11300
11301    fn go_to_prev_diagnostic(
11302        &mut self,
11303        _: &GoToPreviousDiagnostic,
11304        window: &mut Window,
11305        cx: &mut Context<Self>,
11306    ) {
11307        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11308    }
11309
11310    pub fn go_to_diagnostic_impl(
11311        &mut self,
11312        direction: Direction,
11313        window: &mut Window,
11314        cx: &mut Context<Self>,
11315    ) {
11316        let buffer = self.buffer.read(cx).snapshot(cx);
11317        let selection = self.selections.newest::<usize>(cx);
11318
11319        // If there is an active Diagnostic Popover jump to its diagnostic instead.
11320        if direction == Direction::Next {
11321            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11322                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11323                    return;
11324                };
11325                self.activate_diagnostics(
11326                    buffer_id,
11327                    popover.local_diagnostic.diagnostic.group_id,
11328                    window,
11329                    cx,
11330                );
11331                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11332                    let primary_range_start = active_diagnostics.primary_range.start;
11333                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11334                        let mut new_selection = s.newest_anchor().clone();
11335                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11336                        s.select_anchors(vec![new_selection.clone()]);
11337                    });
11338                    self.refresh_inline_completion(false, true, window, cx);
11339                }
11340                return;
11341            }
11342        }
11343
11344        let active_group_id = self
11345            .active_diagnostics
11346            .as_ref()
11347            .map(|active_group| active_group.group_id);
11348        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11349            active_diagnostics
11350                .primary_range
11351                .to_offset(&buffer)
11352                .to_inclusive()
11353        });
11354        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11355            if active_primary_range.contains(&selection.head()) {
11356                *active_primary_range.start()
11357            } else {
11358                selection.head()
11359            }
11360        } else {
11361            selection.head()
11362        };
11363
11364        let snapshot = self.snapshot(window, cx);
11365        let primary_diagnostics_before = buffer
11366            .diagnostics_in_range::<usize>(0..search_start)
11367            .filter(|entry| entry.diagnostic.is_primary)
11368            .filter(|entry| entry.range.start != entry.range.end)
11369            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11370            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11371            .collect::<Vec<_>>();
11372        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11373            primary_diagnostics_before
11374                .iter()
11375                .position(|entry| entry.diagnostic.group_id == active_group_id)
11376        });
11377
11378        let primary_diagnostics_after = buffer
11379            .diagnostics_in_range::<usize>(search_start..buffer.len())
11380            .filter(|entry| entry.diagnostic.is_primary)
11381            .filter(|entry| entry.range.start != entry.range.end)
11382            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11383            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11384            .collect::<Vec<_>>();
11385        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11386            primary_diagnostics_after
11387                .iter()
11388                .enumerate()
11389                .rev()
11390                .find_map(|(i, entry)| {
11391                    if entry.diagnostic.group_id == active_group_id {
11392                        Some(i)
11393                    } else {
11394                        None
11395                    }
11396                })
11397        });
11398
11399        let next_primary_diagnostic = match direction {
11400            Direction::Prev => primary_diagnostics_before
11401                .iter()
11402                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11403                .rev()
11404                .next(),
11405            Direction::Next => primary_diagnostics_after
11406                .iter()
11407                .skip(
11408                    last_same_group_diagnostic_after
11409                        .map(|index| index + 1)
11410                        .unwrap_or(0),
11411                )
11412                .next(),
11413        };
11414
11415        // Cycle around to the start of the buffer, potentially moving back to the start of
11416        // the currently active diagnostic.
11417        let cycle_around = || match direction {
11418            Direction::Prev => primary_diagnostics_after
11419                .iter()
11420                .rev()
11421                .chain(primary_diagnostics_before.iter().rev())
11422                .next(),
11423            Direction::Next => primary_diagnostics_before
11424                .iter()
11425                .chain(primary_diagnostics_after.iter())
11426                .next(),
11427        };
11428
11429        if let Some((primary_range, group_id)) = next_primary_diagnostic
11430            .or_else(cycle_around)
11431            .map(|entry| (&entry.range, entry.diagnostic.group_id))
11432        {
11433            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11434                return;
11435            };
11436            self.activate_diagnostics(buffer_id, group_id, window, cx);
11437            if self.active_diagnostics.is_some() {
11438                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11439                    s.select(vec![Selection {
11440                        id: selection.id,
11441                        start: primary_range.start,
11442                        end: primary_range.start,
11443                        reversed: false,
11444                        goal: SelectionGoal::None,
11445                    }]);
11446                });
11447                self.refresh_inline_completion(false, true, window, cx);
11448            }
11449        }
11450    }
11451
11452    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11453        let snapshot = self.snapshot(window, cx);
11454        let selection = self.selections.newest::<Point>(cx);
11455        self.go_to_hunk_after_or_before_position(
11456            &snapshot,
11457            selection.head(),
11458            Direction::Next,
11459            window,
11460            cx,
11461        );
11462    }
11463
11464    fn go_to_hunk_after_or_before_position(
11465        &mut self,
11466        snapshot: &EditorSnapshot,
11467        position: Point,
11468        direction: Direction,
11469        window: &mut Window,
11470        cx: &mut Context<Editor>,
11471    ) {
11472        let row = if direction == Direction::Next {
11473            self.hunk_after_position(snapshot, position)
11474                .map(|hunk| hunk.row_range.start)
11475        } else {
11476            self.hunk_before_position(snapshot, position)
11477        };
11478
11479        if let Some(row) = row {
11480            let destination = Point::new(row.0, 0);
11481            let autoscroll = Autoscroll::center();
11482
11483            self.unfold_ranges(&[destination..destination], false, false, cx);
11484            self.change_selections(Some(autoscroll), window, cx, |s| {
11485                s.select_ranges([destination..destination]);
11486            });
11487        }
11488    }
11489
11490    fn hunk_after_position(
11491        &mut self,
11492        snapshot: &EditorSnapshot,
11493        position: Point,
11494    ) -> Option<MultiBufferDiffHunk> {
11495        snapshot
11496            .buffer_snapshot
11497            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11498            .find(|hunk| hunk.row_range.start.0 > position.row)
11499            .or_else(|| {
11500                snapshot
11501                    .buffer_snapshot
11502                    .diff_hunks_in_range(Point::zero()..position)
11503                    .find(|hunk| hunk.row_range.end.0 < position.row)
11504            })
11505    }
11506
11507    fn go_to_prev_hunk(
11508        &mut self,
11509        _: &GoToPreviousHunk,
11510        window: &mut Window,
11511        cx: &mut Context<Self>,
11512    ) {
11513        let snapshot = self.snapshot(window, cx);
11514        let selection = self.selections.newest::<Point>(cx);
11515        self.go_to_hunk_after_or_before_position(
11516            &snapshot,
11517            selection.head(),
11518            Direction::Prev,
11519            window,
11520            cx,
11521        );
11522    }
11523
11524    fn hunk_before_position(
11525        &mut self,
11526        snapshot: &EditorSnapshot,
11527        position: Point,
11528    ) -> Option<MultiBufferRow> {
11529        snapshot
11530            .buffer_snapshot
11531            .diff_hunk_before(position)
11532            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11533    }
11534
11535    pub fn go_to_definition(
11536        &mut self,
11537        _: &GoToDefinition,
11538        window: &mut Window,
11539        cx: &mut Context<Self>,
11540    ) -> Task<Result<Navigated>> {
11541        let definition =
11542            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11543        cx.spawn_in(window, |editor, mut cx| async move {
11544            if definition.await? == Navigated::Yes {
11545                return Ok(Navigated::Yes);
11546            }
11547            match editor.update_in(&mut cx, |editor, window, cx| {
11548                editor.find_all_references(&FindAllReferences, window, cx)
11549            })? {
11550                Some(references) => references.await,
11551                None => Ok(Navigated::No),
11552            }
11553        })
11554    }
11555
11556    pub fn go_to_declaration(
11557        &mut self,
11558        _: &GoToDeclaration,
11559        window: &mut Window,
11560        cx: &mut Context<Self>,
11561    ) -> Task<Result<Navigated>> {
11562        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11563    }
11564
11565    pub fn go_to_declaration_split(
11566        &mut self,
11567        _: &GoToDeclaration,
11568        window: &mut Window,
11569        cx: &mut Context<Self>,
11570    ) -> Task<Result<Navigated>> {
11571        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11572    }
11573
11574    pub fn go_to_implementation(
11575        &mut self,
11576        _: &GoToImplementation,
11577        window: &mut Window,
11578        cx: &mut Context<Self>,
11579    ) -> Task<Result<Navigated>> {
11580        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11581    }
11582
11583    pub fn go_to_implementation_split(
11584        &mut self,
11585        _: &GoToImplementationSplit,
11586        window: &mut Window,
11587        cx: &mut Context<Self>,
11588    ) -> Task<Result<Navigated>> {
11589        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11590    }
11591
11592    pub fn go_to_type_definition(
11593        &mut self,
11594        _: &GoToTypeDefinition,
11595        window: &mut Window,
11596        cx: &mut Context<Self>,
11597    ) -> Task<Result<Navigated>> {
11598        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11599    }
11600
11601    pub fn go_to_definition_split(
11602        &mut self,
11603        _: &GoToDefinitionSplit,
11604        window: &mut Window,
11605        cx: &mut Context<Self>,
11606    ) -> Task<Result<Navigated>> {
11607        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11608    }
11609
11610    pub fn go_to_type_definition_split(
11611        &mut self,
11612        _: &GoToTypeDefinitionSplit,
11613        window: &mut Window,
11614        cx: &mut Context<Self>,
11615    ) -> Task<Result<Navigated>> {
11616        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11617    }
11618
11619    fn go_to_definition_of_kind(
11620        &mut self,
11621        kind: GotoDefinitionKind,
11622        split: bool,
11623        window: &mut Window,
11624        cx: &mut Context<Self>,
11625    ) -> Task<Result<Navigated>> {
11626        let Some(provider) = self.semantics_provider.clone() else {
11627            return Task::ready(Ok(Navigated::No));
11628        };
11629        let head = self.selections.newest::<usize>(cx).head();
11630        let buffer = self.buffer.read(cx);
11631        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11632            text_anchor
11633        } else {
11634            return Task::ready(Ok(Navigated::No));
11635        };
11636
11637        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11638            return Task::ready(Ok(Navigated::No));
11639        };
11640
11641        cx.spawn_in(window, |editor, mut cx| async move {
11642            let definitions = definitions.await?;
11643            let navigated = editor
11644                .update_in(&mut cx, |editor, window, cx| {
11645                    editor.navigate_to_hover_links(
11646                        Some(kind),
11647                        definitions
11648                            .into_iter()
11649                            .filter(|location| {
11650                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11651                            })
11652                            .map(HoverLink::Text)
11653                            .collect::<Vec<_>>(),
11654                        split,
11655                        window,
11656                        cx,
11657                    )
11658                })?
11659                .await?;
11660            anyhow::Ok(navigated)
11661        })
11662    }
11663
11664    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11665        let selection = self.selections.newest_anchor();
11666        let head = selection.head();
11667        let tail = selection.tail();
11668
11669        let Some((buffer, start_position)) =
11670            self.buffer.read(cx).text_anchor_for_position(head, cx)
11671        else {
11672            return;
11673        };
11674
11675        let end_position = if head != tail {
11676            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11677                return;
11678            };
11679            Some(pos)
11680        } else {
11681            None
11682        };
11683
11684        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11685            let url = if let Some(end_pos) = end_position {
11686                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11687            } else {
11688                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11689            };
11690
11691            if let Some(url) = url {
11692                editor.update(&mut cx, |_, cx| {
11693                    cx.open_url(&url);
11694                })
11695            } else {
11696                Ok(())
11697            }
11698        });
11699
11700        url_finder.detach();
11701    }
11702
11703    pub fn open_selected_filename(
11704        &mut self,
11705        _: &OpenSelectedFilename,
11706        window: &mut Window,
11707        cx: &mut Context<Self>,
11708    ) {
11709        let Some(workspace) = self.workspace() else {
11710            return;
11711        };
11712
11713        let position = self.selections.newest_anchor().head();
11714
11715        let Some((buffer, buffer_position)) =
11716            self.buffer.read(cx).text_anchor_for_position(position, cx)
11717        else {
11718            return;
11719        };
11720
11721        let project = self.project.clone();
11722
11723        cx.spawn_in(window, |_, mut cx| async move {
11724            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11725
11726            if let Some((_, path)) = result {
11727                workspace
11728                    .update_in(&mut cx, |workspace, window, cx| {
11729                        workspace.open_resolved_path(path, window, cx)
11730                    })?
11731                    .await?;
11732            }
11733            anyhow::Ok(())
11734        })
11735        .detach();
11736    }
11737
11738    pub(crate) fn navigate_to_hover_links(
11739        &mut self,
11740        kind: Option<GotoDefinitionKind>,
11741        mut definitions: Vec<HoverLink>,
11742        split: bool,
11743        window: &mut Window,
11744        cx: &mut Context<Editor>,
11745    ) -> Task<Result<Navigated>> {
11746        // If there is one definition, just open it directly
11747        if definitions.len() == 1 {
11748            let definition = definitions.pop().unwrap();
11749
11750            enum TargetTaskResult {
11751                Location(Option<Location>),
11752                AlreadyNavigated,
11753            }
11754
11755            let target_task = match definition {
11756                HoverLink::Text(link) => {
11757                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11758                }
11759                HoverLink::InlayHint(lsp_location, server_id) => {
11760                    let computation =
11761                        self.compute_target_location(lsp_location, server_id, window, cx);
11762                    cx.background_spawn(async move {
11763                        let location = computation.await?;
11764                        Ok(TargetTaskResult::Location(location))
11765                    })
11766                }
11767                HoverLink::Url(url) => {
11768                    cx.open_url(&url);
11769                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11770                }
11771                HoverLink::File(path) => {
11772                    if let Some(workspace) = self.workspace() {
11773                        cx.spawn_in(window, |_, mut cx| async move {
11774                            workspace
11775                                .update_in(&mut cx, |workspace, window, cx| {
11776                                    workspace.open_resolved_path(path, window, cx)
11777                                })?
11778                                .await
11779                                .map(|_| TargetTaskResult::AlreadyNavigated)
11780                        })
11781                    } else {
11782                        Task::ready(Ok(TargetTaskResult::Location(None)))
11783                    }
11784                }
11785            };
11786            cx.spawn_in(window, |editor, mut cx| async move {
11787                let target = match target_task.await.context("target resolution task")? {
11788                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11789                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11790                    TargetTaskResult::Location(Some(target)) => target,
11791                };
11792
11793                editor.update_in(&mut cx, |editor, window, cx| {
11794                    let Some(workspace) = editor.workspace() else {
11795                        return Navigated::No;
11796                    };
11797                    let pane = workspace.read(cx).active_pane().clone();
11798
11799                    let range = target.range.to_point(target.buffer.read(cx));
11800                    let range = editor.range_for_match(&range);
11801                    let range = collapse_multiline_range(range);
11802
11803                    if !split
11804                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11805                    {
11806                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11807                    } else {
11808                        window.defer(cx, move |window, cx| {
11809                            let target_editor: Entity<Self> =
11810                                workspace.update(cx, |workspace, cx| {
11811                                    let pane = if split {
11812                                        workspace.adjacent_pane(window, cx)
11813                                    } else {
11814                                        workspace.active_pane().clone()
11815                                    };
11816
11817                                    workspace.open_project_item(
11818                                        pane,
11819                                        target.buffer.clone(),
11820                                        true,
11821                                        true,
11822                                        window,
11823                                        cx,
11824                                    )
11825                                });
11826                            target_editor.update(cx, |target_editor, cx| {
11827                                // When selecting a definition in a different buffer, disable the nav history
11828                                // to avoid creating a history entry at the previous cursor location.
11829                                pane.update(cx, |pane, _| pane.disable_history());
11830                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11831                                pane.update(cx, |pane, _| pane.enable_history());
11832                            });
11833                        });
11834                    }
11835                    Navigated::Yes
11836                })
11837            })
11838        } else if !definitions.is_empty() {
11839            cx.spawn_in(window, |editor, mut cx| async move {
11840                let (title, location_tasks, workspace) = editor
11841                    .update_in(&mut cx, |editor, window, cx| {
11842                        let tab_kind = match kind {
11843                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11844                            _ => "Definitions",
11845                        };
11846                        let title = definitions
11847                            .iter()
11848                            .find_map(|definition| match definition {
11849                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11850                                    let buffer = origin.buffer.read(cx);
11851                                    format!(
11852                                        "{} for {}",
11853                                        tab_kind,
11854                                        buffer
11855                                            .text_for_range(origin.range.clone())
11856                                            .collect::<String>()
11857                                    )
11858                                }),
11859                                HoverLink::InlayHint(_, _) => None,
11860                                HoverLink::Url(_) => None,
11861                                HoverLink::File(_) => None,
11862                            })
11863                            .unwrap_or(tab_kind.to_string());
11864                        let location_tasks = definitions
11865                            .into_iter()
11866                            .map(|definition| match definition {
11867                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11868                                HoverLink::InlayHint(lsp_location, server_id) => editor
11869                                    .compute_target_location(lsp_location, server_id, window, cx),
11870                                HoverLink::Url(_) => Task::ready(Ok(None)),
11871                                HoverLink::File(_) => Task::ready(Ok(None)),
11872                            })
11873                            .collect::<Vec<_>>();
11874                        (title, location_tasks, editor.workspace().clone())
11875                    })
11876                    .context("location tasks preparation")?;
11877
11878                let locations = future::join_all(location_tasks)
11879                    .await
11880                    .into_iter()
11881                    .filter_map(|location| location.transpose())
11882                    .collect::<Result<_>>()
11883                    .context("location tasks")?;
11884
11885                let Some(workspace) = workspace else {
11886                    return Ok(Navigated::No);
11887                };
11888                let opened = workspace
11889                    .update_in(&mut cx, |workspace, window, cx| {
11890                        Self::open_locations_in_multibuffer(
11891                            workspace,
11892                            locations,
11893                            title,
11894                            split,
11895                            MultibufferSelectionMode::First,
11896                            window,
11897                            cx,
11898                        )
11899                    })
11900                    .ok();
11901
11902                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11903            })
11904        } else {
11905            Task::ready(Ok(Navigated::No))
11906        }
11907    }
11908
11909    fn compute_target_location(
11910        &self,
11911        lsp_location: lsp::Location,
11912        server_id: LanguageServerId,
11913        window: &mut Window,
11914        cx: &mut Context<Self>,
11915    ) -> Task<anyhow::Result<Option<Location>>> {
11916        let Some(project) = self.project.clone() else {
11917            return Task::ready(Ok(None));
11918        };
11919
11920        cx.spawn_in(window, move |editor, mut cx| async move {
11921            let location_task = editor.update(&mut cx, |_, cx| {
11922                project.update(cx, |project, cx| {
11923                    let language_server_name = project
11924                        .language_server_statuses(cx)
11925                        .find(|(id, _)| server_id == *id)
11926                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11927                    language_server_name.map(|language_server_name| {
11928                        project.open_local_buffer_via_lsp(
11929                            lsp_location.uri.clone(),
11930                            server_id,
11931                            language_server_name,
11932                            cx,
11933                        )
11934                    })
11935                })
11936            })?;
11937            let location = match location_task {
11938                Some(task) => Some({
11939                    let target_buffer_handle = task.await.context("open local buffer")?;
11940                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11941                        let target_start = target_buffer
11942                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11943                        let target_end = target_buffer
11944                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11945                        target_buffer.anchor_after(target_start)
11946                            ..target_buffer.anchor_before(target_end)
11947                    })?;
11948                    Location {
11949                        buffer: target_buffer_handle,
11950                        range,
11951                    }
11952                }),
11953                None => None,
11954            };
11955            Ok(location)
11956        })
11957    }
11958
11959    pub fn find_all_references(
11960        &mut self,
11961        _: &FindAllReferences,
11962        window: &mut Window,
11963        cx: &mut Context<Self>,
11964    ) -> Option<Task<Result<Navigated>>> {
11965        let selection = self.selections.newest::<usize>(cx);
11966        let multi_buffer = self.buffer.read(cx);
11967        let head = selection.head();
11968
11969        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11970        let head_anchor = multi_buffer_snapshot.anchor_at(
11971            head,
11972            if head < selection.tail() {
11973                Bias::Right
11974            } else {
11975                Bias::Left
11976            },
11977        );
11978
11979        match self
11980            .find_all_references_task_sources
11981            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11982        {
11983            Ok(_) => {
11984                log::info!(
11985                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11986                );
11987                return None;
11988            }
11989            Err(i) => {
11990                self.find_all_references_task_sources.insert(i, head_anchor);
11991            }
11992        }
11993
11994        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11995        let workspace = self.workspace()?;
11996        let project = workspace.read(cx).project().clone();
11997        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11998        Some(cx.spawn_in(window, |editor, mut cx| async move {
11999            let _cleanup = defer({
12000                let mut cx = cx.clone();
12001                move || {
12002                    let _ = editor.update(&mut cx, |editor, _| {
12003                        if let Ok(i) =
12004                            editor
12005                                .find_all_references_task_sources
12006                                .binary_search_by(|anchor| {
12007                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
12008                                })
12009                        {
12010                            editor.find_all_references_task_sources.remove(i);
12011                        }
12012                    });
12013                }
12014            });
12015
12016            let locations = references.await?;
12017            if locations.is_empty() {
12018                return anyhow::Ok(Navigated::No);
12019            }
12020
12021            workspace.update_in(&mut cx, |workspace, window, cx| {
12022                let title = locations
12023                    .first()
12024                    .as_ref()
12025                    .map(|location| {
12026                        let buffer = location.buffer.read(cx);
12027                        format!(
12028                            "References to `{}`",
12029                            buffer
12030                                .text_for_range(location.range.clone())
12031                                .collect::<String>()
12032                        )
12033                    })
12034                    .unwrap();
12035                Self::open_locations_in_multibuffer(
12036                    workspace,
12037                    locations,
12038                    title,
12039                    false,
12040                    MultibufferSelectionMode::First,
12041                    window,
12042                    cx,
12043                );
12044                Navigated::Yes
12045            })
12046        }))
12047    }
12048
12049    /// Opens a multibuffer with the given project locations in it
12050    pub fn open_locations_in_multibuffer(
12051        workspace: &mut Workspace,
12052        mut locations: Vec<Location>,
12053        title: String,
12054        split: bool,
12055        multibuffer_selection_mode: MultibufferSelectionMode,
12056        window: &mut Window,
12057        cx: &mut Context<Workspace>,
12058    ) {
12059        // If there are multiple definitions, open them in a multibuffer
12060        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12061        let mut locations = locations.into_iter().peekable();
12062        let mut ranges = Vec::new();
12063        let capability = workspace.project().read(cx).capability();
12064
12065        let excerpt_buffer = cx.new(|cx| {
12066            let mut multibuffer = MultiBuffer::new(capability);
12067            while let Some(location) = locations.next() {
12068                let buffer = location.buffer.read(cx);
12069                let mut ranges_for_buffer = Vec::new();
12070                let range = location.range.to_offset(buffer);
12071                ranges_for_buffer.push(range.clone());
12072
12073                while let Some(next_location) = locations.peek() {
12074                    if next_location.buffer == location.buffer {
12075                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
12076                        locations.next();
12077                    } else {
12078                        break;
12079                    }
12080                }
12081
12082                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12083                ranges.extend(multibuffer.push_excerpts_with_context_lines(
12084                    location.buffer.clone(),
12085                    ranges_for_buffer,
12086                    DEFAULT_MULTIBUFFER_CONTEXT,
12087                    cx,
12088                ))
12089            }
12090
12091            multibuffer.with_title(title)
12092        });
12093
12094        let editor = cx.new(|cx| {
12095            Editor::for_multibuffer(
12096                excerpt_buffer,
12097                Some(workspace.project().clone()),
12098                true,
12099                window,
12100                cx,
12101            )
12102        });
12103        editor.update(cx, |editor, cx| {
12104            match multibuffer_selection_mode {
12105                MultibufferSelectionMode::First => {
12106                    if let Some(first_range) = ranges.first() {
12107                        editor.change_selections(None, window, cx, |selections| {
12108                            selections.clear_disjoint();
12109                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12110                        });
12111                    }
12112                    editor.highlight_background::<Self>(
12113                        &ranges,
12114                        |theme| theme.editor_highlighted_line_background,
12115                        cx,
12116                    );
12117                }
12118                MultibufferSelectionMode::All => {
12119                    editor.change_selections(None, window, cx, |selections| {
12120                        selections.clear_disjoint();
12121                        selections.select_anchor_ranges(ranges);
12122                    });
12123                }
12124            }
12125            editor.register_buffers_with_language_servers(cx);
12126        });
12127
12128        let item = Box::new(editor);
12129        let item_id = item.item_id();
12130
12131        if split {
12132            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12133        } else {
12134            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12135                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12136                    pane.close_current_preview_item(window, cx)
12137                } else {
12138                    None
12139                }
12140            });
12141            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12142        }
12143        workspace.active_pane().update(cx, |pane, cx| {
12144            pane.set_preview_item_id(Some(item_id), cx);
12145        });
12146    }
12147
12148    pub fn rename(
12149        &mut self,
12150        _: &Rename,
12151        window: &mut Window,
12152        cx: &mut Context<Self>,
12153    ) -> Option<Task<Result<()>>> {
12154        use language::ToOffset as _;
12155
12156        let provider = self.semantics_provider.clone()?;
12157        let selection = self.selections.newest_anchor().clone();
12158        let (cursor_buffer, cursor_buffer_position) = self
12159            .buffer
12160            .read(cx)
12161            .text_anchor_for_position(selection.head(), cx)?;
12162        let (tail_buffer, cursor_buffer_position_end) = self
12163            .buffer
12164            .read(cx)
12165            .text_anchor_for_position(selection.tail(), cx)?;
12166        if tail_buffer != cursor_buffer {
12167            return None;
12168        }
12169
12170        let snapshot = cursor_buffer.read(cx).snapshot();
12171        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12172        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12173        let prepare_rename = provider
12174            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12175            .unwrap_or_else(|| Task::ready(Ok(None)));
12176        drop(snapshot);
12177
12178        Some(cx.spawn_in(window, |this, mut cx| async move {
12179            let rename_range = if let Some(range) = prepare_rename.await? {
12180                Some(range)
12181            } else {
12182                this.update(&mut cx, |this, cx| {
12183                    let buffer = this.buffer.read(cx).snapshot(cx);
12184                    let mut buffer_highlights = this
12185                        .document_highlights_for_position(selection.head(), &buffer)
12186                        .filter(|highlight| {
12187                            highlight.start.excerpt_id == selection.head().excerpt_id
12188                                && highlight.end.excerpt_id == selection.head().excerpt_id
12189                        });
12190                    buffer_highlights
12191                        .next()
12192                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12193                })?
12194            };
12195            if let Some(rename_range) = rename_range {
12196                this.update_in(&mut cx, |this, window, cx| {
12197                    let snapshot = cursor_buffer.read(cx).snapshot();
12198                    let rename_buffer_range = rename_range.to_offset(&snapshot);
12199                    let cursor_offset_in_rename_range =
12200                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12201                    let cursor_offset_in_rename_range_end =
12202                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12203
12204                    this.take_rename(false, window, cx);
12205                    let buffer = this.buffer.read(cx).read(cx);
12206                    let cursor_offset = selection.head().to_offset(&buffer);
12207                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12208                    let rename_end = rename_start + rename_buffer_range.len();
12209                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12210                    let mut old_highlight_id = None;
12211                    let old_name: Arc<str> = buffer
12212                        .chunks(rename_start..rename_end, true)
12213                        .map(|chunk| {
12214                            if old_highlight_id.is_none() {
12215                                old_highlight_id = chunk.syntax_highlight_id;
12216                            }
12217                            chunk.text
12218                        })
12219                        .collect::<String>()
12220                        .into();
12221
12222                    drop(buffer);
12223
12224                    // Position the selection in the rename editor so that it matches the current selection.
12225                    this.show_local_selections = false;
12226                    let rename_editor = cx.new(|cx| {
12227                        let mut editor = Editor::single_line(window, cx);
12228                        editor.buffer.update(cx, |buffer, cx| {
12229                            buffer.edit([(0..0, old_name.clone())], None, cx)
12230                        });
12231                        let rename_selection_range = match cursor_offset_in_rename_range
12232                            .cmp(&cursor_offset_in_rename_range_end)
12233                        {
12234                            Ordering::Equal => {
12235                                editor.select_all(&SelectAll, window, cx);
12236                                return editor;
12237                            }
12238                            Ordering::Less => {
12239                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12240                            }
12241                            Ordering::Greater => {
12242                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12243                            }
12244                        };
12245                        if rename_selection_range.end > old_name.len() {
12246                            editor.select_all(&SelectAll, window, cx);
12247                        } else {
12248                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12249                                s.select_ranges([rename_selection_range]);
12250                            });
12251                        }
12252                        editor
12253                    });
12254                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12255                        if e == &EditorEvent::Focused {
12256                            cx.emit(EditorEvent::FocusedIn)
12257                        }
12258                    })
12259                    .detach();
12260
12261                    let write_highlights =
12262                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12263                    let read_highlights =
12264                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
12265                    let ranges = write_highlights
12266                        .iter()
12267                        .flat_map(|(_, ranges)| ranges.iter())
12268                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12269                        .cloned()
12270                        .collect();
12271
12272                    this.highlight_text::<Rename>(
12273                        ranges,
12274                        HighlightStyle {
12275                            fade_out: Some(0.6),
12276                            ..Default::default()
12277                        },
12278                        cx,
12279                    );
12280                    let rename_focus_handle = rename_editor.focus_handle(cx);
12281                    window.focus(&rename_focus_handle);
12282                    let block_id = this.insert_blocks(
12283                        [BlockProperties {
12284                            style: BlockStyle::Flex,
12285                            placement: BlockPlacement::Below(range.start),
12286                            height: 1,
12287                            render: Arc::new({
12288                                let rename_editor = rename_editor.clone();
12289                                move |cx: &mut BlockContext| {
12290                                    let mut text_style = cx.editor_style.text.clone();
12291                                    if let Some(highlight_style) = old_highlight_id
12292                                        .and_then(|h| h.style(&cx.editor_style.syntax))
12293                                    {
12294                                        text_style = text_style.highlight(highlight_style);
12295                                    }
12296                                    div()
12297                                        .block_mouse_down()
12298                                        .pl(cx.anchor_x)
12299                                        .child(EditorElement::new(
12300                                            &rename_editor,
12301                                            EditorStyle {
12302                                                background: cx.theme().system().transparent,
12303                                                local_player: cx.editor_style.local_player,
12304                                                text: text_style,
12305                                                scrollbar_width: cx.editor_style.scrollbar_width,
12306                                                syntax: cx.editor_style.syntax.clone(),
12307                                                status: cx.editor_style.status.clone(),
12308                                                inlay_hints_style: HighlightStyle {
12309                                                    font_weight: Some(FontWeight::BOLD),
12310                                                    ..make_inlay_hints_style(cx.app)
12311                                                },
12312                                                inline_completion_styles: make_suggestion_styles(
12313                                                    cx.app,
12314                                                ),
12315                                                ..EditorStyle::default()
12316                                            },
12317                                        ))
12318                                        .into_any_element()
12319                                }
12320                            }),
12321                            priority: 0,
12322                        }],
12323                        Some(Autoscroll::fit()),
12324                        cx,
12325                    )[0];
12326                    this.pending_rename = Some(RenameState {
12327                        range,
12328                        old_name,
12329                        editor: rename_editor,
12330                        block_id,
12331                    });
12332                })?;
12333            }
12334
12335            Ok(())
12336        }))
12337    }
12338
12339    pub fn confirm_rename(
12340        &mut self,
12341        _: &ConfirmRename,
12342        window: &mut Window,
12343        cx: &mut Context<Self>,
12344    ) -> Option<Task<Result<()>>> {
12345        let rename = self.take_rename(false, window, cx)?;
12346        let workspace = self.workspace()?.downgrade();
12347        let (buffer, start) = self
12348            .buffer
12349            .read(cx)
12350            .text_anchor_for_position(rename.range.start, cx)?;
12351        let (end_buffer, _) = self
12352            .buffer
12353            .read(cx)
12354            .text_anchor_for_position(rename.range.end, cx)?;
12355        if buffer != end_buffer {
12356            return None;
12357        }
12358
12359        let old_name = rename.old_name;
12360        let new_name = rename.editor.read(cx).text(cx);
12361
12362        let rename = self.semantics_provider.as_ref()?.perform_rename(
12363            &buffer,
12364            start,
12365            new_name.clone(),
12366            cx,
12367        )?;
12368
12369        Some(cx.spawn_in(window, |editor, mut cx| async move {
12370            let project_transaction = rename.await?;
12371            Self::open_project_transaction(
12372                &editor,
12373                workspace,
12374                project_transaction,
12375                format!("Rename: {}{}", old_name, new_name),
12376                cx.clone(),
12377            )
12378            .await?;
12379
12380            editor.update(&mut cx, |editor, cx| {
12381                editor.refresh_document_highlights(cx);
12382            })?;
12383            Ok(())
12384        }))
12385    }
12386
12387    fn take_rename(
12388        &mut self,
12389        moving_cursor: bool,
12390        window: &mut Window,
12391        cx: &mut Context<Self>,
12392    ) -> Option<RenameState> {
12393        let rename = self.pending_rename.take()?;
12394        if rename.editor.focus_handle(cx).is_focused(window) {
12395            window.focus(&self.focus_handle);
12396        }
12397
12398        self.remove_blocks(
12399            [rename.block_id].into_iter().collect(),
12400            Some(Autoscroll::fit()),
12401            cx,
12402        );
12403        self.clear_highlights::<Rename>(cx);
12404        self.show_local_selections = true;
12405
12406        if moving_cursor {
12407            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12408                editor.selections.newest::<usize>(cx).head()
12409            });
12410
12411            // Update the selection to match the position of the selection inside
12412            // the rename editor.
12413            let snapshot = self.buffer.read(cx).read(cx);
12414            let rename_range = rename.range.to_offset(&snapshot);
12415            let cursor_in_editor = snapshot
12416                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12417                .min(rename_range.end);
12418            drop(snapshot);
12419
12420            self.change_selections(None, window, cx, |s| {
12421                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12422            });
12423        } else {
12424            self.refresh_document_highlights(cx);
12425        }
12426
12427        Some(rename)
12428    }
12429
12430    pub fn pending_rename(&self) -> Option<&RenameState> {
12431        self.pending_rename.as_ref()
12432    }
12433
12434    fn format(
12435        &mut self,
12436        _: &Format,
12437        window: &mut Window,
12438        cx: &mut Context<Self>,
12439    ) -> Option<Task<Result<()>>> {
12440        let project = match &self.project {
12441            Some(project) => project.clone(),
12442            None => return None,
12443        };
12444
12445        Some(self.perform_format(
12446            project,
12447            FormatTrigger::Manual,
12448            FormatTarget::Buffers,
12449            window,
12450            cx,
12451        ))
12452    }
12453
12454    fn format_selections(
12455        &mut self,
12456        _: &FormatSelections,
12457        window: &mut Window,
12458        cx: &mut Context<Self>,
12459    ) -> Option<Task<Result<()>>> {
12460        let project = match &self.project {
12461            Some(project) => project.clone(),
12462            None => return None,
12463        };
12464
12465        let ranges = self
12466            .selections
12467            .all_adjusted(cx)
12468            .into_iter()
12469            .map(|selection| selection.range())
12470            .collect_vec();
12471
12472        Some(self.perform_format(
12473            project,
12474            FormatTrigger::Manual,
12475            FormatTarget::Ranges(ranges),
12476            window,
12477            cx,
12478        ))
12479    }
12480
12481    fn perform_format(
12482        &mut self,
12483        project: Entity<Project>,
12484        trigger: FormatTrigger,
12485        target: FormatTarget,
12486        window: &mut Window,
12487        cx: &mut Context<Self>,
12488    ) -> Task<Result<()>> {
12489        let buffer = self.buffer.clone();
12490        let (buffers, target) = match target {
12491            FormatTarget::Buffers => {
12492                let mut buffers = buffer.read(cx).all_buffers();
12493                if trigger == FormatTrigger::Save {
12494                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
12495                }
12496                (buffers, LspFormatTarget::Buffers)
12497            }
12498            FormatTarget::Ranges(selection_ranges) => {
12499                let multi_buffer = buffer.read(cx);
12500                let snapshot = multi_buffer.read(cx);
12501                let mut buffers = HashSet::default();
12502                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12503                    BTreeMap::new();
12504                for selection_range in selection_ranges {
12505                    for (buffer, buffer_range, _) in
12506                        snapshot.range_to_buffer_ranges(selection_range)
12507                    {
12508                        let buffer_id = buffer.remote_id();
12509                        let start = buffer.anchor_before(buffer_range.start);
12510                        let end = buffer.anchor_after(buffer_range.end);
12511                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12512                        buffer_id_to_ranges
12513                            .entry(buffer_id)
12514                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12515                            .or_insert_with(|| vec![start..end]);
12516                    }
12517                }
12518                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12519            }
12520        };
12521
12522        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12523        let format = project.update(cx, |project, cx| {
12524            project.format(buffers, target, true, trigger, cx)
12525        });
12526
12527        cx.spawn_in(window, |_, mut cx| async move {
12528            let transaction = futures::select_biased! {
12529                () = timeout => {
12530                    log::warn!("timed out waiting for formatting");
12531                    None
12532                }
12533                transaction = format.log_err().fuse() => transaction,
12534            };
12535
12536            buffer
12537                .update(&mut cx, |buffer, cx| {
12538                    if let Some(transaction) = transaction {
12539                        if !buffer.is_singleton() {
12540                            buffer.push_transaction(&transaction.0, cx);
12541                        }
12542                    }
12543                    cx.notify();
12544                })
12545                .ok();
12546
12547            Ok(())
12548        })
12549    }
12550
12551    fn organize_imports(
12552        &mut self,
12553        _: &OrganizeImports,
12554        window: &mut Window,
12555        cx: &mut Context<Self>,
12556    ) -> Option<Task<Result<()>>> {
12557        let project = match &self.project {
12558            Some(project) => project.clone(),
12559            None => return None,
12560        };
12561        Some(self.perform_code_action_kind(
12562            project,
12563            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12564            window,
12565            cx,
12566        ))
12567    }
12568
12569    fn perform_code_action_kind(
12570        &mut self,
12571        project: Entity<Project>,
12572        kind: CodeActionKind,
12573        window: &mut Window,
12574        cx: &mut Context<Self>,
12575    ) -> Task<Result<()>> {
12576        let buffer = self.buffer.clone();
12577        let buffers = buffer.read(cx).all_buffers();
12578        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12579        let apply_action = project.update(cx, |project, cx| {
12580            project.apply_code_action_kind(buffers, kind, true, cx)
12581        });
12582        cx.spawn_in(window, |_, mut cx| async move {
12583            let transaction = futures::select_biased! {
12584                () = timeout => {
12585                    log::warn!("timed out waiting for executing code action");
12586                    None
12587                }
12588                transaction = apply_action.log_err().fuse() => transaction,
12589            };
12590            buffer
12591                .update(&mut cx, |buffer, cx| {
12592                    // check if we need this
12593                    if let Some(transaction) = transaction {
12594                        if !buffer.is_singleton() {
12595                            buffer.push_transaction(&transaction.0, cx);
12596                        }
12597                    }
12598                    cx.notify();
12599                })
12600                .ok();
12601            Ok(())
12602        })
12603    }
12604
12605    fn restart_language_server(
12606        &mut self,
12607        _: &RestartLanguageServer,
12608        _: &mut Window,
12609        cx: &mut Context<Self>,
12610    ) {
12611        if let Some(project) = self.project.clone() {
12612            self.buffer.update(cx, |multi_buffer, cx| {
12613                project.update(cx, |project, cx| {
12614                    project.restart_language_servers_for_buffers(
12615                        multi_buffer.all_buffers().into_iter().collect(),
12616                        cx,
12617                    );
12618                });
12619            })
12620        }
12621    }
12622
12623    fn cancel_language_server_work(
12624        workspace: &mut Workspace,
12625        _: &actions::CancelLanguageServerWork,
12626        _: &mut Window,
12627        cx: &mut Context<Workspace>,
12628    ) {
12629        let project = workspace.project();
12630        let buffers = workspace
12631            .active_item(cx)
12632            .and_then(|item| item.act_as::<Editor>(cx))
12633            .map_or(HashSet::default(), |editor| {
12634                editor.read(cx).buffer.read(cx).all_buffers()
12635            });
12636        project.update(cx, |project, cx| {
12637            project.cancel_language_server_work_for_buffers(buffers, cx);
12638        });
12639    }
12640
12641    fn show_character_palette(
12642        &mut self,
12643        _: &ShowCharacterPalette,
12644        window: &mut Window,
12645        _: &mut Context<Self>,
12646    ) {
12647        window.show_character_palette();
12648    }
12649
12650    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12651        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12652            let buffer = self.buffer.read(cx).snapshot(cx);
12653            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12654            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12655            let is_valid = buffer
12656                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12657                .any(|entry| {
12658                    entry.diagnostic.is_primary
12659                        && !entry.range.is_empty()
12660                        && entry.range.start == primary_range_start
12661                        && entry.diagnostic.message == active_diagnostics.primary_message
12662                });
12663
12664            if is_valid != active_diagnostics.is_valid {
12665                active_diagnostics.is_valid = is_valid;
12666                if is_valid {
12667                    let mut new_styles = HashMap::default();
12668                    for (block_id, diagnostic) in &active_diagnostics.blocks {
12669                        new_styles.insert(
12670                            *block_id,
12671                            diagnostic_block_renderer(diagnostic.clone(), None, true),
12672                        );
12673                    }
12674                    self.display_map.update(cx, |display_map, _cx| {
12675                        display_map.replace_blocks(new_styles);
12676                    });
12677                } else {
12678                    self.dismiss_diagnostics(cx);
12679                }
12680            }
12681        }
12682    }
12683
12684    fn activate_diagnostics(
12685        &mut self,
12686        buffer_id: BufferId,
12687        group_id: usize,
12688        window: &mut Window,
12689        cx: &mut Context<Self>,
12690    ) {
12691        self.dismiss_diagnostics(cx);
12692        let snapshot = self.snapshot(window, cx);
12693        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12694            let buffer = self.buffer.read(cx).snapshot(cx);
12695
12696            let mut primary_range = None;
12697            let mut primary_message = None;
12698            let diagnostic_group = buffer
12699                .diagnostic_group(buffer_id, group_id)
12700                .filter_map(|entry| {
12701                    let start = entry.range.start;
12702                    let end = entry.range.end;
12703                    if snapshot.is_line_folded(MultiBufferRow(start.row))
12704                        && (start.row == end.row
12705                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
12706                    {
12707                        return None;
12708                    }
12709                    if entry.diagnostic.is_primary {
12710                        primary_range = Some(entry.range.clone());
12711                        primary_message = Some(entry.diagnostic.message.clone());
12712                    }
12713                    Some(entry)
12714                })
12715                .collect::<Vec<_>>();
12716            let primary_range = primary_range?;
12717            let primary_message = primary_message?;
12718
12719            let blocks = display_map
12720                .insert_blocks(
12721                    diagnostic_group.iter().map(|entry| {
12722                        let diagnostic = entry.diagnostic.clone();
12723                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12724                        BlockProperties {
12725                            style: BlockStyle::Fixed,
12726                            placement: BlockPlacement::Below(
12727                                buffer.anchor_after(entry.range.start),
12728                            ),
12729                            height: message_height,
12730                            render: diagnostic_block_renderer(diagnostic, None, true),
12731                            priority: 0,
12732                        }
12733                    }),
12734                    cx,
12735                )
12736                .into_iter()
12737                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12738                .collect();
12739
12740            Some(ActiveDiagnosticGroup {
12741                primary_range: buffer.anchor_before(primary_range.start)
12742                    ..buffer.anchor_after(primary_range.end),
12743                primary_message,
12744                group_id,
12745                blocks,
12746                is_valid: true,
12747            })
12748        });
12749    }
12750
12751    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12752        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12753            self.display_map.update(cx, |display_map, cx| {
12754                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12755            });
12756            cx.notify();
12757        }
12758    }
12759
12760    /// Disable inline diagnostics rendering for this editor.
12761    pub fn disable_inline_diagnostics(&mut self) {
12762        self.inline_diagnostics_enabled = false;
12763        self.inline_diagnostics_update = Task::ready(());
12764        self.inline_diagnostics.clear();
12765    }
12766
12767    pub fn inline_diagnostics_enabled(&self) -> bool {
12768        self.inline_diagnostics_enabled
12769    }
12770
12771    pub fn show_inline_diagnostics(&self) -> bool {
12772        self.show_inline_diagnostics
12773    }
12774
12775    pub fn toggle_inline_diagnostics(
12776        &mut self,
12777        _: &ToggleInlineDiagnostics,
12778        window: &mut Window,
12779        cx: &mut Context<'_, Editor>,
12780    ) {
12781        self.show_inline_diagnostics = !self.show_inline_diagnostics;
12782        self.refresh_inline_diagnostics(false, window, cx);
12783    }
12784
12785    fn refresh_inline_diagnostics(
12786        &mut self,
12787        debounce: bool,
12788        window: &mut Window,
12789        cx: &mut Context<Self>,
12790    ) {
12791        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12792            self.inline_diagnostics_update = Task::ready(());
12793            self.inline_diagnostics.clear();
12794            return;
12795        }
12796
12797        let debounce_ms = ProjectSettings::get_global(cx)
12798            .diagnostics
12799            .inline
12800            .update_debounce_ms;
12801        let debounce = if debounce && debounce_ms > 0 {
12802            Some(Duration::from_millis(debounce_ms))
12803        } else {
12804            None
12805        };
12806        self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12807            if let Some(debounce) = debounce {
12808                cx.background_executor().timer(debounce).await;
12809            }
12810            let Some(snapshot) = editor
12811                .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12812                .ok()
12813            else {
12814                return;
12815            };
12816
12817            let new_inline_diagnostics = cx
12818                .background_spawn(async move {
12819                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12820                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12821                        let message = diagnostic_entry
12822                            .diagnostic
12823                            .message
12824                            .split_once('\n')
12825                            .map(|(line, _)| line)
12826                            .map(SharedString::new)
12827                            .unwrap_or_else(|| {
12828                                SharedString::from(diagnostic_entry.diagnostic.message)
12829                            });
12830                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12831                        let (Ok(i) | Err(i)) = inline_diagnostics
12832                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12833                        inline_diagnostics.insert(
12834                            i,
12835                            (
12836                                start_anchor,
12837                                InlineDiagnostic {
12838                                    message,
12839                                    group_id: diagnostic_entry.diagnostic.group_id,
12840                                    start: diagnostic_entry.range.start.to_point(&snapshot),
12841                                    is_primary: diagnostic_entry.diagnostic.is_primary,
12842                                    severity: diagnostic_entry.diagnostic.severity,
12843                                },
12844                            ),
12845                        );
12846                    }
12847                    inline_diagnostics
12848                })
12849                .await;
12850
12851            editor
12852                .update(&mut cx, |editor, cx| {
12853                    editor.inline_diagnostics = new_inline_diagnostics;
12854                    cx.notify();
12855                })
12856                .ok();
12857        });
12858    }
12859
12860    pub fn set_selections_from_remote(
12861        &mut self,
12862        selections: Vec<Selection<Anchor>>,
12863        pending_selection: Option<Selection<Anchor>>,
12864        window: &mut Window,
12865        cx: &mut Context<Self>,
12866    ) {
12867        let old_cursor_position = self.selections.newest_anchor().head();
12868        self.selections.change_with(cx, |s| {
12869            s.select_anchors(selections);
12870            if let Some(pending_selection) = pending_selection {
12871                s.set_pending(pending_selection, SelectMode::Character);
12872            } else {
12873                s.clear_pending();
12874            }
12875        });
12876        self.selections_did_change(false, &old_cursor_position, true, window, cx);
12877    }
12878
12879    fn push_to_selection_history(&mut self) {
12880        self.selection_history.push(SelectionHistoryEntry {
12881            selections: self.selections.disjoint_anchors(),
12882            select_next_state: self.select_next_state.clone(),
12883            select_prev_state: self.select_prev_state.clone(),
12884            add_selections_state: self.add_selections_state.clone(),
12885        });
12886    }
12887
12888    pub fn transact(
12889        &mut self,
12890        window: &mut Window,
12891        cx: &mut Context<Self>,
12892        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12893    ) -> Option<TransactionId> {
12894        self.start_transaction_at(Instant::now(), window, cx);
12895        update(self, window, cx);
12896        self.end_transaction_at(Instant::now(), cx)
12897    }
12898
12899    pub fn start_transaction_at(
12900        &mut self,
12901        now: Instant,
12902        window: &mut Window,
12903        cx: &mut Context<Self>,
12904    ) {
12905        self.end_selection(window, cx);
12906        if let Some(tx_id) = self
12907            .buffer
12908            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12909        {
12910            self.selection_history
12911                .insert_transaction(tx_id, self.selections.disjoint_anchors());
12912            cx.emit(EditorEvent::TransactionBegun {
12913                transaction_id: tx_id,
12914            })
12915        }
12916    }
12917
12918    pub fn end_transaction_at(
12919        &mut self,
12920        now: Instant,
12921        cx: &mut Context<Self>,
12922    ) -> Option<TransactionId> {
12923        if let Some(transaction_id) = self
12924            .buffer
12925            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12926        {
12927            if let Some((_, end_selections)) =
12928                self.selection_history.transaction_mut(transaction_id)
12929            {
12930                *end_selections = Some(self.selections.disjoint_anchors());
12931            } else {
12932                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12933            }
12934
12935            cx.emit(EditorEvent::Edited { transaction_id });
12936            Some(transaction_id)
12937        } else {
12938            None
12939        }
12940    }
12941
12942    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12943        if self.selection_mark_mode {
12944            self.change_selections(None, window, cx, |s| {
12945                s.move_with(|_, sel| {
12946                    sel.collapse_to(sel.head(), SelectionGoal::None);
12947                });
12948            })
12949        }
12950        self.selection_mark_mode = true;
12951        cx.notify();
12952    }
12953
12954    pub fn swap_selection_ends(
12955        &mut self,
12956        _: &actions::SwapSelectionEnds,
12957        window: &mut Window,
12958        cx: &mut Context<Self>,
12959    ) {
12960        self.change_selections(None, window, cx, |s| {
12961            s.move_with(|_, sel| {
12962                if sel.start != sel.end {
12963                    sel.reversed = !sel.reversed
12964                }
12965            });
12966        });
12967        self.request_autoscroll(Autoscroll::newest(), cx);
12968        cx.notify();
12969    }
12970
12971    pub fn toggle_fold(
12972        &mut self,
12973        _: &actions::ToggleFold,
12974        window: &mut Window,
12975        cx: &mut Context<Self>,
12976    ) {
12977        if self.is_singleton(cx) {
12978            let selection = self.selections.newest::<Point>(cx);
12979
12980            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12981            let range = if selection.is_empty() {
12982                let point = selection.head().to_display_point(&display_map);
12983                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12984                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12985                    .to_point(&display_map);
12986                start..end
12987            } else {
12988                selection.range()
12989            };
12990            if display_map.folds_in_range(range).next().is_some() {
12991                self.unfold_lines(&Default::default(), window, cx)
12992            } else {
12993                self.fold(&Default::default(), window, cx)
12994            }
12995        } else {
12996            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12997            let buffer_ids: HashSet<_> = self
12998                .selections
12999                .disjoint_anchor_ranges()
13000                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13001                .collect();
13002
13003            let should_unfold = buffer_ids
13004                .iter()
13005                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13006
13007            for buffer_id in buffer_ids {
13008                if should_unfold {
13009                    self.unfold_buffer(buffer_id, cx);
13010                } else {
13011                    self.fold_buffer(buffer_id, cx);
13012                }
13013            }
13014        }
13015    }
13016
13017    pub fn toggle_fold_recursive(
13018        &mut self,
13019        _: &actions::ToggleFoldRecursive,
13020        window: &mut Window,
13021        cx: &mut Context<Self>,
13022    ) {
13023        let selection = self.selections.newest::<Point>(cx);
13024
13025        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13026        let range = if selection.is_empty() {
13027            let point = selection.head().to_display_point(&display_map);
13028            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13029            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13030                .to_point(&display_map);
13031            start..end
13032        } else {
13033            selection.range()
13034        };
13035        if display_map.folds_in_range(range).next().is_some() {
13036            self.unfold_recursive(&Default::default(), window, cx)
13037        } else {
13038            self.fold_recursive(&Default::default(), window, cx)
13039        }
13040    }
13041
13042    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13043        if self.is_singleton(cx) {
13044            let mut to_fold = Vec::new();
13045            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13046            let selections = self.selections.all_adjusted(cx);
13047
13048            for selection in selections {
13049                let range = selection.range().sorted();
13050                let buffer_start_row = range.start.row;
13051
13052                if range.start.row != range.end.row {
13053                    let mut found = false;
13054                    let mut row = range.start.row;
13055                    while row <= range.end.row {
13056                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13057                        {
13058                            found = true;
13059                            row = crease.range().end.row + 1;
13060                            to_fold.push(crease);
13061                        } else {
13062                            row += 1
13063                        }
13064                    }
13065                    if found {
13066                        continue;
13067                    }
13068                }
13069
13070                for row in (0..=range.start.row).rev() {
13071                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13072                        if crease.range().end.row >= buffer_start_row {
13073                            to_fold.push(crease);
13074                            if row <= range.start.row {
13075                                break;
13076                            }
13077                        }
13078                    }
13079                }
13080            }
13081
13082            self.fold_creases(to_fold, true, window, cx);
13083        } else {
13084            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13085            let buffer_ids = self
13086                .selections
13087                .disjoint_anchor_ranges()
13088                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13089                .collect::<HashSet<_>>();
13090            for buffer_id in buffer_ids {
13091                self.fold_buffer(buffer_id, cx);
13092            }
13093        }
13094    }
13095
13096    fn fold_at_level(
13097        &mut self,
13098        fold_at: &FoldAtLevel,
13099        window: &mut Window,
13100        cx: &mut Context<Self>,
13101    ) {
13102        if !self.buffer.read(cx).is_singleton() {
13103            return;
13104        }
13105
13106        let fold_at_level = fold_at.0;
13107        let snapshot = self.buffer.read(cx).snapshot(cx);
13108        let mut to_fold = Vec::new();
13109        let mut stack = vec![(0, snapshot.max_row().0, 1)];
13110
13111        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13112            while start_row < end_row {
13113                match self
13114                    .snapshot(window, cx)
13115                    .crease_for_buffer_row(MultiBufferRow(start_row))
13116                {
13117                    Some(crease) => {
13118                        let nested_start_row = crease.range().start.row + 1;
13119                        let nested_end_row = crease.range().end.row;
13120
13121                        if current_level < fold_at_level {
13122                            stack.push((nested_start_row, nested_end_row, current_level + 1));
13123                        } else if current_level == fold_at_level {
13124                            to_fold.push(crease);
13125                        }
13126
13127                        start_row = nested_end_row + 1;
13128                    }
13129                    None => start_row += 1,
13130                }
13131            }
13132        }
13133
13134        self.fold_creases(to_fold, true, window, cx);
13135    }
13136
13137    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13138        if self.buffer.read(cx).is_singleton() {
13139            let mut fold_ranges = Vec::new();
13140            let snapshot = self.buffer.read(cx).snapshot(cx);
13141
13142            for row in 0..snapshot.max_row().0 {
13143                if let Some(foldable_range) = self
13144                    .snapshot(window, cx)
13145                    .crease_for_buffer_row(MultiBufferRow(row))
13146                {
13147                    fold_ranges.push(foldable_range);
13148                }
13149            }
13150
13151            self.fold_creases(fold_ranges, true, window, cx);
13152        } else {
13153            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13154                editor
13155                    .update_in(&mut cx, |editor, _, cx| {
13156                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13157                            editor.fold_buffer(buffer_id, cx);
13158                        }
13159                    })
13160                    .ok();
13161            });
13162        }
13163    }
13164
13165    pub fn fold_function_bodies(
13166        &mut self,
13167        _: &actions::FoldFunctionBodies,
13168        window: &mut Window,
13169        cx: &mut Context<Self>,
13170    ) {
13171        let snapshot = self.buffer.read(cx).snapshot(cx);
13172
13173        let ranges = snapshot
13174            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13175            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13176            .collect::<Vec<_>>();
13177
13178        let creases = ranges
13179            .into_iter()
13180            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13181            .collect();
13182
13183        self.fold_creases(creases, true, window, cx);
13184    }
13185
13186    pub fn fold_recursive(
13187        &mut self,
13188        _: &actions::FoldRecursive,
13189        window: &mut Window,
13190        cx: &mut Context<Self>,
13191    ) {
13192        let mut to_fold = Vec::new();
13193        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13194        let selections = self.selections.all_adjusted(cx);
13195
13196        for selection in selections {
13197            let range = selection.range().sorted();
13198            let buffer_start_row = range.start.row;
13199
13200            if range.start.row != range.end.row {
13201                let mut found = false;
13202                for row in range.start.row..=range.end.row {
13203                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13204                        found = true;
13205                        to_fold.push(crease);
13206                    }
13207                }
13208                if found {
13209                    continue;
13210                }
13211            }
13212
13213            for row in (0..=range.start.row).rev() {
13214                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13215                    if crease.range().end.row >= buffer_start_row {
13216                        to_fold.push(crease);
13217                    } else {
13218                        break;
13219                    }
13220                }
13221            }
13222        }
13223
13224        self.fold_creases(to_fold, true, window, cx);
13225    }
13226
13227    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13228        let buffer_row = fold_at.buffer_row;
13229        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13230
13231        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13232            let autoscroll = self
13233                .selections
13234                .all::<Point>(cx)
13235                .iter()
13236                .any(|selection| crease.range().overlaps(&selection.range()));
13237
13238            self.fold_creases(vec![crease], autoscroll, window, cx);
13239        }
13240    }
13241
13242    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13243        if self.is_singleton(cx) {
13244            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13245            let buffer = &display_map.buffer_snapshot;
13246            let selections = self.selections.all::<Point>(cx);
13247            let ranges = selections
13248                .iter()
13249                .map(|s| {
13250                    let range = s.display_range(&display_map).sorted();
13251                    let mut start = range.start.to_point(&display_map);
13252                    let mut end = range.end.to_point(&display_map);
13253                    start.column = 0;
13254                    end.column = buffer.line_len(MultiBufferRow(end.row));
13255                    start..end
13256                })
13257                .collect::<Vec<_>>();
13258
13259            self.unfold_ranges(&ranges, true, true, cx);
13260        } else {
13261            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13262            let buffer_ids = self
13263                .selections
13264                .disjoint_anchor_ranges()
13265                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13266                .collect::<HashSet<_>>();
13267            for buffer_id in buffer_ids {
13268                self.unfold_buffer(buffer_id, cx);
13269            }
13270        }
13271    }
13272
13273    pub fn unfold_recursive(
13274        &mut self,
13275        _: &UnfoldRecursive,
13276        _window: &mut Window,
13277        cx: &mut Context<Self>,
13278    ) {
13279        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13280        let selections = self.selections.all::<Point>(cx);
13281        let ranges = selections
13282            .iter()
13283            .map(|s| {
13284                let mut range = s.display_range(&display_map).sorted();
13285                *range.start.column_mut() = 0;
13286                *range.end.column_mut() = display_map.line_len(range.end.row());
13287                let start = range.start.to_point(&display_map);
13288                let end = range.end.to_point(&display_map);
13289                start..end
13290            })
13291            .collect::<Vec<_>>();
13292
13293        self.unfold_ranges(&ranges, true, true, cx);
13294    }
13295
13296    pub fn unfold_at(
13297        &mut self,
13298        unfold_at: &UnfoldAt,
13299        _window: &mut Window,
13300        cx: &mut Context<Self>,
13301    ) {
13302        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13303
13304        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13305            ..Point::new(
13306                unfold_at.buffer_row.0,
13307                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13308            );
13309
13310        let autoscroll = self
13311            .selections
13312            .all::<Point>(cx)
13313            .iter()
13314            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13315
13316        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13317    }
13318
13319    pub fn unfold_all(
13320        &mut self,
13321        _: &actions::UnfoldAll,
13322        _window: &mut Window,
13323        cx: &mut Context<Self>,
13324    ) {
13325        if self.buffer.read(cx).is_singleton() {
13326            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13327            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13328        } else {
13329            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13330                editor
13331                    .update(&mut cx, |editor, cx| {
13332                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13333                            editor.unfold_buffer(buffer_id, cx);
13334                        }
13335                    })
13336                    .ok();
13337            });
13338        }
13339    }
13340
13341    pub fn fold_selected_ranges(
13342        &mut self,
13343        _: &FoldSelectedRanges,
13344        window: &mut Window,
13345        cx: &mut Context<Self>,
13346    ) {
13347        let selections = self.selections.all::<Point>(cx);
13348        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13349        let line_mode = self.selections.line_mode;
13350        let ranges = selections
13351            .into_iter()
13352            .map(|s| {
13353                if line_mode {
13354                    let start = Point::new(s.start.row, 0);
13355                    let end = Point::new(
13356                        s.end.row,
13357                        display_map
13358                            .buffer_snapshot
13359                            .line_len(MultiBufferRow(s.end.row)),
13360                    );
13361                    Crease::simple(start..end, display_map.fold_placeholder.clone())
13362                } else {
13363                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13364                }
13365            })
13366            .collect::<Vec<_>>();
13367        self.fold_creases(ranges, true, window, cx);
13368    }
13369
13370    pub fn fold_ranges<T: ToOffset + Clone>(
13371        &mut self,
13372        ranges: Vec<Range<T>>,
13373        auto_scroll: bool,
13374        window: &mut Window,
13375        cx: &mut Context<Self>,
13376    ) {
13377        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13378        let ranges = ranges
13379            .into_iter()
13380            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13381            .collect::<Vec<_>>();
13382        self.fold_creases(ranges, auto_scroll, window, cx);
13383    }
13384
13385    pub fn fold_creases<T: ToOffset + Clone>(
13386        &mut self,
13387        creases: Vec<Crease<T>>,
13388        auto_scroll: bool,
13389        window: &mut Window,
13390        cx: &mut Context<Self>,
13391    ) {
13392        if creases.is_empty() {
13393            return;
13394        }
13395
13396        let mut buffers_affected = HashSet::default();
13397        let multi_buffer = self.buffer().read(cx);
13398        for crease in &creases {
13399            if let Some((_, buffer, _)) =
13400                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13401            {
13402                buffers_affected.insert(buffer.read(cx).remote_id());
13403            };
13404        }
13405
13406        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13407
13408        if auto_scroll {
13409            self.request_autoscroll(Autoscroll::fit(), cx);
13410        }
13411
13412        cx.notify();
13413
13414        if let Some(active_diagnostics) = self.active_diagnostics.take() {
13415            // Clear diagnostics block when folding a range that contains it.
13416            let snapshot = self.snapshot(window, cx);
13417            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13418                drop(snapshot);
13419                self.active_diagnostics = Some(active_diagnostics);
13420                self.dismiss_diagnostics(cx);
13421            } else {
13422                self.active_diagnostics = Some(active_diagnostics);
13423            }
13424        }
13425
13426        self.scrollbar_marker_state.dirty = true;
13427    }
13428
13429    /// Removes any folds whose ranges intersect any of the given ranges.
13430    pub fn unfold_ranges<T: ToOffset + Clone>(
13431        &mut self,
13432        ranges: &[Range<T>],
13433        inclusive: bool,
13434        auto_scroll: bool,
13435        cx: &mut Context<Self>,
13436    ) {
13437        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13438            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13439        });
13440    }
13441
13442    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13443        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13444            return;
13445        }
13446        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13447        self.display_map.update(cx, |display_map, cx| {
13448            display_map.fold_buffers([buffer_id], cx)
13449        });
13450        cx.emit(EditorEvent::BufferFoldToggled {
13451            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13452            folded: true,
13453        });
13454        cx.notify();
13455    }
13456
13457    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13458        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13459            return;
13460        }
13461        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13462        self.display_map.update(cx, |display_map, cx| {
13463            display_map.unfold_buffers([buffer_id], cx);
13464        });
13465        cx.emit(EditorEvent::BufferFoldToggled {
13466            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13467            folded: false,
13468        });
13469        cx.notify();
13470    }
13471
13472    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13473        self.display_map.read(cx).is_buffer_folded(buffer)
13474    }
13475
13476    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13477        self.display_map.read(cx).folded_buffers()
13478    }
13479
13480    /// Removes any folds with the given ranges.
13481    pub fn remove_folds_with_type<T: ToOffset + Clone>(
13482        &mut self,
13483        ranges: &[Range<T>],
13484        type_id: TypeId,
13485        auto_scroll: bool,
13486        cx: &mut Context<Self>,
13487    ) {
13488        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13489            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13490        });
13491    }
13492
13493    fn remove_folds_with<T: ToOffset + Clone>(
13494        &mut self,
13495        ranges: &[Range<T>],
13496        auto_scroll: bool,
13497        cx: &mut Context<Self>,
13498        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13499    ) {
13500        if ranges.is_empty() {
13501            return;
13502        }
13503
13504        let mut buffers_affected = HashSet::default();
13505        let multi_buffer = self.buffer().read(cx);
13506        for range in ranges {
13507            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13508                buffers_affected.insert(buffer.read(cx).remote_id());
13509            };
13510        }
13511
13512        self.display_map.update(cx, update);
13513
13514        if auto_scroll {
13515            self.request_autoscroll(Autoscroll::fit(), cx);
13516        }
13517
13518        cx.notify();
13519        self.scrollbar_marker_state.dirty = true;
13520        self.active_indent_guides_state.dirty = true;
13521    }
13522
13523    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13524        self.display_map.read(cx).fold_placeholder.clone()
13525    }
13526
13527    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13528        self.buffer.update(cx, |buffer, cx| {
13529            buffer.set_all_diff_hunks_expanded(cx);
13530        });
13531    }
13532
13533    pub fn expand_all_diff_hunks(
13534        &mut self,
13535        _: &ExpandAllDiffHunks,
13536        _window: &mut Window,
13537        cx: &mut Context<Self>,
13538    ) {
13539        self.buffer.update(cx, |buffer, cx| {
13540            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13541        });
13542    }
13543
13544    pub fn toggle_selected_diff_hunks(
13545        &mut self,
13546        _: &ToggleSelectedDiffHunks,
13547        _window: &mut Window,
13548        cx: &mut Context<Self>,
13549    ) {
13550        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13551        self.toggle_diff_hunks_in_ranges(ranges, cx);
13552    }
13553
13554    pub fn diff_hunks_in_ranges<'a>(
13555        &'a self,
13556        ranges: &'a [Range<Anchor>],
13557        buffer: &'a MultiBufferSnapshot,
13558    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13559        ranges.iter().flat_map(move |range| {
13560            let end_excerpt_id = range.end.excerpt_id;
13561            let range = range.to_point(buffer);
13562            let mut peek_end = range.end;
13563            if range.end.row < buffer.max_row().0 {
13564                peek_end = Point::new(range.end.row + 1, 0);
13565            }
13566            buffer
13567                .diff_hunks_in_range(range.start..peek_end)
13568                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13569        })
13570    }
13571
13572    pub fn has_stageable_diff_hunks_in_ranges(
13573        &self,
13574        ranges: &[Range<Anchor>],
13575        snapshot: &MultiBufferSnapshot,
13576    ) -> bool {
13577        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13578        hunks.any(|hunk| hunk.status().has_secondary_hunk())
13579    }
13580
13581    pub fn toggle_staged_selected_diff_hunks(
13582        &mut self,
13583        _: &::git::ToggleStaged,
13584        window: &mut Window,
13585        cx: &mut Context<Self>,
13586    ) {
13587        let snapshot = self.buffer.read(cx).snapshot(cx);
13588        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13589        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13590        self.stage_or_unstage_diff_hunks(stage, &ranges, window, cx);
13591    }
13592
13593    pub fn stage_and_next(
13594        &mut self,
13595        _: &::git::StageAndNext,
13596        window: &mut Window,
13597        cx: &mut Context<Self>,
13598    ) {
13599        self.do_stage_or_unstage_and_next(true, window, cx);
13600    }
13601
13602    pub fn unstage_and_next(
13603        &mut self,
13604        _: &::git::UnstageAndNext,
13605        window: &mut Window,
13606        cx: &mut Context<Self>,
13607    ) {
13608        self.do_stage_or_unstage_and_next(false, window, cx);
13609    }
13610
13611    pub fn stage_or_unstage_diff_hunks(
13612        &mut self,
13613        stage: bool,
13614        ranges: &[Range<Anchor>],
13615        window: &mut Window,
13616        cx: &mut Context<Self>,
13617    ) {
13618        let snapshot = self.buffer.read(cx).snapshot(cx);
13619        let chunk_by = self
13620            .diff_hunks_in_ranges(&ranges, &snapshot)
13621            .chunk_by(|hunk| hunk.buffer_id);
13622        for (buffer_id, hunks) in &chunk_by {
13623            self.do_stage_or_unstage(stage, buffer_id, hunks, window, cx);
13624        }
13625    }
13626
13627    fn do_stage_or_unstage_and_next(
13628        &mut self,
13629        stage: bool,
13630        window: &mut Window,
13631        cx: &mut Context<Self>,
13632    ) {
13633        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13634
13635        if ranges.iter().any(|range| range.start != range.end) {
13636            self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13637            return;
13638        }
13639
13640        let snapshot = self.snapshot(window, cx);
13641        let newest_range = self.selections.newest::<Point>(cx).range();
13642
13643        let run_twice = snapshot
13644            .hunks_for_ranges([newest_range])
13645            .first()
13646            .is_some_and(|hunk| {
13647                let next_line = Point::new(hunk.row_range.end.0 + 1, 0);
13648                self.hunk_after_position(&snapshot, next_line)
13649                    .is_some_and(|other| other.row_range == hunk.row_range)
13650            });
13651
13652        if run_twice {
13653            self.go_to_next_hunk(&GoToHunk, window, cx);
13654        }
13655        self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13656        self.go_to_next_hunk(&GoToHunk, window, cx);
13657    }
13658
13659    fn do_stage_or_unstage(
13660        &self,
13661        stage: bool,
13662        buffer_id: BufferId,
13663        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13664        window: &mut Window,
13665        cx: &mut App,
13666    ) {
13667        let Some(project) = self.project.as_ref() else {
13668            return;
13669        };
13670        let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
13671            return;
13672        };
13673        let Some(diff) = self.buffer.read(cx).diff_for(buffer_id) else {
13674            return;
13675        };
13676        let buffer_snapshot = buffer.read(cx).snapshot();
13677        let file_exists = buffer_snapshot
13678            .file()
13679            .is_some_and(|file| file.disk_state().exists());
13680        let Some((repo, path)) = project
13681            .read(cx)
13682            .repository_and_path_for_buffer_id(buffer_id, cx)
13683        else {
13684            log::debug!("no git repo for buffer id");
13685            return;
13686        };
13687
13688        let new_index_text = diff.update(cx, |diff, cx| {
13689            diff.stage_or_unstage_hunks(
13690                stage,
13691                &hunks
13692                    .map(|hunk| buffer_diff::DiffHunk {
13693                        buffer_range: hunk.buffer_range,
13694                        diff_base_byte_range: hunk.diff_base_byte_range,
13695                        secondary_status: hunk.secondary_status,
13696                        range: Point::zero()..Point::zero(), // unused
13697                    })
13698                    .collect::<Vec<_>>(),
13699                &buffer_snapshot,
13700                file_exists,
13701                cx,
13702            )
13703        });
13704
13705        if file_exists {
13706            let buffer_store = project.read(cx).buffer_store().clone();
13707            buffer_store
13708                .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
13709                .detach_and_log_err(cx);
13710        }
13711
13712        let recv = repo
13713            .read(cx)
13714            .set_index_text(&path, new_index_text.map(|rope| rope.to_string()));
13715
13716        cx.background_spawn(async move { recv.await? })
13717            .detach_and_notify_err(window, cx);
13718    }
13719
13720    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13721        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13722        self.buffer
13723            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13724    }
13725
13726    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13727        self.buffer.update(cx, |buffer, cx| {
13728            let ranges = vec![Anchor::min()..Anchor::max()];
13729            if !buffer.all_diff_hunks_expanded()
13730                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13731            {
13732                buffer.collapse_diff_hunks(ranges, cx);
13733                true
13734            } else {
13735                false
13736            }
13737        })
13738    }
13739
13740    fn toggle_diff_hunks_in_ranges(
13741        &mut self,
13742        ranges: Vec<Range<Anchor>>,
13743        cx: &mut Context<'_, Editor>,
13744    ) {
13745        self.buffer.update(cx, |buffer, cx| {
13746            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13747            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13748        })
13749    }
13750
13751    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13752        self.buffer.update(cx, |buffer, cx| {
13753            let snapshot = buffer.snapshot(cx);
13754            let excerpt_id = range.end.excerpt_id;
13755            let point_range = range.to_point(&snapshot);
13756            let expand = !buffer.single_hunk_is_expanded(range, cx);
13757            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13758        })
13759    }
13760
13761    pub(crate) fn apply_all_diff_hunks(
13762        &mut self,
13763        _: &ApplyAllDiffHunks,
13764        window: &mut Window,
13765        cx: &mut Context<Self>,
13766    ) {
13767        let buffers = self.buffer.read(cx).all_buffers();
13768        for branch_buffer in buffers {
13769            branch_buffer.update(cx, |branch_buffer, cx| {
13770                branch_buffer.merge_into_base(Vec::new(), cx);
13771            });
13772        }
13773
13774        if let Some(project) = self.project.clone() {
13775            self.save(true, project, window, cx).detach_and_log_err(cx);
13776        }
13777    }
13778
13779    pub(crate) fn apply_selected_diff_hunks(
13780        &mut self,
13781        _: &ApplyDiffHunk,
13782        window: &mut Window,
13783        cx: &mut Context<Self>,
13784    ) {
13785        let snapshot = self.snapshot(window, cx);
13786        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
13787        let mut ranges_by_buffer = HashMap::default();
13788        self.transact(window, cx, |editor, _window, cx| {
13789            for hunk in hunks {
13790                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13791                    ranges_by_buffer
13792                        .entry(buffer.clone())
13793                        .or_insert_with(Vec::new)
13794                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13795                }
13796            }
13797
13798            for (buffer, ranges) in ranges_by_buffer {
13799                buffer.update(cx, |buffer, cx| {
13800                    buffer.merge_into_base(ranges, cx);
13801                });
13802            }
13803        });
13804
13805        if let Some(project) = self.project.clone() {
13806            self.save(true, project, window, cx).detach_and_log_err(cx);
13807        }
13808    }
13809
13810    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13811        if hovered != self.gutter_hovered {
13812            self.gutter_hovered = hovered;
13813            cx.notify();
13814        }
13815    }
13816
13817    pub fn insert_blocks(
13818        &mut self,
13819        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13820        autoscroll: Option<Autoscroll>,
13821        cx: &mut Context<Self>,
13822    ) -> Vec<CustomBlockId> {
13823        let blocks = self
13824            .display_map
13825            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13826        if let Some(autoscroll) = autoscroll {
13827            self.request_autoscroll(autoscroll, cx);
13828        }
13829        cx.notify();
13830        blocks
13831    }
13832
13833    pub fn resize_blocks(
13834        &mut self,
13835        heights: HashMap<CustomBlockId, u32>,
13836        autoscroll: Option<Autoscroll>,
13837        cx: &mut Context<Self>,
13838    ) {
13839        self.display_map
13840            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13841        if let Some(autoscroll) = autoscroll {
13842            self.request_autoscroll(autoscroll, cx);
13843        }
13844        cx.notify();
13845    }
13846
13847    pub fn replace_blocks(
13848        &mut self,
13849        renderers: HashMap<CustomBlockId, RenderBlock>,
13850        autoscroll: Option<Autoscroll>,
13851        cx: &mut Context<Self>,
13852    ) {
13853        self.display_map
13854            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13855        if let Some(autoscroll) = autoscroll {
13856            self.request_autoscroll(autoscroll, cx);
13857        }
13858        cx.notify();
13859    }
13860
13861    pub fn remove_blocks(
13862        &mut self,
13863        block_ids: HashSet<CustomBlockId>,
13864        autoscroll: Option<Autoscroll>,
13865        cx: &mut Context<Self>,
13866    ) {
13867        self.display_map.update(cx, |display_map, cx| {
13868            display_map.remove_blocks(block_ids, cx)
13869        });
13870        if let Some(autoscroll) = autoscroll {
13871            self.request_autoscroll(autoscroll, cx);
13872        }
13873        cx.notify();
13874    }
13875
13876    pub fn row_for_block(
13877        &self,
13878        block_id: CustomBlockId,
13879        cx: &mut Context<Self>,
13880    ) -> Option<DisplayRow> {
13881        self.display_map
13882            .update(cx, |map, cx| map.row_for_block(block_id, cx))
13883    }
13884
13885    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13886        self.focused_block = Some(focused_block);
13887    }
13888
13889    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13890        self.focused_block.take()
13891    }
13892
13893    pub fn insert_creases(
13894        &mut self,
13895        creases: impl IntoIterator<Item = Crease<Anchor>>,
13896        cx: &mut Context<Self>,
13897    ) -> Vec<CreaseId> {
13898        self.display_map
13899            .update(cx, |map, cx| map.insert_creases(creases, cx))
13900    }
13901
13902    pub fn remove_creases(
13903        &mut self,
13904        ids: impl IntoIterator<Item = CreaseId>,
13905        cx: &mut Context<Self>,
13906    ) {
13907        self.display_map
13908            .update(cx, |map, cx| map.remove_creases(ids, cx));
13909    }
13910
13911    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13912        self.display_map
13913            .update(cx, |map, cx| map.snapshot(cx))
13914            .longest_row()
13915    }
13916
13917    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13918        self.display_map
13919            .update(cx, |map, cx| map.snapshot(cx))
13920            .max_point()
13921    }
13922
13923    pub fn text(&self, cx: &App) -> String {
13924        self.buffer.read(cx).read(cx).text()
13925    }
13926
13927    pub fn is_empty(&self, cx: &App) -> bool {
13928        self.buffer.read(cx).read(cx).is_empty()
13929    }
13930
13931    pub fn text_option(&self, cx: &App) -> Option<String> {
13932        let text = self.text(cx);
13933        let text = text.trim();
13934
13935        if text.is_empty() {
13936            return None;
13937        }
13938
13939        Some(text.to_string())
13940    }
13941
13942    pub fn set_text(
13943        &mut self,
13944        text: impl Into<Arc<str>>,
13945        window: &mut Window,
13946        cx: &mut Context<Self>,
13947    ) {
13948        self.transact(window, cx, |this, _, cx| {
13949            this.buffer
13950                .read(cx)
13951                .as_singleton()
13952                .expect("you can only call set_text on editors for singleton buffers")
13953                .update(cx, |buffer, cx| buffer.set_text(text, cx));
13954        });
13955    }
13956
13957    pub fn display_text(&self, cx: &mut App) -> String {
13958        self.display_map
13959            .update(cx, |map, cx| map.snapshot(cx))
13960            .text()
13961    }
13962
13963    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
13964        let mut wrap_guides = smallvec::smallvec![];
13965
13966        if self.show_wrap_guides == Some(false) {
13967            return wrap_guides;
13968        }
13969
13970        let settings = self.buffer.read(cx).settings_at(0, cx);
13971        if settings.show_wrap_guides {
13972            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
13973                wrap_guides.push((soft_wrap as usize, true));
13974            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
13975                wrap_guides.push((soft_wrap as usize, true));
13976            }
13977            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
13978        }
13979
13980        wrap_guides
13981    }
13982
13983    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
13984        let settings = self.buffer.read(cx).settings_at(0, cx);
13985        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
13986        match mode {
13987            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
13988                SoftWrap::None
13989            }
13990            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13991            language_settings::SoftWrap::PreferredLineLength => {
13992                SoftWrap::Column(settings.preferred_line_length)
13993            }
13994            language_settings::SoftWrap::Bounded => {
13995                SoftWrap::Bounded(settings.preferred_line_length)
13996            }
13997        }
13998    }
13999
14000    pub fn set_soft_wrap_mode(
14001        &mut self,
14002        mode: language_settings::SoftWrap,
14003
14004        cx: &mut Context<Self>,
14005    ) {
14006        self.soft_wrap_mode_override = Some(mode);
14007        cx.notify();
14008    }
14009
14010    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14011        self.text_style_refinement = Some(style);
14012    }
14013
14014    /// called by the Element so we know what style we were most recently rendered with.
14015    pub(crate) fn set_style(
14016        &mut self,
14017        style: EditorStyle,
14018        window: &mut Window,
14019        cx: &mut Context<Self>,
14020    ) {
14021        let rem_size = window.rem_size();
14022        self.display_map.update(cx, |map, cx| {
14023            map.set_font(
14024                style.text.font(),
14025                style.text.font_size.to_pixels(rem_size),
14026                cx,
14027            )
14028        });
14029        self.style = Some(style);
14030    }
14031
14032    pub fn style(&self) -> Option<&EditorStyle> {
14033        self.style.as_ref()
14034    }
14035
14036    // Called by the element. This method is not designed to be called outside of the editor
14037    // element's layout code because it does not notify when rewrapping is computed synchronously.
14038    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14039        self.display_map
14040            .update(cx, |map, cx| map.set_wrap_width(width, cx))
14041    }
14042
14043    pub fn set_soft_wrap(&mut self) {
14044        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14045    }
14046
14047    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14048        if self.soft_wrap_mode_override.is_some() {
14049            self.soft_wrap_mode_override.take();
14050        } else {
14051            let soft_wrap = match self.soft_wrap_mode(cx) {
14052                SoftWrap::GitDiff => return,
14053                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14054                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14055                    language_settings::SoftWrap::None
14056                }
14057            };
14058            self.soft_wrap_mode_override = Some(soft_wrap);
14059        }
14060        cx.notify();
14061    }
14062
14063    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14064        let Some(workspace) = self.workspace() else {
14065            return;
14066        };
14067        let fs = workspace.read(cx).app_state().fs.clone();
14068        let current_show = TabBarSettings::get_global(cx).show;
14069        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14070            setting.show = Some(!current_show);
14071        });
14072    }
14073
14074    pub fn toggle_indent_guides(
14075        &mut self,
14076        _: &ToggleIndentGuides,
14077        _: &mut Window,
14078        cx: &mut Context<Self>,
14079    ) {
14080        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14081            self.buffer
14082                .read(cx)
14083                .settings_at(0, cx)
14084                .indent_guides
14085                .enabled
14086        });
14087        self.show_indent_guides = Some(!currently_enabled);
14088        cx.notify();
14089    }
14090
14091    fn should_show_indent_guides(&self) -> Option<bool> {
14092        self.show_indent_guides
14093    }
14094
14095    pub fn toggle_line_numbers(
14096        &mut self,
14097        _: &ToggleLineNumbers,
14098        _: &mut Window,
14099        cx: &mut Context<Self>,
14100    ) {
14101        let mut editor_settings = EditorSettings::get_global(cx).clone();
14102        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14103        EditorSettings::override_global(editor_settings, cx);
14104    }
14105
14106    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14107        self.use_relative_line_numbers
14108            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14109    }
14110
14111    pub fn toggle_relative_line_numbers(
14112        &mut self,
14113        _: &ToggleRelativeLineNumbers,
14114        _: &mut Window,
14115        cx: &mut Context<Self>,
14116    ) {
14117        let is_relative = self.should_use_relative_line_numbers(cx);
14118        self.set_relative_line_number(Some(!is_relative), cx)
14119    }
14120
14121    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14122        self.use_relative_line_numbers = is_relative;
14123        cx.notify();
14124    }
14125
14126    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14127        self.show_gutter = show_gutter;
14128        cx.notify();
14129    }
14130
14131    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14132        self.show_scrollbars = show_scrollbars;
14133        cx.notify();
14134    }
14135
14136    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14137        self.show_line_numbers = Some(show_line_numbers);
14138        cx.notify();
14139    }
14140
14141    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14142        self.show_git_diff_gutter = Some(show_git_diff_gutter);
14143        cx.notify();
14144    }
14145
14146    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14147        self.show_code_actions = Some(show_code_actions);
14148        cx.notify();
14149    }
14150
14151    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14152        self.show_runnables = Some(show_runnables);
14153        cx.notify();
14154    }
14155
14156    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14157        if self.display_map.read(cx).masked != masked {
14158            self.display_map.update(cx, |map, _| map.masked = masked);
14159        }
14160        cx.notify()
14161    }
14162
14163    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14164        self.show_wrap_guides = Some(show_wrap_guides);
14165        cx.notify();
14166    }
14167
14168    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14169        self.show_indent_guides = Some(show_indent_guides);
14170        cx.notify();
14171    }
14172
14173    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14174        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14175            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14176                if let Some(dir) = file.abs_path(cx).parent() {
14177                    return Some(dir.to_owned());
14178                }
14179            }
14180
14181            if let Some(project_path) = buffer.read(cx).project_path(cx) {
14182                return Some(project_path.path.to_path_buf());
14183            }
14184        }
14185
14186        None
14187    }
14188
14189    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14190        self.active_excerpt(cx)?
14191            .1
14192            .read(cx)
14193            .file()
14194            .and_then(|f| f.as_local())
14195    }
14196
14197    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14198        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14199            let buffer = buffer.read(cx);
14200            if let Some(project_path) = buffer.project_path(cx) {
14201                let project = self.project.as_ref()?.read(cx);
14202                project.absolute_path(&project_path, cx)
14203            } else {
14204                buffer
14205                    .file()
14206                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14207            }
14208        })
14209    }
14210
14211    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14212        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14213            let project_path = buffer.read(cx).project_path(cx)?;
14214            let project = self.project.as_ref()?.read(cx);
14215            let entry = project.entry_for_path(&project_path, cx)?;
14216            let path = entry.path.to_path_buf();
14217            Some(path)
14218        })
14219    }
14220
14221    pub fn reveal_in_finder(
14222        &mut self,
14223        _: &RevealInFileManager,
14224        _window: &mut Window,
14225        cx: &mut Context<Self>,
14226    ) {
14227        if let Some(target) = self.target_file(cx) {
14228            cx.reveal_path(&target.abs_path(cx));
14229        }
14230    }
14231
14232    pub fn copy_path(
14233        &mut self,
14234        _: &zed_actions::workspace::CopyPath,
14235        _window: &mut Window,
14236        cx: &mut Context<Self>,
14237    ) {
14238        if let Some(path) = self.target_file_abs_path(cx) {
14239            if let Some(path) = path.to_str() {
14240                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14241            }
14242        }
14243    }
14244
14245    pub fn copy_relative_path(
14246        &mut self,
14247        _: &zed_actions::workspace::CopyRelativePath,
14248        _window: &mut Window,
14249        cx: &mut Context<Self>,
14250    ) {
14251        if let Some(path) = self.target_file_path(cx) {
14252            if let Some(path) = path.to_str() {
14253                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14254            }
14255        }
14256    }
14257
14258    pub fn copy_file_name_without_extension(
14259        &mut self,
14260        _: &CopyFileNameWithoutExtension,
14261        _: &mut Window,
14262        cx: &mut Context<Self>,
14263    ) {
14264        if let Some(file) = self.target_file(cx) {
14265            if let Some(file_stem) = file.path().file_stem() {
14266                if let Some(name) = file_stem.to_str() {
14267                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14268                }
14269            }
14270        }
14271    }
14272
14273    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14274        if let Some(file) = self.target_file(cx) {
14275            if let Some(file_name) = file.path().file_name() {
14276                if let Some(name) = file_name.to_str() {
14277                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14278                }
14279            }
14280        }
14281    }
14282
14283    pub fn toggle_git_blame(
14284        &mut self,
14285        _: &ToggleGitBlame,
14286        window: &mut Window,
14287        cx: &mut Context<Self>,
14288    ) {
14289        self.show_git_blame_gutter = !self.show_git_blame_gutter;
14290
14291        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14292            self.start_git_blame(true, window, cx);
14293        }
14294
14295        cx.notify();
14296    }
14297
14298    pub fn toggle_git_blame_inline(
14299        &mut self,
14300        _: &ToggleGitBlameInline,
14301        window: &mut Window,
14302        cx: &mut Context<Self>,
14303    ) {
14304        self.toggle_git_blame_inline_internal(true, window, cx);
14305        cx.notify();
14306    }
14307
14308    pub fn git_blame_inline_enabled(&self) -> bool {
14309        self.git_blame_inline_enabled
14310    }
14311
14312    pub fn toggle_selection_menu(
14313        &mut self,
14314        _: &ToggleSelectionMenu,
14315        _: &mut Window,
14316        cx: &mut Context<Self>,
14317    ) {
14318        self.show_selection_menu = self
14319            .show_selection_menu
14320            .map(|show_selections_menu| !show_selections_menu)
14321            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14322
14323        cx.notify();
14324    }
14325
14326    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14327        self.show_selection_menu
14328            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14329    }
14330
14331    fn start_git_blame(
14332        &mut self,
14333        user_triggered: bool,
14334        window: &mut Window,
14335        cx: &mut Context<Self>,
14336    ) {
14337        if let Some(project) = self.project.as_ref() {
14338            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14339                return;
14340            };
14341
14342            if buffer.read(cx).file().is_none() {
14343                return;
14344            }
14345
14346            let focused = self.focus_handle(cx).contains_focused(window, cx);
14347
14348            let project = project.clone();
14349            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14350            self.blame_subscription =
14351                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14352            self.blame = Some(blame);
14353        }
14354    }
14355
14356    fn toggle_git_blame_inline_internal(
14357        &mut self,
14358        user_triggered: bool,
14359        window: &mut Window,
14360        cx: &mut Context<Self>,
14361    ) {
14362        if self.git_blame_inline_enabled {
14363            self.git_blame_inline_enabled = false;
14364            self.show_git_blame_inline = false;
14365            self.show_git_blame_inline_delay_task.take();
14366        } else {
14367            self.git_blame_inline_enabled = true;
14368            self.start_git_blame_inline(user_triggered, window, cx);
14369        }
14370
14371        cx.notify();
14372    }
14373
14374    fn start_git_blame_inline(
14375        &mut self,
14376        user_triggered: bool,
14377        window: &mut Window,
14378        cx: &mut Context<Self>,
14379    ) {
14380        self.start_git_blame(user_triggered, window, cx);
14381
14382        if ProjectSettings::get_global(cx)
14383            .git
14384            .inline_blame_delay()
14385            .is_some()
14386        {
14387            self.start_inline_blame_timer(window, cx);
14388        } else {
14389            self.show_git_blame_inline = true
14390        }
14391    }
14392
14393    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14394        self.blame.as_ref()
14395    }
14396
14397    pub fn show_git_blame_gutter(&self) -> bool {
14398        self.show_git_blame_gutter
14399    }
14400
14401    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14402        self.show_git_blame_gutter && self.has_blame_entries(cx)
14403    }
14404
14405    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14406        self.show_git_blame_inline
14407            && (self.focus_handle.is_focused(window)
14408                || self
14409                    .git_blame_inline_tooltip
14410                    .as_ref()
14411                    .and_then(|t| t.upgrade())
14412                    .is_some())
14413            && !self.newest_selection_head_on_empty_line(cx)
14414            && self.has_blame_entries(cx)
14415    }
14416
14417    fn has_blame_entries(&self, cx: &App) -> bool {
14418        self.blame()
14419            .map_or(false, |blame| blame.read(cx).has_generated_entries())
14420    }
14421
14422    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14423        let cursor_anchor = self.selections.newest_anchor().head();
14424
14425        let snapshot = self.buffer.read(cx).snapshot(cx);
14426        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14427
14428        snapshot.line_len(buffer_row) == 0
14429    }
14430
14431    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14432        let buffer_and_selection = maybe!({
14433            let selection = self.selections.newest::<Point>(cx);
14434            let selection_range = selection.range();
14435
14436            let multi_buffer = self.buffer().read(cx);
14437            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14438            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14439
14440            let (buffer, range, _) = if selection.reversed {
14441                buffer_ranges.first()
14442            } else {
14443                buffer_ranges.last()
14444            }?;
14445
14446            let selection = text::ToPoint::to_point(&range.start, &buffer).row
14447                ..text::ToPoint::to_point(&range.end, &buffer).row;
14448            Some((
14449                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14450                selection,
14451            ))
14452        });
14453
14454        let Some((buffer, selection)) = buffer_and_selection else {
14455            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14456        };
14457
14458        let Some(project) = self.project.as_ref() else {
14459            return Task::ready(Err(anyhow!("editor does not have project")));
14460        };
14461
14462        project.update(cx, |project, cx| {
14463            project.get_permalink_to_line(&buffer, selection, cx)
14464        })
14465    }
14466
14467    pub fn copy_permalink_to_line(
14468        &mut self,
14469        _: &CopyPermalinkToLine,
14470        window: &mut Window,
14471        cx: &mut Context<Self>,
14472    ) {
14473        let permalink_task = self.get_permalink_to_line(cx);
14474        let workspace = self.workspace();
14475
14476        cx.spawn_in(window, |_, mut cx| async move {
14477            match permalink_task.await {
14478                Ok(permalink) => {
14479                    cx.update(|_, cx| {
14480                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14481                    })
14482                    .ok();
14483                }
14484                Err(err) => {
14485                    let message = format!("Failed to copy permalink: {err}");
14486
14487                    Err::<(), anyhow::Error>(err).log_err();
14488
14489                    if let Some(workspace) = workspace {
14490                        workspace
14491                            .update_in(&mut cx, |workspace, _, cx| {
14492                                struct CopyPermalinkToLine;
14493
14494                                workspace.show_toast(
14495                                    Toast::new(
14496                                        NotificationId::unique::<CopyPermalinkToLine>(),
14497                                        message,
14498                                    ),
14499                                    cx,
14500                                )
14501                            })
14502                            .ok();
14503                    }
14504                }
14505            }
14506        })
14507        .detach();
14508    }
14509
14510    pub fn copy_file_location(
14511        &mut self,
14512        _: &CopyFileLocation,
14513        _: &mut Window,
14514        cx: &mut Context<Self>,
14515    ) {
14516        let selection = self.selections.newest::<Point>(cx).start.row + 1;
14517        if let Some(file) = self.target_file(cx) {
14518            if let Some(path) = file.path().to_str() {
14519                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14520            }
14521        }
14522    }
14523
14524    pub fn open_permalink_to_line(
14525        &mut self,
14526        _: &OpenPermalinkToLine,
14527        window: &mut Window,
14528        cx: &mut Context<Self>,
14529    ) {
14530        let permalink_task = self.get_permalink_to_line(cx);
14531        let workspace = self.workspace();
14532
14533        cx.spawn_in(window, |_, mut cx| async move {
14534            match permalink_task.await {
14535                Ok(permalink) => {
14536                    cx.update(|_, cx| {
14537                        cx.open_url(permalink.as_ref());
14538                    })
14539                    .ok();
14540                }
14541                Err(err) => {
14542                    let message = format!("Failed to open permalink: {err}");
14543
14544                    Err::<(), anyhow::Error>(err).log_err();
14545
14546                    if let Some(workspace) = workspace {
14547                        workspace
14548                            .update(&mut cx, |workspace, cx| {
14549                                struct OpenPermalinkToLine;
14550
14551                                workspace.show_toast(
14552                                    Toast::new(
14553                                        NotificationId::unique::<OpenPermalinkToLine>(),
14554                                        message,
14555                                    ),
14556                                    cx,
14557                                )
14558                            })
14559                            .ok();
14560                    }
14561                }
14562            }
14563        })
14564        .detach();
14565    }
14566
14567    pub fn insert_uuid_v4(
14568        &mut self,
14569        _: &InsertUuidV4,
14570        window: &mut Window,
14571        cx: &mut Context<Self>,
14572    ) {
14573        self.insert_uuid(UuidVersion::V4, window, cx);
14574    }
14575
14576    pub fn insert_uuid_v7(
14577        &mut self,
14578        _: &InsertUuidV7,
14579        window: &mut Window,
14580        cx: &mut Context<Self>,
14581    ) {
14582        self.insert_uuid(UuidVersion::V7, window, cx);
14583    }
14584
14585    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14586        self.transact(window, cx, |this, window, cx| {
14587            let edits = this
14588                .selections
14589                .all::<Point>(cx)
14590                .into_iter()
14591                .map(|selection| {
14592                    let uuid = match version {
14593                        UuidVersion::V4 => uuid::Uuid::new_v4(),
14594                        UuidVersion::V7 => uuid::Uuid::now_v7(),
14595                    };
14596
14597                    (selection.range(), uuid.to_string())
14598                });
14599            this.edit(edits, cx);
14600            this.refresh_inline_completion(true, false, window, cx);
14601        });
14602    }
14603
14604    pub fn open_selections_in_multibuffer(
14605        &mut self,
14606        _: &OpenSelectionsInMultibuffer,
14607        window: &mut Window,
14608        cx: &mut Context<Self>,
14609    ) {
14610        let multibuffer = self.buffer.read(cx);
14611
14612        let Some(buffer) = multibuffer.as_singleton() else {
14613            return;
14614        };
14615
14616        let Some(workspace) = self.workspace() else {
14617            return;
14618        };
14619
14620        let locations = self
14621            .selections
14622            .disjoint_anchors()
14623            .iter()
14624            .map(|range| Location {
14625                buffer: buffer.clone(),
14626                range: range.start.text_anchor..range.end.text_anchor,
14627            })
14628            .collect::<Vec<_>>();
14629
14630        let title = multibuffer.title(cx).to_string();
14631
14632        cx.spawn_in(window, |_, mut cx| async move {
14633            workspace.update_in(&mut cx, |workspace, window, cx| {
14634                Self::open_locations_in_multibuffer(
14635                    workspace,
14636                    locations,
14637                    format!("Selections for '{title}'"),
14638                    false,
14639                    MultibufferSelectionMode::All,
14640                    window,
14641                    cx,
14642                );
14643            })
14644        })
14645        .detach();
14646    }
14647
14648    /// Adds a row highlight for the given range. If a row has multiple highlights, the
14649    /// last highlight added will be used.
14650    ///
14651    /// If the range ends at the beginning of a line, then that line will not be highlighted.
14652    pub fn highlight_rows<T: 'static>(
14653        &mut self,
14654        range: Range<Anchor>,
14655        color: Hsla,
14656        should_autoscroll: bool,
14657        cx: &mut Context<Self>,
14658    ) {
14659        let snapshot = self.buffer().read(cx).snapshot(cx);
14660        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14661        let ix = row_highlights.binary_search_by(|highlight| {
14662            Ordering::Equal
14663                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14664                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14665        });
14666
14667        if let Err(mut ix) = ix {
14668            let index = post_inc(&mut self.highlight_order);
14669
14670            // If this range intersects with the preceding highlight, then merge it with
14671            // the preceding highlight. Otherwise insert a new highlight.
14672            let mut merged = false;
14673            if ix > 0 {
14674                let prev_highlight = &mut row_highlights[ix - 1];
14675                if prev_highlight
14676                    .range
14677                    .end
14678                    .cmp(&range.start, &snapshot)
14679                    .is_ge()
14680                {
14681                    ix -= 1;
14682                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14683                        prev_highlight.range.end = range.end;
14684                    }
14685                    merged = true;
14686                    prev_highlight.index = index;
14687                    prev_highlight.color = color;
14688                    prev_highlight.should_autoscroll = should_autoscroll;
14689                }
14690            }
14691
14692            if !merged {
14693                row_highlights.insert(
14694                    ix,
14695                    RowHighlight {
14696                        range: range.clone(),
14697                        index,
14698                        color,
14699                        should_autoscroll,
14700                    },
14701                );
14702            }
14703
14704            // If any of the following highlights intersect with this one, merge them.
14705            while let Some(next_highlight) = row_highlights.get(ix + 1) {
14706                let highlight = &row_highlights[ix];
14707                if next_highlight
14708                    .range
14709                    .start
14710                    .cmp(&highlight.range.end, &snapshot)
14711                    .is_le()
14712                {
14713                    if next_highlight
14714                        .range
14715                        .end
14716                        .cmp(&highlight.range.end, &snapshot)
14717                        .is_gt()
14718                    {
14719                        row_highlights[ix].range.end = next_highlight.range.end;
14720                    }
14721                    row_highlights.remove(ix + 1);
14722                } else {
14723                    break;
14724                }
14725            }
14726        }
14727    }
14728
14729    /// Remove any highlighted row ranges of the given type that intersect the
14730    /// given ranges.
14731    pub fn remove_highlighted_rows<T: 'static>(
14732        &mut self,
14733        ranges_to_remove: Vec<Range<Anchor>>,
14734        cx: &mut Context<Self>,
14735    ) {
14736        let snapshot = self.buffer().read(cx).snapshot(cx);
14737        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14738        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14739        row_highlights.retain(|highlight| {
14740            while let Some(range_to_remove) = ranges_to_remove.peek() {
14741                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14742                    Ordering::Less | Ordering::Equal => {
14743                        ranges_to_remove.next();
14744                    }
14745                    Ordering::Greater => {
14746                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14747                            Ordering::Less | Ordering::Equal => {
14748                                return false;
14749                            }
14750                            Ordering::Greater => break,
14751                        }
14752                    }
14753                }
14754            }
14755
14756            true
14757        })
14758    }
14759
14760    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14761    pub fn clear_row_highlights<T: 'static>(&mut self) {
14762        self.highlighted_rows.remove(&TypeId::of::<T>());
14763    }
14764
14765    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14766    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14767        self.highlighted_rows
14768            .get(&TypeId::of::<T>())
14769            .map_or(&[] as &[_], |vec| vec.as_slice())
14770            .iter()
14771            .map(|highlight| (highlight.range.clone(), highlight.color))
14772    }
14773
14774    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14775    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14776    /// Allows to ignore certain kinds of highlights.
14777    pub fn highlighted_display_rows(
14778        &self,
14779        window: &mut Window,
14780        cx: &mut App,
14781    ) -> BTreeMap<DisplayRow, Background> {
14782        let snapshot = self.snapshot(window, cx);
14783        let mut used_highlight_orders = HashMap::default();
14784        self.highlighted_rows
14785            .iter()
14786            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14787            .fold(
14788                BTreeMap::<DisplayRow, Background>::new(),
14789                |mut unique_rows, highlight| {
14790                    let start = highlight.range.start.to_display_point(&snapshot);
14791                    let end = highlight.range.end.to_display_point(&snapshot);
14792                    let start_row = start.row().0;
14793                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14794                        && end.column() == 0
14795                    {
14796                        end.row().0.saturating_sub(1)
14797                    } else {
14798                        end.row().0
14799                    };
14800                    for row in start_row..=end_row {
14801                        let used_index =
14802                            used_highlight_orders.entry(row).or_insert(highlight.index);
14803                        if highlight.index >= *used_index {
14804                            *used_index = highlight.index;
14805                            unique_rows.insert(DisplayRow(row), highlight.color.into());
14806                        }
14807                    }
14808                    unique_rows
14809                },
14810            )
14811    }
14812
14813    pub fn highlighted_display_row_for_autoscroll(
14814        &self,
14815        snapshot: &DisplaySnapshot,
14816    ) -> Option<DisplayRow> {
14817        self.highlighted_rows
14818            .values()
14819            .flat_map(|highlighted_rows| highlighted_rows.iter())
14820            .filter_map(|highlight| {
14821                if highlight.should_autoscroll {
14822                    Some(highlight.range.start.to_display_point(snapshot).row())
14823                } else {
14824                    None
14825                }
14826            })
14827            .min()
14828    }
14829
14830    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14831        self.highlight_background::<SearchWithinRange>(
14832            ranges,
14833            |colors| colors.editor_document_highlight_read_background,
14834            cx,
14835        )
14836    }
14837
14838    pub fn set_breadcrumb_header(&mut self, new_header: String) {
14839        self.breadcrumb_header = Some(new_header);
14840    }
14841
14842    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14843        self.clear_background_highlights::<SearchWithinRange>(cx);
14844    }
14845
14846    pub fn highlight_background<T: 'static>(
14847        &mut self,
14848        ranges: &[Range<Anchor>],
14849        color_fetcher: fn(&ThemeColors) -> Hsla,
14850        cx: &mut Context<Self>,
14851    ) {
14852        self.background_highlights
14853            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14854        self.scrollbar_marker_state.dirty = true;
14855        cx.notify();
14856    }
14857
14858    pub fn clear_background_highlights<T: 'static>(
14859        &mut self,
14860        cx: &mut Context<Self>,
14861    ) -> Option<BackgroundHighlight> {
14862        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14863        if !text_highlights.1.is_empty() {
14864            self.scrollbar_marker_state.dirty = true;
14865            cx.notify();
14866        }
14867        Some(text_highlights)
14868    }
14869
14870    pub fn highlight_gutter<T: 'static>(
14871        &mut self,
14872        ranges: &[Range<Anchor>],
14873        color_fetcher: fn(&App) -> Hsla,
14874        cx: &mut Context<Self>,
14875    ) {
14876        self.gutter_highlights
14877            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14878        cx.notify();
14879    }
14880
14881    pub fn clear_gutter_highlights<T: 'static>(
14882        &mut self,
14883        cx: &mut Context<Self>,
14884    ) -> Option<GutterHighlight> {
14885        cx.notify();
14886        self.gutter_highlights.remove(&TypeId::of::<T>())
14887    }
14888
14889    #[cfg(feature = "test-support")]
14890    pub fn all_text_background_highlights(
14891        &self,
14892        window: &mut Window,
14893        cx: &mut Context<Self>,
14894    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14895        let snapshot = self.snapshot(window, cx);
14896        let buffer = &snapshot.buffer_snapshot;
14897        let start = buffer.anchor_before(0);
14898        let end = buffer.anchor_after(buffer.len());
14899        let theme = cx.theme().colors();
14900        self.background_highlights_in_range(start..end, &snapshot, theme)
14901    }
14902
14903    #[cfg(feature = "test-support")]
14904    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14905        let snapshot = self.buffer().read(cx).snapshot(cx);
14906
14907        let highlights = self
14908            .background_highlights
14909            .get(&TypeId::of::<items::BufferSearchHighlights>());
14910
14911        if let Some((_color, ranges)) = highlights {
14912            ranges
14913                .iter()
14914                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14915                .collect_vec()
14916        } else {
14917            vec![]
14918        }
14919    }
14920
14921    fn document_highlights_for_position<'a>(
14922        &'a self,
14923        position: Anchor,
14924        buffer: &'a MultiBufferSnapshot,
14925    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
14926        let read_highlights = self
14927            .background_highlights
14928            .get(&TypeId::of::<DocumentHighlightRead>())
14929            .map(|h| &h.1);
14930        let write_highlights = self
14931            .background_highlights
14932            .get(&TypeId::of::<DocumentHighlightWrite>())
14933            .map(|h| &h.1);
14934        let left_position = position.bias_left(buffer);
14935        let right_position = position.bias_right(buffer);
14936        read_highlights
14937            .into_iter()
14938            .chain(write_highlights)
14939            .flat_map(move |ranges| {
14940                let start_ix = match ranges.binary_search_by(|probe| {
14941                    let cmp = probe.end.cmp(&left_position, buffer);
14942                    if cmp.is_ge() {
14943                        Ordering::Greater
14944                    } else {
14945                        Ordering::Less
14946                    }
14947                }) {
14948                    Ok(i) | Err(i) => i,
14949                };
14950
14951                ranges[start_ix..]
14952                    .iter()
14953                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
14954            })
14955    }
14956
14957    pub fn has_background_highlights<T: 'static>(&self) -> bool {
14958        self.background_highlights
14959            .get(&TypeId::of::<T>())
14960            .map_or(false, |(_, highlights)| !highlights.is_empty())
14961    }
14962
14963    pub fn background_highlights_in_range(
14964        &self,
14965        search_range: Range<Anchor>,
14966        display_snapshot: &DisplaySnapshot,
14967        theme: &ThemeColors,
14968    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14969        let mut results = Vec::new();
14970        for (color_fetcher, ranges) in self.background_highlights.values() {
14971            let color = color_fetcher(theme);
14972            let start_ix = match ranges.binary_search_by(|probe| {
14973                let cmp = probe
14974                    .end
14975                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14976                if cmp.is_gt() {
14977                    Ordering::Greater
14978                } else {
14979                    Ordering::Less
14980                }
14981            }) {
14982                Ok(i) | Err(i) => i,
14983            };
14984            for range in &ranges[start_ix..] {
14985                if range
14986                    .start
14987                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14988                    .is_ge()
14989                {
14990                    break;
14991                }
14992
14993                let start = range.start.to_display_point(display_snapshot);
14994                let end = range.end.to_display_point(display_snapshot);
14995                results.push((start..end, color))
14996            }
14997        }
14998        results
14999    }
15000
15001    pub fn background_highlight_row_ranges<T: 'static>(
15002        &self,
15003        search_range: Range<Anchor>,
15004        display_snapshot: &DisplaySnapshot,
15005        count: usize,
15006    ) -> Vec<RangeInclusive<DisplayPoint>> {
15007        let mut results = Vec::new();
15008        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15009            return vec![];
15010        };
15011
15012        let start_ix = match ranges.binary_search_by(|probe| {
15013            let cmp = probe
15014                .end
15015                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15016            if cmp.is_gt() {
15017                Ordering::Greater
15018            } else {
15019                Ordering::Less
15020            }
15021        }) {
15022            Ok(i) | Err(i) => i,
15023        };
15024        let mut push_region = |start: Option<Point>, end: Option<Point>| {
15025            if let (Some(start_display), Some(end_display)) = (start, end) {
15026                results.push(
15027                    start_display.to_display_point(display_snapshot)
15028                        ..=end_display.to_display_point(display_snapshot),
15029                );
15030            }
15031        };
15032        let mut start_row: Option<Point> = None;
15033        let mut end_row: Option<Point> = None;
15034        if ranges.len() > count {
15035            return Vec::new();
15036        }
15037        for range in &ranges[start_ix..] {
15038            if range
15039                .start
15040                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15041                .is_ge()
15042            {
15043                break;
15044            }
15045            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15046            if let Some(current_row) = &end_row {
15047                if end.row == current_row.row {
15048                    continue;
15049                }
15050            }
15051            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15052            if start_row.is_none() {
15053                assert_eq!(end_row, None);
15054                start_row = Some(start);
15055                end_row = Some(end);
15056                continue;
15057            }
15058            if let Some(current_end) = end_row.as_mut() {
15059                if start.row > current_end.row + 1 {
15060                    push_region(start_row, end_row);
15061                    start_row = Some(start);
15062                    end_row = Some(end);
15063                } else {
15064                    // Merge two hunks.
15065                    *current_end = end;
15066                }
15067            } else {
15068                unreachable!();
15069            }
15070        }
15071        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15072        push_region(start_row, end_row);
15073        results
15074    }
15075
15076    pub fn gutter_highlights_in_range(
15077        &self,
15078        search_range: Range<Anchor>,
15079        display_snapshot: &DisplaySnapshot,
15080        cx: &App,
15081    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15082        let mut results = Vec::new();
15083        for (color_fetcher, ranges) in self.gutter_highlights.values() {
15084            let color = color_fetcher(cx);
15085            let start_ix = match ranges.binary_search_by(|probe| {
15086                let cmp = probe
15087                    .end
15088                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15089                if cmp.is_gt() {
15090                    Ordering::Greater
15091                } else {
15092                    Ordering::Less
15093                }
15094            }) {
15095                Ok(i) | Err(i) => i,
15096            };
15097            for range in &ranges[start_ix..] {
15098                if range
15099                    .start
15100                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15101                    .is_ge()
15102                {
15103                    break;
15104                }
15105
15106                let start = range.start.to_display_point(display_snapshot);
15107                let end = range.end.to_display_point(display_snapshot);
15108                results.push((start..end, color))
15109            }
15110        }
15111        results
15112    }
15113
15114    /// Get the text ranges corresponding to the redaction query
15115    pub fn redacted_ranges(
15116        &self,
15117        search_range: Range<Anchor>,
15118        display_snapshot: &DisplaySnapshot,
15119        cx: &App,
15120    ) -> Vec<Range<DisplayPoint>> {
15121        display_snapshot
15122            .buffer_snapshot
15123            .redacted_ranges(search_range, |file| {
15124                if let Some(file) = file {
15125                    file.is_private()
15126                        && EditorSettings::get(
15127                            Some(SettingsLocation {
15128                                worktree_id: file.worktree_id(cx),
15129                                path: file.path().as_ref(),
15130                            }),
15131                            cx,
15132                        )
15133                        .redact_private_values
15134                } else {
15135                    false
15136                }
15137            })
15138            .map(|range| {
15139                range.start.to_display_point(display_snapshot)
15140                    ..range.end.to_display_point(display_snapshot)
15141            })
15142            .collect()
15143    }
15144
15145    pub fn highlight_text<T: 'static>(
15146        &mut self,
15147        ranges: Vec<Range<Anchor>>,
15148        style: HighlightStyle,
15149        cx: &mut Context<Self>,
15150    ) {
15151        self.display_map.update(cx, |map, _| {
15152            map.highlight_text(TypeId::of::<T>(), ranges, style)
15153        });
15154        cx.notify();
15155    }
15156
15157    pub(crate) fn highlight_inlays<T: 'static>(
15158        &mut self,
15159        highlights: Vec<InlayHighlight>,
15160        style: HighlightStyle,
15161        cx: &mut Context<Self>,
15162    ) {
15163        self.display_map.update(cx, |map, _| {
15164            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15165        });
15166        cx.notify();
15167    }
15168
15169    pub fn text_highlights<'a, T: 'static>(
15170        &'a self,
15171        cx: &'a App,
15172    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15173        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15174    }
15175
15176    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15177        let cleared = self
15178            .display_map
15179            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15180        if cleared {
15181            cx.notify();
15182        }
15183    }
15184
15185    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15186        (self.read_only(cx) || self.blink_manager.read(cx).visible())
15187            && self.focus_handle.is_focused(window)
15188    }
15189
15190    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15191        self.show_cursor_when_unfocused = is_enabled;
15192        cx.notify();
15193    }
15194
15195    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15196        cx.notify();
15197    }
15198
15199    fn on_buffer_event(
15200        &mut self,
15201        multibuffer: &Entity<MultiBuffer>,
15202        event: &multi_buffer::Event,
15203        window: &mut Window,
15204        cx: &mut Context<Self>,
15205    ) {
15206        match event {
15207            multi_buffer::Event::Edited {
15208                singleton_buffer_edited,
15209                edited_buffer: buffer_edited,
15210            } => {
15211                self.scrollbar_marker_state.dirty = true;
15212                self.active_indent_guides_state.dirty = true;
15213                self.refresh_active_diagnostics(cx);
15214                self.refresh_code_actions(window, cx);
15215                if self.has_active_inline_completion() {
15216                    self.update_visible_inline_completion(window, cx);
15217                }
15218                if let Some(buffer) = buffer_edited {
15219                    let buffer_id = buffer.read(cx).remote_id();
15220                    if !self.registered_buffers.contains_key(&buffer_id) {
15221                        if let Some(project) = self.project.as_ref() {
15222                            project.update(cx, |project, cx| {
15223                                self.registered_buffers.insert(
15224                                    buffer_id,
15225                                    project.register_buffer_with_language_servers(&buffer, cx),
15226                                );
15227                            })
15228                        }
15229                    }
15230                }
15231                cx.emit(EditorEvent::BufferEdited);
15232                cx.emit(SearchEvent::MatchesInvalidated);
15233                if *singleton_buffer_edited {
15234                    if let Some(project) = &self.project {
15235                        #[allow(clippy::mutable_key_type)]
15236                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15237                            multibuffer
15238                                .all_buffers()
15239                                .into_iter()
15240                                .filter_map(|buffer| {
15241                                    buffer.update(cx, |buffer, cx| {
15242                                        let language = buffer.language()?;
15243                                        let should_discard = project.update(cx, |project, cx| {
15244                                            project.is_local()
15245                                                && !project.has_language_servers_for(buffer, cx)
15246                                        });
15247                                        should_discard.not().then_some(language.clone())
15248                                    })
15249                                })
15250                                .collect::<HashSet<_>>()
15251                        });
15252                        if !languages_affected.is_empty() {
15253                            self.refresh_inlay_hints(
15254                                InlayHintRefreshReason::BufferEdited(languages_affected),
15255                                cx,
15256                            );
15257                        }
15258                    }
15259                }
15260
15261                let Some(project) = &self.project else { return };
15262                let (telemetry, is_via_ssh) = {
15263                    let project = project.read(cx);
15264                    let telemetry = project.client().telemetry().clone();
15265                    let is_via_ssh = project.is_via_ssh();
15266                    (telemetry, is_via_ssh)
15267                };
15268                refresh_linked_ranges(self, window, cx);
15269                telemetry.log_edit_event("editor", is_via_ssh);
15270            }
15271            multi_buffer::Event::ExcerptsAdded {
15272                buffer,
15273                predecessor,
15274                excerpts,
15275            } => {
15276                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15277                let buffer_id = buffer.read(cx).remote_id();
15278                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15279                    if let Some(project) = &self.project {
15280                        get_uncommitted_diff_for_buffer(
15281                            project,
15282                            [buffer.clone()],
15283                            self.buffer.clone(),
15284                            cx,
15285                        )
15286                        .detach();
15287                    }
15288                }
15289                cx.emit(EditorEvent::ExcerptsAdded {
15290                    buffer: buffer.clone(),
15291                    predecessor: *predecessor,
15292                    excerpts: excerpts.clone(),
15293                });
15294                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15295            }
15296            multi_buffer::Event::ExcerptsRemoved { ids } => {
15297                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15298                let buffer = self.buffer.read(cx);
15299                self.registered_buffers
15300                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15301                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15302            }
15303            multi_buffer::Event::ExcerptsEdited {
15304                excerpt_ids,
15305                buffer_ids,
15306            } => {
15307                self.display_map.update(cx, |map, cx| {
15308                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
15309                });
15310                cx.emit(EditorEvent::ExcerptsEdited {
15311                    ids: excerpt_ids.clone(),
15312                })
15313            }
15314            multi_buffer::Event::ExcerptsExpanded { ids } => {
15315                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15316                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15317            }
15318            multi_buffer::Event::Reparsed(buffer_id) => {
15319                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15320
15321                cx.emit(EditorEvent::Reparsed(*buffer_id));
15322            }
15323            multi_buffer::Event::DiffHunksToggled => {
15324                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15325            }
15326            multi_buffer::Event::LanguageChanged(buffer_id) => {
15327                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15328                cx.emit(EditorEvent::Reparsed(*buffer_id));
15329                cx.notify();
15330            }
15331            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15332            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15333            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15334                cx.emit(EditorEvent::TitleChanged)
15335            }
15336            // multi_buffer::Event::DiffBaseChanged => {
15337            //     self.scrollbar_marker_state.dirty = true;
15338            //     cx.emit(EditorEvent::DiffBaseChanged);
15339            //     cx.notify();
15340            // }
15341            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15342            multi_buffer::Event::DiagnosticsUpdated => {
15343                self.refresh_active_diagnostics(cx);
15344                self.refresh_inline_diagnostics(true, window, cx);
15345                self.scrollbar_marker_state.dirty = true;
15346                cx.notify();
15347            }
15348            _ => {}
15349        };
15350    }
15351
15352    fn on_display_map_changed(
15353        &mut self,
15354        _: Entity<DisplayMap>,
15355        _: &mut Window,
15356        cx: &mut Context<Self>,
15357    ) {
15358        cx.notify();
15359    }
15360
15361    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15362        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15363        self.update_edit_prediction_settings(cx);
15364        self.refresh_inline_completion(true, false, window, cx);
15365        self.refresh_inlay_hints(
15366            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15367                self.selections.newest_anchor().head(),
15368                &self.buffer.read(cx).snapshot(cx),
15369                cx,
15370            )),
15371            cx,
15372        );
15373
15374        let old_cursor_shape = self.cursor_shape;
15375
15376        {
15377            let editor_settings = EditorSettings::get_global(cx);
15378            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15379            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15380            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15381        }
15382
15383        if old_cursor_shape != self.cursor_shape {
15384            cx.emit(EditorEvent::CursorShapeChanged);
15385        }
15386
15387        let project_settings = ProjectSettings::get_global(cx);
15388        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15389
15390        if self.mode == EditorMode::Full {
15391            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15392            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15393            if self.show_inline_diagnostics != show_inline_diagnostics {
15394                self.show_inline_diagnostics = show_inline_diagnostics;
15395                self.refresh_inline_diagnostics(false, window, cx);
15396            }
15397
15398            if self.git_blame_inline_enabled != inline_blame_enabled {
15399                self.toggle_git_blame_inline_internal(false, window, cx);
15400            }
15401        }
15402
15403        cx.notify();
15404    }
15405
15406    pub fn set_searchable(&mut self, searchable: bool) {
15407        self.searchable = searchable;
15408    }
15409
15410    pub fn searchable(&self) -> bool {
15411        self.searchable
15412    }
15413
15414    fn open_proposed_changes_editor(
15415        &mut self,
15416        _: &OpenProposedChangesEditor,
15417        window: &mut Window,
15418        cx: &mut Context<Self>,
15419    ) {
15420        let Some(workspace) = self.workspace() else {
15421            cx.propagate();
15422            return;
15423        };
15424
15425        let selections = self.selections.all::<usize>(cx);
15426        let multi_buffer = self.buffer.read(cx);
15427        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15428        let mut new_selections_by_buffer = HashMap::default();
15429        for selection in selections {
15430            for (buffer, range, _) in
15431                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15432            {
15433                let mut range = range.to_point(buffer);
15434                range.start.column = 0;
15435                range.end.column = buffer.line_len(range.end.row);
15436                new_selections_by_buffer
15437                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15438                    .or_insert(Vec::new())
15439                    .push(range)
15440            }
15441        }
15442
15443        let proposed_changes_buffers = new_selections_by_buffer
15444            .into_iter()
15445            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15446            .collect::<Vec<_>>();
15447        let proposed_changes_editor = cx.new(|cx| {
15448            ProposedChangesEditor::new(
15449                "Proposed changes",
15450                proposed_changes_buffers,
15451                self.project.clone(),
15452                window,
15453                cx,
15454            )
15455        });
15456
15457        window.defer(cx, move |window, cx| {
15458            workspace.update(cx, |workspace, cx| {
15459                workspace.active_pane().update(cx, |pane, cx| {
15460                    pane.add_item(
15461                        Box::new(proposed_changes_editor),
15462                        true,
15463                        true,
15464                        None,
15465                        window,
15466                        cx,
15467                    );
15468                });
15469            });
15470        });
15471    }
15472
15473    pub fn open_excerpts_in_split(
15474        &mut self,
15475        _: &OpenExcerptsSplit,
15476        window: &mut Window,
15477        cx: &mut Context<Self>,
15478    ) {
15479        self.open_excerpts_common(None, true, window, cx)
15480    }
15481
15482    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15483        self.open_excerpts_common(None, false, window, cx)
15484    }
15485
15486    fn open_excerpts_common(
15487        &mut self,
15488        jump_data: Option<JumpData>,
15489        split: bool,
15490        window: &mut Window,
15491        cx: &mut Context<Self>,
15492    ) {
15493        let Some(workspace) = self.workspace() else {
15494            cx.propagate();
15495            return;
15496        };
15497
15498        if self.buffer.read(cx).is_singleton() {
15499            cx.propagate();
15500            return;
15501        }
15502
15503        let mut new_selections_by_buffer = HashMap::default();
15504        match &jump_data {
15505            Some(JumpData::MultiBufferPoint {
15506                excerpt_id,
15507                position,
15508                anchor,
15509                line_offset_from_top,
15510            }) => {
15511                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15512                if let Some(buffer) = multi_buffer_snapshot
15513                    .buffer_id_for_excerpt(*excerpt_id)
15514                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15515                {
15516                    let buffer_snapshot = buffer.read(cx).snapshot();
15517                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15518                        language::ToPoint::to_point(anchor, &buffer_snapshot)
15519                    } else {
15520                        buffer_snapshot.clip_point(*position, Bias::Left)
15521                    };
15522                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15523                    new_selections_by_buffer.insert(
15524                        buffer,
15525                        (
15526                            vec![jump_to_offset..jump_to_offset],
15527                            Some(*line_offset_from_top),
15528                        ),
15529                    );
15530                }
15531            }
15532            Some(JumpData::MultiBufferRow {
15533                row,
15534                line_offset_from_top,
15535            }) => {
15536                let point = MultiBufferPoint::new(row.0, 0);
15537                if let Some((buffer, buffer_point, _)) =
15538                    self.buffer.read(cx).point_to_buffer_point(point, cx)
15539                {
15540                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15541                    new_selections_by_buffer
15542                        .entry(buffer)
15543                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
15544                        .0
15545                        .push(buffer_offset..buffer_offset)
15546                }
15547            }
15548            None => {
15549                let selections = self.selections.all::<usize>(cx);
15550                let multi_buffer = self.buffer.read(cx);
15551                for selection in selections {
15552                    for (snapshot, range, _, anchor) in multi_buffer
15553                        .snapshot(cx)
15554                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15555                    {
15556                        if let Some(anchor) = anchor {
15557                            // selection is in a deleted hunk
15558                            let Some(buffer_id) = anchor.buffer_id else {
15559                                continue;
15560                            };
15561                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15562                                continue;
15563                            };
15564                            let offset = text::ToOffset::to_offset(
15565                                &anchor.text_anchor,
15566                                &buffer_handle.read(cx).snapshot(),
15567                            );
15568                            let range = offset..offset;
15569                            new_selections_by_buffer
15570                                .entry(buffer_handle)
15571                                .or_insert((Vec::new(), None))
15572                                .0
15573                                .push(range)
15574                        } else {
15575                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15576                            else {
15577                                continue;
15578                            };
15579                            new_selections_by_buffer
15580                                .entry(buffer_handle)
15581                                .or_insert((Vec::new(), None))
15582                                .0
15583                                .push(range)
15584                        }
15585                    }
15586                }
15587            }
15588        }
15589
15590        if new_selections_by_buffer.is_empty() {
15591            return;
15592        }
15593
15594        // We defer the pane interaction because we ourselves are a workspace item
15595        // and activating a new item causes the pane to call a method on us reentrantly,
15596        // which panics if we're on the stack.
15597        window.defer(cx, move |window, cx| {
15598            workspace.update(cx, |workspace, cx| {
15599                let pane = if split {
15600                    workspace.adjacent_pane(window, cx)
15601                } else {
15602                    workspace.active_pane().clone()
15603                };
15604
15605                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15606                    let editor = buffer
15607                        .read(cx)
15608                        .file()
15609                        .is_none()
15610                        .then(|| {
15611                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15612                            // so `workspace.open_project_item` will never find them, always opening a new editor.
15613                            // Instead, we try to activate the existing editor in the pane first.
15614                            let (editor, pane_item_index) =
15615                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
15616                                    let editor = item.downcast::<Editor>()?;
15617                                    let singleton_buffer =
15618                                        editor.read(cx).buffer().read(cx).as_singleton()?;
15619                                    if singleton_buffer == buffer {
15620                                        Some((editor, i))
15621                                    } else {
15622                                        None
15623                                    }
15624                                })?;
15625                            pane.update(cx, |pane, cx| {
15626                                pane.activate_item(pane_item_index, true, true, window, cx)
15627                            });
15628                            Some(editor)
15629                        })
15630                        .flatten()
15631                        .unwrap_or_else(|| {
15632                            workspace.open_project_item::<Self>(
15633                                pane.clone(),
15634                                buffer,
15635                                true,
15636                                true,
15637                                window,
15638                                cx,
15639                            )
15640                        });
15641
15642                    editor.update(cx, |editor, cx| {
15643                        let autoscroll = match scroll_offset {
15644                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15645                            None => Autoscroll::newest(),
15646                        };
15647                        let nav_history = editor.nav_history.take();
15648                        editor.change_selections(Some(autoscroll), window, cx, |s| {
15649                            s.select_ranges(ranges);
15650                        });
15651                        editor.nav_history = nav_history;
15652                    });
15653                }
15654            })
15655        });
15656    }
15657
15658    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15659        let snapshot = self.buffer.read(cx).read(cx);
15660        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15661        Some(
15662            ranges
15663                .iter()
15664                .map(move |range| {
15665                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15666                })
15667                .collect(),
15668        )
15669    }
15670
15671    fn selection_replacement_ranges(
15672        &self,
15673        range: Range<OffsetUtf16>,
15674        cx: &mut App,
15675    ) -> Vec<Range<OffsetUtf16>> {
15676        let selections = self.selections.all::<OffsetUtf16>(cx);
15677        let newest_selection = selections
15678            .iter()
15679            .max_by_key(|selection| selection.id)
15680            .unwrap();
15681        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15682        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15683        let snapshot = self.buffer.read(cx).read(cx);
15684        selections
15685            .into_iter()
15686            .map(|mut selection| {
15687                selection.start.0 =
15688                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
15689                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15690                snapshot.clip_offset_utf16(selection.start, Bias::Left)
15691                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15692            })
15693            .collect()
15694    }
15695
15696    fn report_editor_event(
15697        &self,
15698        event_type: &'static str,
15699        file_extension: Option<String>,
15700        cx: &App,
15701    ) {
15702        if cfg!(any(test, feature = "test-support")) {
15703            return;
15704        }
15705
15706        let Some(project) = &self.project else { return };
15707
15708        // If None, we are in a file without an extension
15709        let file = self
15710            .buffer
15711            .read(cx)
15712            .as_singleton()
15713            .and_then(|b| b.read(cx).file());
15714        let file_extension = file_extension.or(file
15715            .as_ref()
15716            .and_then(|file| Path::new(file.file_name(cx)).extension())
15717            .and_then(|e| e.to_str())
15718            .map(|a| a.to_string()));
15719
15720        let vim_mode = cx
15721            .global::<SettingsStore>()
15722            .raw_user_settings()
15723            .get("vim_mode")
15724            == Some(&serde_json::Value::Bool(true));
15725
15726        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15727        let copilot_enabled = edit_predictions_provider
15728            == language::language_settings::EditPredictionProvider::Copilot;
15729        let copilot_enabled_for_language = self
15730            .buffer
15731            .read(cx)
15732            .settings_at(0, cx)
15733            .show_edit_predictions;
15734
15735        let project = project.read(cx);
15736        telemetry::event!(
15737            event_type,
15738            file_extension,
15739            vim_mode,
15740            copilot_enabled,
15741            copilot_enabled_for_language,
15742            edit_predictions_provider,
15743            is_via_ssh = project.is_via_ssh(),
15744        );
15745    }
15746
15747    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15748    /// with each line being an array of {text, highlight} objects.
15749    fn copy_highlight_json(
15750        &mut self,
15751        _: &CopyHighlightJson,
15752        window: &mut Window,
15753        cx: &mut Context<Self>,
15754    ) {
15755        #[derive(Serialize)]
15756        struct Chunk<'a> {
15757            text: String,
15758            highlight: Option<&'a str>,
15759        }
15760
15761        let snapshot = self.buffer.read(cx).snapshot(cx);
15762        let range = self
15763            .selected_text_range(false, window, cx)
15764            .and_then(|selection| {
15765                if selection.range.is_empty() {
15766                    None
15767                } else {
15768                    Some(selection.range)
15769                }
15770            })
15771            .unwrap_or_else(|| 0..snapshot.len());
15772
15773        let chunks = snapshot.chunks(range, true);
15774        let mut lines = Vec::new();
15775        let mut line: VecDeque<Chunk> = VecDeque::new();
15776
15777        let Some(style) = self.style.as_ref() else {
15778            return;
15779        };
15780
15781        for chunk in chunks {
15782            let highlight = chunk
15783                .syntax_highlight_id
15784                .and_then(|id| id.name(&style.syntax));
15785            let mut chunk_lines = chunk.text.split('\n').peekable();
15786            while let Some(text) = chunk_lines.next() {
15787                let mut merged_with_last_token = false;
15788                if let Some(last_token) = line.back_mut() {
15789                    if last_token.highlight == highlight {
15790                        last_token.text.push_str(text);
15791                        merged_with_last_token = true;
15792                    }
15793                }
15794
15795                if !merged_with_last_token {
15796                    line.push_back(Chunk {
15797                        text: text.into(),
15798                        highlight,
15799                    });
15800                }
15801
15802                if chunk_lines.peek().is_some() {
15803                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
15804                        line.pop_front();
15805                    }
15806                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
15807                        line.pop_back();
15808                    }
15809
15810                    lines.push(mem::take(&mut line));
15811                }
15812            }
15813        }
15814
15815        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15816            return;
15817        };
15818        cx.write_to_clipboard(ClipboardItem::new_string(lines));
15819    }
15820
15821    pub fn open_context_menu(
15822        &mut self,
15823        _: &OpenContextMenu,
15824        window: &mut Window,
15825        cx: &mut Context<Self>,
15826    ) {
15827        self.request_autoscroll(Autoscroll::newest(), cx);
15828        let position = self.selections.newest_display(cx).start;
15829        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15830    }
15831
15832    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15833        &self.inlay_hint_cache
15834    }
15835
15836    pub fn replay_insert_event(
15837        &mut self,
15838        text: &str,
15839        relative_utf16_range: Option<Range<isize>>,
15840        window: &mut Window,
15841        cx: &mut Context<Self>,
15842    ) {
15843        if !self.input_enabled {
15844            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15845            return;
15846        }
15847        if let Some(relative_utf16_range) = relative_utf16_range {
15848            let selections = self.selections.all::<OffsetUtf16>(cx);
15849            self.change_selections(None, window, cx, |s| {
15850                let new_ranges = selections.into_iter().map(|range| {
15851                    let start = OffsetUtf16(
15852                        range
15853                            .head()
15854                            .0
15855                            .saturating_add_signed(relative_utf16_range.start),
15856                    );
15857                    let end = OffsetUtf16(
15858                        range
15859                            .head()
15860                            .0
15861                            .saturating_add_signed(relative_utf16_range.end),
15862                    );
15863                    start..end
15864                });
15865                s.select_ranges(new_ranges);
15866            });
15867        }
15868
15869        self.handle_input(text, window, cx);
15870    }
15871
15872    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15873        let Some(provider) = self.semantics_provider.as_ref() else {
15874            return false;
15875        };
15876
15877        let mut supports = false;
15878        self.buffer().update(cx, |this, cx| {
15879            this.for_each_buffer(|buffer| {
15880                supports |= provider.supports_inlay_hints(buffer, cx);
15881            });
15882        });
15883
15884        supports
15885    }
15886
15887    pub fn is_focused(&self, window: &Window) -> bool {
15888        self.focus_handle.is_focused(window)
15889    }
15890
15891    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15892        cx.emit(EditorEvent::Focused);
15893
15894        if let Some(descendant) = self
15895            .last_focused_descendant
15896            .take()
15897            .and_then(|descendant| descendant.upgrade())
15898        {
15899            window.focus(&descendant);
15900        } else {
15901            if let Some(blame) = self.blame.as_ref() {
15902                blame.update(cx, GitBlame::focus)
15903            }
15904
15905            self.blink_manager.update(cx, BlinkManager::enable);
15906            self.show_cursor_names(window, cx);
15907            self.buffer.update(cx, |buffer, cx| {
15908                buffer.finalize_last_transaction(cx);
15909                if self.leader_peer_id.is_none() {
15910                    buffer.set_active_selections(
15911                        &self.selections.disjoint_anchors(),
15912                        self.selections.line_mode,
15913                        self.cursor_shape,
15914                        cx,
15915                    );
15916                }
15917            });
15918        }
15919    }
15920
15921    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15922        cx.emit(EditorEvent::FocusedIn)
15923    }
15924
15925    fn handle_focus_out(
15926        &mut self,
15927        event: FocusOutEvent,
15928        _window: &mut Window,
15929        cx: &mut Context<Self>,
15930    ) {
15931        if event.blurred != self.focus_handle {
15932            self.last_focused_descendant = Some(event.blurred);
15933        }
15934        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
15935    }
15936
15937    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15938        self.blink_manager.update(cx, BlinkManager::disable);
15939        self.buffer
15940            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
15941
15942        if let Some(blame) = self.blame.as_ref() {
15943            blame.update(cx, GitBlame::blur)
15944        }
15945        if !self.hover_state.focused(window, cx) {
15946            hide_hover(self, cx);
15947        }
15948        if !self
15949            .context_menu
15950            .borrow()
15951            .as_ref()
15952            .is_some_and(|context_menu| context_menu.focused(window, cx))
15953        {
15954            self.hide_context_menu(window, cx);
15955        }
15956        self.discard_inline_completion(false, cx);
15957        cx.emit(EditorEvent::Blurred);
15958        cx.notify();
15959    }
15960
15961    pub fn register_action<A: Action>(
15962        &mut self,
15963        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
15964    ) -> Subscription {
15965        let id = self.next_editor_action_id.post_inc();
15966        let listener = Arc::new(listener);
15967        self.editor_actions.borrow_mut().insert(
15968            id,
15969            Box::new(move |window, _| {
15970                let listener = listener.clone();
15971                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
15972                    let action = action.downcast_ref().unwrap();
15973                    if phase == DispatchPhase::Bubble {
15974                        listener(action, window, cx)
15975                    }
15976                })
15977            }),
15978        );
15979
15980        let editor_actions = self.editor_actions.clone();
15981        Subscription::new(move || {
15982            editor_actions.borrow_mut().remove(&id);
15983        })
15984    }
15985
15986    pub fn file_header_size(&self) -> u32 {
15987        FILE_HEADER_HEIGHT
15988    }
15989
15990    pub fn restore(
15991        &mut self,
15992        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
15993        window: &mut Window,
15994        cx: &mut Context<Self>,
15995    ) {
15996        let workspace = self.workspace();
15997        let project = self.project.as_ref();
15998        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
15999            let mut tasks = Vec::new();
16000            for (buffer_id, changes) in revert_changes {
16001                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16002                    buffer.update(cx, |buffer, cx| {
16003                        buffer.edit(
16004                            changes
16005                                .into_iter()
16006                                .map(|(range, text)| (range, text.to_string())),
16007                            None,
16008                            cx,
16009                        );
16010                    });
16011
16012                    if let Some(project) =
16013                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16014                    {
16015                        project.update(cx, |project, cx| {
16016                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16017                        })
16018                    }
16019                }
16020            }
16021            tasks
16022        });
16023        cx.spawn_in(window, |_, mut cx| async move {
16024            for (buffer, task) in save_tasks {
16025                let result = task.await;
16026                if result.is_err() {
16027                    let Some(path) = buffer
16028                        .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16029                        .ok()
16030                    else {
16031                        continue;
16032                    };
16033                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16034                        let Some(task) = cx
16035                            .update_window_entity(&workspace, |workspace, window, cx| {
16036                                workspace
16037                                    .open_path_preview(path, None, false, false, false, window, cx)
16038                            })
16039                            .ok()
16040                        else {
16041                            continue;
16042                        };
16043                        task.await.log_err();
16044                    }
16045                }
16046            }
16047        })
16048        .detach();
16049        self.change_selections(None, window, cx, |selections| selections.refresh());
16050    }
16051
16052    pub fn to_pixel_point(
16053        &self,
16054        source: multi_buffer::Anchor,
16055        editor_snapshot: &EditorSnapshot,
16056        window: &mut Window,
16057    ) -> Option<gpui::Point<Pixels>> {
16058        let source_point = source.to_display_point(editor_snapshot);
16059        self.display_to_pixel_point(source_point, editor_snapshot, window)
16060    }
16061
16062    pub fn display_to_pixel_point(
16063        &self,
16064        source: DisplayPoint,
16065        editor_snapshot: &EditorSnapshot,
16066        window: &mut Window,
16067    ) -> Option<gpui::Point<Pixels>> {
16068        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16069        let text_layout_details = self.text_layout_details(window);
16070        let scroll_top = text_layout_details
16071            .scroll_anchor
16072            .scroll_position(editor_snapshot)
16073            .y;
16074
16075        if source.row().as_f32() < scroll_top.floor() {
16076            return None;
16077        }
16078        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16079        let source_y = line_height * (source.row().as_f32() - scroll_top);
16080        Some(gpui::Point::new(source_x, source_y))
16081    }
16082
16083    pub fn has_visible_completions_menu(&self) -> bool {
16084        !self.edit_prediction_preview_is_active()
16085            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16086                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16087            })
16088    }
16089
16090    pub fn register_addon<T: Addon>(&mut self, instance: T) {
16091        self.addons
16092            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16093    }
16094
16095    pub fn unregister_addon<T: Addon>(&mut self) {
16096        self.addons.remove(&std::any::TypeId::of::<T>());
16097    }
16098
16099    pub fn addon<T: Addon>(&self) -> Option<&T> {
16100        let type_id = std::any::TypeId::of::<T>();
16101        self.addons
16102            .get(&type_id)
16103            .and_then(|item| item.to_any().downcast_ref::<T>())
16104    }
16105
16106    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16107        let text_layout_details = self.text_layout_details(window);
16108        let style = &text_layout_details.editor_style;
16109        let font_id = window.text_system().resolve_font(&style.text.font());
16110        let font_size = style.text.font_size.to_pixels(window.rem_size());
16111        let line_height = style.text.line_height_in_pixels(window.rem_size());
16112        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16113
16114        gpui::Size::new(em_width, line_height)
16115    }
16116
16117    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16118        self.load_diff_task.clone()
16119    }
16120
16121    fn read_selections_from_db(
16122        &mut self,
16123        item_id: u64,
16124        workspace_id: WorkspaceId,
16125        window: &mut Window,
16126        cx: &mut Context<Editor>,
16127    ) {
16128        if !self.is_singleton(cx)
16129            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16130        {
16131            return;
16132        }
16133        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16134            return;
16135        };
16136        if selections.is_empty() {
16137            return;
16138        }
16139
16140        let snapshot = self.buffer.read(cx).snapshot(cx);
16141        self.change_selections(None, window, cx, |s| {
16142            s.select_ranges(selections.into_iter().map(|(start, end)| {
16143                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16144            }));
16145        });
16146    }
16147}
16148
16149fn insert_extra_newline_brackets(
16150    buffer: &MultiBufferSnapshot,
16151    range: Range<usize>,
16152    language: &language::LanguageScope,
16153) -> bool {
16154    let leading_whitespace_len = buffer
16155        .reversed_chars_at(range.start)
16156        .take_while(|c| c.is_whitespace() && *c != '\n')
16157        .map(|c| c.len_utf8())
16158        .sum::<usize>();
16159    let trailing_whitespace_len = buffer
16160        .chars_at(range.end)
16161        .take_while(|c| c.is_whitespace() && *c != '\n')
16162        .map(|c| c.len_utf8())
16163        .sum::<usize>();
16164    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16165
16166    language.brackets().any(|(pair, enabled)| {
16167        let pair_start = pair.start.trim_end();
16168        let pair_end = pair.end.trim_start();
16169
16170        enabled
16171            && pair.newline
16172            && buffer.contains_str_at(range.end, pair_end)
16173            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16174    })
16175}
16176
16177fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16178    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16179        [(buffer, range, _)] => (*buffer, range.clone()),
16180        _ => return false,
16181    };
16182    let pair = {
16183        let mut result: Option<BracketMatch> = None;
16184
16185        for pair in buffer
16186            .all_bracket_ranges(range.clone())
16187            .filter(move |pair| {
16188                pair.open_range.start <= range.start && pair.close_range.end >= range.end
16189            })
16190        {
16191            let len = pair.close_range.end - pair.open_range.start;
16192
16193            if let Some(existing) = &result {
16194                let existing_len = existing.close_range.end - existing.open_range.start;
16195                if len > existing_len {
16196                    continue;
16197                }
16198            }
16199
16200            result = Some(pair);
16201        }
16202
16203        result
16204    };
16205    let Some(pair) = pair else {
16206        return false;
16207    };
16208    pair.newline_only
16209        && buffer
16210            .chars_for_range(pair.open_range.end..range.start)
16211            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16212            .all(|c| c.is_whitespace() && c != '\n')
16213}
16214
16215fn get_uncommitted_diff_for_buffer(
16216    project: &Entity<Project>,
16217    buffers: impl IntoIterator<Item = Entity<Buffer>>,
16218    buffer: Entity<MultiBuffer>,
16219    cx: &mut App,
16220) -> Task<()> {
16221    let mut tasks = Vec::new();
16222    project.update(cx, |project, cx| {
16223        for buffer in buffers {
16224            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16225        }
16226    });
16227    cx.spawn(|mut cx| async move {
16228        let diffs = futures::future::join_all(tasks).await;
16229        buffer
16230            .update(&mut cx, |buffer, cx| {
16231                for diff in diffs.into_iter().flatten() {
16232                    buffer.add_diff(diff, cx);
16233                }
16234            })
16235            .ok();
16236    })
16237}
16238
16239fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16240    let tab_size = tab_size.get() as usize;
16241    let mut width = offset;
16242
16243    for ch in text.chars() {
16244        width += if ch == '\t' {
16245            tab_size - (width % tab_size)
16246        } else {
16247            1
16248        };
16249    }
16250
16251    width - offset
16252}
16253
16254#[cfg(test)]
16255mod tests {
16256    use super::*;
16257
16258    #[test]
16259    fn test_string_size_with_expanded_tabs() {
16260        let nz = |val| NonZeroU32::new(val).unwrap();
16261        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16262        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16263        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16264        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16265        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16266        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16267        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16268        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16269    }
16270}
16271
16272/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16273struct WordBreakingTokenizer<'a> {
16274    input: &'a str,
16275}
16276
16277impl<'a> WordBreakingTokenizer<'a> {
16278    fn new(input: &'a str) -> Self {
16279        Self { input }
16280    }
16281}
16282
16283fn is_char_ideographic(ch: char) -> bool {
16284    use unicode_script::Script::*;
16285    use unicode_script::UnicodeScript;
16286    matches!(ch.script(), Han | Tangut | Yi)
16287}
16288
16289fn is_grapheme_ideographic(text: &str) -> bool {
16290    text.chars().any(is_char_ideographic)
16291}
16292
16293fn is_grapheme_whitespace(text: &str) -> bool {
16294    text.chars().any(|x| x.is_whitespace())
16295}
16296
16297fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16298    text.chars().next().map_or(false, |ch| {
16299        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16300    })
16301}
16302
16303#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16304struct WordBreakToken<'a> {
16305    token: &'a str,
16306    grapheme_len: usize,
16307    is_whitespace: bool,
16308}
16309
16310impl<'a> Iterator for WordBreakingTokenizer<'a> {
16311    /// Yields a span, the count of graphemes in the token, and whether it was
16312    /// whitespace. Note that it also breaks at word boundaries.
16313    type Item = WordBreakToken<'a>;
16314
16315    fn next(&mut self) -> Option<Self::Item> {
16316        use unicode_segmentation::UnicodeSegmentation;
16317        if self.input.is_empty() {
16318            return None;
16319        }
16320
16321        let mut iter = self.input.graphemes(true).peekable();
16322        let mut offset = 0;
16323        let mut graphemes = 0;
16324        if let Some(first_grapheme) = iter.next() {
16325            let is_whitespace = is_grapheme_whitespace(first_grapheme);
16326            offset += first_grapheme.len();
16327            graphemes += 1;
16328            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16329                if let Some(grapheme) = iter.peek().copied() {
16330                    if should_stay_with_preceding_ideograph(grapheme) {
16331                        offset += grapheme.len();
16332                        graphemes += 1;
16333                    }
16334                }
16335            } else {
16336                let mut words = self.input[offset..].split_word_bound_indices().peekable();
16337                let mut next_word_bound = words.peek().copied();
16338                if next_word_bound.map_or(false, |(i, _)| i == 0) {
16339                    next_word_bound = words.next();
16340                }
16341                while let Some(grapheme) = iter.peek().copied() {
16342                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
16343                        break;
16344                    };
16345                    if is_grapheme_whitespace(grapheme) != is_whitespace {
16346                        break;
16347                    };
16348                    offset += grapheme.len();
16349                    graphemes += 1;
16350                    iter.next();
16351                }
16352            }
16353            let token = &self.input[..offset];
16354            self.input = &self.input[offset..];
16355            if is_whitespace {
16356                Some(WordBreakToken {
16357                    token: " ",
16358                    grapheme_len: 1,
16359                    is_whitespace: true,
16360                })
16361            } else {
16362                Some(WordBreakToken {
16363                    token,
16364                    grapheme_len: graphemes,
16365                    is_whitespace: false,
16366                })
16367            }
16368        } else {
16369            None
16370        }
16371    }
16372}
16373
16374#[test]
16375fn test_word_breaking_tokenizer() {
16376    let tests: &[(&str, &[(&str, usize, bool)])] = &[
16377        ("", &[]),
16378        ("  ", &[(" ", 1, true)]),
16379        ("Ʒ", &[("Ʒ", 1, false)]),
16380        ("Ǽ", &[("Ǽ", 1, false)]),
16381        ("", &[("", 1, false)]),
16382        ("⋑⋑", &[("⋑⋑", 2, false)]),
16383        (
16384            "原理,进而",
16385            &[
16386                ("", 1, false),
16387                ("理,", 2, false),
16388                ("", 1, false),
16389                ("", 1, false),
16390            ],
16391        ),
16392        (
16393            "hello world",
16394            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16395        ),
16396        (
16397            "hello, world",
16398            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16399        ),
16400        (
16401            "  hello world",
16402            &[
16403                (" ", 1, true),
16404                ("hello", 5, false),
16405                (" ", 1, true),
16406                ("world", 5, false),
16407            ],
16408        ),
16409        (
16410            "这是什么 \n 钢笔",
16411            &[
16412                ("", 1, false),
16413                ("", 1, false),
16414                ("", 1, false),
16415                ("", 1, false),
16416                (" ", 1, true),
16417                ("", 1, false),
16418                ("", 1, false),
16419            ],
16420        ),
16421        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16422    ];
16423
16424    for (input, result) in tests {
16425        assert_eq!(
16426            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16427            result
16428                .iter()
16429                .copied()
16430                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16431                    token,
16432                    grapheme_len,
16433                    is_whitespace,
16434                })
16435                .collect::<Vec<_>>()
16436        );
16437    }
16438}
16439
16440fn wrap_with_prefix(
16441    line_prefix: String,
16442    unwrapped_text: String,
16443    wrap_column: usize,
16444    tab_size: NonZeroU32,
16445) -> String {
16446    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16447    let mut wrapped_text = String::new();
16448    let mut current_line = line_prefix.clone();
16449
16450    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16451    let mut current_line_len = line_prefix_len;
16452    for WordBreakToken {
16453        token,
16454        grapheme_len,
16455        is_whitespace,
16456    } in tokenizer
16457    {
16458        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16459            wrapped_text.push_str(current_line.trim_end());
16460            wrapped_text.push('\n');
16461            current_line.truncate(line_prefix.len());
16462            current_line_len = line_prefix_len;
16463            if !is_whitespace {
16464                current_line.push_str(token);
16465                current_line_len += grapheme_len;
16466            }
16467        } else if !is_whitespace {
16468            current_line.push_str(token);
16469            current_line_len += grapheme_len;
16470        } else if current_line_len != line_prefix_len {
16471            current_line.push(' ');
16472            current_line_len += 1;
16473        }
16474    }
16475
16476    if !current_line.is_empty() {
16477        wrapped_text.push_str(&current_line);
16478    }
16479    wrapped_text
16480}
16481
16482#[test]
16483fn test_wrap_with_prefix() {
16484    assert_eq!(
16485        wrap_with_prefix(
16486            "# ".to_string(),
16487            "abcdefg".to_string(),
16488            4,
16489            NonZeroU32::new(4).unwrap()
16490        ),
16491        "# abcdefg"
16492    );
16493    assert_eq!(
16494        wrap_with_prefix(
16495            "".to_string(),
16496            "\thello world".to_string(),
16497            8,
16498            NonZeroU32::new(4).unwrap()
16499        ),
16500        "hello\nworld"
16501    );
16502    assert_eq!(
16503        wrap_with_prefix(
16504            "// ".to_string(),
16505            "xx \nyy zz aa bb cc".to_string(),
16506            12,
16507            NonZeroU32::new(4).unwrap()
16508        ),
16509        "// xx yy zz\n// aa bb cc"
16510    );
16511    assert_eq!(
16512        wrap_with_prefix(
16513            String::new(),
16514            "这是什么 \n 钢笔".to_string(),
16515            3,
16516            NonZeroU32::new(4).unwrap()
16517        ),
16518        "这是什\n么 钢\n"
16519    );
16520}
16521
16522pub trait CollaborationHub {
16523    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16524    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16525    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16526}
16527
16528impl CollaborationHub for Entity<Project> {
16529    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16530        self.read(cx).collaborators()
16531    }
16532
16533    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16534        self.read(cx).user_store().read(cx).participant_indices()
16535    }
16536
16537    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16538        let this = self.read(cx);
16539        let user_ids = this.collaborators().values().map(|c| c.user_id);
16540        this.user_store().read_with(cx, |user_store, cx| {
16541            user_store.participant_names(user_ids, cx)
16542        })
16543    }
16544}
16545
16546pub trait SemanticsProvider {
16547    fn hover(
16548        &self,
16549        buffer: &Entity<Buffer>,
16550        position: text::Anchor,
16551        cx: &mut App,
16552    ) -> Option<Task<Vec<project::Hover>>>;
16553
16554    fn inlay_hints(
16555        &self,
16556        buffer_handle: Entity<Buffer>,
16557        range: Range<text::Anchor>,
16558        cx: &mut App,
16559    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16560
16561    fn resolve_inlay_hint(
16562        &self,
16563        hint: InlayHint,
16564        buffer_handle: Entity<Buffer>,
16565        server_id: LanguageServerId,
16566        cx: &mut App,
16567    ) -> Option<Task<anyhow::Result<InlayHint>>>;
16568
16569    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16570
16571    fn document_highlights(
16572        &self,
16573        buffer: &Entity<Buffer>,
16574        position: text::Anchor,
16575        cx: &mut App,
16576    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16577
16578    fn definitions(
16579        &self,
16580        buffer: &Entity<Buffer>,
16581        position: text::Anchor,
16582        kind: GotoDefinitionKind,
16583        cx: &mut App,
16584    ) -> Option<Task<Result<Vec<LocationLink>>>>;
16585
16586    fn range_for_rename(
16587        &self,
16588        buffer: &Entity<Buffer>,
16589        position: text::Anchor,
16590        cx: &mut App,
16591    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16592
16593    fn perform_rename(
16594        &self,
16595        buffer: &Entity<Buffer>,
16596        position: text::Anchor,
16597        new_name: String,
16598        cx: &mut App,
16599    ) -> Option<Task<Result<ProjectTransaction>>>;
16600}
16601
16602pub trait CompletionProvider {
16603    fn completions(
16604        &self,
16605        buffer: &Entity<Buffer>,
16606        buffer_position: text::Anchor,
16607        trigger: CompletionContext,
16608        window: &mut Window,
16609        cx: &mut Context<Editor>,
16610    ) -> Task<Result<Vec<Completion>>>;
16611
16612    fn resolve_completions(
16613        &self,
16614        buffer: Entity<Buffer>,
16615        completion_indices: Vec<usize>,
16616        completions: Rc<RefCell<Box<[Completion]>>>,
16617        cx: &mut Context<Editor>,
16618    ) -> Task<Result<bool>>;
16619
16620    fn apply_additional_edits_for_completion(
16621        &self,
16622        _buffer: Entity<Buffer>,
16623        _completions: Rc<RefCell<Box<[Completion]>>>,
16624        _completion_index: usize,
16625        _push_to_history: bool,
16626        _cx: &mut Context<Editor>,
16627    ) -> Task<Result<Option<language::Transaction>>> {
16628        Task::ready(Ok(None))
16629    }
16630
16631    fn is_completion_trigger(
16632        &self,
16633        buffer: &Entity<Buffer>,
16634        position: language::Anchor,
16635        text: &str,
16636        trigger_in_words: bool,
16637        cx: &mut Context<Editor>,
16638    ) -> bool;
16639
16640    fn sort_completions(&self) -> bool {
16641        true
16642    }
16643}
16644
16645pub trait CodeActionProvider {
16646    fn id(&self) -> Arc<str>;
16647
16648    fn code_actions(
16649        &self,
16650        buffer: &Entity<Buffer>,
16651        range: Range<text::Anchor>,
16652        window: &mut Window,
16653        cx: &mut App,
16654    ) -> Task<Result<Vec<CodeAction>>>;
16655
16656    fn apply_code_action(
16657        &self,
16658        buffer_handle: Entity<Buffer>,
16659        action: CodeAction,
16660        excerpt_id: ExcerptId,
16661        push_to_history: bool,
16662        window: &mut Window,
16663        cx: &mut App,
16664    ) -> Task<Result<ProjectTransaction>>;
16665}
16666
16667impl CodeActionProvider for Entity<Project> {
16668    fn id(&self) -> Arc<str> {
16669        "project".into()
16670    }
16671
16672    fn code_actions(
16673        &self,
16674        buffer: &Entity<Buffer>,
16675        range: Range<text::Anchor>,
16676        _window: &mut Window,
16677        cx: &mut App,
16678    ) -> Task<Result<Vec<CodeAction>>> {
16679        self.update(cx, |project, cx| {
16680            project.code_actions(buffer, range, None, cx)
16681        })
16682    }
16683
16684    fn apply_code_action(
16685        &self,
16686        buffer_handle: Entity<Buffer>,
16687        action: CodeAction,
16688        _excerpt_id: ExcerptId,
16689        push_to_history: bool,
16690        _window: &mut Window,
16691        cx: &mut App,
16692    ) -> Task<Result<ProjectTransaction>> {
16693        self.update(cx, |project, cx| {
16694            project.apply_code_action(buffer_handle, action, push_to_history, cx)
16695        })
16696    }
16697}
16698
16699fn snippet_completions(
16700    project: &Project,
16701    buffer: &Entity<Buffer>,
16702    buffer_position: text::Anchor,
16703    cx: &mut App,
16704) -> Task<Result<Vec<Completion>>> {
16705    let language = buffer.read(cx).language_at(buffer_position);
16706    let language_name = language.as_ref().map(|language| language.lsp_id());
16707    let snippet_store = project.snippets().read(cx);
16708    let snippets = snippet_store.snippets_for(language_name, cx);
16709
16710    if snippets.is_empty() {
16711        return Task::ready(Ok(vec![]));
16712    }
16713    let snapshot = buffer.read(cx).text_snapshot();
16714    let chars: String = snapshot
16715        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16716        .collect();
16717
16718    let scope = language.map(|language| language.default_scope());
16719    let executor = cx.background_executor().clone();
16720
16721    cx.background_spawn(async move {
16722        let classifier = CharClassifier::new(scope).for_completion(true);
16723        let mut last_word = chars
16724            .chars()
16725            .take_while(|c| classifier.is_word(*c))
16726            .collect::<String>();
16727        last_word = last_word.chars().rev().collect();
16728
16729        if last_word.is_empty() {
16730            return Ok(vec![]);
16731        }
16732
16733        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16734        let to_lsp = |point: &text::Anchor| {
16735            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16736            point_to_lsp(end)
16737        };
16738        let lsp_end = to_lsp(&buffer_position);
16739
16740        let candidates = snippets
16741            .iter()
16742            .enumerate()
16743            .flat_map(|(ix, snippet)| {
16744                snippet
16745                    .prefix
16746                    .iter()
16747                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16748            })
16749            .collect::<Vec<StringMatchCandidate>>();
16750
16751        let mut matches = fuzzy::match_strings(
16752            &candidates,
16753            &last_word,
16754            last_word.chars().any(|c| c.is_uppercase()),
16755            100,
16756            &Default::default(),
16757            executor,
16758        )
16759        .await;
16760
16761        // Remove all candidates where the query's start does not match the start of any word in the candidate
16762        if let Some(query_start) = last_word.chars().next() {
16763            matches.retain(|string_match| {
16764                split_words(&string_match.string).any(|word| {
16765                    // Check that the first codepoint of the word as lowercase matches the first
16766                    // codepoint of the query as lowercase
16767                    word.chars()
16768                        .flat_map(|codepoint| codepoint.to_lowercase())
16769                        .zip(query_start.to_lowercase())
16770                        .all(|(word_cp, query_cp)| word_cp == query_cp)
16771                })
16772            });
16773        }
16774
16775        let matched_strings = matches
16776            .into_iter()
16777            .map(|m| m.string)
16778            .collect::<HashSet<_>>();
16779
16780        let result: Vec<Completion> = snippets
16781            .into_iter()
16782            .filter_map(|snippet| {
16783                let matching_prefix = snippet
16784                    .prefix
16785                    .iter()
16786                    .find(|prefix| matched_strings.contains(*prefix))?;
16787                let start = as_offset - last_word.len();
16788                let start = snapshot.anchor_before(start);
16789                let range = start..buffer_position;
16790                let lsp_start = to_lsp(&start);
16791                let lsp_range = lsp::Range {
16792                    start: lsp_start,
16793                    end: lsp_end,
16794                };
16795                Some(Completion {
16796                    old_range: range,
16797                    new_text: snippet.body.clone(),
16798                    resolved: false,
16799                    label: CodeLabel {
16800                        text: matching_prefix.clone(),
16801                        runs: vec![],
16802                        filter_range: 0..matching_prefix.len(),
16803                    },
16804                    server_id: LanguageServerId(usize::MAX),
16805                    documentation: snippet
16806                        .description
16807                        .clone()
16808                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
16809                    lsp_completion: lsp::CompletionItem {
16810                        label: snippet.prefix.first().unwrap().clone(),
16811                        kind: Some(CompletionItemKind::SNIPPET),
16812                        label_details: snippet.description.as_ref().map(|description| {
16813                            lsp::CompletionItemLabelDetails {
16814                                detail: Some(description.clone()),
16815                                description: None,
16816                            }
16817                        }),
16818                        insert_text_format: Some(InsertTextFormat::SNIPPET),
16819                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16820                            lsp::InsertReplaceEdit {
16821                                new_text: snippet.body.clone(),
16822                                insert: lsp_range,
16823                                replace: lsp_range,
16824                            },
16825                        )),
16826                        filter_text: Some(snippet.body.clone()),
16827                        sort_text: Some(char::MAX.to_string()),
16828                        ..Default::default()
16829                    },
16830                    confirm: None,
16831                })
16832            })
16833            .collect();
16834
16835        Ok(result)
16836    })
16837}
16838
16839impl CompletionProvider for Entity<Project> {
16840    fn completions(
16841        &self,
16842        buffer: &Entity<Buffer>,
16843        buffer_position: text::Anchor,
16844        options: CompletionContext,
16845        _window: &mut Window,
16846        cx: &mut Context<Editor>,
16847    ) -> Task<Result<Vec<Completion>>> {
16848        self.update(cx, |project, cx| {
16849            let snippets = snippet_completions(project, buffer, buffer_position, cx);
16850            let project_completions = project.completions(buffer, buffer_position, options, cx);
16851            cx.background_spawn(async move {
16852                let mut completions = project_completions.await?;
16853                let snippets_completions = snippets.await?;
16854                completions.extend(snippets_completions);
16855                Ok(completions)
16856            })
16857        })
16858    }
16859
16860    fn resolve_completions(
16861        &self,
16862        buffer: Entity<Buffer>,
16863        completion_indices: Vec<usize>,
16864        completions: Rc<RefCell<Box<[Completion]>>>,
16865        cx: &mut Context<Editor>,
16866    ) -> Task<Result<bool>> {
16867        self.update(cx, |project, cx| {
16868            project.lsp_store().update(cx, |lsp_store, cx| {
16869                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16870            })
16871        })
16872    }
16873
16874    fn apply_additional_edits_for_completion(
16875        &self,
16876        buffer: Entity<Buffer>,
16877        completions: Rc<RefCell<Box<[Completion]>>>,
16878        completion_index: usize,
16879        push_to_history: bool,
16880        cx: &mut Context<Editor>,
16881    ) -> Task<Result<Option<language::Transaction>>> {
16882        self.update(cx, |project, cx| {
16883            project.lsp_store().update(cx, |lsp_store, cx| {
16884                lsp_store.apply_additional_edits_for_completion(
16885                    buffer,
16886                    completions,
16887                    completion_index,
16888                    push_to_history,
16889                    cx,
16890                )
16891            })
16892        })
16893    }
16894
16895    fn is_completion_trigger(
16896        &self,
16897        buffer: &Entity<Buffer>,
16898        position: language::Anchor,
16899        text: &str,
16900        trigger_in_words: bool,
16901        cx: &mut Context<Editor>,
16902    ) -> bool {
16903        let mut chars = text.chars();
16904        let char = if let Some(char) = chars.next() {
16905            char
16906        } else {
16907            return false;
16908        };
16909        if chars.next().is_some() {
16910            return false;
16911        }
16912
16913        let buffer = buffer.read(cx);
16914        let snapshot = buffer.snapshot();
16915        if !snapshot.settings_at(position, cx).show_completions_on_input {
16916            return false;
16917        }
16918        let classifier = snapshot.char_classifier_at(position).for_completion(true);
16919        if trigger_in_words && classifier.is_word(char) {
16920            return true;
16921        }
16922
16923        buffer.completion_triggers().contains(text)
16924    }
16925}
16926
16927impl SemanticsProvider for Entity<Project> {
16928    fn hover(
16929        &self,
16930        buffer: &Entity<Buffer>,
16931        position: text::Anchor,
16932        cx: &mut App,
16933    ) -> Option<Task<Vec<project::Hover>>> {
16934        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
16935    }
16936
16937    fn document_highlights(
16938        &self,
16939        buffer: &Entity<Buffer>,
16940        position: text::Anchor,
16941        cx: &mut App,
16942    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
16943        Some(self.update(cx, |project, cx| {
16944            project.document_highlights(buffer, position, cx)
16945        }))
16946    }
16947
16948    fn definitions(
16949        &self,
16950        buffer: &Entity<Buffer>,
16951        position: text::Anchor,
16952        kind: GotoDefinitionKind,
16953        cx: &mut App,
16954    ) -> Option<Task<Result<Vec<LocationLink>>>> {
16955        Some(self.update(cx, |project, cx| match kind {
16956            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
16957            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
16958            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
16959            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
16960        }))
16961    }
16962
16963    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
16964        // TODO: make this work for remote projects
16965        self.update(cx, |this, cx| {
16966            buffer.update(cx, |buffer, cx| {
16967                this.any_language_server_supports_inlay_hints(buffer, cx)
16968            })
16969        })
16970    }
16971
16972    fn inlay_hints(
16973        &self,
16974        buffer_handle: Entity<Buffer>,
16975        range: Range<text::Anchor>,
16976        cx: &mut App,
16977    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
16978        Some(self.update(cx, |project, cx| {
16979            project.inlay_hints(buffer_handle, range, cx)
16980        }))
16981    }
16982
16983    fn resolve_inlay_hint(
16984        &self,
16985        hint: InlayHint,
16986        buffer_handle: Entity<Buffer>,
16987        server_id: LanguageServerId,
16988        cx: &mut App,
16989    ) -> Option<Task<anyhow::Result<InlayHint>>> {
16990        Some(self.update(cx, |project, cx| {
16991            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
16992        }))
16993    }
16994
16995    fn range_for_rename(
16996        &self,
16997        buffer: &Entity<Buffer>,
16998        position: text::Anchor,
16999        cx: &mut App,
17000    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17001        Some(self.update(cx, |project, cx| {
17002            let buffer = buffer.clone();
17003            let task = project.prepare_rename(buffer.clone(), position, cx);
17004            cx.spawn(|_, mut cx| async move {
17005                Ok(match task.await? {
17006                    PrepareRenameResponse::Success(range) => Some(range),
17007                    PrepareRenameResponse::InvalidPosition => None,
17008                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17009                        // Fallback on using TreeSitter info to determine identifier range
17010                        buffer.update(&mut cx, |buffer, _| {
17011                            let snapshot = buffer.snapshot();
17012                            let (range, kind) = snapshot.surrounding_word(position);
17013                            if kind != Some(CharKind::Word) {
17014                                return None;
17015                            }
17016                            Some(
17017                                snapshot.anchor_before(range.start)
17018                                    ..snapshot.anchor_after(range.end),
17019                            )
17020                        })?
17021                    }
17022                })
17023            })
17024        }))
17025    }
17026
17027    fn perform_rename(
17028        &self,
17029        buffer: &Entity<Buffer>,
17030        position: text::Anchor,
17031        new_name: String,
17032        cx: &mut App,
17033    ) -> Option<Task<Result<ProjectTransaction>>> {
17034        Some(self.update(cx, |project, cx| {
17035            project.perform_rename(buffer.clone(), position, new_name, cx)
17036        }))
17037    }
17038}
17039
17040fn inlay_hint_settings(
17041    location: Anchor,
17042    snapshot: &MultiBufferSnapshot,
17043    cx: &mut Context<Editor>,
17044) -> InlayHintSettings {
17045    let file = snapshot.file_at(location);
17046    let language = snapshot.language_at(location).map(|l| l.name());
17047    language_settings(language, file, cx).inlay_hints
17048}
17049
17050fn consume_contiguous_rows(
17051    contiguous_row_selections: &mut Vec<Selection<Point>>,
17052    selection: &Selection<Point>,
17053    display_map: &DisplaySnapshot,
17054    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17055) -> (MultiBufferRow, MultiBufferRow) {
17056    contiguous_row_selections.push(selection.clone());
17057    let start_row = MultiBufferRow(selection.start.row);
17058    let mut end_row = ending_row(selection, display_map);
17059
17060    while let Some(next_selection) = selections.peek() {
17061        if next_selection.start.row <= end_row.0 {
17062            end_row = ending_row(next_selection, display_map);
17063            contiguous_row_selections.push(selections.next().unwrap().clone());
17064        } else {
17065            break;
17066        }
17067    }
17068    (start_row, end_row)
17069}
17070
17071fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17072    if next_selection.end.column > 0 || next_selection.is_empty() {
17073        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17074    } else {
17075        MultiBufferRow(next_selection.end.row)
17076    }
17077}
17078
17079impl EditorSnapshot {
17080    pub fn remote_selections_in_range<'a>(
17081        &'a self,
17082        range: &'a Range<Anchor>,
17083        collaboration_hub: &dyn CollaborationHub,
17084        cx: &'a App,
17085    ) -> impl 'a + Iterator<Item = RemoteSelection> {
17086        let participant_names = collaboration_hub.user_names(cx);
17087        let participant_indices = collaboration_hub.user_participant_indices(cx);
17088        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17089        let collaborators_by_replica_id = collaborators_by_peer_id
17090            .iter()
17091            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17092            .collect::<HashMap<_, _>>();
17093        self.buffer_snapshot
17094            .selections_in_range(range, false)
17095            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17096                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17097                let participant_index = participant_indices.get(&collaborator.user_id).copied();
17098                let user_name = participant_names.get(&collaborator.user_id).cloned();
17099                Some(RemoteSelection {
17100                    replica_id,
17101                    selection,
17102                    cursor_shape,
17103                    line_mode,
17104                    participant_index,
17105                    peer_id: collaborator.peer_id,
17106                    user_name,
17107                })
17108            })
17109    }
17110
17111    pub fn hunks_for_ranges(
17112        &self,
17113        ranges: impl IntoIterator<Item = Range<Point>>,
17114    ) -> Vec<MultiBufferDiffHunk> {
17115        let mut hunks = Vec::new();
17116        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17117            HashMap::default();
17118        for query_range in ranges {
17119            let query_rows =
17120                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17121            for hunk in self.buffer_snapshot.diff_hunks_in_range(
17122                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17123            ) {
17124                // Include deleted hunks that are adjacent to the query range, because
17125                // otherwise they would be missed.
17126                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
17127                if hunk.status().is_deleted() {
17128                    intersects_range |= hunk.row_range.start == query_rows.end;
17129                    intersects_range |= hunk.row_range.end == query_rows.start;
17130                }
17131                if intersects_range {
17132                    if !processed_buffer_rows
17133                        .entry(hunk.buffer_id)
17134                        .or_default()
17135                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17136                    {
17137                        continue;
17138                    }
17139                    hunks.push(hunk);
17140                }
17141            }
17142        }
17143
17144        hunks
17145    }
17146
17147    fn display_diff_hunks_for_rows<'a>(
17148        &'a self,
17149        display_rows: Range<DisplayRow>,
17150        folded_buffers: &'a HashSet<BufferId>,
17151    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17152        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17153        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17154
17155        self.buffer_snapshot
17156            .diff_hunks_in_range(buffer_start..buffer_end)
17157            .filter_map(|hunk| {
17158                if folded_buffers.contains(&hunk.buffer_id) {
17159                    return None;
17160                }
17161
17162                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17163                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17164
17165                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17166                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17167
17168                let display_hunk = if hunk_display_start.column() != 0 {
17169                    DisplayDiffHunk::Folded {
17170                        display_row: hunk_display_start.row(),
17171                    }
17172                } else {
17173                    let mut end_row = hunk_display_end.row();
17174                    if hunk_display_end.column() > 0 {
17175                        end_row.0 += 1;
17176                    }
17177                    DisplayDiffHunk::Unfolded {
17178                        status: hunk.status(),
17179                        diff_base_byte_range: hunk.diff_base_byte_range,
17180                        display_row_range: hunk_display_start.row()..end_row,
17181                        multi_buffer_range: Anchor::range_in_buffer(
17182                            hunk.excerpt_id,
17183                            hunk.buffer_id,
17184                            hunk.buffer_range,
17185                        ),
17186                    }
17187                };
17188
17189                Some(display_hunk)
17190            })
17191    }
17192
17193    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17194        self.display_snapshot.buffer_snapshot.language_at(position)
17195    }
17196
17197    pub fn is_focused(&self) -> bool {
17198        self.is_focused
17199    }
17200
17201    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17202        self.placeholder_text.as_ref()
17203    }
17204
17205    pub fn scroll_position(&self) -> gpui::Point<f32> {
17206        self.scroll_anchor.scroll_position(&self.display_snapshot)
17207    }
17208
17209    fn gutter_dimensions(
17210        &self,
17211        font_id: FontId,
17212        font_size: Pixels,
17213        max_line_number_width: Pixels,
17214        cx: &App,
17215    ) -> Option<GutterDimensions> {
17216        if !self.show_gutter {
17217            return None;
17218        }
17219
17220        let descent = cx.text_system().descent(font_id, font_size);
17221        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17222        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17223
17224        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17225            matches!(
17226                ProjectSettings::get_global(cx).git.git_gutter,
17227                Some(GitGutterSetting::TrackedFiles)
17228            )
17229        });
17230        let gutter_settings = EditorSettings::get_global(cx).gutter;
17231        let show_line_numbers = self
17232            .show_line_numbers
17233            .unwrap_or(gutter_settings.line_numbers);
17234        let line_gutter_width = if show_line_numbers {
17235            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17236            let min_width_for_number_on_gutter = em_advance * 4.0;
17237            max_line_number_width.max(min_width_for_number_on_gutter)
17238        } else {
17239            0.0.into()
17240        };
17241
17242        let show_code_actions = self
17243            .show_code_actions
17244            .unwrap_or(gutter_settings.code_actions);
17245
17246        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17247
17248        let git_blame_entries_width =
17249            self.git_blame_gutter_max_author_length
17250                .map(|max_author_length| {
17251                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17252
17253                    /// The number of characters to dedicate to gaps and margins.
17254                    const SPACING_WIDTH: usize = 4;
17255
17256                    let max_char_count = max_author_length
17257                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17258                        + ::git::SHORT_SHA_LENGTH
17259                        + MAX_RELATIVE_TIMESTAMP.len()
17260                        + SPACING_WIDTH;
17261
17262                    em_advance * max_char_count
17263                });
17264
17265        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17266        left_padding += if show_code_actions || show_runnables {
17267            em_width * 3.0
17268        } else if show_git_gutter && show_line_numbers {
17269            em_width * 2.0
17270        } else if show_git_gutter || show_line_numbers {
17271            em_width
17272        } else {
17273            px(0.)
17274        };
17275
17276        let right_padding = if gutter_settings.folds && show_line_numbers {
17277            em_width * 4.0
17278        } else if gutter_settings.folds {
17279            em_width * 3.0
17280        } else if show_line_numbers {
17281            em_width
17282        } else {
17283            px(0.)
17284        };
17285
17286        Some(GutterDimensions {
17287            left_padding,
17288            right_padding,
17289            width: line_gutter_width + left_padding + right_padding,
17290            margin: -descent,
17291            git_blame_entries_width,
17292        })
17293    }
17294
17295    pub fn render_crease_toggle(
17296        &self,
17297        buffer_row: MultiBufferRow,
17298        row_contains_cursor: bool,
17299        editor: Entity<Editor>,
17300        window: &mut Window,
17301        cx: &mut App,
17302    ) -> Option<AnyElement> {
17303        let folded = self.is_line_folded(buffer_row);
17304        let mut is_foldable = false;
17305
17306        if let Some(crease) = self
17307            .crease_snapshot
17308            .query_row(buffer_row, &self.buffer_snapshot)
17309        {
17310            is_foldable = true;
17311            match crease {
17312                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17313                    if let Some(render_toggle) = render_toggle {
17314                        let toggle_callback =
17315                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17316                                if folded {
17317                                    editor.update(cx, |editor, cx| {
17318                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17319                                    });
17320                                } else {
17321                                    editor.update(cx, |editor, cx| {
17322                                        editor.unfold_at(
17323                                            &crate::UnfoldAt { buffer_row },
17324                                            window,
17325                                            cx,
17326                                        )
17327                                    });
17328                                }
17329                            });
17330                        return Some((render_toggle)(
17331                            buffer_row,
17332                            folded,
17333                            toggle_callback,
17334                            window,
17335                            cx,
17336                        ));
17337                    }
17338                }
17339            }
17340        }
17341
17342        is_foldable |= self.starts_indent(buffer_row);
17343
17344        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17345            Some(
17346                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17347                    .toggle_state(folded)
17348                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17349                        if folded {
17350                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17351                        } else {
17352                            this.fold_at(&FoldAt { buffer_row }, window, cx);
17353                        }
17354                    }))
17355                    .into_any_element(),
17356            )
17357        } else {
17358            None
17359        }
17360    }
17361
17362    pub fn render_crease_trailer(
17363        &self,
17364        buffer_row: MultiBufferRow,
17365        window: &mut Window,
17366        cx: &mut App,
17367    ) -> Option<AnyElement> {
17368        let folded = self.is_line_folded(buffer_row);
17369        if let Crease::Inline { render_trailer, .. } = self
17370            .crease_snapshot
17371            .query_row(buffer_row, &self.buffer_snapshot)?
17372        {
17373            let render_trailer = render_trailer.as_ref()?;
17374            Some(render_trailer(buffer_row, folded, window, cx))
17375        } else {
17376            None
17377        }
17378    }
17379}
17380
17381impl Deref for EditorSnapshot {
17382    type Target = DisplaySnapshot;
17383
17384    fn deref(&self) -> &Self::Target {
17385        &self.display_snapshot
17386    }
17387}
17388
17389#[derive(Clone, Debug, PartialEq, Eq)]
17390pub enum EditorEvent {
17391    InputIgnored {
17392        text: Arc<str>,
17393    },
17394    InputHandled {
17395        utf16_range_to_replace: Option<Range<isize>>,
17396        text: Arc<str>,
17397    },
17398    ExcerptsAdded {
17399        buffer: Entity<Buffer>,
17400        predecessor: ExcerptId,
17401        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17402    },
17403    ExcerptsRemoved {
17404        ids: Vec<ExcerptId>,
17405    },
17406    BufferFoldToggled {
17407        ids: Vec<ExcerptId>,
17408        folded: bool,
17409    },
17410    ExcerptsEdited {
17411        ids: Vec<ExcerptId>,
17412    },
17413    ExcerptsExpanded {
17414        ids: Vec<ExcerptId>,
17415    },
17416    BufferEdited,
17417    Edited {
17418        transaction_id: clock::Lamport,
17419    },
17420    Reparsed(BufferId),
17421    Focused,
17422    FocusedIn,
17423    Blurred,
17424    DirtyChanged,
17425    Saved,
17426    TitleChanged,
17427    DiffBaseChanged,
17428    SelectionsChanged {
17429        local: bool,
17430    },
17431    ScrollPositionChanged {
17432        local: bool,
17433        autoscroll: bool,
17434    },
17435    Closed,
17436    TransactionUndone {
17437        transaction_id: clock::Lamport,
17438    },
17439    TransactionBegun {
17440        transaction_id: clock::Lamport,
17441    },
17442    Reloaded,
17443    CursorShapeChanged,
17444}
17445
17446impl EventEmitter<EditorEvent> for Editor {}
17447
17448impl Focusable for Editor {
17449    fn focus_handle(&self, _cx: &App) -> FocusHandle {
17450        self.focus_handle.clone()
17451    }
17452}
17453
17454impl Render for Editor {
17455    fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17456        let settings = ThemeSettings::get_global(cx);
17457
17458        let mut text_style = match self.mode {
17459            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17460                color: cx.theme().colors().editor_foreground,
17461                font_family: settings.ui_font.family.clone(),
17462                font_features: settings.ui_font.features.clone(),
17463                font_fallbacks: settings.ui_font.fallbacks.clone(),
17464                font_size: rems(0.875).into(),
17465                font_weight: settings.ui_font.weight,
17466                line_height: relative(settings.buffer_line_height.value()),
17467                ..Default::default()
17468            },
17469            EditorMode::Full => TextStyle {
17470                color: cx.theme().colors().editor_foreground,
17471                font_family: settings.buffer_font.family.clone(),
17472                font_features: settings.buffer_font.features.clone(),
17473                font_fallbacks: settings.buffer_font.fallbacks.clone(),
17474                font_size: settings.buffer_font_size(cx).into(),
17475                font_weight: settings.buffer_font.weight,
17476                line_height: relative(settings.buffer_line_height.value()),
17477                ..Default::default()
17478            },
17479        };
17480        if let Some(text_style_refinement) = &self.text_style_refinement {
17481            text_style.refine(text_style_refinement)
17482        }
17483
17484        let background = match self.mode {
17485            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17486            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17487            EditorMode::Full => cx.theme().colors().editor_background,
17488        };
17489
17490        EditorElement::new(
17491            &cx.entity(),
17492            EditorStyle {
17493                background,
17494                local_player: cx.theme().players().local(),
17495                text: text_style,
17496                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17497                syntax: cx.theme().syntax().clone(),
17498                status: cx.theme().status().clone(),
17499                inlay_hints_style: make_inlay_hints_style(cx),
17500                inline_completion_styles: make_suggestion_styles(cx),
17501                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17502            },
17503        )
17504    }
17505}
17506
17507impl EntityInputHandler for Editor {
17508    fn text_for_range(
17509        &mut self,
17510        range_utf16: Range<usize>,
17511        adjusted_range: &mut Option<Range<usize>>,
17512        _: &mut Window,
17513        cx: &mut Context<Self>,
17514    ) -> Option<String> {
17515        let snapshot = self.buffer.read(cx).read(cx);
17516        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17517        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17518        if (start.0..end.0) != range_utf16 {
17519            adjusted_range.replace(start.0..end.0);
17520        }
17521        Some(snapshot.text_for_range(start..end).collect())
17522    }
17523
17524    fn selected_text_range(
17525        &mut self,
17526        ignore_disabled_input: bool,
17527        _: &mut Window,
17528        cx: &mut Context<Self>,
17529    ) -> Option<UTF16Selection> {
17530        // Prevent the IME menu from appearing when holding down an alphabetic key
17531        // while input is disabled.
17532        if !ignore_disabled_input && !self.input_enabled {
17533            return None;
17534        }
17535
17536        let selection = self.selections.newest::<OffsetUtf16>(cx);
17537        let range = selection.range();
17538
17539        Some(UTF16Selection {
17540            range: range.start.0..range.end.0,
17541            reversed: selection.reversed,
17542        })
17543    }
17544
17545    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17546        let snapshot = self.buffer.read(cx).read(cx);
17547        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17548        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17549    }
17550
17551    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17552        self.clear_highlights::<InputComposition>(cx);
17553        self.ime_transaction.take();
17554    }
17555
17556    fn replace_text_in_range(
17557        &mut self,
17558        range_utf16: Option<Range<usize>>,
17559        text: &str,
17560        window: &mut Window,
17561        cx: &mut Context<Self>,
17562    ) {
17563        if !self.input_enabled {
17564            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17565            return;
17566        }
17567
17568        self.transact(window, cx, |this, window, cx| {
17569            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17570                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17571                Some(this.selection_replacement_ranges(range_utf16, cx))
17572            } else {
17573                this.marked_text_ranges(cx)
17574            };
17575
17576            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17577                let newest_selection_id = this.selections.newest_anchor().id;
17578                this.selections
17579                    .all::<OffsetUtf16>(cx)
17580                    .iter()
17581                    .zip(ranges_to_replace.iter())
17582                    .find_map(|(selection, range)| {
17583                        if selection.id == newest_selection_id {
17584                            Some(
17585                                (range.start.0 as isize - selection.head().0 as isize)
17586                                    ..(range.end.0 as isize - selection.head().0 as isize),
17587                            )
17588                        } else {
17589                            None
17590                        }
17591                    })
17592            });
17593
17594            cx.emit(EditorEvent::InputHandled {
17595                utf16_range_to_replace: range_to_replace,
17596                text: text.into(),
17597            });
17598
17599            if let Some(new_selected_ranges) = new_selected_ranges {
17600                this.change_selections(None, window, cx, |selections| {
17601                    selections.select_ranges(new_selected_ranges)
17602                });
17603                this.backspace(&Default::default(), window, cx);
17604            }
17605
17606            this.handle_input(text, window, cx);
17607        });
17608
17609        if let Some(transaction) = self.ime_transaction {
17610            self.buffer.update(cx, |buffer, cx| {
17611                buffer.group_until_transaction(transaction, cx);
17612            });
17613        }
17614
17615        self.unmark_text(window, cx);
17616    }
17617
17618    fn replace_and_mark_text_in_range(
17619        &mut self,
17620        range_utf16: Option<Range<usize>>,
17621        text: &str,
17622        new_selected_range_utf16: Option<Range<usize>>,
17623        window: &mut Window,
17624        cx: &mut Context<Self>,
17625    ) {
17626        if !self.input_enabled {
17627            return;
17628        }
17629
17630        let transaction = self.transact(window, cx, |this, window, cx| {
17631            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17632                let snapshot = this.buffer.read(cx).read(cx);
17633                if let Some(relative_range_utf16) = range_utf16.as_ref() {
17634                    for marked_range in &mut marked_ranges {
17635                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17636                        marked_range.start.0 += relative_range_utf16.start;
17637                        marked_range.start =
17638                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17639                        marked_range.end =
17640                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17641                    }
17642                }
17643                Some(marked_ranges)
17644            } else if let Some(range_utf16) = range_utf16 {
17645                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17646                Some(this.selection_replacement_ranges(range_utf16, cx))
17647            } else {
17648                None
17649            };
17650
17651            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17652                let newest_selection_id = this.selections.newest_anchor().id;
17653                this.selections
17654                    .all::<OffsetUtf16>(cx)
17655                    .iter()
17656                    .zip(ranges_to_replace.iter())
17657                    .find_map(|(selection, range)| {
17658                        if selection.id == newest_selection_id {
17659                            Some(
17660                                (range.start.0 as isize - selection.head().0 as isize)
17661                                    ..(range.end.0 as isize - selection.head().0 as isize),
17662                            )
17663                        } else {
17664                            None
17665                        }
17666                    })
17667            });
17668
17669            cx.emit(EditorEvent::InputHandled {
17670                utf16_range_to_replace: range_to_replace,
17671                text: text.into(),
17672            });
17673
17674            if let Some(ranges) = ranges_to_replace {
17675                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17676            }
17677
17678            let marked_ranges = {
17679                let snapshot = this.buffer.read(cx).read(cx);
17680                this.selections
17681                    .disjoint_anchors()
17682                    .iter()
17683                    .map(|selection| {
17684                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17685                    })
17686                    .collect::<Vec<_>>()
17687            };
17688
17689            if text.is_empty() {
17690                this.unmark_text(window, cx);
17691            } else {
17692                this.highlight_text::<InputComposition>(
17693                    marked_ranges.clone(),
17694                    HighlightStyle {
17695                        underline: Some(UnderlineStyle {
17696                            thickness: px(1.),
17697                            color: None,
17698                            wavy: false,
17699                        }),
17700                        ..Default::default()
17701                    },
17702                    cx,
17703                );
17704            }
17705
17706            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17707            let use_autoclose = this.use_autoclose;
17708            let use_auto_surround = this.use_auto_surround;
17709            this.set_use_autoclose(false);
17710            this.set_use_auto_surround(false);
17711            this.handle_input(text, window, cx);
17712            this.set_use_autoclose(use_autoclose);
17713            this.set_use_auto_surround(use_auto_surround);
17714
17715            if let Some(new_selected_range) = new_selected_range_utf16 {
17716                let snapshot = this.buffer.read(cx).read(cx);
17717                let new_selected_ranges = marked_ranges
17718                    .into_iter()
17719                    .map(|marked_range| {
17720                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17721                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17722                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17723                        snapshot.clip_offset_utf16(new_start, Bias::Left)
17724                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17725                    })
17726                    .collect::<Vec<_>>();
17727
17728                drop(snapshot);
17729                this.change_selections(None, window, cx, |selections| {
17730                    selections.select_ranges(new_selected_ranges)
17731                });
17732            }
17733        });
17734
17735        self.ime_transaction = self.ime_transaction.or(transaction);
17736        if let Some(transaction) = self.ime_transaction {
17737            self.buffer.update(cx, |buffer, cx| {
17738                buffer.group_until_transaction(transaction, cx);
17739            });
17740        }
17741
17742        if self.text_highlights::<InputComposition>(cx).is_none() {
17743            self.ime_transaction.take();
17744        }
17745    }
17746
17747    fn bounds_for_range(
17748        &mut self,
17749        range_utf16: Range<usize>,
17750        element_bounds: gpui::Bounds<Pixels>,
17751        window: &mut Window,
17752        cx: &mut Context<Self>,
17753    ) -> Option<gpui::Bounds<Pixels>> {
17754        let text_layout_details = self.text_layout_details(window);
17755        let gpui::Size {
17756            width: em_width,
17757            height: line_height,
17758        } = self.character_size(window);
17759
17760        let snapshot = self.snapshot(window, cx);
17761        let scroll_position = snapshot.scroll_position();
17762        let scroll_left = scroll_position.x * em_width;
17763
17764        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17765        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17766            + self.gutter_dimensions.width
17767            + self.gutter_dimensions.margin;
17768        let y = line_height * (start.row().as_f32() - scroll_position.y);
17769
17770        Some(Bounds {
17771            origin: element_bounds.origin + point(x, y),
17772            size: size(em_width, line_height),
17773        })
17774    }
17775
17776    fn character_index_for_point(
17777        &mut self,
17778        point: gpui::Point<Pixels>,
17779        _window: &mut Window,
17780        _cx: &mut Context<Self>,
17781    ) -> Option<usize> {
17782        let position_map = self.last_position_map.as_ref()?;
17783        if !position_map.text_hitbox.contains(&point) {
17784            return None;
17785        }
17786        let display_point = position_map.point_for_position(point).previous_valid;
17787        let anchor = position_map
17788            .snapshot
17789            .display_point_to_anchor(display_point, Bias::Left);
17790        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17791        Some(utf16_offset.0)
17792    }
17793}
17794
17795trait SelectionExt {
17796    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17797    fn spanned_rows(
17798        &self,
17799        include_end_if_at_line_start: bool,
17800        map: &DisplaySnapshot,
17801    ) -> Range<MultiBufferRow>;
17802}
17803
17804impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17805    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17806        let start = self
17807            .start
17808            .to_point(&map.buffer_snapshot)
17809            .to_display_point(map);
17810        let end = self
17811            .end
17812            .to_point(&map.buffer_snapshot)
17813            .to_display_point(map);
17814        if self.reversed {
17815            end..start
17816        } else {
17817            start..end
17818        }
17819    }
17820
17821    fn spanned_rows(
17822        &self,
17823        include_end_if_at_line_start: bool,
17824        map: &DisplaySnapshot,
17825    ) -> Range<MultiBufferRow> {
17826        let start = self.start.to_point(&map.buffer_snapshot);
17827        let mut end = self.end.to_point(&map.buffer_snapshot);
17828        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17829            end.row -= 1;
17830        }
17831
17832        let buffer_start = map.prev_line_boundary(start).0;
17833        let buffer_end = map.next_line_boundary(end).0;
17834        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17835    }
17836}
17837
17838impl<T: InvalidationRegion> InvalidationStack<T> {
17839    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17840    where
17841        S: Clone + ToOffset,
17842    {
17843        while let Some(region) = self.last() {
17844            let all_selections_inside_invalidation_ranges =
17845                if selections.len() == region.ranges().len() {
17846                    selections
17847                        .iter()
17848                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17849                        .all(|(selection, invalidation_range)| {
17850                            let head = selection.head().to_offset(buffer);
17851                            invalidation_range.start <= head && invalidation_range.end >= head
17852                        })
17853                } else {
17854                    false
17855                };
17856
17857            if all_selections_inside_invalidation_ranges {
17858                break;
17859            } else {
17860                self.pop();
17861            }
17862        }
17863    }
17864}
17865
17866impl<T> Default for InvalidationStack<T> {
17867    fn default() -> Self {
17868        Self(Default::default())
17869    }
17870}
17871
17872impl<T> Deref for InvalidationStack<T> {
17873    type Target = Vec<T>;
17874
17875    fn deref(&self) -> &Self::Target {
17876        &self.0
17877    }
17878}
17879
17880impl<T> DerefMut for InvalidationStack<T> {
17881    fn deref_mut(&mut self) -> &mut Self::Target {
17882        &mut self.0
17883    }
17884}
17885
17886impl InvalidationRegion for SnippetState {
17887    fn ranges(&self) -> &[Range<Anchor>] {
17888        &self.ranges[self.active_index]
17889    }
17890}
17891
17892pub fn diagnostic_block_renderer(
17893    diagnostic: Diagnostic,
17894    max_message_rows: Option<u8>,
17895    allow_closing: bool,
17896) -> RenderBlock {
17897    let (text_without_backticks, code_ranges) =
17898        highlight_diagnostic_message(&diagnostic, max_message_rows);
17899
17900    Arc::new(move |cx: &mut BlockContext| {
17901        let group_id: SharedString = cx.block_id.to_string().into();
17902
17903        let mut text_style = cx.window.text_style().clone();
17904        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17905        let theme_settings = ThemeSettings::get_global(cx);
17906        text_style.font_family = theme_settings.buffer_font.family.clone();
17907        text_style.font_style = theme_settings.buffer_font.style;
17908        text_style.font_features = theme_settings.buffer_font.features.clone();
17909        text_style.font_weight = theme_settings.buffer_font.weight;
17910
17911        let multi_line_diagnostic = diagnostic.message.contains('\n');
17912
17913        let buttons = |diagnostic: &Diagnostic| {
17914            if multi_line_diagnostic {
17915                v_flex()
17916            } else {
17917                h_flex()
17918            }
17919            .when(allow_closing, |div| {
17920                div.children(diagnostic.is_primary.then(|| {
17921                    IconButton::new("close-block", IconName::XCircle)
17922                        .icon_color(Color::Muted)
17923                        .size(ButtonSize::Compact)
17924                        .style(ButtonStyle::Transparent)
17925                        .visible_on_hover(group_id.clone())
17926                        .on_click(move |_click, window, cx| {
17927                            window.dispatch_action(Box::new(Cancel), cx)
17928                        })
17929                        .tooltip(|window, cx| {
17930                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
17931                        })
17932                }))
17933            })
17934            .child(
17935                IconButton::new("copy-block", IconName::Copy)
17936                    .icon_color(Color::Muted)
17937                    .size(ButtonSize::Compact)
17938                    .style(ButtonStyle::Transparent)
17939                    .visible_on_hover(group_id.clone())
17940                    .on_click({
17941                        let message = diagnostic.message.clone();
17942                        move |_click, _, cx| {
17943                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
17944                        }
17945                    })
17946                    .tooltip(Tooltip::text("Copy diagnostic message")),
17947            )
17948        };
17949
17950        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
17951            AvailableSpace::min_size(),
17952            cx.window,
17953            cx.app,
17954        );
17955
17956        h_flex()
17957            .id(cx.block_id)
17958            .group(group_id.clone())
17959            .relative()
17960            .size_full()
17961            .block_mouse_down()
17962            .pl(cx.gutter_dimensions.width)
17963            .w(cx.max_width - cx.gutter_dimensions.full_width())
17964            .child(
17965                div()
17966                    .flex()
17967                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
17968                    .flex_shrink(),
17969            )
17970            .child(buttons(&diagnostic))
17971            .child(div().flex().flex_shrink_0().child(
17972                StyledText::new(text_without_backticks.clone()).with_default_highlights(
17973                    &text_style,
17974                    code_ranges.iter().map(|range| {
17975                        (
17976                            range.clone(),
17977                            HighlightStyle {
17978                                font_weight: Some(FontWeight::BOLD),
17979                                ..Default::default()
17980                            },
17981                        )
17982                    }),
17983                ),
17984            ))
17985            .into_any_element()
17986    })
17987}
17988
17989fn inline_completion_edit_text(
17990    current_snapshot: &BufferSnapshot,
17991    edits: &[(Range<Anchor>, String)],
17992    edit_preview: &EditPreview,
17993    include_deletions: bool,
17994    cx: &App,
17995) -> HighlightedText {
17996    let edits = edits
17997        .iter()
17998        .map(|(anchor, text)| {
17999            (
18000                anchor.start.text_anchor..anchor.end.text_anchor,
18001                text.clone(),
18002            )
18003        })
18004        .collect::<Vec<_>>();
18005
18006    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18007}
18008
18009pub fn highlight_diagnostic_message(
18010    diagnostic: &Diagnostic,
18011    mut max_message_rows: Option<u8>,
18012) -> (SharedString, Vec<Range<usize>>) {
18013    let mut text_without_backticks = String::new();
18014    let mut code_ranges = Vec::new();
18015
18016    if let Some(source) = &diagnostic.source {
18017        text_without_backticks.push_str(source);
18018        code_ranges.push(0..source.len());
18019        text_without_backticks.push_str(": ");
18020    }
18021
18022    let mut prev_offset = 0;
18023    let mut in_code_block = false;
18024    let has_row_limit = max_message_rows.is_some();
18025    let mut newline_indices = diagnostic
18026        .message
18027        .match_indices('\n')
18028        .filter(|_| has_row_limit)
18029        .map(|(ix, _)| ix)
18030        .fuse()
18031        .peekable();
18032
18033    for (quote_ix, _) in diagnostic
18034        .message
18035        .match_indices('`')
18036        .chain([(diagnostic.message.len(), "")])
18037    {
18038        let mut first_newline_ix = None;
18039        let mut last_newline_ix = None;
18040        while let Some(newline_ix) = newline_indices.peek() {
18041            if *newline_ix < quote_ix {
18042                if first_newline_ix.is_none() {
18043                    first_newline_ix = Some(*newline_ix);
18044                }
18045                last_newline_ix = Some(*newline_ix);
18046
18047                if let Some(rows_left) = &mut max_message_rows {
18048                    if *rows_left == 0 {
18049                        break;
18050                    } else {
18051                        *rows_left -= 1;
18052                    }
18053                }
18054                let _ = newline_indices.next();
18055            } else {
18056                break;
18057            }
18058        }
18059        let prev_len = text_without_backticks.len();
18060        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18061        text_without_backticks.push_str(new_text);
18062        if in_code_block {
18063            code_ranges.push(prev_len..text_without_backticks.len());
18064        }
18065        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18066        in_code_block = !in_code_block;
18067        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18068            text_without_backticks.push_str("...");
18069            break;
18070        }
18071    }
18072
18073    (text_without_backticks.into(), code_ranges)
18074}
18075
18076fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18077    match severity {
18078        DiagnosticSeverity::ERROR => colors.error,
18079        DiagnosticSeverity::WARNING => colors.warning,
18080        DiagnosticSeverity::INFORMATION => colors.info,
18081        DiagnosticSeverity::HINT => colors.info,
18082        _ => colors.ignored,
18083    }
18084}
18085
18086pub fn styled_runs_for_code_label<'a>(
18087    label: &'a CodeLabel,
18088    syntax_theme: &'a theme::SyntaxTheme,
18089) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18090    let fade_out = HighlightStyle {
18091        fade_out: Some(0.35),
18092        ..Default::default()
18093    };
18094
18095    let mut prev_end = label.filter_range.end;
18096    label
18097        .runs
18098        .iter()
18099        .enumerate()
18100        .flat_map(move |(ix, (range, highlight_id))| {
18101            let style = if let Some(style) = highlight_id.style(syntax_theme) {
18102                style
18103            } else {
18104                return Default::default();
18105            };
18106            let mut muted_style = style;
18107            muted_style.highlight(fade_out);
18108
18109            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18110            if range.start >= label.filter_range.end {
18111                if range.start > prev_end {
18112                    runs.push((prev_end..range.start, fade_out));
18113                }
18114                runs.push((range.clone(), muted_style));
18115            } else if range.end <= label.filter_range.end {
18116                runs.push((range.clone(), style));
18117            } else {
18118                runs.push((range.start..label.filter_range.end, style));
18119                runs.push((label.filter_range.end..range.end, muted_style));
18120            }
18121            prev_end = cmp::max(prev_end, range.end);
18122
18123            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18124                runs.push((prev_end..label.text.len(), fade_out));
18125            }
18126
18127            runs
18128        })
18129}
18130
18131pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18132    let mut prev_index = 0;
18133    let mut prev_codepoint: Option<char> = None;
18134    text.char_indices()
18135        .chain([(text.len(), '\0')])
18136        .filter_map(move |(index, codepoint)| {
18137            let prev_codepoint = prev_codepoint.replace(codepoint)?;
18138            let is_boundary = index == text.len()
18139                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18140                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18141            if is_boundary {
18142                let chunk = &text[prev_index..index];
18143                prev_index = index;
18144                Some(chunk)
18145            } else {
18146                None
18147            }
18148        })
18149}
18150
18151pub trait RangeToAnchorExt: Sized {
18152    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18153
18154    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18155        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18156        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18157    }
18158}
18159
18160impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18161    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18162        let start_offset = self.start.to_offset(snapshot);
18163        let end_offset = self.end.to_offset(snapshot);
18164        if start_offset == end_offset {
18165            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18166        } else {
18167            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18168        }
18169    }
18170}
18171
18172pub trait RowExt {
18173    fn as_f32(&self) -> f32;
18174
18175    fn next_row(&self) -> Self;
18176
18177    fn previous_row(&self) -> Self;
18178
18179    fn minus(&self, other: Self) -> u32;
18180}
18181
18182impl RowExt for DisplayRow {
18183    fn as_f32(&self) -> f32 {
18184        self.0 as f32
18185    }
18186
18187    fn next_row(&self) -> Self {
18188        Self(self.0 + 1)
18189    }
18190
18191    fn previous_row(&self) -> Self {
18192        Self(self.0.saturating_sub(1))
18193    }
18194
18195    fn minus(&self, other: Self) -> u32 {
18196        self.0 - other.0
18197    }
18198}
18199
18200impl RowExt for MultiBufferRow {
18201    fn as_f32(&self) -> f32 {
18202        self.0 as f32
18203    }
18204
18205    fn next_row(&self) -> Self {
18206        Self(self.0 + 1)
18207    }
18208
18209    fn previous_row(&self) -> Self {
18210        Self(self.0.saturating_sub(1))
18211    }
18212
18213    fn minus(&self, other: Self) -> u32 {
18214        self.0 - other.0
18215    }
18216}
18217
18218trait RowRangeExt {
18219    type Row;
18220
18221    fn len(&self) -> usize;
18222
18223    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18224}
18225
18226impl RowRangeExt for Range<MultiBufferRow> {
18227    type Row = MultiBufferRow;
18228
18229    fn len(&self) -> usize {
18230        (self.end.0 - self.start.0) as usize
18231    }
18232
18233    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18234        (self.start.0..self.end.0).map(MultiBufferRow)
18235    }
18236}
18237
18238impl RowRangeExt for Range<DisplayRow> {
18239    type Row = DisplayRow;
18240
18241    fn len(&self) -> usize {
18242        (self.end.0 - self.start.0) as usize
18243    }
18244
18245    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18246        (self.start.0..self.end.0).map(DisplayRow)
18247    }
18248}
18249
18250/// If select range has more than one line, we
18251/// just point the cursor to range.start.
18252fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18253    if range.start.row == range.end.row {
18254        range
18255    } else {
18256        range.start..range.start
18257    }
18258}
18259pub struct KillRing(ClipboardItem);
18260impl Global for KillRing {}
18261
18262const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18263
18264fn all_edits_insertions_or_deletions(
18265    edits: &Vec<(Range<Anchor>, String)>,
18266    snapshot: &MultiBufferSnapshot,
18267) -> bool {
18268    let mut all_insertions = true;
18269    let mut all_deletions = true;
18270
18271    for (range, new_text) in edits.iter() {
18272        let range_is_empty = range.to_offset(&snapshot).is_empty();
18273        let text_is_empty = new_text.is_empty();
18274
18275        if range_is_empty != text_is_empty {
18276            if range_is_empty {
18277                all_deletions = false;
18278            } else {
18279                all_insertions = false;
18280            }
18281        } else {
18282            return false;
18283        }
18284
18285        if !all_insertions && !all_deletions {
18286            return false;
18287        }
18288    }
18289    all_insertions || all_deletions
18290}