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, Stateful, Styled, StyledText, Subscription,
   89    Task, 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                    if other_selections.is_empty() {
 2251                        return;
 2252                    }
 2253                    this.selections.change_with(cx, |selections| {
 2254                        selections.select_anchors(other_selections);
 2255                    });
 2256                }
 2257                _ => {}
 2258            });
 2259
 2260        let this_subscription =
 2261            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2262                EditorEvent::SelectionsChanged { local: true } => {
 2263                    let these_selections = this.selections.disjoint.to_vec();
 2264                    if these_selections.is_empty() {
 2265                        return;
 2266                    }
 2267                    other.update(cx, |other_editor, cx| {
 2268                        other_editor.selections.change_with(cx, |selections| {
 2269                            selections.select_anchors(these_selections);
 2270                        })
 2271                    });
 2272                }
 2273                _ => {}
 2274            });
 2275
 2276        Subscription::join(other_subscription, this_subscription)
 2277    }
 2278
 2279    pub fn change_selections<R>(
 2280        &mut self,
 2281        autoscroll: Option<Autoscroll>,
 2282        window: &mut Window,
 2283        cx: &mut Context<Self>,
 2284        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2285    ) -> R {
 2286        self.change_selections_inner(autoscroll, true, window, cx, change)
 2287    }
 2288
 2289    fn change_selections_inner<R>(
 2290        &mut self,
 2291        autoscroll: Option<Autoscroll>,
 2292        request_completions: bool,
 2293        window: &mut Window,
 2294        cx: &mut Context<Self>,
 2295        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2296    ) -> R {
 2297        let old_cursor_position = self.selections.newest_anchor().head();
 2298        self.push_to_selection_history();
 2299
 2300        let (changed, result) = self.selections.change_with(cx, change);
 2301
 2302        if changed {
 2303            if let Some(autoscroll) = autoscroll {
 2304                self.request_autoscroll(autoscroll, cx);
 2305            }
 2306            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2307
 2308            if self.should_open_signature_help_automatically(
 2309                &old_cursor_position,
 2310                self.signature_help_state.backspace_pressed(),
 2311                cx,
 2312            ) {
 2313                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2314            }
 2315            self.signature_help_state.set_backspace_pressed(false);
 2316        }
 2317
 2318        result
 2319    }
 2320
 2321    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2322    where
 2323        I: IntoIterator<Item = (Range<S>, T)>,
 2324        S: ToOffset,
 2325        T: Into<Arc<str>>,
 2326    {
 2327        if self.read_only(cx) {
 2328            return;
 2329        }
 2330
 2331        self.buffer
 2332            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2333    }
 2334
 2335    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2336    where
 2337        I: IntoIterator<Item = (Range<S>, T)>,
 2338        S: ToOffset,
 2339        T: Into<Arc<str>>,
 2340    {
 2341        if self.read_only(cx) {
 2342            return;
 2343        }
 2344
 2345        self.buffer.update(cx, |buffer, cx| {
 2346            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2347        });
 2348    }
 2349
 2350    pub fn edit_with_block_indent<I, S, T>(
 2351        &mut self,
 2352        edits: I,
 2353        original_start_columns: Vec<u32>,
 2354        cx: &mut Context<Self>,
 2355    ) where
 2356        I: IntoIterator<Item = (Range<S>, T)>,
 2357        S: ToOffset,
 2358        T: Into<Arc<str>>,
 2359    {
 2360        if self.read_only(cx) {
 2361            return;
 2362        }
 2363
 2364        self.buffer.update(cx, |buffer, cx| {
 2365            buffer.edit(
 2366                edits,
 2367                Some(AutoindentMode::Block {
 2368                    original_start_columns,
 2369                }),
 2370                cx,
 2371            )
 2372        });
 2373    }
 2374
 2375    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2376        self.hide_context_menu(window, cx);
 2377
 2378        match phase {
 2379            SelectPhase::Begin {
 2380                position,
 2381                add,
 2382                click_count,
 2383            } => self.begin_selection(position, add, click_count, window, cx),
 2384            SelectPhase::BeginColumnar {
 2385                position,
 2386                goal_column,
 2387                reset,
 2388            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2389            SelectPhase::Extend {
 2390                position,
 2391                click_count,
 2392            } => self.extend_selection(position, click_count, window, cx),
 2393            SelectPhase::Update {
 2394                position,
 2395                goal_column,
 2396                scroll_delta,
 2397            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2398            SelectPhase::End => self.end_selection(window, cx),
 2399        }
 2400    }
 2401
 2402    fn extend_selection(
 2403        &mut self,
 2404        position: DisplayPoint,
 2405        click_count: usize,
 2406        window: &mut Window,
 2407        cx: &mut Context<Self>,
 2408    ) {
 2409        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2410        let tail = self.selections.newest::<usize>(cx).tail();
 2411        self.begin_selection(position, false, click_count, window, cx);
 2412
 2413        let position = position.to_offset(&display_map, Bias::Left);
 2414        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2415
 2416        let mut pending_selection = self
 2417            .selections
 2418            .pending_anchor()
 2419            .expect("extend_selection not called with pending selection");
 2420        if position >= tail {
 2421            pending_selection.start = tail_anchor;
 2422        } else {
 2423            pending_selection.end = tail_anchor;
 2424            pending_selection.reversed = true;
 2425        }
 2426
 2427        let mut pending_mode = self.selections.pending_mode().unwrap();
 2428        match &mut pending_mode {
 2429            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2430            _ => {}
 2431        }
 2432
 2433        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2434            s.set_pending(pending_selection, pending_mode)
 2435        });
 2436    }
 2437
 2438    fn begin_selection(
 2439        &mut self,
 2440        position: DisplayPoint,
 2441        add: bool,
 2442        click_count: usize,
 2443        window: &mut Window,
 2444        cx: &mut Context<Self>,
 2445    ) {
 2446        if !self.focus_handle.is_focused(window) {
 2447            self.last_focused_descendant = None;
 2448            window.focus(&self.focus_handle);
 2449        }
 2450
 2451        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2452        let buffer = &display_map.buffer_snapshot;
 2453        let newest_selection = self.selections.newest_anchor().clone();
 2454        let position = display_map.clip_point(position, Bias::Left);
 2455
 2456        let start;
 2457        let end;
 2458        let mode;
 2459        let mut auto_scroll;
 2460        match click_count {
 2461            1 => {
 2462                start = buffer.anchor_before(position.to_point(&display_map));
 2463                end = start;
 2464                mode = SelectMode::Character;
 2465                auto_scroll = true;
 2466            }
 2467            2 => {
 2468                let range = movement::surrounding_word(&display_map, position);
 2469                start = buffer.anchor_before(range.start.to_point(&display_map));
 2470                end = buffer.anchor_before(range.end.to_point(&display_map));
 2471                mode = SelectMode::Word(start..end);
 2472                auto_scroll = true;
 2473            }
 2474            3 => {
 2475                let position = display_map
 2476                    .clip_point(position, Bias::Left)
 2477                    .to_point(&display_map);
 2478                let line_start = display_map.prev_line_boundary(position).0;
 2479                let next_line_start = buffer.clip_point(
 2480                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2481                    Bias::Left,
 2482                );
 2483                start = buffer.anchor_before(line_start);
 2484                end = buffer.anchor_before(next_line_start);
 2485                mode = SelectMode::Line(start..end);
 2486                auto_scroll = true;
 2487            }
 2488            _ => {
 2489                start = buffer.anchor_before(0);
 2490                end = buffer.anchor_before(buffer.len());
 2491                mode = SelectMode::All;
 2492                auto_scroll = false;
 2493            }
 2494        }
 2495        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2496
 2497        let point_to_delete: Option<usize> = {
 2498            let selected_points: Vec<Selection<Point>> =
 2499                self.selections.disjoint_in_range(start..end, cx);
 2500
 2501            if !add || click_count > 1 {
 2502                None
 2503            } else if !selected_points.is_empty() {
 2504                Some(selected_points[0].id)
 2505            } else {
 2506                let clicked_point_already_selected =
 2507                    self.selections.disjoint.iter().find(|selection| {
 2508                        selection.start.to_point(buffer) == start.to_point(buffer)
 2509                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2510                    });
 2511
 2512                clicked_point_already_selected.map(|selection| selection.id)
 2513            }
 2514        };
 2515
 2516        let selections_count = self.selections.count();
 2517
 2518        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2519            if let Some(point_to_delete) = point_to_delete {
 2520                s.delete(point_to_delete);
 2521
 2522                if selections_count == 1 {
 2523                    s.set_pending_anchor_range(start..end, mode);
 2524                }
 2525            } else {
 2526                if !add {
 2527                    s.clear_disjoint();
 2528                } else if click_count > 1 {
 2529                    s.delete(newest_selection.id)
 2530                }
 2531
 2532                s.set_pending_anchor_range(start..end, mode);
 2533            }
 2534        });
 2535    }
 2536
 2537    fn begin_columnar_selection(
 2538        &mut self,
 2539        position: DisplayPoint,
 2540        goal_column: u32,
 2541        reset: bool,
 2542        window: &mut Window,
 2543        cx: &mut Context<Self>,
 2544    ) {
 2545        if !self.focus_handle.is_focused(window) {
 2546            self.last_focused_descendant = None;
 2547            window.focus(&self.focus_handle);
 2548        }
 2549
 2550        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2551
 2552        if reset {
 2553            let pointer_position = display_map
 2554                .buffer_snapshot
 2555                .anchor_before(position.to_point(&display_map));
 2556
 2557            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2558                s.clear_disjoint();
 2559                s.set_pending_anchor_range(
 2560                    pointer_position..pointer_position,
 2561                    SelectMode::Character,
 2562                );
 2563            });
 2564        }
 2565
 2566        let tail = self.selections.newest::<Point>(cx).tail();
 2567        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2568
 2569        if !reset {
 2570            self.select_columns(
 2571                tail.to_display_point(&display_map),
 2572                position,
 2573                goal_column,
 2574                &display_map,
 2575                window,
 2576                cx,
 2577            );
 2578        }
 2579    }
 2580
 2581    fn update_selection(
 2582        &mut self,
 2583        position: DisplayPoint,
 2584        goal_column: u32,
 2585        scroll_delta: gpui::Point<f32>,
 2586        window: &mut Window,
 2587        cx: &mut Context<Self>,
 2588    ) {
 2589        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2590
 2591        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2592            let tail = tail.to_display_point(&display_map);
 2593            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2594        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2595            let buffer = self.buffer.read(cx).snapshot(cx);
 2596            let head;
 2597            let tail;
 2598            let mode = self.selections.pending_mode().unwrap();
 2599            match &mode {
 2600                SelectMode::Character => {
 2601                    head = position.to_point(&display_map);
 2602                    tail = pending.tail().to_point(&buffer);
 2603                }
 2604                SelectMode::Word(original_range) => {
 2605                    let original_display_range = original_range.start.to_display_point(&display_map)
 2606                        ..original_range.end.to_display_point(&display_map);
 2607                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2608                        ..original_display_range.end.to_point(&display_map);
 2609                    if movement::is_inside_word(&display_map, position)
 2610                        || original_display_range.contains(&position)
 2611                    {
 2612                        let word_range = movement::surrounding_word(&display_map, position);
 2613                        if word_range.start < original_display_range.start {
 2614                            head = word_range.start.to_point(&display_map);
 2615                        } else {
 2616                            head = word_range.end.to_point(&display_map);
 2617                        }
 2618                    } else {
 2619                        head = position.to_point(&display_map);
 2620                    }
 2621
 2622                    if head <= original_buffer_range.start {
 2623                        tail = original_buffer_range.end;
 2624                    } else {
 2625                        tail = original_buffer_range.start;
 2626                    }
 2627                }
 2628                SelectMode::Line(original_range) => {
 2629                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2630
 2631                    let position = display_map
 2632                        .clip_point(position, Bias::Left)
 2633                        .to_point(&display_map);
 2634                    let line_start = display_map.prev_line_boundary(position).0;
 2635                    let next_line_start = buffer.clip_point(
 2636                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2637                        Bias::Left,
 2638                    );
 2639
 2640                    if line_start < original_range.start {
 2641                        head = line_start
 2642                    } else {
 2643                        head = next_line_start
 2644                    }
 2645
 2646                    if head <= original_range.start {
 2647                        tail = original_range.end;
 2648                    } else {
 2649                        tail = original_range.start;
 2650                    }
 2651                }
 2652                SelectMode::All => {
 2653                    return;
 2654                }
 2655            };
 2656
 2657            if head < tail {
 2658                pending.start = buffer.anchor_before(head);
 2659                pending.end = buffer.anchor_before(tail);
 2660                pending.reversed = true;
 2661            } else {
 2662                pending.start = buffer.anchor_before(tail);
 2663                pending.end = buffer.anchor_before(head);
 2664                pending.reversed = false;
 2665            }
 2666
 2667            self.change_selections(None, window, cx, |s| {
 2668                s.set_pending(pending, mode);
 2669            });
 2670        } else {
 2671            log::error!("update_selection dispatched with no pending selection");
 2672            return;
 2673        }
 2674
 2675        self.apply_scroll_delta(scroll_delta, window, cx);
 2676        cx.notify();
 2677    }
 2678
 2679    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2680        self.columnar_selection_tail.take();
 2681        if self.selections.pending_anchor().is_some() {
 2682            let selections = self.selections.all::<usize>(cx);
 2683            self.change_selections(None, window, cx, |s| {
 2684                s.select(selections);
 2685                s.clear_pending();
 2686            });
 2687        }
 2688    }
 2689
 2690    fn select_columns(
 2691        &mut self,
 2692        tail: DisplayPoint,
 2693        head: DisplayPoint,
 2694        goal_column: u32,
 2695        display_map: &DisplaySnapshot,
 2696        window: &mut Window,
 2697        cx: &mut Context<Self>,
 2698    ) {
 2699        let start_row = cmp::min(tail.row(), head.row());
 2700        let end_row = cmp::max(tail.row(), head.row());
 2701        let start_column = cmp::min(tail.column(), goal_column);
 2702        let end_column = cmp::max(tail.column(), goal_column);
 2703        let reversed = start_column < tail.column();
 2704
 2705        let selection_ranges = (start_row.0..=end_row.0)
 2706            .map(DisplayRow)
 2707            .filter_map(|row| {
 2708                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2709                    let start = display_map
 2710                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2711                        .to_point(display_map);
 2712                    let end = display_map
 2713                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2714                        .to_point(display_map);
 2715                    if reversed {
 2716                        Some(end..start)
 2717                    } else {
 2718                        Some(start..end)
 2719                    }
 2720                } else {
 2721                    None
 2722                }
 2723            })
 2724            .collect::<Vec<_>>();
 2725
 2726        self.change_selections(None, window, cx, |s| {
 2727            s.select_ranges(selection_ranges);
 2728        });
 2729        cx.notify();
 2730    }
 2731
 2732    pub fn has_pending_nonempty_selection(&self) -> bool {
 2733        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2734            Some(Selection { start, end, .. }) => start != end,
 2735            None => false,
 2736        };
 2737
 2738        pending_nonempty_selection
 2739            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2740    }
 2741
 2742    pub fn has_pending_selection(&self) -> bool {
 2743        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2744    }
 2745
 2746    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2747        self.selection_mark_mode = false;
 2748
 2749        if self.clear_expanded_diff_hunks(cx) {
 2750            cx.notify();
 2751            return;
 2752        }
 2753        if self.dismiss_menus_and_popups(true, window, cx) {
 2754            return;
 2755        }
 2756
 2757        if self.mode == EditorMode::Full
 2758            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2759        {
 2760            return;
 2761        }
 2762
 2763        cx.propagate();
 2764    }
 2765
 2766    pub fn dismiss_menus_and_popups(
 2767        &mut self,
 2768        is_user_requested: bool,
 2769        window: &mut Window,
 2770        cx: &mut Context<Self>,
 2771    ) -> bool {
 2772        if self.take_rename(false, window, cx).is_some() {
 2773            return true;
 2774        }
 2775
 2776        if hide_hover(self, cx) {
 2777            return true;
 2778        }
 2779
 2780        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2781            return true;
 2782        }
 2783
 2784        if self.hide_context_menu(window, cx).is_some() {
 2785            return true;
 2786        }
 2787
 2788        if self.mouse_context_menu.take().is_some() {
 2789            return true;
 2790        }
 2791
 2792        if is_user_requested && self.discard_inline_completion(true, cx) {
 2793            return true;
 2794        }
 2795
 2796        if self.snippet_stack.pop().is_some() {
 2797            return true;
 2798        }
 2799
 2800        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2801            self.dismiss_diagnostics(cx);
 2802            return true;
 2803        }
 2804
 2805        false
 2806    }
 2807
 2808    fn linked_editing_ranges_for(
 2809        &self,
 2810        selection: Range<text::Anchor>,
 2811        cx: &App,
 2812    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2813        if self.linked_edit_ranges.is_empty() {
 2814            return None;
 2815        }
 2816        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2817            selection.end.buffer_id.and_then(|end_buffer_id| {
 2818                if selection.start.buffer_id != Some(end_buffer_id) {
 2819                    return None;
 2820                }
 2821                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2822                let snapshot = buffer.read(cx).snapshot();
 2823                self.linked_edit_ranges
 2824                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2825                    .map(|ranges| (ranges, snapshot, buffer))
 2826            })?;
 2827        use text::ToOffset as TO;
 2828        // find offset from the start of current range to current cursor position
 2829        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2830
 2831        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2832        let start_difference = start_offset - start_byte_offset;
 2833        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2834        let end_difference = end_offset - start_byte_offset;
 2835        // Current range has associated linked ranges.
 2836        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2837        for range in linked_ranges.iter() {
 2838            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2839            let end_offset = start_offset + end_difference;
 2840            let start_offset = start_offset + start_difference;
 2841            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2842                continue;
 2843            }
 2844            if self.selections.disjoint_anchor_ranges().any(|s| {
 2845                if s.start.buffer_id != selection.start.buffer_id
 2846                    || s.end.buffer_id != selection.end.buffer_id
 2847                {
 2848                    return false;
 2849                }
 2850                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2851                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2852            }) {
 2853                continue;
 2854            }
 2855            let start = buffer_snapshot.anchor_after(start_offset);
 2856            let end = buffer_snapshot.anchor_after(end_offset);
 2857            linked_edits
 2858                .entry(buffer.clone())
 2859                .or_default()
 2860                .push(start..end);
 2861        }
 2862        Some(linked_edits)
 2863    }
 2864
 2865    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2866        let text: Arc<str> = text.into();
 2867
 2868        if self.read_only(cx) {
 2869            return;
 2870        }
 2871
 2872        let selections = self.selections.all_adjusted(cx);
 2873        let mut bracket_inserted = false;
 2874        let mut edits = Vec::new();
 2875        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2876        let mut new_selections = Vec::with_capacity(selections.len());
 2877        let mut new_autoclose_regions = Vec::new();
 2878        let snapshot = self.buffer.read(cx).read(cx);
 2879
 2880        for (selection, autoclose_region) in
 2881            self.selections_with_autoclose_regions(selections, &snapshot)
 2882        {
 2883            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2884                // Determine if the inserted text matches the opening or closing
 2885                // bracket of any of this language's bracket pairs.
 2886                let mut bracket_pair = None;
 2887                let mut is_bracket_pair_start = false;
 2888                let mut is_bracket_pair_end = false;
 2889                if !text.is_empty() {
 2890                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2891                    //  and they are removing the character that triggered IME popup.
 2892                    for (pair, enabled) in scope.brackets() {
 2893                        if !pair.close && !pair.surround {
 2894                            continue;
 2895                        }
 2896
 2897                        if enabled && pair.start.ends_with(text.as_ref()) {
 2898                            let prefix_len = pair.start.len() - text.len();
 2899                            let preceding_text_matches_prefix = prefix_len == 0
 2900                                || (selection.start.column >= (prefix_len as u32)
 2901                                    && snapshot.contains_str_at(
 2902                                        Point::new(
 2903                                            selection.start.row,
 2904                                            selection.start.column - (prefix_len as u32),
 2905                                        ),
 2906                                        &pair.start[..prefix_len],
 2907                                    ));
 2908                            if preceding_text_matches_prefix {
 2909                                bracket_pair = Some(pair.clone());
 2910                                is_bracket_pair_start = true;
 2911                                break;
 2912                            }
 2913                        }
 2914                        if pair.end.as_str() == text.as_ref() {
 2915                            bracket_pair = Some(pair.clone());
 2916                            is_bracket_pair_end = true;
 2917                            break;
 2918                        }
 2919                    }
 2920                }
 2921
 2922                if let Some(bracket_pair) = bracket_pair {
 2923                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 2924                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2925                    let auto_surround =
 2926                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2927                    if selection.is_empty() {
 2928                        if is_bracket_pair_start {
 2929                            // If the inserted text is a suffix of an opening bracket and the
 2930                            // selection is preceded by the rest of the opening bracket, then
 2931                            // insert the closing bracket.
 2932                            let following_text_allows_autoclose = snapshot
 2933                                .chars_at(selection.start)
 2934                                .next()
 2935                                .map_or(true, |c| scope.should_autoclose_before(c));
 2936
 2937                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2938                                && bracket_pair.start.len() == 1
 2939                            {
 2940                                let target = bracket_pair.start.chars().next().unwrap();
 2941                                let current_line_count = snapshot
 2942                                    .reversed_chars_at(selection.start)
 2943                                    .take_while(|&c| c != '\n')
 2944                                    .filter(|&c| c == target)
 2945                                    .count();
 2946                                current_line_count % 2 == 1
 2947                            } else {
 2948                                false
 2949                            };
 2950
 2951                            if autoclose
 2952                                && bracket_pair.close
 2953                                && following_text_allows_autoclose
 2954                                && !is_closing_quote
 2955                            {
 2956                                let anchor = snapshot.anchor_before(selection.end);
 2957                                new_selections.push((selection.map(|_| anchor), text.len()));
 2958                                new_autoclose_regions.push((
 2959                                    anchor,
 2960                                    text.len(),
 2961                                    selection.id,
 2962                                    bracket_pair.clone(),
 2963                                ));
 2964                                edits.push((
 2965                                    selection.range(),
 2966                                    format!("{}{}", text, bracket_pair.end).into(),
 2967                                ));
 2968                                bracket_inserted = true;
 2969                                continue;
 2970                            }
 2971                        }
 2972
 2973                        if let Some(region) = autoclose_region {
 2974                            // If the selection is followed by an auto-inserted closing bracket,
 2975                            // then don't insert that closing bracket again; just move the selection
 2976                            // past the closing bracket.
 2977                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2978                                && text.as_ref() == region.pair.end.as_str();
 2979                            if should_skip {
 2980                                let anchor = snapshot.anchor_after(selection.end);
 2981                                new_selections
 2982                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2983                                continue;
 2984                            }
 2985                        }
 2986
 2987                        let always_treat_brackets_as_autoclosed = snapshot
 2988                            .language_settings_at(selection.start, cx)
 2989                            .always_treat_brackets_as_autoclosed;
 2990                        if always_treat_brackets_as_autoclosed
 2991                            && is_bracket_pair_end
 2992                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2993                        {
 2994                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2995                            // and the inserted text is a closing bracket and the selection is followed
 2996                            // by the closing bracket then move the selection past the closing bracket.
 2997                            let anchor = snapshot.anchor_after(selection.end);
 2998                            new_selections.push((selection.map(|_| anchor), text.len()));
 2999                            continue;
 3000                        }
 3001                    }
 3002                    // If an opening bracket is 1 character long and is typed while
 3003                    // text is selected, then surround that text with the bracket pair.
 3004                    else if auto_surround
 3005                        && bracket_pair.surround
 3006                        && is_bracket_pair_start
 3007                        && bracket_pair.start.chars().count() == 1
 3008                    {
 3009                        edits.push((selection.start..selection.start, text.clone()));
 3010                        edits.push((
 3011                            selection.end..selection.end,
 3012                            bracket_pair.end.as_str().into(),
 3013                        ));
 3014                        bracket_inserted = true;
 3015                        new_selections.push((
 3016                            Selection {
 3017                                id: selection.id,
 3018                                start: snapshot.anchor_after(selection.start),
 3019                                end: snapshot.anchor_before(selection.end),
 3020                                reversed: selection.reversed,
 3021                                goal: selection.goal,
 3022                            },
 3023                            0,
 3024                        ));
 3025                        continue;
 3026                    }
 3027                }
 3028            }
 3029
 3030            if self.auto_replace_emoji_shortcode
 3031                && selection.is_empty()
 3032                && text.as_ref().ends_with(':')
 3033            {
 3034                if let Some(possible_emoji_short_code) =
 3035                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3036                {
 3037                    if !possible_emoji_short_code.is_empty() {
 3038                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3039                            let emoji_shortcode_start = Point::new(
 3040                                selection.start.row,
 3041                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3042                            );
 3043
 3044                            // Remove shortcode from buffer
 3045                            edits.push((
 3046                                emoji_shortcode_start..selection.start,
 3047                                "".to_string().into(),
 3048                            ));
 3049                            new_selections.push((
 3050                                Selection {
 3051                                    id: selection.id,
 3052                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3053                                    end: snapshot.anchor_before(selection.start),
 3054                                    reversed: selection.reversed,
 3055                                    goal: selection.goal,
 3056                                },
 3057                                0,
 3058                            ));
 3059
 3060                            // Insert emoji
 3061                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3062                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3063                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3064
 3065                            continue;
 3066                        }
 3067                    }
 3068                }
 3069            }
 3070
 3071            // If not handling any auto-close operation, then just replace the selected
 3072            // text with the given input and move the selection to the end of the
 3073            // newly inserted text.
 3074            let anchor = snapshot.anchor_after(selection.end);
 3075            if !self.linked_edit_ranges.is_empty() {
 3076                let start_anchor = snapshot.anchor_before(selection.start);
 3077
 3078                let is_word_char = text.chars().next().map_or(true, |char| {
 3079                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3080                    classifier.is_word(char)
 3081                });
 3082
 3083                if is_word_char {
 3084                    if let Some(ranges) = self
 3085                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3086                    {
 3087                        for (buffer, edits) in ranges {
 3088                            linked_edits
 3089                                .entry(buffer.clone())
 3090                                .or_default()
 3091                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3092                        }
 3093                    }
 3094                }
 3095            }
 3096
 3097            new_selections.push((selection.map(|_| anchor), 0));
 3098            edits.push((selection.start..selection.end, text.clone()));
 3099        }
 3100
 3101        drop(snapshot);
 3102
 3103        self.transact(window, cx, |this, window, cx| {
 3104            this.buffer.update(cx, |buffer, cx| {
 3105                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3106            });
 3107            for (buffer, edits) in linked_edits {
 3108                buffer.update(cx, |buffer, cx| {
 3109                    let snapshot = buffer.snapshot();
 3110                    let edits = edits
 3111                        .into_iter()
 3112                        .map(|(range, text)| {
 3113                            use text::ToPoint as TP;
 3114                            let end_point = TP::to_point(&range.end, &snapshot);
 3115                            let start_point = TP::to_point(&range.start, &snapshot);
 3116                            (start_point..end_point, text)
 3117                        })
 3118                        .sorted_by_key(|(range, _)| range.start)
 3119                        .collect::<Vec<_>>();
 3120                    buffer.edit(edits, None, cx);
 3121                })
 3122            }
 3123            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3124            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3125            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3126            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3127                .zip(new_selection_deltas)
 3128                .map(|(selection, delta)| Selection {
 3129                    id: selection.id,
 3130                    start: selection.start + delta,
 3131                    end: selection.end + delta,
 3132                    reversed: selection.reversed,
 3133                    goal: SelectionGoal::None,
 3134                })
 3135                .collect::<Vec<_>>();
 3136
 3137            let mut i = 0;
 3138            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3139                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3140                let start = map.buffer_snapshot.anchor_before(position);
 3141                let end = map.buffer_snapshot.anchor_after(position);
 3142                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3143                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3144                        Ordering::Less => i += 1,
 3145                        Ordering::Greater => break,
 3146                        Ordering::Equal => {
 3147                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3148                                Ordering::Less => i += 1,
 3149                                Ordering::Equal => break,
 3150                                Ordering::Greater => break,
 3151                            }
 3152                        }
 3153                    }
 3154                }
 3155                this.autoclose_regions.insert(
 3156                    i,
 3157                    AutocloseRegion {
 3158                        selection_id,
 3159                        range: start..end,
 3160                        pair,
 3161                    },
 3162                );
 3163            }
 3164
 3165            let had_active_inline_completion = this.has_active_inline_completion();
 3166            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3167                s.select(new_selections)
 3168            });
 3169
 3170            if !bracket_inserted {
 3171                if let Some(on_type_format_task) =
 3172                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3173                {
 3174                    on_type_format_task.detach_and_log_err(cx);
 3175                }
 3176            }
 3177
 3178            let editor_settings = EditorSettings::get_global(cx);
 3179            if bracket_inserted
 3180                && (editor_settings.auto_signature_help
 3181                    || editor_settings.show_signature_help_after_edits)
 3182            {
 3183                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3184            }
 3185
 3186            let trigger_in_words =
 3187                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3188            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3189            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3190            this.refresh_inline_completion(true, false, window, cx);
 3191        });
 3192    }
 3193
 3194    fn find_possible_emoji_shortcode_at_position(
 3195        snapshot: &MultiBufferSnapshot,
 3196        position: Point,
 3197    ) -> Option<String> {
 3198        let mut chars = Vec::new();
 3199        let mut found_colon = false;
 3200        for char in snapshot.reversed_chars_at(position).take(100) {
 3201            // Found a possible emoji shortcode in the middle of the buffer
 3202            if found_colon {
 3203                if char.is_whitespace() {
 3204                    chars.reverse();
 3205                    return Some(chars.iter().collect());
 3206                }
 3207                // If the previous character is not a whitespace, we are in the middle of a word
 3208                // and we only want to complete the shortcode if the word is made up of other emojis
 3209                let mut containing_word = String::new();
 3210                for ch in snapshot
 3211                    .reversed_chars_at(position)
 3212                    .skip(chars.len() + 1)
 3213                    .take(100)
 3214                {
 3215                    if ch.is_whitespace() {
 3216                        break;
 3217                    }
 3218                    containing_word.push(ch);
 3219                }
 3220                let containing_word = containing_word.chars().rev().collect::<String>();
 3221                if util::word_consists_of_emojis(containing_word.as_str()) {
 3222                    chars.reverse();
 3223                    return Some(chars.iter().collect());
 3224                }
 3225            }
 3226
 3227            if char.is_whitespace() || !char.is_ascii() {
 3228                return None;
 3229            }
 3230            if char == ':' {
 3231                found_colon = true;
 3232            } else {
 3233                chars.push(char);
 3234            }
 3235        }
 3236        // Found a possible emoji shortcode at the beginning of the buffer
 3237        chars.reverse();
 3238        Some(chars.iter().collect())
 3239    }
 3240
 3241    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3242        self.transact(window, cx, |this, window, cx| {
 3243            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3244                let selections = this.selections.all::<usize>(cx);
 3245                let multi_buffer = this.buffer.read(cx);
 3246                let buffer = multi_buffer.snapshot(cx);
 3247                selections
 3248                    .iter()
 3249                    .map(|selection| {
 3250                        let start_point = selection.start.to_point(&buffer);
 3251                        let mut indent =
 3252                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3253                        indent.len = cmp::min(indent.len, start_point.column);
 3254                        let start = selection.start;
 3255                        let end = selection.end;
 3256                        let selection_is_empty = start == end;
 3257                        let language_scope = buffer.language_scope_at(start);
 3258                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3259                            &language_scope
 3260                        {
 3261                            let insert_extra_newline =
 3262                                insert_extra_newline_brackets(&buffer, start..end, language)
 3263                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3264
 3265                            // Comment extension on newline is allowed only for cursor selections
 3266                            let comment_delimiter = maybe!({
 3267                                if !selection_is_empty {
 3268                                    return None;
 3269                                }
 3270
 3271                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3272                                    return None;
 3273                                }
 3274
 3275                                let delimiters = language.line_comment_prefixes();
 3276                                let max_len_of_delimiter =
 3277                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3278                                let (snapshot, range) =
 3279                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3280
 3281                                let mut index_of_first_non_whitespace = 0;
 3282                                let comment_candidate = snapshot
 3283                                    .chars_for_range(range)
 3284                                    .skip_while(|c| {
 3285                                        let should_skip = c.is_whitespace();
 3286                                        if should_skip {
 3287                                            index_of_first_non_whitespace += 1;
 3288                                        }
 3289                                        should_skip
 3290                                    })
 3291                                    .take(max_len_of_delimiter)
 3292                                    .collect::<String>();
 3293                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3294                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3295                                })?;
 3296                                let cursor_is_placed_after_comment_marker =
 3297                                    index_of_first_non_whitespace + comment_prefix.len()
 3298                                        <= start_point.column as usize;
 3299                                if cursor_is_placed_after_comment_marker {
 3300                                    Some(comment_prefix.clone())
 3301                                } else {
 3302                                    None
 3303                                }
 3304                            });
 3305                            (comment_delimiter, insert_extra_newline)
 3306                        } else {
 3307                            (None, false)
 3308                        };
 3309
 3310                        let capacity_for_delimiter = comment_delimiter
 3311                            .as_deref()
 3312                            .map(str::len)
 3313                            .unwrap_or_default();
 3314                        let mut new_text =
 3315                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3316                        new_text.push('\n');
 3317                        new_text.extend(indent.chars());
 3318                        if let Some(delimiter) = &comment_delimiter {
 3319                            new_text.push_str(delimiter);
 3320                        }
 3321                        if insert_extra_newline {
 3322                            new_text = new_text.repeat(2);
 3323                        }
 3324
 3325                        let anchor = buffer.anchor_after(end);
 3326                        let new_selection = selection.map(|_| anchor);
 3327                        (
 3328                            (start..end, new_text),
 3329                            (insert_extra_newline, new_selection),
 3330                        )
 3331                    })
 3332                    .unzip()
 3333            };
 3334
 3335            this.edit_with_autoindent(edits, cx);
 3336            let buffer = this.buffer.read(cx).snapshot(cx);
 3337            let new_selections = selection_fixup_info
 3338                .into_iter()
 3339                .map(|(extra_newline_inserted, new_selection)| {
 3340                    let mut cursor = new_selection.end.to_point(&buffer);
 3341                    if extra_newline_inserted {
 3342                        cursor.row -= 1;
 3343                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3344                    }
 3345                    new_selection.map(|_| cursor)
 3346                })
 3347                .collect();
 3348
 3349            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3350                s.select(new_selections)
 3351            });
 3352            this.refresh_inline_completion(true, false, window, cx);
 3353        });
 3354    }
 3355
 3356    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3357        let buffer = self.buffer.read(cx);
 3358        let snapshot = buffer.snapshot(cx);
 3359
 3360        let mut edits = Vec::new();
 3361        let mut rows = Vec::new();
 3362
 3363        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3364            let cursor = selection.head();
 3365            let row = cursor.row;
 3366
 3367            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3368
 3369            let newline = "\n".to_string();
 3370            edits.push((start_of_line..start_of_line, newline));
 3371
 3372            rows.push(row + rows_inserted as u32);
 3373        }
 3374
 3375        self.transact(window, cx, |editor, window, cx| {
 3376            editor.edit(edits, cx);
 3377
 3378            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3379                let mut index = 0;
 3380                s.move_cursors_with(|map, _, _| {
 3381                    let row = rows[index];
 3382                    index += 1;
 3383
 3384                    let point = Point::new(row, 0);
 3385                    let boundary = map.next_line_boundary(point).1;
 3386                    let clipped = map.clip_point(boundary, Bias::Left);
 3387
 3388                    (clipped, SelectionGoal::None)
 3389                });
 3390            });
 3391
 3392            let mut indent_edits = Vec::new();
 3393            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3394            for row in rows {
 3395                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3396                for (row, indent) in indents {
 3397                    if indent.len == 0 {
 3398                        continue;
 3399                    }
 3400
 3401                    let text = match indent.kind {
 3402                        IndentKind::Space => " ".repeat(indent.len as usize),
 3403                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3404                    };
 3405                    let point = Point::new(row.0, 0);
 3406                    indent_edits.push((point..point, text));
 3407                }
 3408            }
 3409            editor.edit(indent_edits, cx);
 3410        });
 3411    }
 3412
 3413    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3414        let buffer = self.buffer.read(cx);
 3415        let snapshot = buffer.snapshot(cx);
 3416
 3417        let mut edits = Vec::new();
 3418        let mut rows = Vec::new();
 3419        let mut rows_inserted = 0;
 3420
 3421        for selection in self.selections.all_adjusted(cx) {
 3422            let cursor = selection.head();
 3423            let row = cursor.row;
 3424
 3425            let point = Point::new(row + 1, 0);
 3426            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3427
 3428            let newline = "\n".to_string();
 3429            edits.push((start_of_line..start_of_line, newline));
 3430
 3431            rows_inserted += 1;
 3432            rows.push(row + rows_inserted);
 3433        }
 3434
 3435        self.transact(window, cx, |editor, window, cx| {
 3436            editor.edit(edits, cx);
 3437
 3438            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3439                let mut index = 0;
 3440                s.move_cursors_with(|map, _, _| {
 3441                    let row = rows[index];
 3442                    index += 1;
 3443
 3444                    let point = Point::new(row, 0);
 3445                    let boundary = map.next_line_boundary(point).1;
 3446                    let clipped = map.clip_point(boundary, Bias::Left);
 3447
 3448                    (clipped, SelectionGoal::None)
 3449                });
 3450            });
 3451
 3452            let mut indent_edits = Vec::new();
 3453            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3454            for row in rows {
 3455                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3456                for (row, indent) in indents {
 3457                    if indent.len == 0 {
 3458                        continue;
 3459                    }
 3460
 3461                    let text = match indent.kind {
 3462                        IndentKind::Space => " ".repeat(indent.len as usize),
 3463                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3464                    };
 3465                    let point = Point::new(row.0, 0);
 3466                    indent_edits.push((point..point, text));
 3467                }
 3468            }
 3469            editor.edit(indent_edits, cx);
 3470        });
 3471    }
 3472
 3473    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3474        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3475            original_start_columns: Vec::new(),
 3476        });
 3477        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3478    }
 3479
 3480    fn insert_with_autoindent_mode(
 3481        &mut self,
 3482        text: &str,
 3483        autoindent_mode: Option<AutoindentMode>,
 3484        window: &mut Window,
 3485        cx: &mut Context<Self>,
 3486    ) {
 3487        if self.read_only(cx) {
 3488            return;
 3489        }
 3490
 3491        let text: Arc<str> = text.into();
 3492        self.transact(window, cx, |this, window, cx| {
 3493            let old_selections = this.selections.all_adjusted(cx);
 3494            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3495                let anchors = {
 3496                    let snapshot = buffer.read(cx);
 3497                    old_selections
 3498                        .iter()
 3499                        .map(|s| {
 3500                            let anchor = snapshot.anchor_after(s.head());
 3501                            s.map(|_| anchor)
 3502                        })
 3503                        .collect::<Vec<_>>()
 3504                };
 3505                buffer.edit(
 3506                    old_selections
 3507                        .iter()
 3508                        .map(|s| (s.start..s.end, text.clone())),
 3509                    autoindent_mode,
 3510                    cx,
 3511                );
 3512                anchors
 3513            });
 3514
 3515            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3516                s.select_anchors(selection_anchors);
 3517            });
 3518
 3519            cx.notify();
 3520        });
 3521    }
 3522
 3523    fn trigger_completion_on_input(
 3524        &mut self,
 3525        text: &str,
 3526        trigger_in_words: bool,
 3527        window: &mut Window,
 3528        cx: &mut Context<Self>,
 3529    ) {
 3530        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3531            self.show_completions(
 3532                &ShowCompletions {
 3533                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3534                },
 3535                window,
 3536                cx,
 3537            );
 3538        } else {
 3539            self.hide_context_menu(window, cx);
 3540        }
 3541    }
 3542
 3543    fn is_completion_trigger(
 3544        &self,
 3545        text: &str,
 3546        trigger_in_words: bool,
 3547        cx: &mut Context<Self>,
 3548    ) -> bool {
 3549        let position = self.selections.newest_anchor().head();
 3550        let multibuffer = self.buffer.read(cx);
 3551        let Some(buffer) = position
 3552            .buffer_id
 3553            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3554        else {
 3555            return false;
 3556        };
 3557
 3558        if let Some(completion_provider) = &self.completion_provider {
 3559            completion_provider.is_completion_trigger(
 3560                &buffer,
 3561                position.text_anchor,
 3562                text,
 3563                trigger_in_words,
 3564                cx,
 3565            )
 3566        } else {
 3567            false
 3568        }
 3569    }
 3570
 3571    /// If any empty selections is touching the start of its innermost containing autoclose
 3572    /// region, expand it to select the brackets.
 3573    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3574        let selections = self.selections.all::<usize>(cx);
 3575        let buffer = self.buffer.read(cx).read(cx);
 3576        let new_selections = self
 3577            .selections_with_autoclose_regions(selections, &buffer)
 3578            .map(|(mut selection, region)| {
 3579                if !selection.is_empty() {
 3580                    return selection;
 3581                }
 3582
 3583                if let Some(region) = region {
 3584                    let mut range = region.range.to_offset(&buffer);
 3585                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3586                        range.start -= region.pair.start.len();
 3587                        if buffer.contains_str_at(range.start, &region.pair.start)
 3588                            && buffer.contains_str_at(range.end, &region.pair.end)
 3589                        {
 3590                            range.end += region.pair.end.len();
 3591                            selection.start = range.start;
 3592                            selection.end = range.end;
 3593
 3594                            return selection;
 3595                        }
 3596                    }
 3597                }
 3598
 3599                let always_treat_brackets_as_autoclosed = buffer
 3600                    .language_settings_at(selection.start, cx)
 3601                    .always_treat_brackets_as_autoclosed;
 3602
 3603                if !always_treat_brackets_as_autoclosed {
 3604                    return selection;
 3605                }
 3606
 3607                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3608                    for (pair, enabled) in scope.brackets() {
 3609                        if !enabled || !pair.close {
 3610                            continue;
 3611                        }
 3612
 3613                        if buffer.contains_str_at(selection.start, &pair.end) {
 3614                            let pair_start_len = pair.start.len();
 3615                            if buffer.contains_str_at(
 3616                                selection.start.saturating_sub(pair_start_len),
 3617                                &pair.start,
 3618                            ) {
 3619                                selection.start -= pair_start_len;
 3620                                selection.end += pair.end.len();
 3621
 3622                                return selection;
 3623                            }
 3624                        }
 3625                    }
 3626                }
 3627
 3628                selection
 3629            })
 3630            .collect();
 3631
 3632        drop(buffer);
 3633        self.change_selections(None, window, cx, |selections| {
 3634            selections.select(new_selections)
 3635        });
 3636    }
 3637
 3638    /// Iterate the given selections, and for each one, find the smallest surrounding
 3639    /// autoclose region. This uses the ordering of the selections and the autoclose
 3640    /// regions to avoid repeated comparisons.
 3641    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3642        &'a self,
 3643        selections: impl IntoIterator<Item = Selection<D>>,
 3644        buffer: &'a MultiBufferSnapshot,
 3645    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3646        let mut i = 0;
 3647        let mut regions = self.autoclose_regions.as_slice();
 3648        selections.into_iter().map(move |selection| {
 3649            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3650
 3651            let mut enclosing = None;
 3652            while let Some(pair_state) = regions.get(i) {
 3653                if pair_state.range.end.to_offset(buffer) < range.start {
 3654                    regions = &regions[i + 1..];
 3655                    i = 0;
 3656                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3657                    break;
 3658                } else {
 3659                    if pair_state.selection_id == selection.id {
 3660                        enclosing = Some(pair_state);
 3661                    }
 3662                    i += 1;
 3663                }
 3664            }
 3665
 3666            (selection, enclosing)
 3667        })
 3668    }
 3669
 3670    /// Remove any autoclose regions that no longer contain their selection.
 3671    fn invalidate_autoclose_regions(
 3672        &mut self,
 3673        mut selections: &[Selection<Anchor>],
 3674        buffer: &MultiBufferSnapshot,
 3675    ) {
 3676        self.autoclose_regions.retain(|state| {
 3677            let mut i = 0;
 3678            while let Some(selection) = selections.get(i) {
 3679                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3680                    selections = &selections[1..];
 3681                    continue;
 3682                }
 3683                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3684                    break;
 3685                }
 3686                if selection.id == state.selection_id {
 3687                    return true;
 3688                } else {
 3689                    i += 1;
 3690                }
 3691            }
 3692            false
 3693        });
 3694    }
 3695
 3696    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3697        let offset = position.to_offset(buffer);
 3698        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3699        if offset > word_range.start && kind == Some(CharKind::Word) {
 3700            Some(
 3701                buffer
 3702                    .text_for_range(word_range.start..offset)
 3703                    .collect::<String>(),
 3704            )
 3705        } else {
 3706            None
 3707        }
 3708    }
 3709
 3710    pub fn toggle_inlay_hints(
 3711        &mut self,
 3712        _: &ToggleInlayHints,
 3713        _: &mut Window,
 3714        cx: &mut Context<Self>,
 3715    ) {
 3716        self.refresh_inlay_hints(
 3717            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 3718            cx,
 3719        );
 3720    }
 3721
 3722    pub fn inlay_hints_enabled(&self) -> bool {
 3723        self.inlay_hint_cache.enabled
 3724    }
 3725
 3726    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3727        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3728            return;
 3729        }
 3730
 3731        let reason_description = reason.description();
 3732        let ignore_debounce = matches!(
 3733            reason,
 3734            InlayHintRefreshReason::SettingsChange(_)
 3735                | InlayHintRefreshReason::Toggle(_)
 3736                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3737                | InlayHintRefreshReason::ModifiersChanged(_)
 3738        );
 3739        let (invalidate_cache, required_languages) = match reason {
 3740            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 3741                match self.inlay_hint_cache.modifiers_override(enabled) {
 3742                    Some(enabled) => {
 3743                        if enabled {
 3744                            (InvalidationStrategy::RefreshRequested, None)
 3745                        } else {
 3746                            self.splice_inlays(
 3747                                &self
 3748                                    .visible_inlay_hints(cx)
 3749                                    .iter()
 3750                                    .map(|inlay| inlay.id)
 3751                                    .collect::<Vec<InlayId>>(),
 3752                                Vec::new(),
 3753                                cx,
 3754                            );
 3755                            return;
 3756                        }
 3757                    }
 3758                    None => return,
 3759                }
 3760            }
 3761            InlayHintRefreshReason::Toggle(enabled) => {
 3762                if self.inlay_hint_cache.toggle(enabled) {
 3763                    if enabled {
 3764                        (InvalidationStrategy::RefreshRequested, None)
 3765                    } else {
 3766                        self.splice_inlays(
 3767                            &self
 3768                                .visible_inlay_hints(cx)
 3769                                .iter()
 3770                                .map(|inlay| inlay.id)
 3771                                .collect::<Vec<InlayId>>(),
 3772                            Vec::new(),
 3773                            cx,
 3774                        );
 3775                        return;
 3776                    }
 3777                } else {
 3778                    return;
 3779                }
 3780            }
 3781            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3782                match self.inlay_hint_cache.update_settings(
 3783                    &self.buffer,
 3784                    new_settings,
 3785                    self.visible_inlay_hints(cx),
 3786                    cx,
 3787                ) {
 3788                    ControlFlow::Break(Some(InlaySplice {
 3789                        to_remove,
 3790                        to_insert,
 3791                    })) => {
 3792                        self.splice_inlays(&to_remove, to_insert, cx);
 3793                        return;
 3794                    }
 3795                    ControlFlow::Break(None) => return,
 3796                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3797                }
 3798            }
 3799            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3800                if let Some(InlaySplice {
 3801                    to_remove,
 3802                    to_insert,
 3803                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3804                {
 3805                    self.splice_inlays(&to_remove, to_insert, cx);
 3806                }
 3807                return;
 3808            }
 3809            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3810            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3811                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3812            }
 3813            InlayHintRefreshReason::RefreshRequested => {
 3814                (InvalidationStrategy::RefreshRequested, None)
 3815            }
 3816        };
 3817
 3818        if let Some(InlaySplice {
 3819            to_remove,
 3820            to_insert,
 3821        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3822            reason_description,
 3823            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3824            invalidate_cache,
 3825            ignore_debounce,
 3826            cx,
 3827        ) {
 3828            self.splice_inlays(&to_remove, to_insert, cx);
 3829        }
 3830    }
 3831
 3832    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3833        self.display_map
 3834            .read(cx)
 3835            .current_inlays()
 3836            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3837            .cloned()
 3838            .collect()
 3839    }
 3840
 3841    pub fn excerpts_for_inlay_hints_query(
 3842        &self,
 3843        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3844        cx: &mut Context<Editor>,
 3845    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3846        let Some(project) = self.project.as_ref() else {
 3847            return HashMap::default();
 3848        };
 3849        let project = project.read(cx);
 3850        let multi_buffer = self.buffer().read(cx);
 3851        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3852        let multi_buffer_visible_start = self
 3853            .scroll_manager
 3854            .anchor()
 3855            .anchor
 3856            .to_point(&multi_buffer_snapshot);
 3857        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3858            multi_buffer_visible_start
 3859                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3860            Bias::Left,
 3861        );
 3862        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3863        multi_buffer_snapshot
 3864            .range_to_buffer_ranges(multi_buffer_visible_range)
 3865            .into_iter()
 3866            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3867            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3868                let buffer_file = project::File::from_dyn(buffer.file())?;
 3869                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3870                let worktree_entry = buffer_worktree
 3871                    .read(cx)
 3872                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3873                if worktree_entry.is_ignored {
 3874                    return None;
 3875                }
 3876
 3877                let language = buffer.language()?;
 3878                if let Some(restrict_to_languages) = restrict_to_languages {
 3879                    if !restrict_to_languages.contains(language) {
 3880                        return None;
 3881                    }
 3882                }
 3883                Some((
 3884                    excerpt_id,
 3885                    (
 3886                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3887                        buffer.version().clone(),
 3888                        excerpt_visible_range,
 3889                    ),
 3890                ))
 3891            })
 3892            .collect()
 3893    }
 3894
 3895    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3896        TextLayoutDetails {
 3897            text_system: window.text_system().clone(),
 3898            editor_style: self.style.clone().unwrap(),
 3899            rem_size: window.rem_size(),
 3900            scroll_anchor: self.scroll_manager.anchor(),
 3901            visible_rows: self.visible_line_count(),
 3902            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3903        }
 3904    }
 3905
 3906    pub fn splice_inlays(
 3907        &self,
 3908        to_remove: &[InlayId],
 3909        to_insert: Vec<Inlay>,
 3910        cx: &mut Context<Self>,
 3911    ) {
 3912        self.display_map.update(cx, |display_map, cx| {
 3913            display_map.splice_inlays(to_remove, to_insert, cx)
 3914        });
 3915        cx.notify();
 3916    }
 3917
 3918    fn trigger_on_type_formatting(
 3919        &self,
 3920        input: String,
 3921        window: &mut Window,
 3922        cx: &mut Context<Self>,
 3923    ) -> Option<Task<Result<()>>> {
 3924        if input.len() != 1 {
 3925            return None;
 3926        }
 3927
 3928        let project = self.project.as_ref()?;
 3929        let position = self.selections.newest_anchor().head();
 3930        let (buffer, buffer_position) = self
 3931            .buffer
 3932            .read(cx)
 3933            .text_anchor_for_position(position, cx)?;
 3934
 3935        let settings = language_settings::language_settings(
 3936            buffer
 3937                .read(cx)
 3938                .language_at(buffer_position)
 3939                .map(|l| l.name()),
 3940            buffer.read(cx).file(),
 3941            cx,
 3942        );
 3943        if !settings.use_on_type_format {
 3944            return None;
 3945        }
 3946
 3947        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3948        // hence we do LSP request & edit on host side only — add formats to host's history.
 3949        let push_to_lsp_host_history = true;
 3950        // If this is not the host, append its history with new edits.
 3951        let push_to_client_history = project.read(cx).is_via_collab();
 3952
 3953        let on_type_formatting = project.update(cx, |project, cx| {
 3954            project.on_type_format(
 3955                buffer.clone(),
 3956                buffer_position,
 3957                input,
 3958                push_to_lsp_host_history,
 3959                cx,
 3960            )
 3961        });
 3962        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3963            if let Some(transaction) = on_type_formatting.await? {
 3964                if push_to_client_history {
 3965                    buffer
 3966                        .update(&mut cx, |buffer, _| {
 3967                            buffer.push_transaction(transaction, Instant::now());
 3968                        })
 3969                        .ok();
 3970                }
 3971                editor.update(&mut cx, |editor, cx| {
 3972                    editor.refresh_document_highlights(cx);
 3973                })?;
 3974            }
 3975            Ok(())
 3976        }))
 3977    }
 3978
 3979    pub fn show_completions(
 3980        &mut self,
 3981        options: &ShowCompletions,
 3982        window: &mut Window,
 3983        cx: &mut Context<Self>,
 3984    ) {
 3985        if self.pending_rename.is_some() {
 3986            return;
 3987        }
 3988
 3989        let Some(provider) = self.completion_provider.as_ref() else {
 3990            return;
 3991        };
 3992
 3993        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3994            return;
 3995        }
 3996
 3997        let position = self.selections.newest_anchor().head();
 3998        if position.diff_base_anchor.is_some() {
 3999            return;
 4000        }
 4001        let (buffer, buffer_position) =
 4002            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4003                output
 4004            } else {
 4005                return;
 4006            };
 4007        let show_completion_documentation = buffer
 4008            .read(cx)
 4009            .snapshot()
 4010            .settings_at(buffer_position, cx)
 4011            .show_completion_documentation;
 4012
 4013        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4014
 4015        let trigger_kind = match &options.trigger {
 4016            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4017                CompletionTriggerKind::TRIGGER_CHARACTER
 4018            }
 4019            _ => CompletionTriggerKind::INVOKED,
 4020        };
 4021        let completion_context = CompletionContext {
 4022            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4023                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4024                    Some(String::from(trigger))
 4025                } else {
 4026                    None
 4027                }
 4028            }),
 4029            trigger_kind,
 4030        };
 4031        let completions =
 4032            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 4033        let sort_completions = provider.sort_completions();
 4034
 4035        let id = post_inc(&mut self.next_completion_id);
 4036        let task = cx.spawn_in(window, |editor, mut cx| {
 4037            async move {
 4038                editor.update(&mut cx, |this, _| {
 4039                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4040                })?;
 4041                let completions = completions.await.log_err();
 4042                let menu = if let Some(completions) = completions {
 4043                    let mut menu = CompletionsMenu::new(
 4044                        id,
 4045                        sort_completions,
 4046                        show_completion_documentation,
 4047                        position,
 4048                        buffer.clone(),
 4049                        completions.into(),
 4050                    );
 4051
 4052                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4053                        .await;
 4054
 4055                    menu.visible().then_some(menu)
 4056                } else {
 4057                    None
 4058                };
 4059
 4060                editor.update_in(&mut cx, |editor, window, cx| {
 4061                    match editor.context_menu.borrow().as_ref() {
 4062                        None => {}
 4063                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4064                            if prev_menu.id > id {
 4065                                return;
 4066                            }
 4067                        }
 4068                        _ => return,
 4069                    }
 4070
 4071                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4072                        let mut menu = menu.unwrap();
 4073                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4074
 4075                        *editor.context_menu.borrow_mut() =
 4076                            Some(CodeContextMenu::Completions(menu));
 4077
 4078                        if editor.show_edit_predictions_in_menu() {
 4079                            editor.update_visible_inline_completion(window, cx);
 4080                        } else {
 4081                            editor.discard_inline_completion(false, cx);
 4082                        }
 4083
 4084                        cx.notify();
 4085                    } else if editor.completion_tasks.len() <= 1 {
 4086                        // If there are no more completion tasks and the last menu was
 4087                        // empty, we should hide it.
 4088                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4089                        // If it was already hidden and we don't show inline
 4090                        // completions in the menu, we should also show the
 4091                        // inline-completion when available.
 4092                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4093                            editor.update_visible_inline_completion(window, cx);
 4094                        }
 4095                    }
 4096                })?;
 4097
 4098                Ok::<_, anyhow::Error>(())
 4099            }
 4100            .log_err()
 4101        });
 4102
 4103        self.completion_tasks.push((id, task));
 4104    }
 4105
 4106    pub fn confirm_completion(
 4107        &mut self,
 4108        action: &ConfirmCompletion,
 4109        window: &mut Window,
 4110        cx: &mut Context<Self>,
 4111    ) -> Option<Task<Result<()>>> {
 4112        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4113    }
 4114
 4115    pub fn compose_completion(
 4116        &mut self,
 4117        action: &ComposeCompletion,
 4118        window: &mut Window,
 4119        cx: &mut Context<Self>,
 4120    ) -> Option<Task<Result<()>>> {
 4121        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4122    }
 4123
 4124    fn do_completion(
 4125        &mut self,
 4126        item_ix: Option<usize>,
 4127        intent: CompletionIntent,
 4128        window: &mut Window,
 4129        cx: &mut Context<Editor>,
 4130    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4131        use language::ToOffset as _;
 4132
 4133        let completions_menu =
 4134            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4135                menu
 4136            } else {
 4137                return None;
 4138            };
 4139
 4140        let entries = completions_menu.entries.borrow();
 4141        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4142        if self.show_edit_predictions_in_menu() {
 4143            self.discard_inline_completion(true, cx);
 4144        }
 4145        let candidate_id = mat.candidate_id;
 4146        drop(entries);
 4147
 4148        let buffer_handle = completions_menu.buffer;
 4149        let completion = completions_menu
 4150            .completions
 4151            .borrow()
 4152            .get(candidate_id)?
 4153            .clone();
 4154        cx.stop_propagation();
 4155
 4156        let snippet;
 4157        let text;
 4158
 4159        if completion.is_snippet() {
 4160            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4161            text = snippet.as_ref().unwrap().text.clone();
 4162        } else {
 4163            snippet = None;
 4164            text = completion.new_text.clone();
 4165        };
 4166        let selections = self.selections.all::<usize>(cx);
 4167        let buffer = buffer_handle.read(cx);
 4168        let old_range = completion.old_range.to_offset(buffer);
 4169        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4170
 4171        let newest_selection = self.selections.newest_anchor();
 4172        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4173            return None;
 4174        }
 4175
 4176        let lookbehind = newest_selection
 4177            .start
 4178            .text_anchor
 4179            .to_offset(buffer)
 4180            .saturating_sub(old_range.start);
 4181        let lookahead = old_range
 4182            .end
 4183            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4184        let mut common_prefix_len = old_text
 4185            .bytes()
 4186            .zip(text.bytes())
 4187            .take_while(|(a, b)| a == b)
 4188            .count();
 4189
 4190        let snapshot = self.buffer.read(cx).snapshot(cx);
 4191        let mut range_to_replace: Option<Range<isize>> = None;
 4192        let mut ranges = Vec::new();
 4193        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4194        for selection in &selections {
 4195            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4196                let start = selection.start.saturating_sub(lookbehind);
 4197                let end = selection.end + lookahead;
 4198                if selection.id == newest_selection.id {
 4199                    range_to_replace = Some(
 4200                        ((start + common_prefix_len) as isize - selection.start as isize)
 4201                            ..(end as isize - selection.start as isize),
 4202                    );
 4203                }
 4204                ranges.push(start + common_prefix_len..end);
 4205            } else {
 4206                common_prefix_len = 0;
 4207                ranges.clear();
 4208                ranges.extend(selections.iter().map(|s| {
 4209                    if s.id == newest_selection.id {
 4210                        range_to_replace = Some(
 4211                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4212                                - selection.start as isize
 4213                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4214                                    - selection.start as isize,
 4215                        );
 4216                        old_range.clone()
 4217                    } else {
 4218                        s.start..s.end
 4219                    }
 4220                }));
 4221                break;
 4222            }
 4223            if !self.linked_edit_ranges.is_empty() {
 4224                let start_anchor = snapshot.anchor_before(selection.head());
 4225                let end_anchor = snapshot.anchor_after(selection.tail());
 4226                if let Some(ranges) = self
 4227                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4228                {
 4229                    for (buffer, edits) in ranges {
 4230                        linked_edits.entry(buffer.clone()).or_default().extend(
 4231                            edits
 4232                                .into_iter()
 4233                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4234                        );
 4235                    }
 4236                }
 4237            }
 4238        }
 4239        let text = &text[common_prefix_len..];
 4240
 4241        cx.emit(EditorEvent::InputHandled {
 4242            utf16_range_to_replace: range_to_replace,
 4243            text: text.into(),
 4244        });
 4245
 4246        self.transact(window, cx, |this, window, cx| {
 4247            if let Some(mut snippet) = snippet {
 4248                snippet.text = text.to_string();
 4249                for tabstop in snippet
 4250                    .tabstops
 4251                    .iter_mut()
 4252                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4253                {
 4254                    tabstop.start -= common_prefix_len as isize;
 4255                    tabstop.end -= common_prefix_len as isize;
 4256                }
 4257
 4258                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4259            } else {
 4260                this.buffer.update(cx, |buffer, cx| {
 4261                    buffer.edit(
 4262                        ranges.iter().map(|range| (range.clone(), text)),
 4263                        this.autoindent_mode.clone(),
 4264                        cx,
 4265                    );
 4266                });
 4267            }
 4268            for (buffer, edits) in linked_edits {
 4269                buffer.update(cx, |buffer, cx| {
 4270                    let snapshot = buffer.snapshot();
 4271                    let edits = edits
 4272                        .into_iter()
 4273                        .map(|(range, text)| {
 4274                            use text::ToPoint as TP;
 4275                            let end_point = TP::to_point(&range.end, &snapshot);
 4276                            let start_point = TP::to_point(&range.start, &snapshot);
 4277                            (start_point..end_point, text)
 4278                        })
 4279                        .sorted_by_key(|(range, _)| range.start)
 4280                        .collect::<Vec<_>>();
 4281                    buffer.edit(edits, None, cx);
 4282                })
 4283            }
 4284
 4285            this.refresh_inline_completion(true, false, window, cx);
 4286        });
 4287
 4288        let show_new_completions_on_confirm = completion
 4289            .confirm
 4290            .as_ref()
 4291            .map_or(false, |confirm| confirm(intent, window, cx));
 4292        if show_new_completions_on_confirm {
 4293            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4294        }
 4295
 4296        let provider = self.completion_provider.as_ref()?;
 4297        drop(completion);
 4298        let apply_edits = provider.apply_additional_edits_for_completion(
 4299            buffer_handle,
 4300            completions_menu.completions.clone(),
 4301            candidate_id,
 4302            true,
 4303            cx,
 4304        );
 4305
 4306        let editor_settings = EditorSettings::get_global(cx);
 4307        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4308            // After the code completion is finished, users often want to know what signatures are needed.
 4309            // so we should automatically call signature_help
 4310            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4311        }
 4312
 4313        Some(cx.foreground_executor().spawn(async move {
 4314            apply_edits.await?;
 4315            Ok(())
 4316        }))
 4317    }
 4318
 4319    pub fn toggle_code_actions(
 4320        &mut self,
 4321        action: &ToggleCodeActions,
 4322        window: &mut Window,
 4323        cx: &mut Context<Self>,
 4324    ) {
 4325        let mut context_menu = self.context_menu.borrow_mut();
 4326        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4327            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4328                // Toggle if we're selecting the same one
 4329                *context_menu = None;
 4330                cx.notify();
 4331                return;
 4332            } else {
 4333                // Otherwise, clear it and start a new one
 4334                *context_menu = None;
 4335                cx.notify();
 4336            }
 4337        }
 4338        drop(context_menu);
 4339        let snapshot = self.snapshot(window, cx);
 4340        let deployed_from_indicator = action.deployed_from_indicator;
 4341        let mut task = self.code_actions_task.take();
 4342        let action = action.clone();
 4343        cx.spawn_in(window, |editor, mut cx| async move {
 4344            while let Some(prev_task) = task {
 4345                prev_task.await.log_err();
 4346                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4347            }
 4348
 4349            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4350                if editor.focus_handle.is_focused(window) {
 4351                    let multibuffer_point = action
 4352                        .deployed_from_indicator
 4353                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4354                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4355                    let (buffer, buffer_row) = snapshot
 4356                        .buffer_snapshot
 4357                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4358                        .and_then(|(buffer_snapshot, range)| {
 4359                            editor
 4360                                .buffer
 4361                                .read(cx)
 4362                                .buffer(buffer_snapshot.remote_id())
 4363                                .map(|buffer| (buffer, range.start.row))
 4364                        })?;
 4365                    let (_, code_actions) = editor
 4366                        .available_code_actions
 4367                        .clone()
 4368                        .and_then(|(location, code_actions)| {
 4369                            let snapshot = location.buffer.read(cx).snapshot();
 4370                            let point_range = location.range.to_point(&snapshot);
 4371                            let point_range = point_range.start.row..=point_range.end.row;
 4372                            if point_range.contains(&buffer_row) {
 4373                                Some((location, code_actions))
 4374                            } else {
 4375                                None
 4376                            }
 4377                        })
 4378                        .unzip();
 4379                    let buffer_id = buffer.read(cx).remote_id();
 4380                    let tasks = editor
 4381                        .tasks
 4382                        .get(&(buffer_id, buffer_row))
 4383                        .map(|t| Arc::new(t.to_owned()));
 4384                    if tasks.is_none() && code_actions.is_none() {
 4385                        return None;
 4386                    }
 4387
 4388                    editor.completion_tasks.clear();
 4389                    editor.discard_inline_completion(false, cx);
 4390                    let task_context =
 4391                        tasks
 4392                            .as_ref()
 4393                            .zip(editor.project.clone())
 4394                            .map(|(tasks, project)| {
 4395                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4396                            });
 4397
 4398                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4399                        let task_context = match task_context {
 4400                            Some(task_context) => task_context.await,
 4401                            None => None,
 4402                        };
 4403                        let resolved_tasks =
 4404                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4405                                Rc::new(ResolvedTasks {
 4406                                    templates: tasks.resolve(&task_context).collect(),
 4407                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4408                                        multibuffer_point.row,
 4409                                        tasks.column,
 4410                                    )),
 4411                                })
 4412                            });
 4413                        let spawn_straight_away = resolved_tasks
 4414                            .as_ref()
 4415                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4416                            && code_actions
 4417                                .as_ref()
 4418                                .map_or(true, |actions| actions.is_empty());
 4419                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4420                            *editor.context_menu.borrow_mut() =
 4421                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4422                                    buffer,
 4423                                    actions: CodeActionContents {
 4424                                        tasks: resolved_tasks,
 4425                                        actions: code_actions,
 4426                                    },
 4427                                    selected_item: Default::default(),
 4428                                    scroll_handle: UniformListScrollHandle::default(),
 4429                                    deployed_from_indicator,
 4430                                }));
 4431                            if spawn_straight_away {
 4432                                if let Some(task) = editor.confirm_code_action(
 4433                                    &ConfirmCodeAction { item_ix: Some(0) },
 4434                                    window,
 4435                                    cx,
 4436                                ) {
 4437                                    cx.notify();
 4438                                    return task;
 4439                                }
 4440                            }
 4441                            cx.notify();
 4442                            Task::ready(Ok(()))
 4443                        }) {
 4444                            task.await
 4445                        } else {
 4446                            Ok(())
 4447                        }
 4448                    }))
 4449                } else {
 4450                    Some(Task::ready(Ok(())))
 4451                }
 4452            })?;
 4453            if let Some(task) = spawned_test_task {
 4454                task.await?;
 4455            }
 4456
 4457            Ok::<_, anyhow::Error>(())
 4458        })
 4459        .detach_and_log_err(cx);
 4460    }
 4461
 4462    pub fn confirm_code_action(
 4463        &mut self,
 4464        action: &ConfirmCodeAction,
 4465        window: &mut Window,
 4466        cx: &mut Context<Self>,
 4467    ) -> Option<Task<Result<()>>> {
 4468        let actions_menu =
 4469            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4470                menu
 4471            } else {
 4472                return None;
 4473            };
 4474        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4475        let action = actions_menu.actions.get(action_ix)?;
 4476        let title = action.label();
 4477        let buffer = actions_menu.buffer;
 4478        let workspace = self.workspace()?;
 4479
 4480        match action {
 4481            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4482                workspace.update(cx, |workspace, cx| {
 4483                    workspace::tasks::schedule_resolved_task(
 4484                        workspace,
 4485                        task_source_kind,
 4486                        resolved_task,
 4487                        false,
 4488                        cx,
 4489                    );
 4490
 4491                    Some(Task::ready(Ok(())))
 4492                })
 4493            }
 4494            CodeActionsItem::CodeAction {
 4495                excerpt_id,
 4496                action,
 4497                provider,
 4498            } => {
 4499                let apply_code_action =
 4500                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4501                let workspace = workspace.downgrade();
 4502                Some(cx.spawn_in(window, |editor, cx| async move {
 4503                    let project_transaction = apply_code_action.await?;
 4504                    Self::open_project_transaction(
 4505                        &editor,
 4506                        workspace,
 4507                        project_transaction,
 4508                        title,
 4509                        cx,
 4510                    )
 4511                    .await
 4512                }))
 4513            }
 4514        }
 4515    }
 4516
 4517    pub async fn open_project_transaction(
 4518        this: &WeakEntity<Editor>,
 4519        workspace: WeakEntity<Workspace>,
 4520        transaction: ProjectTransaction,
 4521        title: String,
 4522        mut cx: AsyncWindowContext,
 4523    ) -> Result<()> {
 4524        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4525        cx.update(|_, cx| {
 4526            entries.sort_unstable_by_key(|(buffer, _)| {
 4527                buffer.read(cx).file().map(|f| f.path().clone())
 4528            });
 4529        })?;
 4530
 4531        // If the project transaction's edits are all contained within this editor, then
 4532        // avoid opening a new editor to display them.
 4533
 4534        if let Some((buffer, transaction)) = entries.first() {
 4535            if entries.len() == 1 {
 4536                let excerpt = this.update(&mut cx, |editor, cx| {
 4537                    editor
 4538                        .buffer()
 4539                        .read(cx)
 4540                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4541                })?;
 4542                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4543                    if excerpted_buffer == *buffer {
 4544                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4545                            let excerpt_range = excerpt_range.to_offset(buffer);
 4546                            buffer
 4547                                .edited_ranges_for_transaction::<usize>(transaction)
 4548                                .all(|range| {
 4549                                    excerpt_range.start <= range.start
 4550                                        && excerpt_range.end >= range.end
 4551                                })
 4552                        })?;
 4553
 4554                        if all_edits_within_excerpt {
 4555                            return Ok(());
 4556                        }
 4557                    }
 4558                }
 4559            }
 4560        } else {
 4561            return Ok(());
 4562        }
 4563
 4564        let mut ranges_to_highlight = Vec::new();
 4565        let excerpt_buffer = cx.new(|cx| {
 4566            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4567            for (buffer_handle, transaction) in &entries {
 4568                let buffer = buffer_handle.read(cx);
 4569                ranges_to_highlight.extend(
 4570                    multibuffer.push_excerpts_with_context_lines(
 4571                        buffer_handle.clone(),
 4572                        buffer
 4573                            .edited_ranges_for_transaction::<usize>(transaction)
 4574                            .collect(),
 4575                        DEFAULT_MULTIBUFFER_CONTEXT,
 4576                        cx,
 4577                    ),
 4578                );
 4579            }
 4580            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4581            multibuffer
 4582        })?;
 4583
 4584        workspace.update_in(&mut cx, |workspace, window, cx| {
 4585            let project = workspace.project().clone();
 4586            let editor = cx
 4587                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4588            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4589            editor.update(cx, |editor, cx| {
 4590                editor.highlight_background::<Self>(
 4591                    &ranges_to_highlight,
 4592                    |theme| theme.editor_highlighted_line_background,
 4593                    cx,
 4594                );
 4595            });
 4596        })?;
 4597
 4598        Ok(())
 4599    }
 4600
 4601    pub fn clear_code_action_providers(&mut self) {
 4602        self.code_action_providers.clear();
 4603        self.available_code_actions.take();
 4604    }
 4605
 4606    pub fn add_code_action_provider(
 4607        &mut self,
 4608        provider: Rc<dyn CodeActionProvider>,
 4609        window: &mut Window,
 4610        cx: &mut Context<Self>,
 4611    ) {
 4612        if self
 4613            .code_action_providers
 4614            .iter()
 4615            .any(|existing_provider| existing_provider.id() == provider.id())
 4616        {
 4617            return;
 4618        }
 4619
 4620        self.code_action_providers.push(provider);
 4621        self.refresh_code_actions(window, cx);
 4622    }
 4623
 4624    pub fn remove_code_action_provider(
 4625        &mut self,
 4626        id: Arc<str>,
 4627        window: &mut Window,
 4628        cx: &mut Context<Self>,
 4629    ) {
 4630        self.code_action_providers
 4631            .retain(|provider| provider.id() != id);
 4632        self.refresh_code_actions(window, cx);
 4633    }
 4634
 4635    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4636        let buffer = self.buffer.read(cx);
 4637        let newest_selection = self.selections.newest_anchor().clone();
 4638        if newest_selection.head().diff_base_anchor.is_some() {
 4639            return None;
 4640        }
 4641        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4642        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4643        if start_buffer != end_buffer {
 4644            return None;
 4645        }
 4646
 4647        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4648            cx.background_executor()
 4649                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4650                .await;
 4651
 4652            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4653                let providers = this.code_action_providers.clone();
 4654                let tasks = this
 4655                    .code_action_providers
 4656                    .iter()
 4657                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4658                    .collect::<Vec<_>>();
 4659                (providers, tasks)
 4660            })?;
 4661
 4662            let mut actions = Vec::new();
 4663            for (provider, provider_actions) in
 4664                providers.into_iter().zip(future::join_all(tasks).await)
 4665            {
 4666                if let Some(provider_actions) = provider_actions.log_err() {
 4667                    actions.extend(provider_actions.into_iter().map(|action| {
 4668                        AvailableCodeAction {
 4669                            excerpt_id: newest_selection.start.excerpt_id,
 4670                            action,
 4671                            provider: provider.clone(),
 4672                        }
 4673                    }));
 4674                }
 4675            }
 4676
 4677            this.update(&mut cx, |this, cx| {
 4678                this.available_code_actions = if actions.is_empty() {
 4679                    None
 4680                } else {
 4681                    Some((
 4682                        Location {
 4683                            buffer: start_buffer,
 4684                            range: start..end,
 4685                        },
 4686                        actions.into(),
 4687                    ))
 4688                };
 4689                cx.notify();
 4690            })
 4691        }));
 4692        None
 4693    }
 4694
 4695    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4696        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4697            self.show_git_blame_inline = false;
 4698
 4699            self.show_git_blame_inline_delay_task =
 4700                Some(cx.spawn_in(window, |this, mut cx| async move {
 4701                    cx.background_executor().timer(delay).await;
 4702
 4703                    this.update(&mut cx, |this, cx| {
 4704                        this.show_git_blame_inline = true;
 4705                        cx.notify();
 4706                    })
 4707                    .log_err();
 4708                }));
 4709        }
 4710    }
 4711
 4712    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4713        if self.pending_rename.is_some() {
 4714            return None;
 4715        }
 4716
 4717        let provider = self.semantics_provider.clone()?;
 4718        let buffer = self.buffer.read(cx);
 4719        let newest_selection = self.selections.newest_anchor().clone();
 4720        let cursor_position = newest_selection.head();
 4721        let (cursor_buffer, cursor_buffer_position) =
 4722            buffer.text_anchor_for_position(cursor_position, cx)?;
 4723        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4724        if cursor_buffer != tail_buffer {
 4725            return None;
 4726        }
 4727        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4728        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4729            cx.background_executor()
 4730                .timer(Duration::from_millis(debounce))
 4731                .await;
 4732
 4733            let highlights = if let Some(highlights) = cx
 4734                .update(|cx| {
 4735                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4736                })
 4737                .ok()
 4738                .flatten()
 4739            {
 4740                highlights.await.log_err()
 4741            } else {
 4742                None
 4743            };
 4744
 4745            if let Some(highlights) = highlights {
 4746                this.update(&mut cx, |this, cx| {
 4747                    if this.pending_rename.is_some() {
 4748                        return;
 4749                    }
 4750
 4751                    let buffer_id = cursor_position.buffer_id;
 4752                    let buffer = this.buffer.read(cx);
 4753                    if !buffer
 4754                        .text_anchor_for_position(cursor_position, cx)
 4755                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4756                    {
 4757                        return;
 4758                    }
 4759
 4760                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4761                    let mut write_ranges = Vec::new();
 4762                    let mut read_ranges = Vec::new();
 4763                    for highlight in highlights {
 4764                        for (excerpt_id, excerpt_range) in
 4765                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4766                        {
 4767                            let start = highlight
 4768                                .range
 4769                                .start
 4770                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4771                            let end = highlight
 4772                                .range
 4773                                .end
 4774                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4775                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4776                                continue;
 4777                            }
 4778
 4779                            let range = Anchor {
 4780                                buffer_id,
 4781                                excerpt_id,
 4782                                text_anchor: start,
 4783                                diff_base_anchor: None,
 4784                            }..Anchor {
 4785                                buffer_id,
 4786                                excerpt_id,
 4787                                text_anchor: end,
 4788                                diff_base_anchor: None,
 4789                            };
 4790                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4791                                write_ranges.push(range);
 4792                            } else {
 4793                                read_ranges.push(range);
 4794                            }
 4795                        }
 4796                    }
 4797
 4798                    this.highlight_background::<DocumentHighlightRead>(
 4799                        &read_ranges,
 4800                        |theme| theme.editor_document_highlight_read_background,
 4801                        cx,
 4802                    );
 4803                    this.highlight_background::<DocumentHighlightWrite>(
 4804                        &write_ranges,
 4805                        |theme| theme.editor_document_highlight_write_background,
 4806                        cx,
 4807                    );
 4808                    cx.notify();
 4809                })
 4810                .log_err();
 4811            }
 4812        }));
 4813        None
 4814    }
 4815
 4816    pub fn refresh_selected_text_highlights(
 4817        &mut self,
 4818        window: &mut Window,
 4819        cx: &mut Context<Editor>,
 4820    ) {
 4821        self.selection_highlight_task.take();
 4822        if !EditorSettings::get_global(cx).selection_highlight {
 4823            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4824            return;
 4825        }
 4826        if self.selections.count() != 1 || self.selections.line_mode {
 4827            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4828            return;
 4829        }
 4830        let selection = self.selections.newest::<Point>(cx);
 4831        if selection.is_empty() || selection.start.row != selection.end.row {
 4832            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4833            return;
 4834        }
 4835        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4836        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4837            cx.background_executor()
 4838                .timer(Duration::from_millis(debounce))
 4839                .await;
 4840            let Some(Some(matches_task)) = editor
 4841                .update_in(&mut cx, |editor, _, cx| {
 4842                    if editor.selections.count() != 1 || editor.selections.line_mode {
 4843                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4844                        return None;
 4845                    }
 4846                    let selection = editor.selections.newest::<Point>(cx);
 4847                    if selection.is_empty() || selection.start.row != selection.end.row {
 4848                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4849                        return None;
 4850                    }
 4851                    let buffer = editor.buffer().read(cx).snapshot(cx);
 4852                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 4853                    if query.trim().is_empty() {
 4854                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4855                        return None;
 4856                    }
 4857                    Some(cx.background_spawn(async move {
 4858                        let mut ranges = Vec::new();
 4859                        let selection_anchors = selection.range().to_anchors(&buffer);
 4860                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 4861                            for (search_buffer, search_range, excerpt_id) in
 4862                                buffer.range_to_buffer_ranges(range)
 4863                            {
 4864                                ranges.extend(
 4865                                    project::search::SearchQuery::text(
 4866                                        query.clone(),
 4867                                        false,
 4868                                        false,
 4869                                        false,
 4870                                        Default::default(),
 4871                                        Default::default(),
 4872                                        None,
 4873                                    )
 4874                                    .unwrap()
 4875                                    .search(search_buffer, Some(search_range.clone()))
 4876                                    .await
 4877                                    .into_iter()
 4878                                    .filter_map(
 4879                                        |match_range| {
 4880                                            let start = search_buffer.anchor_after(
 4881                                                search_range.start + match_range.start,
 4882                                            );
 4883                                            let end = search_buffer.anchor_before(
 4884                                                search_range.start + match_range.end,
 4885                                            );
 4886                                            let range = Anchor::range_in_buffer(
 4887                                                excerpt_id,
 4888                                                search_buffer.remote_id(),
 4889                                                start..end,
 4890                                            );
 4891                                            (range != selection_anchors).then_some(range)
 4892                                        },
 4893                                    ),
 4894                                );
 4895                            }
 4896                        }
 4897                        ranges
 4898                    }))
 4899                })
 4900                .log_err()
 4901            else {
 4902                return;
 4903            };
 4904            let matches = matches_task.await;
 4905            editor
 4906                .update_in(&mut cx, |editor, _, cx| {
 4907                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4908                    if !matches.is_empty() {
 4909                        editor.highlight_background::<SelectedTextHighlight>(
 4910                            &matches,
 4911                            |theme| theme.editor_document_highlight_bracket_background,
 4912                            cx,
 4913                        )
 4914                    }
 4915                })
 4916                .log_err();
 4917        }));
 4918    }
 4919
 4920    pub fn refresh_inline_completion(
 4921        &mut self,
 4922        debounce: bool,
 4923        user_requested: bool,
 4924        window: &mut Window,
 4925        cx: &mut Context<Self>,
 4926    ) -> Option<()> {
 4927        let provider = self.edit_prediction_provider()?;
 4928        let cursor = self.selections.newest_anchor().head();
 4929        let (buffer, cursor_buffer_position) =
 4930            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4931
 4932        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4933            self.discard_inline_completion(false, cx);
 4934            return None;
 4935        }
 4936
 4937        if !user_requested
 4938            && (!self.should_show_edit_predictions()
 4939                || !self.is_focused(window)
 4940                || buffer.read(cx).is_empty())
 4941        {
 4942            self.discard_inline_completion(false, cx);
 4943            return None;
 4944        }
 4945
 4946        self.update_visible_inline_completion(window, cx);
 4947        provider.refresh(
 4948            self.project.clone(),
 4949            buffer,
 4950            cursor_buffer_position,
 4951            debounce,
 4952            cx,
 4953        );
 4954        Some(())
 4955    }
 4956
 4957    fn show_edit_predictions_in_menu(&self) -> bool {
 4958        match self.edit_prediction_settings {
 4959            EditPredictionSettings::Disabled => false,
 4960            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4961        }
 4962    }
 4963
 4964    pub fn edit_predictions_enabled(&self) -> bool {
 4965        match self.edit_prediction_settings {
 4966            EditPredictionSettings::Disabled => false,
 4967            EditPredictionSettings::Enabled { .. } => true,
 4968        }
 4969    }
 4970
 4971    fn edit_prediction_requires_modifier(&self) -> bool {
 4972        match self.edit_prediction_settings {
 4973            EditPredictionSettings::Disabled => false,
 4974            EditPredictionSettings::Enabled {
 4975                preview_requires_modifier,
 4976                ..
 4977            } => preview_requires_modifier,
 4978        }
 4979    }
 4980
 4981    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 4982        if self.edit_prediction_provider.is_none() {
 4983            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 4984        } else {
 4985            let selection = self.selections.newest_anchor();
 4986            let cursor = selection.head();
 4987
 4988            if let Some((buffer, cursor_buffer_position)) =
 4989                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4990            {
 4991                self.edit_prediction_settings =
 4992                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 4993            }
 4994        }
 4995    }
 4996
 4997    fn edit_prediction_settings_at_position(
 4998        &self,
 4999        buffer: &Entity<Buffer>,
 5000        buffer_position: language::Anchor,
 5001        cx: &App,
 5002    ) -> EditPredictionSettings {
 5003        if self.mode != EditorMode::Full
 5004            || !self.show_inline_completions_override.unwrap_or(true)
 5005            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5006        {
 5007            return EditPredictionSettings::Disabled;
 5008        }
 5009
 5010        let buffer = buffer.read(cx);
 5011
 5012        let file = buffer.file();
 5013
 5014        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5015            return EditPredictionSettings::Disabled;
 5016        };
 5017
 5018        let by_provider = matches!(
 5019            self.menu_inline_completions_policy,
 5020            MenuInlineCompletionsPolicy::ByProvider
 5021        );
 5022
 5023        let show_in_menu = by_provider
 5024            && self
 5025                .edit_prediction_provider
 5026                .as_ref()
 5027                .map_or(false, |provider| {
 5028                    provider.provider.show_completions_in_menu()
 5029                });
 5030
 5031        let preview_requires_modifier =
 5032            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5033
 5034        EditPredictionSettings::Enabled {
 5035            show_in_menu,
 5036            preview_requires_modifier,
 5037        }
 5038    }
 5039
 5040    fn should_show_edit_predictions(&self) -> bool {
 5041        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5042    }
 5043
 5044    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5045        matches!(
 5046            self.edit_prediction_preview,
 5047            EditPredictionPreview::Active { .. }
 5048        )
 5049    }
 5050
 5051    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5052        let cursor = self.selections.newest_anchor().head();
 5053        if let Some((buffer, cursor_position)) =
 5054            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5055        {
 5056            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5057        } else {
 5058            false
 5059        }
 5060    }
 5061
 5062    fn edit_predictions_enabled_in_buffer(
 5063        &self,
 5064        buffer: &Entity<Buffer>,
 5065        buffer_position: language::Anchor,
 5066        cx: &App,
 5067    ) -> bool {
 5068        maybe!({
 5069            let provider = self.edit_prediction_provider()?;
 5070            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5071                return Some(false);
 5072            }
 5073            let buffer = buffer.read(cx);
 5074            let Some(file) = buffer.file() else {
 5075                return Some(true);
 5076            };
 5077            let settings = all_language_settings(Some(file), cx);
 5078            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5079        })
 5080        .unwrap_or(false)
 5081    }
 5082
 5083    fn cycle_inline_completion(
 5084        &mut self,
 5085        direction: Direction,
 5086        window: &mut Window,
 5087        cx: &mut Context<Self>,
 5088    ) -> Option<()> {
 5089        let provider = self.edit_prediction_provider()?;
 5090        let cursor = self.selections.newest_anchor().head();
 5091        let (buffer, cursor_buffer_position) =
 5092            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5093        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5094            return None;
 5095        }
 5096
 5097        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5098        self.update_visible_inline_completion(window, cx);
 5099
 5100        Some(())
 5101    }
 5102
 5103    pub fn show_inline_completion(
 5104        &mut self,
 5105        _: &ShowEditPrediction,
 5106        window: &mut Window,
 5107        cx: &mut Context<Self>,
 5108    ) {
 5109        if !self.has_active_inline_completion() {
 5110            self.refresh_inline_completion(false, true, window, cx);
 5111            return;
 5112        }
 5113
 5114        self.update_visible_inline_completion(window, cx);
 5115    }
 5116
 5117    pub fn display_cursor_names(
 5118        &mut self,
 5119        _: &DisplayCursorNames,
 5120        window: &mut Window,
 5121        cx: &mut Context<Self>,
 5122    ) {
 5123        self.show_cursor_names(window, cx);
 5124    }
 5125
 5126    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5127        self.show_cursor_names = true;
 5128        cx.notify();
 5129        cx.spawn_in(window, |this, mut cx| async move {
 5130            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5131            this.update(&mut cx, |this, cx| {
 5132                this.show_cursor_names = false;
 5133                cx.notify()
 5134            })
 5135            .ok()
 5136        })
 5137        .detach();
 5138    }
 5139
 5140    pub fn next_edit_prediction(
 5141        &mut self,
 5142        _: &NextEditPrediction,
 5143        window: &mut Window,
 5144        cx: &mut Context<Self>,
 5145    ) {
 5146        if self.has_active_inline_completion() {
 5147            self.cycle_inline_completion(Direction::Next, window, cx);
 5148        } else {
 5149            let is_copilot_disabled = self
 5150                .refresh_inline_completion(false, true, window, cx)
 5151                .is_none();
 5152            if is_copilot_disabled {
 5153                cx.propagate();
 5154            }
 5155        }
 5156    }
 5157
 5158    pub fn previous_edit_prediction(
 5159        &mut self,
 5160        _: &PreviousEditPrediction,
 5161        window: &mut Window,
 5162        cx: &mut Context<Self>,
 5163    ) {
 5164        if self.has_active_inline_completion() {
 5165            self.cycle_inline_completion(Direction::Prev, window, cx);
 5166        } else {
 5167            let is_copilot_disabled = self
 5168                .refresh_inline_completion(false, true, window, cx)
 5169                .is_none();
 5170            if is_copilot_disabled {
 5171                cx.propagate();
 5172            }
 5173        }
 5174    }
 5175
 5176    pub fn accept_edit_prediction(
 5177        &mut self,
 5178        _: &AcceptEditPrediction,
 5179        window: &mut Window,
 5180        cx: &mut Context<Self>,
 5181    ) {
 5182        if self.show_edit_predictions_in_menu() {
 5183            self.hide_context_menu(window, cx);
 5184        }
 5185
 5186        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5187            return;
 5188        };
 5189
 5190        self.report_inline_completion_event(
 5191            active_inline_completion.completion_id.clone(),
 5192            true,
 5193            cx,
 5194        );
 5195
 5196        match &active_inline_completion.completion {
 5197            InlineCompletion::Move { target, .. } => {
 5198                let target = *target;
 5199
 5200                if let Some(position_map) = &self.last_position_map {
 5201                    if position_map
 5202                        .visible_row_range
 5203                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5204                        || !self.edit_prediction_requires_modifier()
 5205                    {
 5206                        self.unfold_ranges(&[target..target], true, false, cx);
 5207                        // Note that this is also done in vim's handler of the Tab action.
 5208                        self.change_selections(
 5209                            Some(Autoscroll::newest()),
 5210                            window,
 5211                            cx,
 5212                            |selections| {
 5213                                selections.select_anchor_ranges([target..target]);
 5214                            },
 5215                        );
 5216                        self.clear_row_highlights::<EditPredictionPreview>();
 5217
 5218                        self.edit_prediction_preview
 5219                            .set_previous_scroll_position(None);
 5220                    } else {
 5221                        self.edit_prediction_preview
 5222                            .set_previous_scroll_position(Some(
 5223                                position_map.snapshot.scroll_anchor,
 5224                            ));
 5225
 5226                        self.highlight_rows::<EditPredictionPreview>(
 5227                            target..target,
 5228                            cx.theme().colors().editor_highlighted_line_background,
 5229                            true,
 5230                            cx,
 5231                        );
 5232                        self.request_autoscroll(Autoscroll::fit(), cx);
 5233                    }
 5234                }
 5235            }
 5236            InlineCompletion::Edit { edits, .. } => {
 5237                if let Some(provider) = self.edit_prediction_provider() {
 5238                    provider.accept(cx);
 5239                }
 5240
 5241                let snapshot = self.buffer.read(cx).snapshot(cx);
 5242                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5243
 5244                self.buffer.update(cx, |buffer, cx| {
 5245                    buffer.edit(edits.iter().cloned(), None, cx)
 5246                });
 5247
 5248                self.change_selections(None, window, cx, |s| {
 5249                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5250                });
 5251
 5252                self.update_visible_inline_completion(window, cx);
 5253                if self.active_inline_completion.is_none() {
 5254                    self.refresh_inline_completion(true, true, window, cx);
 5255                }
 5256
 5257                cx.notify();
 5258            }
 5259        }
 5260
 5261        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5262    }
 5263
 5264    pub fn accept_partial_inline_completion(
 5265        &mut self,
 5266        _: &AcceptPartialEditPrediction,
 5267        window: &mut Window,
 5268        cx: &mut Context<Self>,
 5269    ) {
 5270        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5271            return;
 5272        };
 5273        if self.selections.count() != 1 {
 5274            return;
 5275        }
 5276
 5277        self.report_inline_completion_event(
 5278            active_inline_completion.completion_id.clone(),
 5279            true,
 5280            cx,
 5281        );
 5282
 5283        match &active_inline_completion.completion {
 5284            InlineCompletion::Move { target, .. } => {
 5285                let target = *target;
 5286                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5287                    selections.select_anchor_ranges([target..target]);
 5288                });
 5289            }
 5290            InlineCompletion::Edit { edits, .. } => {
 5291                // Find an insertion that starts at the cursor position.
 5292                let snapshot = self.buffer.read(cx).snapshot(cx);
 5293                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5294                let insertion = edits.iter().find_map(|(range, text)| {
 5295                    let range = range.to_offset(&snapshot);
 5296                    if range.is_empty() && range.start == cursor_offset {
 5297                        Some(text)
 5298                    } else {
 5299                        None
 5300                    }
 5301                });
 5302
 5303                if let Some(text) = insertion {
 5304                    let mut partial_completion = text
 5305                        .chars()
 5306                        .by_ref()
 5307                        .take_while(|c| c.is_alphabetic())
 5308                        .collect::<String>();
 5309                    if partial_completion.is_empty() {
 5310                        partial_completion = text
 5311                            .chars()
 5312                            .by_ref()
 5313                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5314                            .collect::<String>();
 5315                    }
 5316
 5317                    cx.emit(EditorEvent::InputHandled {
 5318                        utf16_range_to_replace: None,
 5319                        text: partial_completion.clone().into(),
 5320                    });
 5321
 5322                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5323
 5324                    self.refresh_inline_completion(true, true, window, cx);
 5325                    cx.notify();
 5326                } else {
 5327                    self.accept_edit_prediction(&Default::default(), window, cx);
 5328                }
 5329            }
 5330        }
 5331    }
 5332
 5333    fn discard_inline_completion(
 5334        &mut self,
 5335        should_report_inline_completion_event: bool,
 5336        cx: &mut Context<Self>,
 5337    ) -> bool {
 5338        if should_report_inline_completion_event {
 5339            let completion_id = self
 5340                .active_inline_completion
 5341                .as_ref()
 5342                .and_then(|active_completion| active_completion.completion_id.clone());
 5343
 5344            self.report_inline_completion_event(completion_id, false, cx);
 5345        }
 5346
 5347        if let Some(provider) = self.edit_prediction_provider() {
 5348            provider.discard(cx);
 5349        }
 5350
 5351        self.take_active_inline_completion(cx)
 5352    }
 5353
 5354    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5355        let Some(provider) = self.edit_prediction_provider() else {
 5356            return;
 5357        };
 5358
 5359        let Some((_, buffer, _)) = self
 5360            .buffer
 5361            .read(cx)
 5362            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5363        else {
 5364            return;
 5365        };
 5366
 5367        let extension = buffer
 5368            .read(cx)
 5369            .file()
 5370            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5371
 5372        let event_type = match accepted {
 5373            true => "Edit Prediction Accepted",
 5374            false => "Edit Prediction Discarded",
 5375        };
 5376        telemetry::event!(
 5377            event_type,
 5378            provider = provider.name(),
 5379            prediction_id = id,
 5380            suggestion_accepted = accepted,
 5381            file_extension = extension,
 5382        );
 5383    }
 5384
 5385    pub fn has_active_inline_completion(&self) -> bool {
 5386        self.active_inline_completion.is_some()
 5387    }
 5388
 5389    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5390        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5391            return false;
 5392        };
 5393
 5394        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5395        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5396        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5397        true
 5398    }
 5399
 5400    /// Returns true when we're displaying the edit prediction popover below the cursor
 5401    /// like we are not previewing and the LSP autocomplete menu is visible
 5402    /// or we are in `when_holding_modifier` mode.
 5403    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5404        if self.edit_prediction_preview_is_active()
 5405            || !self.show_edit_predictions_in_menu()
 5406            || !self.edit_predictions_enabled()
 5407        {
 5408            return false;
 5409        }
 5410
 5411        if self.has_visible_completions_menu() {
 5412            return true;
 5413        }
 5414
 5415        has_completion && self.edit_prediction_requires_modifier()
 5416    }
 5417
 5418    fn handle_modifiers_changed(
 5419        &mut self,
 5420        modifiers: Modifiers,
 5421        position_map: &PositionMap,
 5422        window: &mut Window,
 5423        cx: &mut Context<Self>,
 5424    ) {
 5425        if self.show_edit_predictions_in_menu() {
 5426            self.update_edit_prediction_preview(&modifiers, window, cx);
 5427        }
 5428
 5429        self.update_selection_mode(&modifiers, position_map, window, cx);
 5430
 5431        let mouse_position = window.mouse_position();
 5432        if !position_map.text_hitbox.is_hovered(window) {
 5433            return;
 5434        }
 5435
 5436        self.update_hovered_link(
 5437            position_map.point_for_position(mouse_position),
 5438            &position_map.snapshot,
 5439            modifiers,
 5440            window,
 5441            cx,
 5442        )
 5443    }
 5444
 5445    fn update_selection_mode(
 5446        &mut self,
 5447        modifiers: &Modifiers,
 5448        position_map: &PositionMap,
 5449        window: &mut Window,
 5450        cx: &mut Context<Self>,
 5451    ) {
 5452        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5453            return;
 5454        }
 5455
 5456        let mouse_position = window.mouse_position();
 5457        let point_for_position = position_map.point_for_position(mouse_position);
 5458        let position = point_for_position.previous_valid;
 5459
 5460        self.select(
 5461            SelectPhase::BeginColumnar {
 5462                position,
 5463                reset: false,
 5464                goal_column: point_for_position.exact_unclipped.column(),
 5465            },
 5466            window,
 5467            cx,
 5468        );
 5469    }
 5470
 5471    fn update_edit_prediction_preview(
 5472        &mut self,
 5473        modifiers: &Modifiers,
 5474        window: &mut Window,
 5475        cx: &mut Context<Self>,
 5476    ) {
 5477        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5478        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5479            return;
 5480        };
 5481
 5482        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5483            if matches!(
 5484                self.edit_prediction_preview,
 5485                EditPredictionPreview::Inactive { .. }
 5486            ) {
 5487                self.edit_prediction_preview = EditPredictionPreview::Active {
 5488                    previous_scroll_position: None,
 5489                    since: Instant::now(),
 5490                };
 5491
 5492                self.update_visible_inline_completion(window, cx);
 5493                cx.notify();
 5494            }
 5495        } else if let EditPredictionPreview::Active {
 5496            previous_scroll_position,
 5497            since,
 5498        } = self.edit_prediction_preview
 5499        {
 5500            if let (Some(previous_scroll_position), Some(position_map)) =
 5501                (previous_scroll_position, self.last_position_map.as_ref())
 5502            {
 5503                self.set_scroll_position(
 5504                    previous_scroll_position
 5505                        .scroll_position(&position_map.snapshot.display_snapshot),
 5506                    window,
 5507                    cx,
 5508                );
 5509            }
 5510
 5511            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 5512                released_too_fast: since.elapsed() < Duration::from_millis(200),
 5513            };
 5514            self.clear_row_highlights::<EditPredictionPreview>();
 5515            self.update_visible_inline_completion(window, cx);
 5516            cx.notify();
 5517        }
 5518    }
 5519
 5520    fn update_visible_inline_completion(
 5521        &mut self,
 5522        _window: &mut Window,
 5523        cx: &mut Context<Self>,
 5524    ) -> Option<()> {
 5525        let selection = self.selections.newest_anchor();
 5526        let cursor = selection.head();
 5527        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5528        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5529        let excerpt_id = cursor.excerpt_id;
 5530
 5531        let show_in_menu = self.show_edit_predictions_in_menu();
 5532        let completions_menu_has_precedence = !show_in_menu
 5533            && (self.context_menu.borrow().is_some()
 5534                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5535
 5536        if completions_menu_has_precedence
 5537            || !offset_selection.is_empty()
 5538            || self
 5539                .active_inline_completion
 5540                .as_ref()
 5541                .map_or(false, |completion| {
 5542                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5543                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5544                    !invalidation_range.contains(&offset_selection.head())
 5545                })
 5546        {
 5547            self.discard_inline_completion(false, cx);
 5548            return None;
 5549        }
 5550
 5551        self.take_active_inline_completion(cx);
 5552        let Some(provider) = self.edit_prediction_provider() else {
 5553            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5554            return None;
 5555        };
 5556
 5557        let (buffer, cursor_buffer_position) =
 5558            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5559
 5560        self.edit_prediction_settings =
 5561            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5562
 5563        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 5564
 5565        if self.edit_prediction_indent_conflict {
 5566            let cursor_point = cursor.to_point(&multibuffer);
 5567
 5568            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 5569
 5570            if let Some((_, indent)) = indents.iter().next() {
 5571                if indent.len == cursor_point.column {
 5572                    self.edit_prediction_indent_conflict = false;
 5573                }
 5574            }
 5575        }
 5576
 5577        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5578        let edits = inline_completion
 5579            .edits
 5580            .into_iter()
 5581            .flat_map(|(range, new_text)| {
 5582                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5583                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5584                Some((start..end, new_text))
 5585            })
 5586            .collect::<Vec<_>>();
 5587        if edits.is_empty() {
 5588            return None;
 5589        }
 5590
 5591        let first_edit_start = edits.first().unwrap().0.start;
 5592        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5593        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5594
 5595        let last_edit_end = edits.last().unwrap().0.end;
 5596        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5597        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5598
 5599        let cursor_row = cursor.to_point(&multibuffer).row;
 5600
 5601        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5602
 5603        let mut inlay_ids = Vec::new();
 5604        let invalidation_row_range;
 5605        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5606            Some(cursor_row..edit_end_row)
 5607        } else if cursor_row > edit_end_row {
 5608            Some(edit_start_row..cursor_row)
 5609        } else {
 5610            None
 5611        };
 5612        let is_move =
 5613            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5614        let completion = if is_move {
 5615            invalidation_row_range =
 5616                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5617            let target = first_edit_start;
 5618            InlineCompletion::Move { target, snapshot }
 5619        } else {
 5620            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5621                && !self.inline_completions_hidden_for_vim_mode;
 5622
 5623            if show_completions_in_buffer {
 5624                if edits
 5625                    .iter()
 5626                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5627                {
 5628                    let mut inlays = Vec::new();
 5629                    for (range, new_text) in &edits {
 5630                        let inlay = Inlay::inline_completion(
 5631                            post_inc(&mut self.next_inlay_id),
 5632                            range.start,
 5633                            new_text.as_str(),
 5634                        );
 5635                        inlay_ids.push(inlay.id);
 5636                        inlays.push(inlay);
 5637                    }
 5638
 5639                    self.splice_inlays(&[], inlays, cx);
 5640                } else {
 5641                    let background_color = cx.theme().status().deleted_background;
 5642                    self.highlight_text::<InlineCompletionHighlight>(
 5643                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5644                        HighlightStyle {
 5645                            background_color: Some(background_color),
 5646                            ..Default::default()
 5647                        },
 5648                        cx,
 5649                    );
 5650                }
 5651            }
 5652
 5653            invalidation_row_range = edit_start_row..edit_end_row;
 5654
 5655            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5656                if provider.show_tab_accept_marker() {
 5657                    EditDisplayMode::TabAccept
 5658                } else {
 5659                    EditDisplayMode::Inline
 5660                }
 5661            } else {
 5662                EditDisplayMode::DiffPopover
 5663            };
 5664
 5665            InlineCompletion::Edit {
 5666                edits,
 5667                edit_preview: inline_completion.edit_preview,
 5668                display_mode,
 5669                snapshot,
 5670            }
 5671        };
 5672
 5673        let invalidation_range = multibuffer
 5674            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5675            ..multibuffer.anchor_after(Point::new(
 5676                invalidation_row_range.end,
 5677                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5678            ));
 5679
 5680        self.stale_inline_completion_in_menu = None;
 5681        self.active_inline_completion = Some(InlineCompletionState {
 5682            inlay_ids,
 5683            completion,
 5684            completion_id: inline_completion.id,
 5685            invalidation_range,
 5686        });
 5687
 5688        cx.notify();
 5689
 5690        Some(())
 5691    }
 5692
 5693    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5694        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5695    }
 5696
 5697    fn render_code_actions_indicator(
 5698        &self,
 5699        _style: &EditorStyle,
 5700        row: DisplayRow,
 5701        is_active: bool,
 5702        cx: &mut Context<Self>,
 5703    ) -> Option<IconButton> {
 5704        if self.available_code_actions.is_some() {
 5705            Some(
 5706                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5707                    .shape(ui::IconButtonShape::Square)
 5708                    .icon_size(IconSize::XSmall)
 5709                    .icon_color(Color::Muted)
 5710                    .toggle_state(is_active)
 5711                    .tooltip({
 5712                        let focus_handle = self.focus_handle.clone();
 5713                        move |window, cx| {
 5714                            Tooltip::for_action_in(
 5715                                "Toggle Code Actions",
 5716                                &ToggleCodeActions {
 5717                                    deployed_from_indicator: None,
 5718                                },
 5719                                &focus_handle,
 5720                                window,
 5721                                cx,
 5722                            )
 5723                        }
 5724                    })
 5725                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5726                        window.focus(&editor.focus_handle(cx));
 5727                        editor.toggle_code_actions(
 5728                            &ToggleCodeActions {
 5729                                deployed_from_indicator: Some(row),
 5730                            },
 5731                            window,
 5732                            cx,
 5733                        );
 5734                    })),
 5735            )
 5736        } else {
 5737            None
 5738        }
 5739    }
 5740
 5741    fn clear_tasks(&mut self) {
 5742        self.tasks.clear()
 5743    }
 5744
 5745    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5746        if self.tasks.insert(key, value).is_some() {
 5747            // This case should hopefully be rare, but just in case...
 5748            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5749        }
 5750    }
 5751
 5752    fn build_tasks_context(
 5753        project: &Entity<Project>,
 5754        buffer: &Entity<Buffer>,
 5755        buffer_row: u32,
 5756        tasks: &Arc<RunnableTasks>,
 5757        cx: &mut Context<Self>,
 5758    ) -> Task<Option<task::TaskContext>> {
 5759        let position = Point::new(buffer_row, tasks.column);
 5760        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5761        let location = Location {
 5762            buffer: buffer.clone(),
 5763            range: range_start..range_start,
 5764        };
 5765        // Fill in the environmental variables from the tree-sitter captures
 5766        let mut captured_task_variables = TaskVariables::default();
 5767        for (capture_name, value) in tasks.extra_variables.clone() {
 5768            captured_task_variables.insert(
 5769                task::VariableName::Custom(capture_name.into()),
 5770                value.clone(),
 5771            );
 5772        }
 5773        project.update(cx, |project, cx| {
 5774            project.task_store().update(cx, |task_store, cx| {
 5775                task_store.task_context_for_location(captured_task_variables, location, cx)
 5776            })
 5777        })
 5778    }
 5779
 5780    pub fn spawn_nearest_task(
 5781        &mut self,
 5782        action: &SpawnNearestTask,
 5783        window: &mut Window,
 5784        cx: &mut Context<Self>,
 5785    ) {
 5786        let Some((workspace, _)) = self.workspace.clone() else {
 5787            return;
 5788        };
 5789        let Some(project) = self.project.clone() else {
 5790            return;
 5791        };
 5792
 5793        // Try to find a closest, enclosing node using tree-sitter that has a
 5794        // task
 5795        let Some((buffer, buffer_row, tasks)) = self
 5796            .find_enclosing_node_task(cx)
 5797            // Or find the task that's closest in row-distance.
 5798            .or_else(|| self.find_closest_task(cx))
 5799        else {
 5800            return;
 5801        };
 5802
 5803        let reveal_strategy = action.reveal;
 5804        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5805        cx.spawn_in(window, |_, mut cx| async move {
 5806            let context = task_context.await?;
 5807            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5808
 5809            let resolved = resolved_task.resolved.as_mut()?;
 5810            resolved.reveal = reveal_strategy;
 5811
 5812            workspace
 5813                .update(&mut cx, |workspace, cx| {
 5814                    workspace::tasks::schedule_resolved_task(
 5815                        workspace,
 5816                        task_source_kind,
 5817                        resolved_task,
 5818                        false,
 5819                        cx,
 5820                    );
 5821                })
 5822                .ok()
 5823        })
 5824        .detach();
 5825    }
 5826
 5827    fn find_closest_task(
 5828        &mut self,
 5829        cx: &mut Context<Self>,
 5830    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5831        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5832
 5833        let ((buffer_id, row), tasks) = self
 5834            .tasks
 5835            .iter()
 5836            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5837
 5838        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5839        let tasks = Arc::new(tasks.to_owned());
 5840        Some((buffer, *row, tasks))
 5841    }
 5842
 5843    fn find_enclosing_node_task(
 5844        &mut self,
 5845        cx: &mut Context<Self>,
 5846    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5847        let snapshot = self.buffer.read(cx).snapshot(cx);
 5848        let offset = self.selections.newest::<usize>(cx).head();
 5849        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5850        let buffer_id = excerpt.buffer().remote_id();
 5851
 5852        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5853        let mut cursor = layer.node().walk();
 5854
 5855        while cursor.goto_first_child_for_byte(offset).is_some() {
 5856            if cursor.node().end_byte() == offset {
 5857                cursor.goto_next_sibling();
 5858            }
 5859        }
 5860
 5861        // Ascend to the smallest ancestor that contains the range and has a task.
 5862        loop {
 5863            let node = cursor.node();
 5864            let node_range = node.byte_range();
 5865            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5866
 5867            // Check if this node contains our offset
 5868            if node_range.start <= offset && node_range.end >= offset {
 5869                // If it contains offset, check for task
 5870                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5871                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5872                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5873                }
 5874            }
 5875
 5876            if !cursor.goto_parent() {
 5877                break;
 5878            }
 5879        }
 5880        None
 5881    }
 5882
 5883    fn render_run_indicator(
 5884        &self,
 5885        _style: &EditorStyle,
 5886        is_active: bool,
 5887        row: DisplayRow,
 5888        cx: &mut Context<Self>,
 5889    ) -> IconButton {
 5890        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5891            .shape(ui::IconButtonShape::Square)
 5892            .icon_size(IconSize::XSmall)
 5893            .icon_color(Color::Muted)
 5894            .toggle_state(is_active)
 5895            .on_click(cx.listener(move |editor, _e, window, cx| {
 5896                window.focus(&editor.focus_handle(cx));
 5897                editor.toggle_code_actions(
 5898                    &ToggleCodeActions {
 5899                        deployed_from_indicator: Some(row),
 5900                    },
 5901                    window,
 5902                    cx,
 5903                );
 5904            }))
 5905    }
 5906
 5907    pub fn context_menu_visible(&self) -> bool {
 5908        !self.edit_prediction_preview_is_active()
 5909            && self
 5910                .context_menu
 5911                .borrow()
 5912                .as_ref()
 5913                .map_or(false, |menu| menu.visible())
 5914    }
 5915
 5916    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5917        self.context_menu
 5918            .borrow()
 5919            .as_ref()
 5920            .map(|menu| menu.origin())
 5921    }
 5922
 5923    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 5924    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 5925
 5926    #[allow(clippy::too_many_arguments)]
 5927    fn render_edit_prediction_popover(
 5928        &mut self,
 5929        text_bounds: &Bounds<Pixels>,
 5930        content_origin: gpui::Point<Pixels>,
 5931        editor_snapshot: &EditorSnapshot,
 5932        visible_row_range: Range<DisplayRow>,
 5933        scroll_top: f32,
 5934        scroll_bottom: f32,
 5935        line_layouts: &[LineWithInvisibles],
 5936        line_height: Pixels,
 5937        scroll_pixel_position: gpui::Point<Pixels>,
 5938        newest_selection_head: Option<DisplayPoint>,
 5939        editor_width: Pixels,
 5940        style: &EditorStyle,
 5941        window: &mut Window,
 5942        cx: &mut App,
 5943    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5944        let active_inline_completion = self.active_inline_completion.as_ref()?;
 5945
 5946        if self.edit_prediction_visible_in_cursor_popover(true) {
 5947            return None;
 5948        }
 5949
 5950        match &active_inline_completion.completion {
 5951            InlineCompletion::Move { target, .. } => {
 5952                let target_display_point = target.to_display_point(editor_snapshot);
 5953
 5954                if self.edit_prediction_requires_modifier() {
 5955                    if !self.edit_prediction_preview_is_active() {
 5956                        return None;
 5957                    }
 5958
 5959                    self.render_edit_prediction_modifier_jump_popover(
 5960                        text_bounds,
 5961                        content_origin,
 5962                        visible_row_range,
 5963                        line_layouts,
 5964                        line_height,
 5965                        scroll_pixel_position,
 5966                        newest_selection_head,
 5967                        target_display_point,
 5968                        window,
 5969                        cx,
 5970                    )
 5971                } else {
 5972                    self.render_edit_prediction_eager_jump_popover(
 5973                        text_bounds,
 5974                        content_origin,
 5975                        editor_snapshot,
 5976                        visible_row_range,
 5977                        scroll_top,
 5978                        scroll_bottom,
 5979                        line_height,
 5980                        scroll_pixel_position,
 5981                        target_display_point,
 5982                        editor_width,
 5983                        window,
 5984                        cx,
 5985                    )
 5986                }
 5987            }
 5988            InlineCompletion::Edit {
 5989                display_mode: EditDisplayMode::Inline,
 5990                ..
 5991            } => None,
 5992            InlineCompletion::Edit {
 5993                display_mode: EditDisplayMode::TabAccept,
 5994                edits,
 5995                ..
 5996            } => {
 5997                let range = &edits.first()?.0;
 5998                let target_display_point = range.end.to_display_point(editor_snapshot);
 5999
 6000                self.render_edit_prediction_end_of_line_popover(
 6001                    "Accept",
 6002                    editor_snapshot,
 6003                    visible_row_range,
 6004                    target_display_point,
 6005                    line_height,
 6006                    scroll_pixel_position,
 6007                    content_origin,
 6008                    editor_width,
 6009                    window,
 6010                    cx,
 6011                )
 6012            }
 6013            InlineCompletion::Edit {
 6014                edits,
 6015                edit_preview,
 6016                display_mode: EditDisplayMode::DiffPopover,
 6017                snapshot,
 6018            } => self.render_edit_prediction_diff_popover(
 6019                text_bounds,
 6020                content_origin,
 6021                editor_snapshot,
 6022                visible_row_range,
 6023                line_layouts,
 6024                line_height,
 6025                scroll_pixel_position,
 6026                newest_selection_head,
 6027                editor_width,
 6028                style,
 6029                edits,
 6030                edit_preview,
 6031                snapshot,
 6032                window,
 6033                cx,
 6034            ),
 6035        }
 6036    }
 6037
 6038    #[allow(clippy::too_many_arguments)]
 6039    fn render_edit_prediction_modifier_jump_popover(
 6040        &mut self,
 6041        text_bounds: &Bounds<Pixels>,
 6042        content_origin: gpui::Point<Pixels>,
 6043        visible_row_range: Range<DisplayRow>,
 6044        line_layouts: &[LineWithInvisibles],
 6045        line_height: Pixels,
 6046        scroll_pixel_position: gpui::Point<Pixels>,
 6047        newest_selection_head: Option<DisplayPoint>,
 6048        target_display_point: DisplayPoint,
 6049        window: &mut Window,
 6050        cx: &mut App,
 6051    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6052        let scrolled_content_origin =
 6053            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 6054
 6055        const SCROLL_PADDING_Y: Pixels = px(12.);
 6056
 6057        if target_display_point.row() < visible_row_range.start {
 6058            return self.render_edit_prediction_scroll_popover(
 6059                |_| SCROLL_PADDING_Y,
 6060                IconName::ArrowUp,
 6061                visible_row_range,
 6062                line_layouts,
 6063                newest_selection_head,
 6064                scrolled_content_origin,
 6065                window,
 6066                cx,
 6067            );
 6068        } else if target_display_point.row() >= visible_row_range.end {
 6069            return self.render_edit_prediction_scroll_popover(
 6070                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 6071                IconName::ArrowDown,
 6072                visible_row_range,
 6073                line_layouts,
 6074                newest_selection_head,
 6075                scrolled_content_origin,
 6076                window,
 6077                cx,
 6078            );
 6079        }
 6080
 6081        const POLE_WIDTH: Pixels = px(2.);
 6082
 6083        let line_layout =
 6084            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 6085        let target_column = target_display_point.column() as usize;
 6086
 6087        let target_x = line_layout.x_for_index(target_column);
 6088        let target_y =
 6089            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 6090
 6091        let flag_on_right = target_x < text_bounds.size.width / 2.;
 6092
 6093        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 6094        border_color.l += 0.001;
 6095
 6096        let mut element = v_flex()
 6097            .items_end()
 6098            .when(flag_on_right, |el| el.items_start())
 6099            .child(if flag_on_right {
 6100                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6101                    .rounded_bl(px(0.))
 6102                    .rounded_tl(px(0.))
 6103                    .border_l_2()
 6104                    .border_color(border_color)
 6105            } else {
 6106                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6107                    .rounded_br(px(0.))
 6108                    .rounded_tr(px(0.))
 6109                    .border_r_2()
 6110                    .border_color(border_color)
 6111            })
 6112            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 6113            .into_any();
 6114
 6115        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6116
 6117        let mut origin = scrolled_content_origin + point(target_x, target_y)
 6118            - point(
 6119                if flag_on_right {
 6120                    POLE_WIDTH
 6121                } else {
 6122                    size.width - POLE_WIDTH
 6123                },
 6124                size.height - line_height,
 6125            );
 6126
 6127        origin.x = origin.x.max(content_origin.x);
 6128
 6129        element.prepaint_at(origin, window, cx);
 6130
 6131        Some((element, origin))
 6132    }
 6133
 6134    #[allow(clippy::too_many_arguments)]
 6135    fn render_edit_prediction_scroll_popover(
 6136        &mut self,
 6137        to_y: impl Fn(Size<Pixels>) -> Pixels,
 6138        scroll_icon: IconName,
 6139        visible_row_range: Range<DisplayRow>,
 6140        line_layouts: &[LineWithInvisibles],
 6141        newest_selection_head: Option<DisplayPoint>,
 6142        scrolled_content_origin: gpui::Point<Pixels>,
 6143        window: &mut Window,
 6144        cx: &mut App,
 6145    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6146        let mut element = self
 6147            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 6148            .into_any();
 6149
 6150        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6151
 6152        let cursor = newest_selection_head?;
 6153        let cursor_row_layout =
 6154            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6155        let cursor_column = cursor.column() as usize;
 6156
 6157        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6158
 6159        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6160
 6161        element.prepaint_at(origin, window, cx);
 6162        Some((element, origin))
 6163    }
 6164
 6165    #[allow(clippy::too_many_arguments)]
 6166    fn render_edit_prediction_eager_jump_popover(
 6167        &mut self,
 6168        text_bounds: &Bounds<Pixels>,
 6169        content_origin: gpui::Point<Pixels>,
 6170        editor_snapshot: &EditorSnapshot,
 6171        visible_row_range: Range<DisplayRow>,
 6172        scroll_top: f32,
 6173        scroll_bottom: f32,
 6174        line_height: Pixels,
 6175        scroll_pixel_position: gpui::Point<Pixels>,
 6176        target_display_point: DisplayPoint,
 6177        editor_width: Pixels,
 6178        window: &mut Window,
 6179        cx: &mut App,
 6180    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6181        if target_display_point.row().as_f32() < scroll_top {
 6182            let mut element = self
 6183                .render_edit_prediction_line_popover(
 6184                    "Jump to Edit",
 6185                    Some(IconName::ArrowUp),
 6186                    window,
 6187                    cx,
 6188                )?
 6189                .into_any();
 6190
 6191            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6192            let offset = point(
 6193                (text_bounds.size.width - size.width) / 2.,
 6194                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6195            );
 6196
 6197            let origin = text_bounds.origin + offset;
 6198            element.prepaint_at(origin, window, cx);
 6199            Some((element, origin))
 6200        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6201            let mut element = self
 6202                .render_edit_prediction_line_popover(
 6203                    "Jump to Edit",
 6204                    Some(IconName::ArrowDown),
 6205                    window,
 6206                    cx,
 6207                )?
 6208                .into_any();
 6209
 6210            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6211            let offset = point(
 6212                (text_bounds.size.width - size.width) / 2.,
 6213                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6214            );
 6215
 6216            let origin = text_bounds.origin + offset;
 6217            element.prepaint_at(origin, window, cx);
 6218            Some((element, origin))
 6219        } else {
 6220            self.render_edit_prediction_end_of_line_popover(
 6221                "Jump to Edit",
 6222                editor_snapshot,
 6223                visible_row_range,
 6224                target_display_point,
 6225                line_height,
 6226                scroll_pixel_position,
 6227                content_origin,
 6228                editor_width,
 6229                window,
 6230                cx,
 6231            )
 6232        }
 6233    }
 6234
 6235    #[allow(clippy::too_many_arguments)]
 6236    fn render_edit_prediction_end_of_line_popover(
 6237        self: &mut Editor,
 6238        label: &'static str,
 6239        editor_snapshot: &EditorSnapshot,
 6240        visible_row_range: Range<DisplayRow>,
 6241        target_display_point: DisplayPoint,
 6242        line_height: Pixels,
 6243        scroll_pixel_position: gpui::Point<Pixels>,
 6244        content_origin: gpui::Point<Pixels>,
 6245        editor_width: Pixels,
 6246        window: &mut Window,
 6247        cx: &mut App,
 6248    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6249        let target_line_end = DisplayPoint::new(
 6250            target_display_point.row(),
 6251            editor_snapshot.line_len(target_display_point.row()),
 6252        );
 6253
 6254        let mut element = self
 6255            .render_edit_prediction_line_popover(label, None, window, cx)?
 6256            .into_any();
 6257
 6258        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6259
 6260        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 6261
 6262        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 6263        let mut origin = start_point
 6264            + line_origin
 6265            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 6266        origin.x = origin.x.max(content_origin.x);
 6267
 6268        let max_x = content_origin.x + editor_width - size.width;
 6269
 6270        if origin.x > max_x {
 6271            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 6272
 6273            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 6274                origin.y += offset;
 6275                IconName::ArrowUp
 6276            } else {
 6277                origin.y -= offset;
 6278                IconName::ArrowDown
 6279            };
 6280
 6281            element = self
 6282                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 6283                .into_any();
 6284
 6285            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6286
 6287            origin.x = content_origin.x + editor_width - size.width - px(2.);
 6288        }
 6289
 6290        element.prepaint_at(origin, window, cx);
 6291        Some((element, origin))
 6292    }
 6293
 6294    #[allow(clippy::too_many_arguments)]
 6295    fn render_edit_prediction_diff_popover(
 6296        self: &Editor,
 6297        text_bounds: &Bounds<Pixels>,
 6298        content_origin: gpui::Point<Pixels>,
 6299        editor_snapshot: &EditorSnapshot,
 6300        visible_row_range: Range<DisplayRow>,
 6301        line_layouts: &[LineWithInvisibles],
 6302        line_height: Pixels,
 6303        scroll_pixel_position: gpui::Point<Pixels>,
 6304        newest_selection_head: Option<DisplayPoint>,
 6305        editor_width: Pixels,
 6306        style: &EditorStyle,
 6307        edits: &Vec<(Range<Anchor>, String)>,
 6308        edit_preview: &Option<language::EditPreview>,
 6309        snapshot: &language::BufferSnapshot,
 6310        window: &mut Window,
 6311        cx: &mut App,
 6312    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6313        let edit_start = edits
 6314            .first()
 6315            .unwrap()
 6316            .0
 6317            .start
 6318            .to_display_point(editor_snapshot);
 6319        let edit_end = edits
 6320            .last()
 6321            .unwrap()
 6322            .0
 6323            .end
 6324            .to_display_point(editor_snapshot);
 6325
 6326        let is_visible = visible_row_range.contains(&edit_start.row())
 6327            || visible_row_range.contains(&edit_end.row());
 6328        if !is_visible {
 6329            return None;
 6330        }
 6331
 6332        let highlighted_edits =
 6333            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 6334
 6335        let styled_text = highlighted_edits.to_styled_text(&style.text);
 6336        let line_count = highlighted_edits.text.lines().count();
 6337
 6338        const BORDER_WIDTH: Pixels = px(1.);
 6339
 6340        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 6341        let has_keybind = keybind.is_some();
 6342
 6343        let mut element = h_flex()
 6344            .items_start()
 6345            .child(
 6346                h_flex()
 6347                    .bg(cx.theme().colors().editor_background)
 6348                    .border(BORDER_WIDTH)
 6349                    .shadow_sm()
 6350                    .border_color(cx.theme().colors().border)
 6351                    .rounded_l_lg()
 6352                    .when(line_count > 1, |el| el.rounded_br_lg())
 6353                    .pr_1()
 6354                    .child(styled_text),
 6355            )
 6356            .child(
 6357                h_flex()
 6358                    .h(line_height + BORDER_WIDTH * px(2.))
 6359                    .px_1p5()
 6360                    .gap_1()
 6361                    // Workaround: For some reason, there's a gap if we don't do this
 6362                    .ml(-BORDER_WIDTH)
 6363                    .shadow(smallvec![gpui::BoxShadow {
 6364                        color: gpui::black().opacity(0.05),
 6365                        offset: point(px(1.), px(1.)),
 6366                        blur_radius: px(2.),
 6367                        spread_radius: px(0.),
 6368                    }])
 6369                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 6370                    .border(BORDER_WIDTH)
 6371                    .border_color(cx.theme().colors().border)
 6372                    .rounded_r_lg()
 6373                    .id("edit_prediction_diff_popover_keybind")
 6374                    .when(!has_keybind, |el| {
 6375                        let status_colors = cx.theme().status();
 6376
 6377                        el.bg(status_colors.error_background)
 6378                            .border_color(status_colors.error.opacity(0.6))
 6379                            .child(Icon::new(IconName::Info).color(Color::Error))
 6380                            .cursor_default()
 6381                            .hoverable_tooltip(move |_window, cx| {
 6382                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 6383                            })
 6384                    })
 6385                    .children(keybind),
 6386            )
 6387            .into_any();
 6388
 6389        let longest_row =
 6390            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 6391        let longest_line_width = if visible_row_range.contains(&longest_row) {
 6392            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 6393        } else {
 6394            layout_line(
 6395                longest_row,
 6396                editor_snapshot,
 6397                style,
 6398                editor_width,
 6399                |_| false,
 6400                window,
 6401                cx,
 6402            )
 6403            .width
 6404        };
 6405
 6406        let viewport_bounds =
 6407            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 6408                right: -EditorElement::SCROLLBAR_WIDTH,
 6409                ..Default::default()
 6410            });
 6411
 6412        let x_after_longest =
 6413            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 6414                - scroll_pixel_position.x;
 6415
 6416        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6417
 6418        // Fully visible if it can be displayed within the window (allow overlapping other
 6419        // panes). However, this is only allowed if the popover starts within text_bounds.
 6420        let can_position_to_the_right = x_after_longest < text_bounds.right()
 6421            && x_after_longest + element_bounds.width < viewport_bounds.right();
 6422
 6423        let mut origin = if can_position_to_the_right {
 6424            point(
 6425                x_after_longest,
 6426                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 6427                    - scroll_pixel_position.y,
 6428            )
 6429        } else {
 6430            let cursor_row = newest_selection_head.map(|head| head.row());
 6431            let above_edit = edit_start
 6432                .row()
 6433                .0
 6434                .checked_sub(line_count as u32)
 6435                .map(DisplayRow);
 6436            let below_edit = Some(edit_end.row() + 1);
 6437            let above_cursor =
 6438                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 6439            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 6440
 6441            // Place the edit popover adjacent to the edit if there is a location
 6442            // available that is onscreen and does not obscure the cursor. Otherwise,
 6443            // place it adjacent to the cursor.
 6444            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 6445                .into_iter()
 6446                .flatten()
 6447                .find(|&start_row| {
 6448                    let end_row = start_row + line_count as u32;
 6449                    visible_row_range.contains(&start_row)
 6450                        && visible_row_range.contains(&end_row)
 6451                        && cursor_row.map_or(true, |cursor_row| {
 6452                            !((start_row..end_row).contains(&cursor_row))
 6453                        })
 6454                })?;
 6455
 6456            content_origin
 6457                + point(
 6458                    -scroll_pixel_position.x,
 6459                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 6460                )
 6461        };
 6462
 6463        origin.x -= BORDER_WIDTH;
 6464
 6465        window.defer_draw(element, origin, 1);
 6466
 6467        // Do not return an element, since it will already be drawn due to defer_draw.
 6468        None
 6469    }
 6470
 6471    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 6472        px(30.)
 6473    }
 6474
 6475    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 6476        if self.read_only(cx) {
 6477            cx.theme().players().read_only()
 6478        } else {
 6479            self.style.as_ref().unwrap().local_player
 6480        }
 6481    }
 6482
 6483    fn render_edit_prediction_accept_keybind(
 6484        &self,
 6485        window: &mut Window,
 6486        cx: &App,
 6487    ) -> Option<AnyElement> {
 6488        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 6489        let accept_keystroke = accept_binding.keystroke()?;
 6490
 6491        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6492
 6493        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 6494            Color::Accent
 6495        } else {
 6496            Color::Muted
 6497        };
 6498
 6499        h_flex()
 6500            .px_0p5()
 6501            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 6502            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6503            .text_size(TextSize::XSmall.rems(cx))
 6504            .child(h_flex().children(ui::render_modifiers(
 6505                &accept_keystroke.modifiers,
 6506                PlatformStyle::platform(),
 6507                Some(modifiers_color),
 6508                Some(IconSize::XSmall.rems().into()),
 6509                true,
 6510            )))
 6511            .when(is_platform_style_mac, |parent| {
 6512                parent.child(accept_keystroke.key.clone())
 6513            })
 6514            .when(!is_platform_style_mac, |parent| {
 6515                parent.child(
 6516                    Key::new(
 6517                        util::capitalize(&accept_keystroke.key),
 6518                        Some(Color::Default),
 6519                    )
 6520                    .size(Some(IconSize::XSmall.rems().into())),
 6521                )
 6522            })
 6523            .into_any()
 6524            .into()
 6525    }
 6526
 6527    fn render_edit_prediction_line_popover(
 6528        &self,
 6529        label: impl Into<SharedString>,
 6530        icon: Option<IconName>,
 6531        window: &mut Window,
 6532        cx: &App,
 6533    ) -> Option<Stateful<Div>> {
 6534        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 6535
 6536        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 6537        let has_keybind = keybind.is_some();
 6538
 6539        let result = h_flex()
 6540            .id("ep-line-popover")
 6541            .py_0p5()
 6542            .pl_1()
 6543            .pr(padding_right)
 6544            .gap_1()
 6545            .rounded(px(6.))
 6546            .border_1()
 6547            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6548            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 6549            .shadow_sm()
 6550            .when(!has_keybind, |el| {
 6551                let status_colors = cx.theme().status();
 6552
 6553                el.bg(status_colors.error_background)
 6554                    .border_color(status_colors.error.opacity(0.6))
 6555                    .pl_2()
 6556                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 6557                    .cursor_default()
 6558                    .hoverable_tooltip(move |_window, cx| {
 6559                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 6560                    })
 6561            })
 6562            .children(keybind)
 6563            .child(
 6564                Label::new(label)
 6565                    .size(LabelSize::Small)
 6566                    .when(!has_keybind, |el| {
 6567                        el.color(cx.theme().status().error.into()).strikethrough()
 6568                    }),
 6569            )
 6570            .when(!has_keybind, |el| {
 6571                el.child(
 6572                    h_flex().ml_1().child(
 6573                        Icon::new(IconName::Info)
 6574                            .size(IconSize::Small)
 6575                            .color(cx.theme().status().error.into()),
 6576                    ),
 6577                )
 6578            })
 6579            .when_some(icon, |element, icon| {
 6580                element.child(
 6581                    div()
 6582                        .mt(px(1.5))
 6583                        .child(Icon::new(icon).size(IconSize::Small)),
 6584                )
 6585            });
 6586
 6587        Some(result)
 6588    }
 6589
 6590    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 6591        let accent_color = cx.theme().colors().text_accent;
 6592        let editor_bg_color = cx.theme().colors().editor_background;
 6593        editor_bg_color.blend(accent_color.opacity(0.1))
 6594    }
 6595
 6596    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 6597        let accent_color = cx.theme().colors().text_accent;
 6598        let editor_bg_color = cx.theme().colors().editor_background;
 6599        editor_bg_color.blend(accent_color.opacity(0.6))
 6600    }
 6601
 6602    #[allow(clippy::too_many_arguments)]
 6603    fn render_edit_prediction_cursor_popover(
 6604        &self,
 6605        min_width: Pixels,
 6606        max_width: Pixels,
 6607        cursor_point: Point,
 6608        style: &EditorStyle,
 6609        accept_keystroke: Option<&gpui::Keystroke>,
 6610        _window: &Window,
 6611        cx: &mut Context<Editor>,
 6612    ) -> Option<AnyElement> {
 6613        let provider = self.edit_prediction_provider.as_ref()?;
 6614
 6615        if provider.provider.needs_terms_acceptance(cx) {
 6616            return Some(
 6617                h_flex()
 6618                    .min_w(min_width)
 6619                    .flex_1()
 6620                    .px_2()
 6621                    .py_1()
 6622                    .gap_3()
 6623                    .elevation_2(cx)
 6624                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 6625                    .id("accept-terms")
 6626                    .cursor_pointer()
 6627                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 6628                    .on_click(cx.listener(|this, _event, window, cx| {
 6629                        cx.stop_propagation();
 6630                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 6631                        window.dispatch_action(
 6632                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 6633                            cx,
 6634                        );
 6635                    }))
 6636                    .child(
 6637                        h_flex()
 6638                            .flex_1()
 6639                            .gap_2()
 6640                            .child(Icon::new(IconName::ZedPredict))
 6641                            .child(Label::new("Accept Terms of Service"))
 6642                            .child(div().w_full())
 6643                            .child(
 6644                                Icon::new(IconName::ArrowUpRight)
 6645                                    .color(Color::Muted)
 6646                                    .size(IconSize::Small),
 6647                            )
 6648                            .into_any_element(),
 6649                    )
 6650                    .into_any(),
 6651            );
 6652        }
 6653
 6654        let is_refreshing = provider.provider.is_refreshing(cx);
 6655
 6656        fn pending_completion_container() -> Div {
 6657            h_flex()
 6658                .h_full()
 6659                .flex_1()
 6660                .gap_2()
 6661                .child(Icon::new(IconName::ZedPredict))
 6662        }
 6663
 6664        let completion = match &self.active_inline_completion {
 6665            Some(prediction) => {
 6666                if !self.has_visible_completions_menu() {
 6667                    const RADIUS: Pixels = px(6.);
 6668                    const BORDER_WIDTH: Pixels = px(1.);
 6669
 6670                    return Some(
 6671                        h_flex()
 6672                            .elevation_2(cx)
 6673                            .border(BORDER_WIDTH)
 6674                            .border_color(cx.theme().colors().border)
 6675                            .when(accept_keystroke.is_none(), |el| {
 6676                                el.border_color(cx.theme().status().error)
 6677                            })
 6678                            .rounded(RADIUS)
 6679                            .rounded_tl(px(0.))
 6680                            .overflow_hidden()
 6681                            .child(div().px_1p5().child(match &prediction.completion {
 6682                                InlineCompletion::Move { target, snapshot } => {
 6683                                    use text::ToPoint as _;
 6684                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 6685                                    {
 6686                                        Icon::new(IconName::ZedPredictDown)
 6687                                    } else {
 6688                                        Icon::new(IconName::ZedPredictUp)
 6689                                    }
 6690                                }
 6691                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 6692                            }))
 6693                            .child(
 6694                                h_flex()
 6695                                    .gap_1()
 6696                                    .py_1()
 6697                                    .px_2()
 6698                                    .rounded_r(RADIUS - BORDER_WIDTH)
 6699                                    .border_l_1()
 6700                                    .border_color(cx.theme().colors().border)
 6701                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6702                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 6703                                        el.child(
 6704                                            Label::new("Hold")
 6705                                                .size(LabelSize::Small)
 6706                                                .when(accept_keystroke.is_none(), |el| {
 6707                                                    el.strikethrough()
 6708                                                })
 6709                                                .line_height_style(LineHeightStyle::UiLabel),
 6710                                        )
 6711                                    })
 6712                                    .id("edit_prediction_cursor_popover_keybind")
 6713                                    .when(accept_keystroke.is_none(), |el| {
 6714                                        let status_colors = cx.theme().status();
 6715
 6716                                        el.bg(status_colors.error_background)
 6717                                            .border_color(status_colors.error.opacity(0.6))
 6718                                            .child(Icon::new(IconName::Info).color(Color::Error))
 6719                                            .cursor_default()
 6720                                            .hoverable_tooltip(move |_window, cx| {
 6721                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 6722                                                    .into()
 6723                                            })
 6724                                    })
 6725                                    .when_some(
 6726                                        accept_keystroke.as_ref(),
 6727                                        |el, accept_keystroke| {
 6728                                            el.child(h_flex().children(ui::render_modifiers(
 6729                                                &accept_keystroke.modifiers,
 6730                                                PlatformStyle::platform(),
 6731                                                Some(Color::Default),
 6732                                                Some(IconSize::XSmall.rems().into()),
 6733                                                false,
 6734                                            )))
 6735                                        },
 6736                                    ),
 6737                            )
 6738                            .into_any(),
 6739                    );
 6740                }
 6741
 6742                self.render_edit_prediction_cursor_popover_preview(
 6743                    prediction,
 6744                    cursor_point,
 6745                    style,
 6746                    cx,
 6747                )?
 6748            }
 6749
 6750            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 6751                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 6752                    stale_completion,
 6753                    cursor_point,
 6754                    style,
 6755                    cx,
 6756                )?,
 6757
 6758                None => {
 6759                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6760                }
 6761            },
 6762
 6763            None => pending_completion_container().child(Label::new("No Prediction")),
 6764        };
 6765
 6766        let completion = if is_refreshing {
 6767            completion
 6768                .with_animation(
 6769                    "loading-completion",
 6770                    Animation::new(Duration::from_secs(2))
 6771                        .repeat()
 6772                        .with_easing(pulsating_between(0.4, 0.8)),
 6773                    |label, delta| label.opacity(delta),
 6774                )
 6775                .into_any_element()
 6776        } else {
 6777            completion.into_any_element()
 6778        };
 6779
 6780        let has_completion = self.active_inline_completion.is_some();
 6781
 6782        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6783        Some(
 6784            h_flex()
 6785                .min_w(min_width)
 6786                .max_w(max_width)
 6787                .flex_1()
 6788                .elevation_2(cx)
 6789                .border_color(cx.theme().colors().border)
 6790                .child(
 6791                    div()
 6792                        .flex_1()
 6793                        .py_1()
 6794                        .px_2()
 6795                        .overflow_hidden()
 6796                        .child(completion),
 6797                )
 6798                .when_some(accept_keystroke, |el, accept_keystroke| {
 6799                    if !accept_keystroke.modifiers.modified() {
 6800                        return el;
 6801                    }
 6802
 6803                    el.child(
 6804                        h_flex()
 6805                            .h_full()
 6806                            .border_l_1()
 6807                            .rounded_r_lg()
 6808                            .border_color(cx.theme().colors().border)
 6809                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6810                            .gap_1()
 6811                            .py_1()
 6812                            .px_2()
 6813                            .child(
 6814                                h_flex()
 6815                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6816                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6817                                    .child(h_flex().children(ui::render_modifiers(
 6818                                        &accept_keystroke.modifiers,
 6819                                        PlatformStyle::platform(),
 6820                                        Some(if !has_completion {
 6821                                            Color::Muted
 6822                                        } else {
 6823                                            Color::Default
 6824                                        }),
 6825                                        None,
 6826                                        false,
 6827                                    ))),
 6828                            )
 6829                            .child(Label::new("Preview").into_any_element())
 6830                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6831                    )
 6832                })
 6833                .into_any(),
 6834        )
 6835    }
 6836
 6837    fn render_edit_prediction_cursor_popover_preview(
 6838        &self,
 6839        completion: &InlineCompletionState,
 6840        cursor_point: Point,
 6841        style: &EditorStyle,
 6842        cx: &mut Context<Editor>,
 6843    ) -> Option<Div> {
 6844        use text::ToPoint as _;
 6845
 6846        fn render_relative_row_jump(
 6847            prefix: impl Into<String>,
 6848            current_row: u32,
 6849            target_row: u32,
 6850        ) -> Div {
 6851            let (row_diff, arrow) = if target_row < current_row {
 6852                (current_row - target_row, IconName::ArrowUp)
 6853            } else {
 6854                (target_row - current_row, IconName::ArrowDown)
 6855            };
 6856
 6857            h_flex()
 6858                .child(
 6859                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6860                        .color(Color::Muted)
 6861                        .size(LabelSize::Small),
 6862                )
 6863                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6864        }
 6865
 6866        match &completion.completion {
 6867            InlineCompletion::Move {
 6868                target, snapshot, ..
 6869            } => Some(
 6870                h_flex()
 6871                    .px_2()
 6872                    .gap_2()
 6873                    .flex_1()
 6874                    .child(
 6875                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6876                            Icon::new(IconName::ZedPredictDown)
 6877                        } else {
 6878                            Icon::new(IconName::ZedPredictUp)
 6879                        },
 6880                    )
 6881                    .child(Label::new("Jump to Edit")),
 6882            ),
 6883
 6884            InlineCompletion::Edit {
 6885                edits,
 6886                edit_preview,
 6887                snapshot,
 6888                display_mode: _,
 6889            } => {
 6890                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6891
 6892                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6893                    &snapshot,
 6894                    &edits,
 6895                    edit_preview.as_ref()?,
 6896                    true,
 6897                    cx,
 6898                )
 6899                .first_line_preview();
 6900
 6901                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6902                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 6903
 6904                let preview = h_flex()
 6905                    .gap_1()
 6906                    .min_w_16()
 6907                    .child(styled_text)
 6908                    .when(has_more_lines, |parent| parent.child(""));
 6909
 6910                let left = if first_edit_row != cursor_point.row {
 6911                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6912                        .into_any_element()
 6913                } else {
 6914                    Icon::new(IconName::ZedPredict).into_any_element()
 6915                };
 6916
 6917                Some(
 6918                    h_flex()
 6919                        .h_full()
 6920                        .flex_1()
 6921                        .gap_2()
 6922                        .pr_1()
 6923                        .overflow_x_hidden()
 6924                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6925                        .child(left)
 6926                        .child(preview),
 6927                )
 6928            }
 6929        }
 6930    }
 6931
 6932    fn render_context_menu(
 6933        &self,
 6934        style: &EditorStyle,
 6935        max_height_in_lines: u32,
 6936        y_flipped: bool,
 6937        window: &mut Window,
 6938        cx: &mut Context<Editor>,
 6939    ) -> Option<AnyElement> {
 6940        let menu = self.context_menu.borrow();
 6941        let menu = menu.as_ref()?;
 6942        if !menu.visible() {
 6943            return None;
 6944        };
 6945        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6946    }
 6947
 6948    fn render_context_menu_aside(
 6949        &mut self,
 6950        max_size: Size<Pixels>,
 6951        window: &mut Window,
 6952        cx: &mut Context<Editor>,
 6953    ) -> Option<AnyElement> {
 6954        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 6955            if menu.visible() {
 6956                menu.render_aside(self, max_size, window, cx)
 6957            } else {
 6958                None
 6959            }
 6960        })
 6961    }
 6962
 6963    fn hide_context_menu(
 6964        &mut self,
 6965        window: &mut Window,
 6966        cx: &mut Context<Self>,
 6967    ) -> Option<CodeContextMenu> {
 6968        cx.notify();
 6969        self.completion_tasks.clear();
 6970        let context_menu = self.context_menu.borrow_mut().take();
 6971        self.stale_inline_completion_in_menu.take();
 6972        self.update_visible_inline_completion(window, cx);
 6973        context_menu
 6974    }
 6975
 6976    fn show_snippet_choices(
 6977        &mut self,
 6978        choices: &Vec<String>,
 6979        selection: Range<Anchor>,
 6980        cx: &mut Context<Self>,
 6981    ) {
 6982        if selection.start.buffer_id.is_none() {
 6983            return;
 6984        }
 6985        let buffer_id = selection.start.buffer_id.unwrap();
 6986        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6987        let id = post_inc(&mut self.next_completion_id);
 6988
 6989        if let Some(buffer) = buffer {
 6990            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6991                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6992            ));
 6993        }
 6994    }
 6995
 6996    pub fn insert_snippet(
 6997        &mut self,
 6998        insertion_ranges: &[Range<usize>],
 6999        snippet: Snippet,
 7000        window: &mut Window,
 7001        cx: &mut Context<Self>,
 7002    ) -> Result<()> {
 7003        struct Tabstop<T> {
 7004            is_end_tabstop: bool,
 7005            ranges: Vec<Range<T>>,
 7006            choices: Option<Vec<String>>,
 7007        }
 7008
 7009        let tabstops = self.buffer.update(cx, |buffer, cx| {
 7010            let snippet_text: Arc<str> = snippet.text.clone().into();
 7011            buffer.edit(
 7012                insertion_ranges
 7013                    .iter()
 7014                    .cloned()
 7015                    .map(|range| (range, snippet_text.clone())),
 7016                Some(AutoindentMode::EachLine),
 7017                cx,
 7018            );
 7019
 7020            let snapshot = &*buffer.read(cx);
 7021            let snippet = &snippet;
 7022            snippet
 7023                .tabstops
 7024                .iter()
 7025                .map(|tabstop| {
 7026                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 7027                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 7028                    });
 7029                    let mut tabstop_ranges = tabstop
 7030                        .ranges
 7031                        .iter()
 7032                        .flat_map(|tabstop_range| {
 7033                            let mut delta = 0_isize;
 7034                            insertion_ranges.iter().map(move |insertion_range| {
 7035                                let insertion_start = insertion_range.start as isize + delta;
 7036                                delta +=
 7037                                    snippet.text.len() as isize - insertion_range.len() as isize;
 7038
 7039                                let start = ((insertion_start + tabstop_range.start) as usize)
 7040                                    .min(snapshot.len());
 7041                                let end = ((insertion_start + tabstop_range.end) as usize)
 7042                                    .min(snapshot.len());
 7043                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 7044                            })
 7045                        })
 7046                        .collect::<Vec<_>>();
 7047                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 7048
 7049                    Tabstop {
 7050                        is_end_tabstop,
 7051                        ranges: tabstop_ranges,
 7052                        choices: tabstop.choices.clone(),
 7053                    }
 7054                })
 7055                .collect::<Vec<_>>()
 7056        });
 7057        if let Some(tabstop) = tabstops.first() {
 7058            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7059                s.select_ranges(tabstop.ranges.iter().cloned());
 7060            });
 7061
 7062            if let Some(choices) = &tabstop.choices {
 7063                if let Some(selection) = tabstop.ranges.first() {
 7064                    self.show_snippet_choices(choices, selection.clone(), cx)
 7065                }
 7066            }
 7067
 7068            // If we're already at the last tabstop and it's at the end of the snippet,
 7069            // we're done, we don't need to keep the state around.
 7070            if !tabstop.is_end_tabstop {
 7071                let choices = tabstops
 7072                    .iter()
 7073                    .map(|tabstop| tabstop.choices.clone())
 7074                    .collect();
 7075
 7076                let ranges = tabstops
 7077                    .into_iter()
 7078                    .map(|tabstop| tabstop.ranges)
 7079                    .collect::<Vec<_>>();
 7080
 7081                self.snippet_stack.push(SnippetState {
 7082                    active_index: 0,
 7083                    ranges,
 7084                    choices,
 7085                });
 7086            }
 7087
 7088            // Check whether the just-entered snippet ends with an auto-closable bracket.
 7089            if self.autoclose_regions.is_empty() {
 7090                let snapshot = self.buffer.read(cx).snapshot(cx);
 7091                for selection in &mut self.selections.all::<Point>(cx) {
 7092                    let selection_head = selection.head();
 7093                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 7094                        continue;
 7095                    };
 7096
 7097                    let mut bracket_pair = None;
 7098                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 7099                    let prev_chars = snapshot
 7100                        .reversed_chars_at(selection_head)
 7101                        .collect::<String>();
 7102                    for (pair, enabled) in scope.brackets() {
 7103                        if enabled
 7104                            && pair.close
 7105                            && prev_chars.starts_with(pair.start.as_str())
 7106                            && next_chars.starts_with(pair.end.as_str())
 7107                        {
 7108                            bracket_pair = Some(pair.clone());
 7109                            break;
 7110                        }
 7111                    }
 7112                    if let Some(pair) = bracket_pair {
 7113                        let start = snapshot.anchor_after(selection_head);
 7114                        let end = snapshot.anchor_after(selection_head);
 7115                        self.autoclose_regions.push(AutocloseRegion {
 7116                            selection_id: selection.id,
 7117                            range: start..end,
 7118                            pair,
 7119                        });
 7120                    }
 7121                }
 7122            }
 7123        }
 7124        Ok(())
 7125    }
 7126
 7127    pub fn move_to_next_snippet_tabstop(
 7128        &mut self,
 7129        window: &mut Window,
 7130        cx: &mut Context<Self>,
 7131    ) -> bool {
 7132        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 7133    }
 7134
 7135    pub fn move_to_prev_snippet_tabstop(
 7136        &mut self,
 7137        window: &mut Window,
 7138        cx: &mut Context<Self>,
 7139    ) -> bool {
 7140        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 7141    }
 7142
 7143    pub fn move_to_snippet_tabstop(
 7144        &mut self,
 7145        bias: Bias,
 7146        window: &mut Window,
 7147        cx: &mut Context<Self>,
 7148    ) -> bool {
 7149        if let Some(mut snippet) = self.snippet_stack.pop() {
 7150            match bias {
 7151                Bias::Left => {
 7152                    if snippet.active_index > 0 {
 7153                        snippet.active_index -= 1;
 7154                    } else {
 7155                        self.snippet_stack.push(snippet);
 7156                        return false;
 7157                    }
 7158                }
 7159                Bias::Right => {
 7160                    if snippet.active_index + 1 < snippet.ranges.len() {
 7161                        snippet.active_index += 1;
 7162                    } else {
 7163                        self.snippet_stack.push(snippet);
 7164                        return false;
 7165                    }
 7166                }
 7167            }
 7168            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 7169                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7170                    s.select_anchor_ranges(current_ranges.iter().cloned())
 7171                });
 7172
 7173                if let Some(choices) = &snippet.choices[snippet.active_index] {
 7174                    if let Some(selection) = current_ranges.first() {
 7175                        self.show_snippet_choices(&choices, selection.clone(), cx);
 7176                    }
 7177                }
 7178
 7179                // If snippet state is not at the last tabstop, push it back on the stack
 7180                if snippet.active_index + 1 < snippet.ranges.len() {
 7181                    self.snippet_stack.push(snippet);
 7182                }
 7183                return true;
 7184            }
 7185        }
 7186
 7187        false
 7188    }
 7189
 7190    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 7191        self.transact(window, cx, |this, window, cx| {
 7192            this.select_all(&SelectAll, window, cx);
 7193            this.insert("", window, cx);
 7194        });
 7195    }
 7196
 7197    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 7198        self.transact(window, cx, |this, window, cx| {
 7199            this.select_autoclose_pair(window, cx);
 7200            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 7201            if !this.linked_edit_ranges.is_empty() {
 7202                let selections = this.selections.all::<MultiBufferPoint>(cx);
 7203                let snapshot = this.buffer.read(cx).snapshot(cx);
 7204
 7205                for selection in selections.iter() {
 7206                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 7207                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 7208                    if selection_start.buffer_id != selection_end.buffer_id {
 7209                        continue;
 7210                    }
 7211                    if let Some(ranges) =
 7212                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 7213                    {
 7214                        for (buffer, entries) in ranges {
 7215                            linked_ranges.entry(buffer).or_default().extend(entries);
 7216                        }
 7217                    }
 7218                }
 7219            }
 7220
 7221            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7222            if !this.selections.line_mode {
 7223                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 7224                for selection in &mut selections {
 7225                    if selection.is_empty() {
 7226                        let old_head = selection.head();
 7227                        let mut new_head =
 7228                            movement::left(&display_map, old_head.to_display_point(&display_map))
 7229                                .to_point(&display_map);
 7230                        if let Some((buffer, line_buffer_range)) = display_map
 7231                            .buffer_snapshot
 7232                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 7233                        {
 7234                            let indent_size =
 7235                                buffer.indent_size_for_line(line_buffer_range.start.row);
 7236                            let indent_len = match indent_size.kind {
 7237                                IndentKind::Space => {
 7238                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 7239                                }
 7240                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 7241                            };
 7242                            if old_head.column <= indent_size.len && old_head.column > 0 {
 7243                                let indent_len = indent_len.get();
 7244                                new_head = cmp::min(
 7245                                    new_head,
 7246                                    MultiBufferPoint::new(
 7247                                        old_head.row,
 7248                                        ((old_head.column - 1) / indent_len) * indent_len,
 7249                                    ),
 7250                                );
 7251                            }
 7252                        }
 7253
 7254                        selection.set_head(new_head, SelectionGoal::None);
 7255                    }
 7256                }
 7257            }
 7258
 7259            this.signature_help_state.set_backspace_pressed(true);
 7260            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7261                s.select(selections)
 7262            });
 7263            this.insert("", window, cx);
 7264            let empty_str: Arc<str> = Arc::from("");
 7265            for (buffer, edits) in linked_ranges {
 7266                let snapshot = buffer.read(cx).snapshot();
 7267                use text::ToPoint as TP;
 7268
 7269                let edits = edits
 7270                    .into_iter()
 7271                    .map(|range| {
 7272                        let end_point = TP::to_point(&range.end, &snapshot);
 7273                        let mut start_point = TP::to_point(&range.start, &snapshot);
 7274
 7275                        if end_point == start_point {
 7276                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 7277                                .saturating_sub(1);
 7278                            start_point =
 7279                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 7280                        };
 7281
 7282                        (start_point..end_point, empty_str.clone())
 7283                    })
 7284                    .sorted_by_key(|(range, _)| range.start)
 7285                    .collect::<Vec<_>>();
 7286                buffer.update(cx, |this, cx| {
 7287                    this.edit(edits, None, cx);
 7288                })
 7289            }
 7290            this.refresh_inline_completion(true, false, window, cx);
 7291            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 7292        });
 7293    }
 7294
 7295    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 7296        self.transact(window, cx, |this, window, cx| {
 7297            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7298                let line_mode = s.line_mode;
 7299                s.move_with(|map, selection| {
 7300                    if selection.is_empty() && !line_mode {
 7301                        let cursor = movement::right(map, selection.head());
 7302                        selection.end = cursor;
 7303                        selection.reversed = true;
 7304                        selection.goal = SelectionGoal::None;
 7305                    }
 7306                })
 7307            });
 7308            this.insert("", window, cx);
 7309            this.refresh_inline_completion(true, false, window, cx);
 7310        });
 7311    }
 7312
 7313    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 7314        if self.move_to_prev_snippet_tabstop(window, cx) {
 7315            return;
 7316        }
 7317
 7318        self.outdent(&Outdent, window, cx);
 7319    }
 7320
 7321    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 7322        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 7323            return;
 7324        }
 7325
 7326        let mut selections = self.selections.all_adjusted(cx);
 7327        let buffer = self.buffer.read(cx);
 7328        let snapshot = buffer.snapshot(cx);
 7329        let rows_iter = selections.iter().map(|s| s.head().row);
 7330        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 7331
 7332        let mut edits = Vec::new();
 7333        let mut prev_edited_row = 0;
 7334        let mut row_delta = 0;
 7335        for selection in &mut selections {
 7336            if selection.start.row != prev_edited_row {
 7337                row_delta = 0;
 7338            }
 7339            prev_edited_row = selection.end.row;
 7340
 7341            // If the selection is non-empty, then increase the indentation of the selected lines.
 7342            if !selection.is_empty() {
 7343                row_delta =
 7344                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7345                continue;
 7346            }
 7347
 7348            // If the selection is empty and the cursor is in the leading whitespace before the
 7349            // suggested indentation, then auto-indent the line.
 7350            let cursor = selection.head();
 7351            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 7352            if let Some(suggested_indent) =
 7353                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 7354            {
 7355                if cursor.column < suggested_indent.len
 7356                    && cursor.column <= current_indent.len
 7357                    && current_indent.len <= suggested_indent.len
 7358                {
 7359                    selection.start = Point::new(cursor.row, suggested_indent.len);
 7360                    selection.end = selection.start;
 7361                    if row_delta == 0 {
 7362                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 7363                            cursor.row,
 7364                            current_indent,
 7365                            suggested_indent,
 7366                        ));
 7367                        row_delta = suggested_indent.len - current_indent.len;
 7368                    }
 7369                    continue;
 7370                }
 7371            }
 7372
 7373            // Otherwise, insert a hard or soft tab.
 7374            let settings = buffer.language_settings_at(cursor, cx);
 7375            let tab_size = if settings.hard_tabs {
 7376                IndentSize::tab()
 7377            } else {
 7378                let tab_size = settings.tab_size.get();
 7379                let char_column = snapshot
 7380                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 7381                    .flat_map(str::chars)
 7382                    .count()
 7383                    + row_delta as usize;
 7384                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 7385                IndentSize::spaces(chars_to_next_tab_stop)
 7386            };
 7387            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 7388            selection.end = selection.start;
 7389            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 7390            row_delta += tab_size.len;
 7391        }
 7392
 7393        self.transact(window, cx, |this, window, cx| {
 7394            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7395            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7396                s.select(selections)
 7397            });
 7398            this.refresh_inline_completion(true, false, window, cx);
 7399        });
 7400    }
 7401
 7402    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 7403        if self.read_only(cx) {
 7404            return;
 7405        }
 7406        let mut selections = self.selections.all::<Point>(cx);
 7407        let mut prev_edited_row = 0;
 7408        let mut row_delta = 0;
 7409        let mut edits = Vec::new();
 7410        let buffer = self.buffer.read(cx);
 7411        let snapshot = buffer.snapshot(cx);
 7412        for selection in &mut selections {
 7413            if selection.start.row != prev_edited_row {
 7414                row_delta = 0;
 7415            }
 7416            prev_edited_row = selection.end.row;
 7417
 7418            row_delta =
 7419                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7420        }
 7421
 7422        self.transact(window, cx, |this, window, cx| {
 7423            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7424            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7425                s.select(selections)
 7426            });
 7427        });
 7428    }
 7429
 7430    fn indent_selection(
 7431        buffer: &MultiBuffer,
 7432        snapshot: &MultiBufferSnapshot,
 7433        selection: &mut Selection<Point>,
 7434        edits: &mut Vec<(Range<Point>, String)>,
 7435        delta_for_start_row: u32,
 7436        cx: &App,
 7437    ) -> u32 {
 7438        let settings = buffer.language_settings_at(selection.start, cx);
 7439        let tab_size = settings.tab_size.get();
 7440        let indent_kind = if settings.hard_tabs {
 7441            IndentKind::Tab
 7442        } else {
 7443            IndentKind::Space
 7444        };
 7445        let mut start_row = selection.start.row;
 7446        let mut end_row = selection.end.row + 1;
 7447
 7448        // If a selection ends at the beginning of a line, don't indent
 7449        // that last line.
 7450        if selection.end.column == 0 && selection.end.row > selection.start.row {
 7451            end_row -= 1;
 7452        }
 7453
 7454        // Avoid re-indenting a row that has already been indented by a
 7455        // previous selection, but still update this selection's column
 7456        // to reflect that indentation.
 7457        if delta_for_start_row > 0 {
 7458            start_row += 1;
 7459            selection.start.column += delta_for_start_row;
 7460            if selection.end.row == selection.start.row {
 7461                selection.end.column += delta_for_start_row;
 7462            }
 7463        }
 7464
 7465        let mut delta_for_end_row = 0;
 7466        let has_multiple_rows = start_row + 1 != end_row;
 7467        for row in start_row..end_row {
 7468            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 7469            let indent_delta = match (current_indent.kind, indent_kind) {
 7470                (IndentKind::Space, IndentKind::Space) => {
 7471                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 7472                    IndentSize::spaces(columns_to_next_tab_stop)
 7473                }
 7474                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 7475                (_, IndentKind::Tab) => IndentSize::tab(),
 7476            };
 7477
 7478            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 7479                0
 7480            } else {
 7481                selection.start.column
 7482            };
 7483            let row_start = Point::new(row, start);
 7484            edits.push((
 7485                row_start..row_start,
 7486                indent_delta.chars().collect::<String>(),
 7487            ));
 7488
 7489            // Update this selection's endpoints to reflect the indentation.
 7490            if row == selection.start.row {
 7491                selection.start.column += indent_delta.len;
 7492            }
 7493            if row == selection.end.row {
 7494                selection.end.column += indent_delta.len;
 7495                delta_for_end_row = indent_delta.len;
 7496            }
 7497        }
 7498
 7499        if selection.start.row == selection.end.row {
 7500            delta_for_start_row + delta_for_end_row
 7501        } else {
 7502            delta_for_end_row
 7503        }
 7504    }
 7505
 7506    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 7507        if self.read_only(cx) {
 7508            return;
 7509        }
 7510        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7511        let selections = self.selections.all::<Point>(cx);
 7512        let mut deletion_ranges = Vec::new();
 7513        let mut last_outdent = None;
 7514        {
 7515            let buffer = self.buffer.read(cx);
 7516            let snapshot = buffer.snapshot(cx);
 7517            for selection in &selections {
 7518                let settings = buffer.language_settings_at(selection.start, cx);
 7519                let tab_size = settings.tab_size.get();
 7520                let mut rows = selection.spanned_rows(false, &display_map);
 7521
 7522                // Avoid re-outdenting a row that has already been outdented by a
 7523                // previous selection.
 7524                if let Some(last_row) = last_outdent {
 7525                    if last_row == rows.start {
 7526                        rows.start = rows.start.next_row();
 7527                    }
 7528                }
 7529                let has_multiple_rows = rows.len() > 1;
 7530                for row in rows.iter_rows() {
 7531                    let indent_size = snapshot.indent_size_for_line(row);
 7532                    if indent_size.len > 0 {
 7533                        let deletion_len = match indent_size.kind {
 7534                            IndentKind::Space => {
 7535                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 7536                                if columns_to_prev_tab_stop == 0 {
 7537                                    tab_size
 7538                                } else {
 7539                                    columns_to_prev_tab_stop
 7540                                }
 7541                            }
 7542                            IndentKind::Tab => 1,
 7543                        };
 7544                        let start = if has_multiple_rows
 7545                            || deletion_len > selection.start.column
 7546                            || indent_size.len < selection.start.column
 7547                        {
 7548                            0
 7549                        } else {
 7550                            selection.start.column - deletion_len
 7551                        };
 7552                        deletion_ranges.push(
 7553                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 7554                        );
 7555                        last_outdent = Some(row);
 7556                    }
 7557                }
 7558            }
 7559        }
 7560
 7561        self.transact(window, cx, |this, window, cx| {
 7562            this.buffer.update(cx, |buffer, cx| {
 7563                let empty_str: Arc<str> = Arc::default();
 7564                buffer.edit(
 7565                    deletion_ranges
 7566                        .into_iter()
 7567                        .map(|range| (range, empty_str.clone())),
 7568                    None,
 7569                    cx,
 7570                );
 7571            });
 7572            let selections = this.selections.all::<usize>(cx);
 7573            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7574                s.select(selections)
 7575            });
 7576        });
 7577    }
 7578
 7579    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 7580        if self.read_only(cx) {
 7581            return;
 7582        }
 7583        let selections = self
 7584            .selections
 7585            .all::<usize>(cx)
 7586            .into_iter()
 7587            .map(|s| s.range());
 7588
 7589        self.transact(window, cx, |this, window, cx| {
 7590            this.buffer.update(cx, |buffer, cx| {
 7591                buffer.autoindent_ranges(selections, cx);
 7592            });
 7593            let selections = this.selections.all::<usize>(cx);
 7594            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7595                s.select(selections)
 7596            });
 7597        });
 7598    }
 7599
 7600    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 7601        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7602        let selections = self.selections.all::<Point>(cx);
 7603
 7604        let mut new_cursors = Vec::new();
 7605        let mut edit_ranges = Vec::new();
 7606        let mut selections = selections.iter().peekable();
 7607        while let Some(selection) = selections.next() {
 7608            let mut rows = selection.spanned_rows(false, &display_map);
 7609            let goal_display_column = selection.head().to_display_point(&display_map).column();
 7610
 7611            // Accumulate contiguous regions of rows that we want to delete.
 7612            while let Some(next_selection) = selections.peek() {
 7613                let next_rows = next_selection.spanned_rows(false, &display_map);
 7614                if next_rows.start <= rows.end {
 7615                    rows.end = next_rows.end;
 7616                    selections.next().unwrap();
 7617                } else {
 7618                    break;
 7619                }
 7620            }
 7621
 7622            let buffer = &display_map.buffer_snapshot;
 7623            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 7624            let edit_end;
 7625            let cursor_buffer_row;
 7626            if buffer.max_point().row >= rows.end.0 {
 7627                // If there's a line after the range, delete the \n from the end of the row range
 7628                // and position the cursor on the next line.
 7629                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 7630                cursor_buffer_row = rows.end;
 7631            } else {
 7632                // If there isn't a line after the range, delete the \n from the line before the
 7633                // start of the row range and position the cursor there.
 7634                edit_start = edit_start.saturating_sub(1);
 7635                edit_end = buffer.len();
 7636                cursor_buffer_row = rows.start.previous_row();
 7637            }
 7638
 7639            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 7640            *cursor.column_mut() =
 7641                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 7642
 7643            new_cursors.push((
 7644                selection.id,
 7645                buffer.anchor_after(cursor.to_point(&display_map)),
 7646            ));
 7647            edit_ranges.push(edit_start..edit_end);
 7648        }
 7649
 7650        self.transact(window, cx, |this, window, cx| {
 7651            let buffer = this.buffer.update(cx, |buffer, cx| {
 7652                let empty_str: Arc<str> = Arc::default();
 7653                buffer.edit(
 7654                    edit_ranges
 7655                        .into_iter()
 7656                        .map(|range| (range, empty_str.clone())),
 7657                    None,
 7658                    cx,
 7659                );
 7660                buffer.snapshot(cx)
 7661            });
 7662            let new_selections = new_cursors
 7663                .into_iter()
 7664                .map(|(id, cursor)| {
 7665                    let cursor = cursor.to_point(&buffer);
 7666                    Selection {
 7667                        id,
 7668                        start: cursor,
 7669                        end: cursor,
 7670                        reversed: false,
 7671                        goal: SelectionGoal::None,
 7672                    }
 7673                })
 7674                .collect();
 7675
 7676            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7677                s.select(new_selections);
 7678            });
 7679        });
 7680    }
 7681
 7682    pub fn join_lines_impl(
 7683        &mut self,
 7684        insert_whitespace: bool,
 7685        window: &mut Window,
 7686        cx: &mut Context<Self>,
 7687    ) {
 7688        if self.read_only(cx) {
 7689            return;
 7690        }
 7691        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 7692        for selection in self.selections.all::<Point>(cx) {
 7693            let start = MultiBufferRow(selection.start.row);
 7694            // Treat single line selections as if they include the next line. Otherwise this action
 7695            // would do nothing for single line selections individual cursors.
 7696            let end = if selection.start.row == selection.end.row {
 7697                MultiBufferRow(selection.start.row + 1)
 7698            } else {
 7699                MultiBufferRow(selection.end.row)
 7700            };
 7701
 7702            if let Some(last_row_range) = row_ranges.last_mut() {
 7703                if start <= last_row_range.end {
 7704                    last_row_range.end = end;
 7705                    continue;
 7706                }
 7707            }
 7708            row_ranges.push(start..end);
 7709        }
 7710
 7711        let snapshot = self.buffer.read(cx).snapshot(cx);
 7712        let mut cursor_positions = Vec::new();
 7713        for row_range in &row_ranges {
 7714            let anchor = snapshot.anchor_before(Point::new(
 7715                row_range.end.previous_row().0,
 7716                snapshot.line_len(row_range.end.previous_row()),
 7717            ));
 7718            cursor_positions.push(anchor..anchor);
 7719        }
 7720
 7721        self.transact(window, cx, |this, window, cx| {
 7722            for row_range in row_ranges.into_iter().rev() {
 7723                for row in row_range.iter_rows().rev() {
 7724                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 7725                    let next_line_row = row.next_row();
 7726                    let indent = snapshot.indent_size_for_line(next_line_row);
 7727                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7728
 7729                    let replace =
 7730                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7731                            " "
 7732                        } else {
 7733                            ""
 7734                        };
 7735
 7736                    this.buffer.update(cx, |buffer, cx| {
 7737                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7738                    });
 7739                }
 7740            }
 7741
 7742            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7743                s.select_anchor_ranges(cursor_positions)
 7744            });
 7745        });
 7746    }
 7747
 7748    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7749        self.join_lines_impl(true, window, cx);
 7750    }
 7751
 7752    pub fn sort_lines_case_sensitive(
 7753        &mut self,
 7754        _: &SortLinesCaseSensitive,
 7755        window: &mut Window,
 7756        cx: &mut Context<Self>,
 7757    ) {
 7758        self.manipulate_lines(window, cx, |lines| lines.sort())
 7759    }
 7760
 7761    pub fn sort_lines_case_insensitive(
 7762        &mut self,
 7763        _: &SortLinesCaseInsensitive,
 7764        window: &mut Window,
 7765        cx: &mut Context<Self>,
 7766    ) {
 7767        self.manipulate_lines(window, cx, |lines| {
 7768            lines.sort_by_key(|line| line.to_lowercase())
 7769        })
 7770    }
 7771
 7772    pub fn unique_lines_case_insensitive(
 7773        &mut self,
 7774        _: &UniqueLinesCaseInsensitive,
 7775        window: &mut Window,
 7776        cx: &mut Context<Self>,
 7777    ) {
 7778        self.manipulate_lines(window, cx, |lines| {
 7779            let mut seen = HashSet::default();
 7780            lines.retain(|line| seen.insert(line.to_lowercase()));
 7781        })
 7782    }
 7783
 7784    pub fn unique_lines_case_sensitive(
 7785        &mut self,
 7786        _: &UniqueLinesCaseSensitive,
 7787        window: &mut Window,
 7788        cx: &mut Context<Self>,
 7789    ) {
 7790        self.manipulate_lines(window, cx, |lines| {
 7791            let mut seen = HashSet::default();
 7792            lines.retain(|line| seen.insert(*line));
 7793        })
 7794    }
 7795
 7796    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7797        let Some(project) = self.project.clone() else {
 7798            return;
 7799        };
 7800        self.reload(project, window, cx)
 7801            .detach_and_notify_err(window, cx);
 7802    }
 7803
 7804    pub fn restore_file(
 7805        &mut self,
 7806        _: &::git::RestoreFile,
 7807        window: &mut Window,
 7808        cx: &mut Context<Self>,
 7809    ) {
 7810        let mut buffer_ids = HashSet::default();
 7811        let snapshot = self.buffer().read(cx).snapshot(cx);
 7812        for selection in self.selections.all::<usize>(cx) {
 7813            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 7814        }
 7815
 7816        let buffer = self.buffer().read(cx);
 7817        let ranges = buffer_ids
 7818            .into_iter()
 7819            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 7820            .collect::<Vec<_>>();
 7821
 7822        self.restore_hunks_in_ranges(ranges, window, cx);
 7823    }
 7824
 7825    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 7826        let selections = self
 7827            .selections
 7828            .all(cx)
 7829            .into_iter()
 7830            .map(|s| s.range())
 7831            .collect();
 7832        self.restore_hunks_in_ranges(selections, window, cx);
 7833    }
 7834
 7835    fn restore_hunks_in_ranges(
 7836        &mut self,
 7837        ranges: Vec<Range<Point>>,
 7838        window: &mut Window,
 7839        cx: &mut Context<Editor>,
 7840    ) {
 7841        let mut revert_changes = HashMap::default();
 7842        let chunk_by = self
 7843            .snapshot(window, cx)
 7844            .hunks_for_ranges(ranges)
 7845            .into_iter()
 7846            .chunk_by(|hunk| hunk.buffer_id);
 7847        for (buffer_id, hunks) in &chunk_by {
 7848            let hunks = hunks.collect::<Vec<_>>();
 7849            for hunk in &hunks {
 7850                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 7851            }
 7852            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 7853        }
 7854        drop(chunk_by);
 7855        if !revert_changes.is_empty() {
 7856            self.transact(window, cx, |editor, window, cx| {
 7857                editor.restore(revert_changes, window, cx);
 7858            });
 7859        }
 7860    }
 7861
 7862    pub fn open_active_item_in_terminal(
 7863        &mut self,
 7864        _: &OpenInTerminal,
 7865        window: &mut Window,
 7866        cx: &mut Context<Self>,
 7867    ) {
 7868        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7869            let project_path = buffer.read(cx).project_path(cx)?;
 7870            let project = self.project.as_ref()?.read(cx);
 7871            let entry = project.entry_for_path(&project_path, cx)?;
 7872            let parent = match &entry.canonical_path {
 7873                Some(canonical_path) => canonical_path.to_path_buf(),
 7874                None => project.absolute_path(&project_path, cx)?,
 7875            }
 7876            .parent()?
 7877            .to_path_buf();
 7878            Some(parent)
 7879        }) {
 7880            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7881        }
 7882    }
 7883
 7884    pub fn prepare_restore_change(
 7885        &self,
 7886        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7887        hunk: &MultiBufferDiffHunk,
 7888        cx: &mut App,
 7889    ) -> Option<()> {
 7890        let buffer = self.buffer.read(cx);
 7891        let diff = buffer.diff_for(hunk.buffer_id)?;
 7892        let buffer = buffer.buffer(hunk.buffer_id)?;
 7893        let buffer = buffer.read(cx);
 7894        let original_text = diff
 7895            .read(cx)
 7896            .base_text()
 7897            .as_rope()
 7898            .slice(hunk.diff_base_byte_range.clone());
 7899        let buffer_snapshot = buffer.snapshot();
 7900        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7901        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7902            probe
 7903                .0
 7904                .start
 7905                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7906                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7907        }) {
 7908            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7909            Some(())
 7910        } else {
 7911            None
 7912        }
 7913    }
 7914
 7915    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7916        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7917    }
 7918
 7919    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7920        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7921    }
 7922
 7923    fn manipulate_lines<Fn>(
 7924        &mut self,
 7925        window: &mut Window,
 7926        cx: &mut Context<Self>,
 7927        mut callback: Fn,
 7928    ) where
 7929        Fn: FnMut(&mut Vec<&str>),
 7930    {
 7931        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7932        let buffer = self.buffer.read(cx).snapshot(cx);
 7933
 7934        let mut edits = Vec::new();
 7935
 7936        let selections = self.selections.all::<Point>(cx);
 7937        let mut selections = selections.iter().peekable();
 7938        let mut contiguous_row_selections = Vec::new();
 7939        let mut new_selections = Vec::new();
 7940        let mut added_lines = 0;
 7941        let mut removed_lines = 0;
 7942
 7943        while let Some(selection) = selections.next() {
 7944            let (start_row, end_row) = consume_contiguous_rows(
 7945                &mut contiguous_row_selections,
 7946                selection,
 7947                &display_map,
 7948                &mut selections,
 7949            );
 7950
 7951            let start_point = Point::new(start_row.0, 0);
 7952            let end_point = Point::new(
 7953                end_row.previous_row().0,
 7954                buffer.line_len(end_row.previous_row()),
 7955            );
 7956            let text = buffer
 7957                .text_for_range(start_point..end_point)
 7958                .collect::<String>();
 7959
 7960            let mut lines = text.split('\n').collect_vec();
 7961
 7962            let lines_before = lines.len();
 7963            callback(&mut lines);
 7964            let lines_after = lines.len();
 7965
 7966            edits.push((start_point..end_point, lines.join("\n")));
 7967
 7968            // Selections must change based on added and removed line count
 7969            let start_row =
 7970                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7971            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7972            new_selections.push(Selection {
 7973                id: selection.id,
 7974                start: start_row,
 7975                end: end_row,
 7976                goal: SelectionGoal::None,
 7977                reversed: selection.reversed,
 7978            });
 7979
 7980            if lines_after > lines_before {
 7981                added_lines += lines_after - lines_before;
 7982            } else if lines_before > lines_after {
 7983                removed_lines += lines_before - lines_after;
 7984            }
 7985        }
 7986
 7987        self.transact(window, cx, |this, window, cx| {
 7988            let buffer = this.buffer.update(cx, |buffer, cx| {
 7989                buffer.edit(edits, None, cx);
 7990                buffer.snapshot(cx)
 7991            });
 7992
 7993            // Recalculate offsets on newly edited buffer
 7994            let new_selections = new_selections
 7995                .iter()
 7996                .map(|s| {
 7997                    let start_point = Point::new(s.start.0, 0);
 7998                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7999                    Selection {
 8000                        id: s.id,
 8001                        start: buffer.point_to_offset(start_point),
 8002                        end: buffer.point_to_offset(end_point),
 8003                        goal: s.goal,
 8004                        reversed: s.reversed,
 8005                    }
 8006                })
 8007                .collect();
 8008
 8009            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8010                s.select(new_selections);
 8011            });
 8012
 8013            this.request_autoscroll(Autoscroll::fit(), cx);
 8014        });
 8015    }
 8016
 8017    pub fn convert_to_upper_case(
 8018        &mut self,
 8019        _: &ConvertToUpperCase,
 8020        window: &mut Window,
 8021        cx: &mut Context<Self>,
 8022    ) {
 8023        self.manipulate_text(window, cx, |text| text.to_uppercase())
 8024    }
 8025
 8026    pub fn convert_to_lower_case(
 8027        &mut self,
 8028        _: &ConvertToLowerCase,
 8029        window: &mut Window,
 8030        cx: &mut Context<Self>,
 8031    ) {
 8032        self.manipulate_text(window, cx, |text| text.to_lowercase())
 8033    }
 8034
 8035    pub fn convert_to_title_case(
 8036        &mut self,
 8037        _: &ConvertToTitleCase,
 8038        window: &mut Window,
 8039        cx: &mut Context<Self>,
 8040    ) {
 8041        self.manipulate_text(window, cx, |text| {
 8042            text.split('\n')
 8043                .map(|line| line.to_case(Case::Title))
 8044                .join("\n")
 8045        })
 8046    }
 8047
 8048    pub fn convert_to_snake_case(
 8049        &mut self,
 8050        _: &ConvertToSnakeCase,
 8051        window: &mut Window,
 8052        cx: &mut Context<Self>,
 8053    ) {
 8054        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 8055    }
 8056
 8057    pub fn convert_to_kebab_case(
 8058        &mut self,
 8059        _: &ConvertToKebabCase,
 8060        window: &mut Window,
 8061        cx: &mut Context<Self>,
 8062    ) {
 8063        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 8064    }
 8065
 8066    pub fn convert_to_upper_camel_case(
 8067        &mut self,
 8068        _: &ConvertToUpperCamelCase,
 8069        window: &mut Window,
 8070        cx: &mut Context<Self>,
 8071    ) {
 8072        self.manipulate_text(window, cx, |text| {
 8073            text.split('\n')
 8074                .map(|line| line.to_case(Case::UpperCamel))
 8075                .join("\n")
 8076        })
 8077    }
 8078
 8079    pub fn convert_to_lower_camel_case(
 8080        &mut self,
 8081        _: &ConvertToLowerCamelCase,
 8082        window: &mut Window,
 8083        cx: &mut Context<Self>,
 8084    ) {
 8085        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 8086    }
 8087
 8088    pub fn convert_to_opposite_case(
 8089        &mut self,
 8090        _: &ConvertToOppositeCase,
 8091        window: &mut Window,
 8092        cx: &mut Context<Self>,
 8093    ) {
 8094        self.manipulate_text(window, cx, |text| {
 8095            text.chars()
 8096                .fold(String::with_capacity(text.len()), |mut t, c| {
 8097                    if c.is_uppercase() {
 8098                        t.extend(c.to_lowercase());
 8099                    } else {
 8100                        t.extend(c.to_uppercase());
 8101                    }
 8102                    t
 8103                })
 8104        })
 8105    }
 8106
 8107    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 8108    where
 8109        Fn: FnMut(&str) -> String,
 8110    {
 8111        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8112        let buffer = self.buffer.read(cx).snapshot(cx);
 8113
 8114        let mut new_selections = Vec::new();
 8115        let mut edits = Vec::new();
 8116        let mut selection_adjustment = 0i32;
 8117
 8118        for selection in self.selections.all::<usize>(cx) {
 8119            let selection_is_empty = selection.is_empty();
 8120
 8121            let (start, end) = if selection_is_empty {
 8122                let word_range = movement::surrounding_word(
 8123                    &display_map,
 8124                    selection.start.to_display_point(&display_map),
 8125                );
 8126                let start = word_range.start.to_offset(&display_map, Bias::Left);
 8127                let end = word_range.end.to_offset(&display_map, Bias::Left);
 8128                (start, end)
 8129            } else {
 8130                (selection.start, selection.end)
 8131            };
 8132
 8133            let text = buffer.text_for_range(start..end).collect::<String>();
 8134            let old_length = text.len() as i32;
 8135            let text = callback(&text);
 8136
 8137            new_selections.push(Selection {
 8138                start: (start as i32 - selection_adjustment) as usize,
 8139                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 8140                goal: SelectionGoal::None,
 8141                ..selection
 8142            });
 8143
 8144            selection_adjustment += old_length - text.len() as i32;
 8145
 8146            edits.push((start..end, text));
 8147        }
 8148
 8149        self.transact(window, cx, |this, window, cx| {
 8150            this.buffer.update(cx, |buffer, cx| {
 8151                buffer.edit(edits, None, cx);
 8152            });
 8153
 8154            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8155                s.select(new_selections);
 8156            });
 8157
 8158            this.request_autoscroll(Autoscroll::fit(), cx);
 8159        });
 8160    }
 8161
 8162    pub fn duplicate(
 8163        &mut self,
 8164        upwards: bool,
 8165        whole_lines: bool,
 8166        window: &mut Window,
 8167        cx: &mut Context<Self>,
 8168    ) {
 8169        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8170        let buffer = &display_map.buffer_snapshot;
 8171        let selections = self.selections.all::<Point>(cx);
 8172
 8173        let mut edits = Vec::new();
 8174        let mut selections_iter = selections.iter().peekable();
 8175        while let Some(selection) = selections_iter.next() {
 8176            let mut rows = selection.spanned_rows(false, &display_map);
 8177            // duplicate line-wise
 8178            if whole_lines || selection.start == selection.end {
 8179                // Avoid duplicating the same lines twice.
 8180                while let Some(next_selection) = selections_iter.peek() {
 8181                    let next_rows = next_selection.spanned_rows(false, &display_map);
 8182                    if next_rows.start < rows.end {
 8183                        rows.end = next_rows.end;
 8184                        selections_iter.next().unwrap();
 8185                    } else {
 8186                        break;
 8187                    }
 8188                }
 8189
 8190                // Copy the text from the selected row region and splice it either at the start
 8191                // or end of the region.
 8192                let start = Point::new(rows.start.0, 0);
 8193                let end = Point::new(
 8194                    rows.end.previous_row().0,
 8195                    buffer.line_len(rows.end.previous_row()),
 8196                );
 8197                let text = buffer
 8198                    .text_for_range(start..end)
 8199                    .chain(Some("\n"))
 8200                    .collect::<String>();
 8201                let insert_location = if upwards {
 8202                    Point::new(rows.end.0, 0)
 8203                } else {
 8204                    start
 8205                };
 8206                edits.push((insert_location..insert_location, text));
 8207            } else {
 8208                // duplicate character-wise
 8209                let start = selection.start;
 8210                let end = selection.end;
 8211                let text = buffer.text_for_range(start..end).collect::<String>();
 8212                edits.push((selection.end..selection.end, text));
 8213            }
 8214        }
 8215
 8216        self.transact(window, cx, |this, _, cx| {
 8217            this.buffer.update(cx, |buffer, cx| {
 8218                buffer.edit(edits, None, cx);
 8219            });
 8220
 8221            this.request_autoscroll(Autoscroll::fit(), cx);
 8222        });
 8223    }
 8224
 8225    pub fn duplicate_line_up(
 8226        &mut self,
 8227        _: &DuplicateLineUp,
 8228        window: &mut Window,
 8229        cx: &mut Context<Self>,
 8230    ) {
 8231        self.duplicate(true, true, window, cx);
 8232    }
 8233
 8234    pub fn duplicate_line_down(
 8235        &mut self,
 8236        _: &DuplicateLineDown,
 8237        window: &mut Window,
 8238        cx: &mut Context<Self>,
 8239    ) {
 8240        self.duplicate(false, true, window, cx);
 8241    }
 8242
 8243    pub fn duplicate_selection(
 8244        &mut self,
 8245        _: &DuplicateSelection,
 8246        window: &mut Window,
 8247        cx: &mut Context<Self>,
 8248    ) {
 8249        self.duplicate(false, false, window, cx);
 8250    }
 8251
 8252    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 8253        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8254        let buffer = self.buffer.read(cx).snapshot(cx);
 8255
 8256        let mut edits = Vec::new();
 8257        let mut unfold_ranges = Vec::new();
 8258        let mut refold_creases = Vec::new();
 8259
 8260        let selections = self.selections.all::<Point>(cx);
 8261        let mut selections = selections.iter().peekable();
 8262        let mut contiguous_row_selections = Vec::new();
 8263        let mut new_selections = Vec::new();
 8264
 8265        while let Some(selection) = selections.next() {
 8266            // Find all the selections that span a contiguous row range
 8267            let (start_row, end_row) = consume_contiguous_rows(
 8268                &mut contiguous_row_selections,
 8269                selection,
 8270                &display_map,
 8271                &mut selections,
 8272            );
 8273
 8274            // Move the text spanned by the row range to be before the line preceding the row range
 8275            if start_row.0 > 0 {
 8276                let range_to_move = Point::new(
 8277                    start_row.previous_row().0,
 8278                    buffer.line_len(start_row.previous_row()),
 8279                )
 8280                    ..Point::new(
 8281                        end_row.previous_row().0,
 8282                        buffer.line_len(end_row.previous_row()),
 8283                    );
 8284                let insertion_point = display_map
 8285                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 8286                    .0;
 8287
 8288                // Don't move lines across excerpts
 8289                if buffer
 8290                    .excerpt_containing(insertion_point..range_to_move.end)
 8291                    .is_some()
 8292                {
 8293                    let text = buffer
 8294                        .text_for_range(range_to_move.clone())
 8295                        .flat_map(|s| s.chars())
 8296                        .skip(1)
 8297                        .chain(['\n'])
 8298                        .collect::<String>();
 8299
 8300                    edits.push((
 8301                        buffer.anchor_after(range_to_move.start)
 8302                            ..buffer.anchor_before(range_to_move.end),
 8303                        String::new(),
 8304                    ));
 8305                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8306                    edits.push((insertion_anchor..insertion_anchor, text));
 8307
 8308                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 8309
 8310                    // Move selections up
 8311                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8312                        |mut selection| {
 8313                            selection.start.row -= row_delta;
 8314                            selection.end.row -= row_delta;
 8315                            selection
 8316                        },
 8317                    ));
 8318
 8319                    // Move folds up
 8320                    unfold_ranges.push(range_to_move.clone());
 8321                    for fold in display_map.folds_in_range(
 8322                        buffer.anchor_before(range_to_move.start)
 8323                            ..buffer.anchor_after(range_to_move.end),
 8324                    ) {
 8325                        let mut start = fold.range.start.to_point(&buffer);
 8326                        let mut end = fold.range.end.to_point(&buffer);
 8327                        start.row -= row_delta;
 8328                        end.row -= row_delta;
 8329                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8330                    }
 8331                }
 8332            }
 8333
 8334            // If we didn't move line(s), preserve the existing selections
 8335            new_selections.append(&mut contiguous_row_selections);
 8336        }
 8337
 8338        self.transact(window, cx, |this, window, cx| {
 8339            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8340            this.buffer.update(cx, |buffer, cx| {
 8341                for (range, text) in edits {
 8342                    buffer.edit([(range, text)], None, cx);
 8343                }
 8344            });
 8345            this.fold_creases(refold_creases, true, window, cx);
 8346            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8347                s.select(new_selections);
 8348            })
 8349        });
 8350    }
 8351
 8352    pub fn move_line_down(
 8353        &mut self,
 8354        _: &MoveLineDown,
 8355        window: &mut Window,
 8356        cx: &mut Context<Self>,
 8357    ) {
 8358        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8359        let buffer = self.buffer.read(cx).snapshot(cx);
 8360
 8361        let mut edits = Vec::new();
 8362        let mut unfold_ranges = Vec::new();
 8363        let mut refold_creases = Vec::new();
 8364
 8365        let selections = self.selections.all::<Point>(cx);
 8366        let mut selections = selections.iter().peekable();
 8367        let mut contiguous_row_selections = Vec::new();
 8368        let mut new_selections = Vec::new();
 8369
 8370        while let Some(selection) = selections.next() {
 8371            // Find all the selections that span a contiguous row range
 8372            let (start_row, end_row) = consume_contiguous_rows(
 8373                &mut contiguous_row_selections,
 8374                selection,
 8375                &display_map,
 8376                &mut selections,
 8377            );
 8378
 8379            // Move the text spanned by the row range to be after the last line of the row range
 8380            if end_row.0 <= buffer.max_point().row {
 8381                let range_to_move =
 8382                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 8383                let insertion_point = display_map
 8384                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 8385                    .0;
 8386
 8387                // Don't move lines across excerpt boundaries
 8388                if buffer
 8389                    .excerpt_containing(range_to_move.start..insertion_point)
 8390                    .is_some()
 8391                {
 8392                    let mut text = String::from("\n");
 8393                    text.extend(buffer.text_for_range(range_to_move.clone()));
 8394                    text.pop(); // Drop trailing newline
 8395                    edits.push((
 8396                        buffer.anchor_after(range_to_move.start)
 8397                            ..buffer.anchor_before(range_to_move.end),
 8398                        String::new(),
 8399                    ));
 8400                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8401                    edits.push((insertion_anchor..insertion_anchor, text));
 8402
 8403                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 8404
 8405                    // Move selections down
 8406                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8407                        |mut selection| {
 8408                            selection.start.row += row_delta;
 8409                            selection.end.row += row_delta;
 8410                            selection
 8411                        },
 8412                    ));
 8413
 8414                    // Move folds down
 8415                    unfold_ranges.push(range_to_move.clone());
 8416                    for fold in display_map.folds_in_range(
 8417                        buffer.anchor_before(range_to_move.start)
 8418                            ..buffer.anchor_after(range_to_move.end),
 8419                    ) {
 8420                        let mut start = fold.range.start.to_point(&buffer);
 8421                        let mut end = fold.range.end.to_point(&buffer);
 8422                        start.row += row_delta;
 8423                        end.row += row_delta;
 8424                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8425                    }
 8426                }
 8427            }
 8428
 8429            // If we didn't move line(s), preserve the existing selections
 8430            new_selections.append(&mut contiguous_row_selections);
 8431        }
 8432
 8433        self.transact(window, cx, |this, window, cx| {
 8434            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8435            this.buffer.update(cx, |buffer, cx| {
 8436                for (range, text) in edits {
 8437                    buffer.edit([(range, text)], None, cx);
 8438                }
 8439            });
 8440            this.fold_creases(refold_creases, true, window, cx);
 8441            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8442                s.select(new_selections)
 8443            });
 8444        });
 8445    }
 8446
 8447    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 8448        let text_layout_details = &self.text_layout_details(window);
 8449        self.transact(window, cx, |this, window, cx| {
 8450            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8451                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 8452                let line_mode = s.line_mode;
 8453                s.move_with(|display_map, selection| {
 8454                    if !selection.is_empty() || line_mode {
 8455                        return;
 8456                    }
 8457
 8458                    let mut head = selection.head();
 8459                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 8460                    if head.column() == display_map.line_len(head.row()) {
 8461                        transpose_offset = display_map
 8462                            .buffer_snapshot
 8463                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8464                    }
 8465
 8466                    if transpose_offset == 0 {
 8467                        return;
 8468                    }
 8469
 8470                    *head.column_mut() += 1;
 8471                    head = display_map.clip_point(head, Bias::Right);
 8472                    let goal = SelectionGoal::HorizontalPosition(
 8473                        display_map
 8474                            .x_for_display_point(head, text_layout_details)
 8475                            .into(),
 8476                    );
 8477                    selection.collapse_to(head, goal);
 8478
 8479                    let transpose_start = display_map
 8480                        .buffer_snapshot
 8481                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8482                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 8483                        let transpose_end = display_map
 8484                            .buffer_snapshot
 8485                            .clip_offset(transpose_offset + 1, Bias::Right);
 8486                        if let Some(ch) =
 8487                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 8488                        {
 8489                            edits.push((transpose_start..transpose_offset, String::new()));
 8490                            edits.push((transpose_end..transpose_end, ch.to_string()));
 8491                        }
 8492                    }
 8493                });
 8494                edits
 8495            });
 8496            this.buffer
 8497                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8498            let selections = this.selections.all::<usize>(cx);
 8499            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8500                s.select(selections);
 8501            });
 8502        });
 8503    }
 8504
 8505    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 8506        self.rewrap_impl(IsVimMode::No, cx)
 8507    }
 8508
 8509    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 8510        let buffer = self.buffer.read(cx).snapshot(cx);
 8511        let selections = self.selections.all::<Point>(cx);
 8512        let mut selections = selections.iter().peekable();
 8513
 8514        let mut edits = Vec::new();
 8515        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 8516
 8517        while let Some(selection) = selections.next() {
 8518            let mut start_row = selection.start.row;
 8519            let mut end_row = selection.end.row;
 8520
 8521            // Skip selections that overlap with a range that has already been rewrapped.
 8522            let selection_range = start_row..end_row;
 8523            if rewrapped_row_ranges
 8524                .iter()
 8525                .any(|range| range.overlaps(&selection_range))
 8526            {
 8527                continue;
 8528            }
 8529
 8530            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 8531
 8532            // Since not all lines in the selection may be at the same indent
 8533            // level, choose the indent size that is the most common between all
 8534            // of the lines.
 8535            //
 8536            // If there is a tie, we use the deepest indent.
 8537            let (indent_size, indent_end) = {
 8538                let mut indent_size_occurrences = HashMap::default();
 8539                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 8540
 8541                for row in start_row..=end_row {
 8542                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 8543                    rows_by_indent_size.entry(indent).or_default().push(row);
 8544                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 8545                }
 8546
 8547                let indent_size = indent_size_occurrences
 8548                    .into_iter()
 8549                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 8550                    .map(|(indent, _)| indent)
 8551                    .unwrap_or_default();
 8552                let row = rows_by_indent_size[&indent_size][0];
 8553                let indent_end = Point::new(row, indent_size.len);
 8554
 8555                (indent_size, indent_end)
 8556            };
 8557
 8558            let mut line_prefix = indent_size.chars().collect::<String>();
 8559
 8560            let mut inside_comment = false;
 8561            if let Some(comment_prefix) =
 8562                buffer
 8563                    .language_scope_at(selection.head())
 8564                    .and_then(|language| {
 8565                        language
 8566                            .line_comment_prefixes()
 8567                            .iter()
 8568                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 8569                            .cloned()
 8570                    })
 8571            {
 8572                line_prefix.push_str(&comment_prefix);
 8573                inside_comment = true;
 8574            }
 8575
 8576            let language_settings = buffer.language_settings_at(selection.head(), cx);
 8577            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 8578                RewrapBehavior::InComments => inside_comment,
 8579                RewrapBehavior::InSelections => !selection.is_empty(),
 8580                RewrapBehavior::Anywhere => true,
 8581            };
 8582
 8583            let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
 8584            if !should_rewrap {
 8585                continue;
 8586            }
 8587
 8588            if selection.is_empty() {
 8589                'expand_upwards: while start_row > 0 {
 8590                    let prev_row = start_row - 1;
 8591                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 8592                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 8593                    {
 8594                        start_row = prev_row;
 8595                    } else {
 8596                        break 'expand_upwards;
 8597                    }
 8598                }
 8599
 8600                'expand_downwards: while end_row < buffer.max_point().row {
 8601                    let next_row = end_row + 1;
 8602                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 8603                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 8604                    {
 8605                        end_row = next_row;
 8606                    } else {
 8607                        break 'expand_downwards;
 8608                    }
 8609                }
 8610            }
 8611
 8612            let start = Point::new(start_row, 0);
 8613            let start_offset = start.to_offset(&buffer);
 8614            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 8615            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 8616            let Some(lines_without_prefixes) = selection_text
 8617                .lines()
 8618                .map(|line| {
 8619                    line.strip_prefix(&line_prefix)
 8620                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 8621                        .ok_or_else(|| {
 8622                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 8623                        })
 8624                })
 8625                .collect::<Result<Vec<_>, _>>()
 8626                .log_err()
 8627            else {
 8628                continue;
 8629            };
 8630
 8631            let wrap_column = buffer
 8632                .language_settings_at(Point::new(start_row, 0), cx)
 8633                .preferred_line_length as usize;
 8634            let wrapped_text = wrap_with_prefix(
 8635                line_prefix,
 8636                lines_without_prefixes.join(" "),
 8637                wrap_column,
 8638                tab_size,
 8639            );
 8640
 8641            // TODO: should always use char-based diff while still supporting cursor behavior that
 8642            // matches vim.
 8643            let mut diff_options = DiffOptions::default();
 8644            if is_vim_mode == IsVimMode::Yes {
 8645                diff_options.max_word_diff_len = 0;
 8646                diff_options.max_word_diff_line_count = 0;
 8647            } else {
 8648                diff_options.max_word_diff_len = usize::MAX;
 8649                diff_options.max_word_diff_line_count = usize::MAX;
 8650            }
 8651
 8652            for (old_range, new_text) in
 8653                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 8654            {
 8655                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 8656                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 8657                edits.push((edit_start..edit_end, new_text));
 8658            }
 8659
 8660            rewrapped_row_ranges.push(start_row..=end_row);
 8661        }
 8662
 8663        self.buffer
 8664            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8665    }
 8666
 8667    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 8668        let mut text = String::new();
 8669        let buffer = self.buffer.read(cx).snapshot(cx);
 8670        let mut selections = self.selections.all::<Point>(cx);
 8671        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8672        {
 8673            let max_point = buffer.max_point();
 8674            let mut is_first = true;
 8675            for selection in &mut selections {
 8676                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8677                if is_entire_line {
 8678                    selection.start = Point::new(selection.start.row, 0);
 8679                    if !selection.is_empty() && selection.end.column == 0 {
 8680                        selection.end = cmp::min(max_point, selection.end);
 8681                    } else {
 8682                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 8683                    }
 8684                    selection.goal = SelectionGoal::None;
 8685                }
 8686                if is_first {
 8687                    is_first = false;
 8688                } else {
 8689                    text += "\n";
 8690                }
 8691                let mut len = 0;
 8692                for chunk in buffer.text_for_range(selection.start..selection.end) {
 8693                    text.push_str(chunk);
 8694                    len += chunk.len();
 8695                }
 8696                clipboard_selections.push(ClipboardSelection {
 8697                    len,
 8698                    is_entire_line,
 8699                    start_column: selection.start.column,
 8700                });
 8701            }
 8702        }
 8703
 8704        self.transact(window, cx, |this, window, cx| {
 8705            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8706                s.select(selections);
 8707            });
 8708            this.insert("", window, cx);
 8709        });
 8710        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 8711    }
 8712
 8713    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8714        let item = self.cut_common(window, cx);
 8715        cx.write_to_clipboard(item);
 8716    }
 8717
 8718    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8719        self.change_selections(None, window, cx, |s| {
 8720            s.move_with(|snapshot, sel| {
 8721                if sel.is_empty() {
 8722                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8723                }
 8724            });
 8725        });
 8726        let item = self.cut_common(window, cx);
 8727        cx.set_global(KillRing(item))
 8728    }
 8729
 8730    pub fn kill_ring_yank(
 8731        &mut self,
 8732        _: &KillRingYank,
 8733        window: &mut Window,
 8734        cx: &mut Context<Self>,
 8735    ) {
 8736        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8737            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8738                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8739            } else {
 8740                return;
 8741            }
 8742        } else {
 8743            return;
 8744        };
 8745        self.do_paste(&text, metadata, false, window, cx);
 8746    }
 8747
 8748    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8749        let selections = self.selections.all::<Point>(cx);
 8750        let buffer = self.buffer.read(cx).read(cx);
 8751        let mut text = String::new();
 8752
 8753        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8754        {
 8755            let max_point = buffer.max_point();
 8756            let mut is_first = true;
 8757            for selection in selections.iter() {
 8758                let mut start = selection.start;
 8759                let mut end = selection.end;
 8760                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8761                if is_entire_line {
 8762                    start = Point::new(start.row, 0);
 8763                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8764                }
 8765                if is_first {
 8766                    is_first = false;
 8767                } else {
 8768                    text += "\n";
 8769                }
 8770                let mut len = 0;
 8771                for chunk in buffer.text_for_range(start..end) {
 8772                    text.push_str(chunk);
 8773                    len += chunk.len();
 8774                }
 8775                clipboard_selections.push(ClipboardSelection {
 8776                    len,
 8777                    is_entire_line,
 8778                    start_column: start.column,
 8779                });
 8780            }
 8781        }
 8782
 8783        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8784            text,
 8785            clipboard_selections,
 8786        ));
 8787    }
 8788
 8789    pub fn do_paste(
 8790        &mut self,
 8791        text: &String,
 8792        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8793        handle_entire_lines: bool,
 8794        window: &mut Window,
 8795        cx: &mut Context<Self>,
 8796    ) {
 8797        if self.read_only(cx) {
 8798            return;
 8799        }
 8800
 8801        let clipboard_text = Cow::Borrowed(text);
 8802
 8803        self.transact(window, cx, |this, window, cx| {
 8804            if let Some(mut clipboard_selections) = clipboard_selections {
 8805                let old_selections = this.selections.all::<usize>(cx);
 8806                let all_selections_were_entire_line =
 8807                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8808                let first_selection_start_column =
 8809                    clipboard_selections.first().map(|s| s.start_column);
 8810                if clipboard_selections.len() != old_selections.len() {
 8811                    clipboard_selections.drain(..);
 8812                }
 8813                let cursor_offset = this.selections.last::<usize>(cx).head();
 8814                let mut auto_indent_on_paste = true;
 8815
 8816                this.buffer.update(cx, |buffer, cx| {
 8817                    let snapshot = buffer.read(cx);
 8818                    auto_indent_on_paste = snapshot
 8819                        .language_settings_at(cursor_offset, cx)
 8820                        .auto_indent_on_paste;
 8821
 8822                    let mut start_offset = 0;
 8823                    let mut edits = Vec::new();
 8824                    let mut original_start_columns = Vec::new();
 8825                    for (ix, selection) in old_selections.iter().enumerate() {
 8826                        let to_insert;
 8827                        let entire_line;
 8828                        let original_start_column;
 8829                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8830                            let end_offset = start_offset + clipboard_selection.len;
 8831                            to_insert = &clipboard_text[start_offset..end_offset];
 8832                            entire_line = clipboard_selection.is_entire_line;
 8833                            start_offset = end_offset + 1;
 8834                            original_start_column = Some(clipboard_selection.start_column);
 8835                        } else {
 8836                            to_insert = clipboard_text.as_str();
 8837                            entire_line = all_selections_were_entire_line;
 8838                            original_start_column = first_selection_start_column
 8839                        }
 8840
 8841                        // If the corresponding selection was empty when this slice of the
 8842                        // clipboard text was written, then the entire line containing the
 8843                        // selection was copied. If this selection is also currently empty,
 8844                        // then paste the line before the current line of the buffer.
 8845                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8846                            let column = selection.start.to_point(&snapshot).column as usize;
 8847                            let line_start = selection.start - column;
 8848                            line_start..line_start
 8849                        } else {
 8850                            selection.range()
 8851                        };
 8852
 8853                        edits.push((range, to_insert));
 8854                        original_start_columns.extend(original_start_column);
 8855                    }
 8856                    drop(snapshot);
 8857
 8858                    buffer.edit(
 8859                        edits,
 8860                        if auto_indent_on_paste {
 8861                            Some(AutoindentMode::Block {
 8862                                original_start_columns,
 8863                            })
 8864                        } else {
 8865                            None
 8866                        },
 8867                        cx,
 8868                    );
 8869                });
 8870
 8871                let selections = this.selections.all::<usize>(cx);
 8872                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8873                    s.select(selections)
 8874                });
 8875            } else {
 8876                this.insert(&clipboard_text, window, cx);
 8877            }
 8878        });
 8879    }
 8880
 8881    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8882        if let Some(item) = cx.read_from_clipboard() {
 8883            let entries = item.entries();
 8884
 8885            match entries.first() {
 8886                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8887                // of all the pasted entries.
 8888                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8889                    .do_paste(
 8890                        clipboard_string.text(),
 8891                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8892                        true,
 8893                        window,
 8894                        cx,
 8895                    ),
 8896                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8897            }
 8898        }
 8899    }
 8900
 8901    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8902        if self.read_only(cx) {
 8903            return;
 8904        }
 8905
 8906        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8907            if let Some((selections, _)) =
 8908                self.selection_history.transaction(transaction_id).cloned()
 8909            {
 8910                self.change_selections(None, window, cx, |s| {
 8911                    s.select_anchors(selections.to_vec());
 8912                });
 8913            } else {
 8914                log::error!(
 8915                    "No entry in selection_history found for undo. \
 8916                     This may correspond to a bug where undo does not update the selection. \
 8917                     If this is occurring, please add details to \
 8918                     https://github.com/zed-industries/zed/issues/22692"
 8919                );
 8920            }
 8921            self.request_autoscroll(Autoscroll::fit(), cx);
 8922            self.unmark_text(window, cx);
 8923            self.refresh_inline_completion(true, false, window, cx);
 8924            cx.emit(EditorEvent::Edited { transaction_id });
 8925            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8926        }
 8927    }
 8928
 8929    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8930        if self.read_only(cx) {
 8931            return;
 8932        }
 8933
 8934        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8935            if let Some((_, Some(selections))) =
 8936                self.selection_history.transaction(transaction_id).cloned()
 8937            {
 8938                self.change_selections(None, window, cx, |s| {
 8939                    s.select_anchors(selections.to_vec());
 8940                });
 8941            } else {
 8942                log::error!(
 8943                    "No entry in selection_history found for redo. \
 8944                     This may correspond to a bug where undo does not update the selection. \
 8945                     If this is occurring, please add details to \
 8946                     https://github.com/zed-industries/zed/issues/22692"
 8947                );
 8948            }
 8949            self.request_autoscroll(Autoscroll::fit(), cx);
 8950            self.unmark_text(window, cx);
 8951            self.refresh_inline_completion(true, false, window, cx);
 8952            cx.emit(EditorEvent::Edited { transaction_id });
 8953        }
 8954    }
 8955
 8956    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8957        self.buffer
 8958            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8959    }
 8960
 8961    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8962        self.buffer
 8963            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8964    }
 8965
 8966    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8967        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8968            let line_mode = s.line_mode;
 8969            s.move_with(|map, selection| {
 8970                let cursor = if selection.is_empty() && !line_mode {
 8971                    movement::left(map, selection.start)
 8972                } else {
 8973                    selection.start
 8974                };
 8975                selection.collapse_to(cursor, SelectionGoal::None);
 8976            });
 8977        })
 8978    }
 8979
 8980    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8981        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8982            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8983        })
 8984    }
 8985
 8986    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8987        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8988            let line_mode = s.line_mode;
 8989            s.move_with(|map, selection| {
 8990                let cursor = if selection.is_empty() && !line_mode {
 8991                    movement::right(map, selection.end)
 8992                } else {
 8993                    selection.end
 8994                };
 8995                selection.collapse_to(cursor, SelectionGoal::None)
 8996            });
 8997        })
 8998    }
 8999
 9000    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 9001        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9002            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 9003        })
 9004    }
 9005
 9006    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 9007        if self.take_rename(true, window, cx).is_some() {
 9008            return;
 9009        }
 9010
 9011        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9012            cx.propagate();
 9013            return;
 9014        }
 9015
 9016        let text_layout_details = &self.text_layout_details(window);
 9017        let selection_count = self.selections.count();
 9018        let first_selection = self.selections.first_anchor();
 9019
 9020        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9021            let line_mode = s.line_mode;
 9022            s.move_with(|map, selection| {
 9023                if !selection.is_empty() && !line_mode {
 9024                    selection.goal = SelectionGoal::None;
 9025                }
 9026                let (cursor, goal) = movement::up(
 9027                    map,
 9028                    selection.start,
 9029                    selection.goal,
 9030                    false,
 9031                    text_layout_details,
 9032                );
 9033                selection.collapse_to(cursor, goal);
 9034            });
 9035        });
 9036
 9037        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9038        {
 9039            cx.propagate();
 9040        }
 9041    }
 9042
 9043    pub fn move_up_by_lines(
 9044        &mut self,
 9045        action: &MoveUpByLines,
 9046        window: &mut Window,
 9047        cx: &mut Context<Self>,
 9048    ) {
 9049        if self.take_rename(true, window, cx).is_some() {
 9050            return;
 9051        }
 9052
 9053        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9054            cx.propagate();
 9055            return;
 9056        }
 9057
 9058        let text_layout_details = &self.text_layout_details(window);
 9059
 9060        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9061            let line_mode = s.line_mode;
 9062            s.move_with(|map, selection| {
 9063                if !selection.is_empty() && !line_mode {
 9064                    selection.goal = SelectionGoal::None;
 9065                }
 9066                let (cursor, goal) = movement::up_by_rows(
 9067                    map,
 9068                    selection.start,
 9069                    action.lines,
 9070                    selection.goal,
 9071                    false,
 9072                    text_layout_details,
 9073                );
 9074                selection.collapse_to(cursor, goal);
 9075            });
 9076        })
 9077    }
 9078
 9079    pub fn move_down_by_lines(
 9080        &mut self,
 9081        action: &MoveDownByLines,
 9082        window: &mut Window,
 9083        cx: &mut Context<Self>,
 9084    ) {
 9085        if self.take_rename(true, window, cx).is_some() {
 9086            return;
 9087        }
 9088
 9089        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9090            cx.propagate();
 9091            return;
 9092        }
 9093
 9094        let text_layout_details = &self.text_layout_details(window);
 9095
 9096        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9097            let line_mode = s.line_mode;
 9098            s.move_with(|map, selection| {
 9099                if !selection.is_empty() && !line_mode {
 9100                    selection.goal = SelectionGoal::None;
 9101                }
 9102                let (cursor, goal) = movement::down_by_rows(
 9103                    map,
 9104                    selection.start,
 9105                    action.lines,
 9106                    selection.goal,
 9107                    false,
 9108                    text_layout_details,
 9109                );
 9110                selection.collapse_to(cursor, goal);
 9111            });
 9112        })
 9113    }
 9114
 9115    pub fn select_down_by_lines(
 9116        &mut self,
 9117        action: &SelectDownByLines,
 9118        window: &mut Window,
 9119        cx: &mut Context<Self>,
 9120    ) {
 9121        let text_layout_details = &self.text_layout_details(window);
 9122        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9123            s.move_heads_with(|map, head, goal| {
 9124                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9125            })
 9126        })
 9127    }
 9128
 9129    pub fn select_up_by_lines(
 9130        &mut self,
 9131        action: &SelectUpByLines,
 9132        window: &mut Window,
 9133        cx: &mut Context<Self>,
 9134    ) {
 9135        let text_layout_details = &self.text_layout_details(window);
 9136        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9137            s.move_heads_with(|map, head, goal| {
 9138                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9139            })
 9140        })
 9141    }
 9142
 9143    pub fn select_page_up(
 9144        &mut self,
 9145        _: &SelectPageUp,
 9146        window: &mut Window,
 9147        cx: &mut Context<Self>,
 9148    ) {
 9149        let Some(row_count) = self.visible_row_count() else {
 9150            return;
 9151        };
 9152
 9153        let text_layout_details = &self.text_layout_details(window);
 9154
 9155        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9156            s.move_heads_with(|map, head, goal| {
 9157                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 9158            })
 9159        })
 9160    }
 9161
 9162    pub fn move_page_up(
 9163        &mut self,
 9164        action: &MovePageUp,
 9165        window: &mut Window,
 9166        cx: &mut Context<Self>,
 9167    ) {
 9168        if self.take_rename(true, window, cx).is_some() {
 9169            return;
 9170        }
 9171
 9172        if self
 9173            .context_menu
 9174            .borrow_mut()
 9175            .as_mut()
 9176            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 9177            .unwrap_or(false)
 9178        {
 9179            return;
 9180        }
 9181
 9182        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9183            cx.propagate();
 9184            return;
 9185        }
 9186
 9187        let Some(row_count) = self.visible_row_count() else {
 9188            return;
 9189        };
 9190
 9191        let autoscroll = if action.center_cursor {
 9192            Autoscroll::center()
 9193        } else {
 9194            Autoscroll::fit()
 9195        };
 9196
 9197        let text_layout_details = &self.text_layout_details(window);
 9198
 9199        self.change_selections(Some(autoscroll), window, cx, |s| {
 9200            let line_mode = s.line_mode;
 9201            s.move_with(|map, selection| {
 9202                if !selection.is_empty() && !line_mode {
 9203                    selection.goal = SelectionGoal::None;
 9204                }
 9205                let (cursor, goal) = movement::up_by_rows(
 9206                    map,
 9207                    selection.end,
 9208                    row_count,
 9209                    selection.goal,
 9210                    false,
 9211                    text_layout_details,
 9212                );
 9213                selection.collapse_to(cursor, goal);
 9214            });
 9215        });
 9216    }
 9217
 9218    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 9219        let text_layout_details = &self.text_layout_details(window);
 9220        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9221            s.move_heads_with(|map, head, goal| {
 9222                movement::up(map, head, goal, false, text_layout_details)
 9223            })
 9224        })
 9225    }
 9226
 9227    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 9228        self.take_rename(true, window, cx);
 9229
 9230        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9231            cx.propagate();
 9232            return;
 9233        }
 9234
 9235        let text_layout_details = &self.text_layout_details(window);
 9236        let selection_count = self.selections.count();
 9237        let first_selection = self.selections.first_anchor();
 9238
 9239        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9240            let line_mode = s.line_mode;
 9241            s.move_with(|map, selection| {
 9242                if !selection.is_empty() && !line_mode {
 9243                    selection.goal = SelectionGoal::None;
 9244                }
 9245                let (cursor, goal) = movement::down(
 9246                    map,
 9247                    selection.end,
 9248                    selection.goal,
 9249                    false,
 9250                    text_layout_details,
 9251                );
 9252                selection.collapse_to(cursor, goal);
 9253            });
 9254        });
 9255
 9256        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9257        {
 9258            cx.propagate();
 9259        }
 9260    }
 9261
 9262    pub fn select_page_down(
 9263        &mut self,
 9264        _: &SelectPageDown,
 9265        window: &mut Window,
 9266        cx: &mut Context<Self>,
 9267    ) {
 9268        let Some(row_count) = self.visible_row_count() else {
 9269            return;
 9270        };
 9271
 9272        let text_layout_details = &self.text_layout_details(window);
 9273
 9274        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9275            s.move_heads_with(|map, head, goal| {
 9276                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 9277            })
 9278        })
 9279    }
 9280
 9281    pub fn move_page_down(
 9282        &mut self,
 9283        action: &MovePageDown,
 9284        window: &mut Window,
 9285        cx: &mut Context<Self>,
 9286    ) {
 9287        if self.take_rename(true, window, cx).is_some() {
 9288            return;
 9289        }
 9290
 9291        if self
 9292            .context_menu
 9293            .borrow_mut()
 9294            .as_mut()
 9295            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 9296            .unwrap_or(false)
 9297        {
 9298            return;
 9299        }
 9300
 9301        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9302            cx.propagate();
 9303            return;
 9304        }
 9305
 9306        let Some(row_count) = self.visible_row_count() else {
 9307            return;
 9308        };
 9309
 9310        let autoscroll = if action.center_cursor {
 9311            Autoscroll::center()
 9312        } else {
 9313            Autoscroll::fit()
 9314        };
 9315
 9316        let text_layout_details = &self.text_layout_details(window);
 9317        self.change_selections(Some(autoscroll), window, cx, |s| {
 9318            let line_mode = s.line_mode;
 9319            s.move_with(|map, selection| {
 9320                if !selection.is_empty() && !line_mode {
 9321                    selection.goal = SelectionGoal::None;
 9322                }
 9323                let (cursor, goal) = movement::down_by_rows(
 9324                    map,
 9325                    selection.end,
 9326                    row_count,
 9327                    selection.goal,
 9328                    false,
 9329                    text_layout_details,
 9330                );
 9331                selection.collapse_to(cursor, goal);
 9332            });
 9333        });
 9334    }
 9335
 9336    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 9337        let text_layout_details = &self.text_layout_details(window);
 9338        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9339            s.move_heads_with(|map, head, goal| {
 9340                movement::down(map, head, goal, false, text_layout_details)
 9341            })
 9342        });
 9343    }
 9344
 9345    pub fn context_menu_first(
 9346        &mut self,
 9347        _: &ContextMenuFirst,
 9348        _window: &mut Window,
 9349        cx: &mut Context<Self>,
 9350    ) {
 9351        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9352            context_menu.select_first(self.completion_provider.as_deref(), cx);
 9353        }
 9354    }
 9355
 9356    pub fn context_menu_prev(
 9357        &mut self,
 9358        _: &ContextMenuPrevious,
 9359        _window: &mut Window,
 9360        cx: &mut Context<Self>,
 9361    ) {
 9362        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9363            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 9364        }
 9365    }
 9366
 9367    pub fn context_menu_next(
 9368        &mut self,
 9369        _: &ContextMenuNext,
 9370        _window: &mut Window,
 9371        cx: &mut Context<Self>,
 9372    ) {
 9373        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9374            context_menu.select_next(self.completion_provider.as_deref(), cx);
 9375        }
 9376    }
 9377
 9378    pub fn context_menu_last(
 9379        &mut self,
 9380        _: &ContextMenuLast,
 9381        _window: &mut Window,
 9382        cx: &mut Context<Self>,
 9383    ) {
 9384        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9385            context_menu.select_last(self.completion_provider.as_deref(), cx);
 9386        }
 9387    }
 9388
 9389    pub fn move_to_previous_word_start(
 9390        &mut self,
 9391        _: &MoveToPreviousWordStart,
 9392        window: &mut Window,
 9393        cx: &mut Context<Self>,
 9394    ) {
 9395        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9396            s.move_cursors_with(|map, head, _| {
 9397                (
 9398                    movement::previous_word_start(map, head),
 9399                    SelectionGoal::None,
 9400                )
 9401            });
 9402        })
 9403    }
 9404
 9405    pub fn move_to_previous_subword_start(
 9406        &mut self,
 9407        _: &MoveToPreviousSubwordStart,
 9408        window: &mut Window,
 9409        cx: &mut Context<Self>,
 9410    ) {
 9411        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9412            s.move_cursors_with(|map, head, _| {
 9413                (
 9414                    movement::previous_subword_start(map, head),
 9415                    SelectionGoal::None,
 9416                )
 9417            });
 9418        })
 9419    }
 9420
 9421    pub fn select_to_previous_word_start(
 9422        &mut self,
 9423        _: &SelectToPreviousWordStart,
 9424        window: &mut Window,
 9425        cx: &mut Context<Self>,
 9426    ) {
 9427        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9428            s.move_heads_with(|map, head, _| {
 9429                (
 9430                    movement::previous_word_start(map, head),
 9431                    SelectionGoal::None,
 9432                )
 9433            });
 9434        })
 9435    }
 9436
 9437    pub fn select_to_previous_subword_start(
 9438        &mut self,
 9439        _: &SelectToPreviousSubwordStart,
 9440        window: &mut Window,
 9441        cx: &mut Context<Self>,
 9442    ) {
 9443        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9444            s.move_heads_with(|map, head, _| {
 9445                (
 9446                    movement::previous_subword_start(map, head),
 9447                    SelectionGoal::None,
 9448                )
 9449            });
 9450        })
 9451    }
 9452
 9453    pub fn delete_to_previous_word_start(
 9454        &mut self,
 9455        action: &DeleteToPreviousWordStart,
 9456        window: &mut Window,
 9457        cx: &mut Context<Self>,
 9458    ) {
 9459        self.transact(window, cx, |this, window, cx| {
 9460            this.select_autoclose_pair(window, cx);
 9461            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9462                let line_mode = s.line_mode;
 9463                s.move_with(|map, selection| {
 9464                    if selection.is_empty() && !line_mode {
 9465                        let cursor = if action.ignore_newlines {
 9466                            movement::previous_word_start(map, selection.head())
 9467                        } else {
 9468                            movement::previous_word_start_or_newline(map, selection.head())
 9469                        };
 9470                        selection.set_head(cursor, SelectionGoal::None);
 9471                    }
 9472                });
 9473            });
 9474            this.insert("", window, cx);
 9475        });
 9476    }
 9477
 9478    pub fn delete_to_previous_subword_start(
 9479        &mut self,
 9480        _: &DeleteToPreviousSubwordStart,
 9481        window: &mut Window,
 9482        cx: &mut Context<Self>,
 9483    ) {
 9484        self.transact(window, cx, |this, window, cx| {
 9485            this.select_autoclose_pair(window, cx);
 9486            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9487                let line_mode = s.line_mode;
 9488                s.move_with(|map, selection| {
 9489                    if selection.is_empty() && !line_mode {
 9490                        let cursor = movement::previous_subword_start(map, selection.head());
 9491                        selection.set_head(cursor, SelectionGoal::None);
 9492                    }
 9493                });
 9494            });
 9495            this.insert("", window, cx);
 9496        });
 9497    }
 9498
 9499    pub fn move_to_next_word_end(
 9500        &mut self,
 9501        _: &MoveToNextWordEnd,
 9502        window: &mut Window,
 9503        cx: &mut Context<Self>,
 9504    ) {
 9505        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9506            s.move_cursors_with(|map, head, _| {
 9507                (movement::next_word_end(map, head), SelectionGoal::None)
 9508            });
 9509        })
 9510    }
 9511
 9512    pub fn move_to_next_subword_end(
 9513        &mut self,
 9514        _: &MoveToNextSubwordEnd,
 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                (movement::next_subword_end(map, head), SelectionGoal::None)
 9521            });
 9522        })
 9523    }
 9524
 9525    pub fn select_to_next_word_end(
 9526        &mut self,
 9527        _: &SelectToNextWordEnd,
 9528        window: &mut Window,
 9529        cx: &mut Context<Self>,
 9530    ) {
 9531        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9532            s.move_heads_with(|map, head, _| {
 9533                (movement::next_word_end(map, head), SelectionGoal::None)
 9534            });
 9535        })
 9536    }
 9537
 9538    pub fn select_to_next_subword_end(
 9539        &mut self,
 9540        _: &SelectToNextSubwordEnd,
 9541        window: &mut Window,
 9542        cx: &mut Context<Self>,
 9543    ) {
 9544        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9545            s.move_heads_with(|map, head, _| {
 9546                (movement::next_subword_end(map, head), SelectionGoal::None)
 9547            });
 9548        })
 9549    }
 9550
 9551    pub fn delete_to_next_word_end(
 9552        &mut self,
 9553        action: &DeleteToNextWordEnd,
 9554        window: &mut Window,
 9555        cx: &mut Context<Self>,
 9556    ) {
 9557        self.transact(window, cx, |this, window, cx| {
 9558            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9559                let line_mode = s.line_mode;
 9560                s.move_with(|map, selection| {
 9561                    if selection.is_empty() && !line_mode {
 9562                        let cursor = if action.ignore_newlines {
 9563                            movement::next_word_end(map, selection.head())
 9564                        } else {
 9565                            movement::next_word_end_or_newline(map, selection.head())
 9566                        };
 9567                        selection.set_head(cursor, SelectionGoal::None);
 9568                    }
 9569                });
 9570            });
 9571            this.insert("", window, cx);
 9572        });
 9573    }
 9574
 9575    pub fn delete_to_next_subword_end(
 9576        &mut self,
 9577        _: &DeleteToNextSubwordEnd,
 9578        window: &mut Window,
 9579        cx: &mut Context<Self>,
 9580    ) {
 9581        self.transact(window, cx, |this, window, cx| {
 9582            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9583                s.move_with(|map, selection| {
 9584                    if selection.is_empty() {
 9585                        let cursor = movement::next_subword_end(map, selection.head());
 9586                        selection.set_head(cursor, SelectionGoal::None);
 9587                    }
 9588                });
 9589            });
 9590            this.insert("", window, cx);
 9591        });
 9592    }
 9593
 9594    pub fn move_to_beginning_of_line(
 9595        &mut self,
 9596        action: &MoveToBeginningOfLine,
 9597        window: &mut Window,
 9598        cx: &mut Context<Self>,
 9599    ) {
 9600        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9601            s.move_cursors_with(|map, head, _| {
 9602                (
 9603                    movement::indented_line_beginning(
 9604                        map,
 9605                        head,
 9606                        action.stop_at_soft_wraps,
 9607                        action.stop_at_indent,
 9608                    ),
 9609                    SelectionGoal::None,
 9610                )
 9611            });
 9612        })
 9613    }
 9614
 9615    pub fn select_to_beginning_of_line(
 9616        &mut self,
 9617        action: &SelectToBeginningOfLine,
 9618        window: &mut Window,
 9619        cx: &mut Context<Self>,
 9620    ) {
 9621        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9622            s.move_heads_with(|map, head, _| {
 9623                (
 9624                    movement::indented_line_beginning(
 9625                        map,
 9626                        head,
 9627                        action.stop_at_soft_wraps,
 9628                        action.stop_at_indent,
 9629                    ),
 9630                    SelectionGoal::None,
 9631                )
 9632            });
 9633        });
 9634    }
 9635
 9636    pub fn delete_to_beginning_of_line(
 9637        &mut self,
 9638        action: &DeleteToBeginningOfLine,
 9639        window: &mut Window,
 9640        cx: &mut Context<Self>,
 9641    ) {
 9642        self.transact(window, cx, |this, window, cx| {
 9643            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9644                s.move_with(|_, selection| {
 9645                    selection.reversed = true;
 9646                });
 9647            });
 9648
 9649            this.select_to_beginning_of_line(
 9650                &SelectToBeginningOfLine {
 9651                    stop_at_soft_wraps: false,
 9652                    stop_at_indent: action.stop_at_indent,
 9653                },
 9654                window,
 9655                cx,
 9656            );
 9657            this.backspace(&Backspace, window, cx);
 9658        });
 9659    }
 9660
 9661    pub fn move_to_end_of_line(
 9662        &mut self,
 9663        action: &MoveToEndOfLine,
 9664        window: &mut Window,
 9665        cx: &mut Context<Self>,
 9666    ) {
 9667        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9668            s.move_cursors_with(|map, head, _| {
 9669                (
 9670                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9671                    SelectionGoal::None,
 9672                )
 9673            });
 9674        })
 9675    }
 9676
 9677    pub fn select_to_end_of_line(
 9678        &mut self,
 9679        action: &SelectToEndOfLine,
 9680        window: &mut Window,
 9681        cx: &mut Context<Self>,
 9682    ) {
 9683        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9684            s.move_heads_with(|map, head, _| {
 9685                (
 9686                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9687                    SelectionGoal::None,
 9688                )
 9689            });
 9690        })
 9691    }
 9692
 9693    pub fn delete_to_end_of_line(
 9694        &mut self,
 9695        _: &DeleteToEndOfLine,
 9696        window: &mut Window,
 9697        cx: &mut Context<Self>,
 9698    ) {
 9699        self.transact(window, cx, |this, window, cx| {
 9700            this.select_to_end_of_line(
 9701                &SelectToEndOfLine {
 9702                    stop_at_soft_wraps: false,
 9703                },
 9704                window,
 9705                cx,
 9706            );
 9707            this.delete(&Delete, window, cx);
 9708        });
 9709    }
 9710
 9711    pub fn cut_to_end_of_line(
 9712        &mut self,
 9713        _: &CutToEndOfLine,
 9714        window: &mut Window,
 9715        cx: &mut Context<Self>,
 9716    ) {
 9717        self.transact(window, cx, |this, window, cx| {
 9718            this.select_to_end_of_line(
 9719                &SelectToEndOfLine {
 9720                    stop_at_soft_wraps: false,
 9721                },
 9722                window,
 9723                cx,
 9724            );
 9725            this.cut(&Cut, window, cx);
 9726        });
 9727    }
 9728
 9729    pub fn move_to_start_of_paragraph(
 9730        &mut self,
 9731        _: &MoveToStartOfParagraph,
 9732        window: &mut Window,
 9733        cx: &mut Context<Self>,
 9734    ) {
 9735        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9736            cx.propagate();
 9737            return;
 9738        }
 9739
 9740        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9741            s.move_with(|map, selection| {
 9742                selection.collapse_to(
 9743                    movement::start_of_paragraph(map, selection.head(), 1),
 9744                    SelectionGoal::None,
 9745                )
 9746            });
 9747        })
 9748    }
 9749
 9750    pub fn move_to_end_of_paragraph(
 9751        &mut self,
 9752        _: &MoveToEndOfParagraph,
 9753        window: &mut Window,
 9754        cx: &mut Context<Self>,
 9755    ) {
 9756        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9757            cx.propagate();
 9758            return;
 9759        }
 9760
 9761        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9762            s.move_with(|map, selection| {
 9763                selection.collapse_to(
 9764                    movement::end_of_paragraph(map, selection.head(), 1),
 9765                    SelectionGoal::None,
 9766                )
 9767            });
 9768        })
 9769    }
 9770
 9771    pub fn select_to_start_of_paragraph(
 9772        &mut self,
 9773        _: &SelectToStartOfParagraph,
 9774        window: &mut Window,
 9775        cx: &mut Context<Self>,
 9776    ) {
 9777        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9778            cx.propagate();
 9779            return;
 9780        }
 9781
 9782        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9783            s.move_heads_with(|map, head, _| {
 9784                (
 9785                    movement::start_of_paragraph(map, head, 1),
 9786                    SelectionGoal::None,
 9787                )
 9788            });
 9789        })
 9790    }
 9791
 9792    pub fn select_to_end_of_paragraph(
 9793        &mut self,
 9794        _: &SelectToEndOfParagraph,
 9795        window: &mut Window,
 9796        cx: &mut Context<Self>,
 9797    ) {
 9798        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9799            cx.propagate();
 9800            return;
 9801        }
 9802
 9803        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9804            s.move_heads_with(|map, head, _| {
 9805                (
 9806                    movement::end_of_paragraph(map, head, 1),
 9807                    SelectionGoal::None,
 9808                )
 9809            });
 9810        })
 9811    }
 9812
 9813    pub fn move_to_start_of_excerpt(
 9814        &mut self,
 9815        _: &MoveToStartOfExcerpt,
 9816        window: &mut Window,
 9817        cx: &mut Context<Self>,
 9818    ) {
 9819        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9820            cx.propagate();
 9821            return;
 9822        }
 9823
 9824        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9825            s.move_with(|map, selection| {
 9826                selection.collapse_to(
 9827                    movement::start_of_excerpt(
 9828                        map,
 9829                        selection.head(),
 9830                        workspace::searchable::Direction::Prev,
 9831                    ),
 9832                    SelectionGoal::None,
 9833                )
 9834            });
 9835        })
 9836    }
 9837
 9838    pub fn move_to_end_of_excerpt(
 9839        &mut self,
 9840        _: &MoveToEndOfExcerpt,
 9841        window: &mut Window,
 9842        cx: &mut Context<Self>,
 9843    ) {
 9844        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9845            cx.propagate();
 9846            return;
 9847        }
 9848
 9849        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9850            s.move_with(|map, selection| {
 9851                selection.collapse_to(
 9852                    movement::end_of_excerpt(
 9853                        map,
 9854                        selection.head(),
 9855                        workspace::searchable::Direction::Next,
 9856                    ),
 9857                    SelectionGoal::None,
 9858                )
 9859            });
 9860        })
 9861    }
 9862
 9863    pub fn select_to_start_of_excerpt(
 9864        &mut self,
 9865        _: &SelectToStartOfExcerpt,
 9866        window: &mut Window,
 9867        cx: &mut Context<Self>,
 9868    ) {
 9869        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9870            cx.propagate();
 9871            return;
 9872        }
 9873
 9874        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9875            s.move_heads_with(|map, head, _| {
 9876                (
 9877                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
 9878                    SelectionGoal::None,
 9879                )
 9880            });
 9881        })
 9882    }
 9883
 9884    pub fn select_to_end_of_excerpt(
 9885        &mut self,
 9886        _: &SelectToEndOfExcerpt,
 9887        window: &mut Window,
 9888        cx: &mut Context<Self>,
 9889    ) {
 9890        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9891            cx.propagate();
 9892            return;
 9893        }
 9894
 9895        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9896            s.move_heads_with(|map, head, _| {
 9897                (
 9898                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
 9899                    SelectionGoal::None,
 9900                )
 9901            });
 9902        })
 9903    }
 9904
 9905    pub fn move_to_beginning(
 9906        &mut self,
 9907        _: &MoveToBeginning,
 9908        window: &mut Window,
 9909        cx: &mut Context<Self>,
 9910    ) {
 9911        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9912            cx.propagate();
 9913            return;
 9914        }
 9915
 9916        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9917            s.select_ranges(vec![0..0]);
 9918        });
 9919    }
 9920
 9921    pub fn select_to_beginning(
 9922        &mut self,
 9923        _: &SelectToBeginning,
 9924        window: &mut Window,
 9925        cx: &mut Context<Self>,
 9926    ) {
 9927        let mut selection = self.selections.last::<Point>(cx);
 9928        selection.set_head(Point::zero(), SelectionGoal::None);
 9929
 9930        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9931            s.select(vec![selection]);
 9932        });
 9933    }
 9934
 9935    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9936        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9937            cx.propagate();
 9938            return;
 9939        }
 9940
 9941        let cursor = self.buffer.read(cx).read(cx).len();
 9942        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9943            s.select_ranges(vec![cursor..cursor])
 9944        });
 9945    }
 9946
 9947    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9948        self.nav_history = nav_history;
 9949    }
 9950
 9951    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9952        self.nav_history.as_ref()
 9953    }
 9954
 9955    fn push_to_nav_history(
 9956        &mut self,
 9957        cursor_anchor: Anchor,
 9958        new_position: Option<Point>,
 9959        cx: &mut Context<Self>,
 9960    ) {
 9961        if let Some(nav_history) = self.nav_history.as_mut() {
 9962            let buffer = self.buffer.read(cx).read(cx);
 9963            let cursor_position = cursor_anchor.to_point(&buffer);
 9964            let scroll_state = self.scroll_manager.anchor();
 9965            let scroll_top_row = scroll_state.top_row(&buffer);
 9966            drop(buffer);
 9967
 9968            if let Some(new_position) = new_position {
 9969                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9970                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9971                    return;
 9972                }
 9973            }
 9974
 9975            nav_history.push(
 9976                Some(NavigationData {
 9977                    cursor_anchor,
 9978                    cursor_position,
 9979                    scroll_anchor: scroll_state,
 9980                    scroll_top_row,
 9981                }),
 9982                cx,
 9983            );
 9984        }
 9985    }
 9986
 9987    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9988        let buffer = self.buffer.read(cx).snapshot(cx);
 9989        let mut selection = self.selections.first::<usize>(cx);
 9990        selection.set_head(buffer.len(), SelectionGoal::None);
 9991        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9992            s.select(vec![selection]);
 9993        });
 9994    }
 9995
 9996    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9997        let end = self.buffer.read(cx).read(cx).len();
 9998        self.change_selections(None, window, cx, |s| {
 9999            s.select_ranges(vec![0..end]);
10000        });
10001    }
10002
10003    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
10004        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10005        let mut selections = self.selections.all::<Point>(cx);
10006        let max_point = display_map.buffer_snapshot.max_point();
10007        for selection in &mut selections {
10008            let rows = selection.spanned_rows(true, &display_map);
10009            selection.start = Point::new(rows.start.0, 0);
10010            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
10011            selection.reversed = false;
10012        }
10013        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10014            s.select(selections);
10015        });
10016    }
10017
10018    pub fn split_selection_into_lines(
10019        &mut self,
10020        _: &SplitSelectionIntoLines,
10021        window: &mut Window,
10022        cx: &mut Context<Self>,
10023    ) {
10024        let selections = self
10025            .selections
10026            .all::<Point>(cx)
10027            .into_iter()
10028            .map(|selection| selection.start..selection.end)
10029            .collect::<Vec<_>>();
10030        self.unfold_ranges(&selections, true, true, cx);
10031
10032        let mut new_selection_ranges = Vec::new();
10033        {
10034            let buffer = self.buffer.read(cx).read(cx);
10035            for selection in selections {
10036                for row in selection.start.row..selection.end.row {
10037                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
10038                    new_selection_ranges.push(cursor..cursor);
10039                }
10040
10041                let is_multiline_selection = selection.start.row != selection.end.row;
10042                // Don't insert last one if it's a multi-line selection ending at the start of a line,
10043                // so this action feels more ergonomic when paired with other selection operations
10044                let should_skip_last = is_multiline_selection && selection.end.column == 0;
10045                if !should_skip_last {
10046                    new_selection_ranges.push(selection.end..selection.end);
10047                }
10048            }
10049        }
10050        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10051            s.select_ranges(new_selection_ranges);
10052        });
10053    }
10054
10055    pub fn add_selection_above(
10056        &mut self,
10057        _: &AddSelectionAbove,
10058        window: &mut Window,
10059        cx: &mut Context<Self>,
10060    ) {
10061        self.add_selection(true, window, cx);
10062    }
10063
10064    pub fn add_selection_below(
10065        &mut self,
10066        _: &AddSelectionBelow,
10067        window: &mut Window,
10068        cx: &mut Context<Self>,
10069    ) {
10070        self.add_selection(false, window, cx);
10071    }
10072
10073    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
10074        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10075        let mut selections = self.selections.all::<Point>(cx);
10076        let text_layout_details = self.text_layout_details(window);
10077        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10078            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10079            let range = oldest_selection.display_range(&display_map).sorted();
10080
10081            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10082            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10083            let positions = start_x.min(end_x)..start_x.max(end_x);
10084
10085            selections.clear();
10086            let mut stack = Vec::new();
10087            for row in range.start.row().0..=range.end.row().0 {
10088                if let Some(selection) = self.selections.build_columnar_selection(
10089                    &display_map,
10090                    DisplayRow(row),
10091                    &positions,
10092                    oldest_selection.reversed,
10093                    &text_layout_details,
10094                ) {
10095                    stack.push(selection.id);
10096                    selections.push(selection);
10097                }
10098            }
10099
10100            if above {
10101                stack.reverse();
10102            }
10103
10104            AddSelectionsState { above, stack }
10105        });
10106
10107        let last_added_selection = *state.stack.last().unwrap();
10108        let mut new_selections = Vec::new();
10109        if above == state.above {
10110            let end_row = if above {
10111                DisplayRow(0)
10112            } else {
10113                display_map.max_point().row()
10114            };
10115
10116            'outer: for selection in selections {
10117                if selection.id == last_added_selection {
10118                    let range = selection.display_range(&display_map).sorted();
10119                    debug_assert_eq!(range.start.row(), range.end.row());
10120                    let mut row = range.start.row();
10121                    let positions =
10122                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10123                            px(start)..px(end)
10124                        } else {
10125                            let start_x =
10126                                display_map.x_for_display_point(range.start, &text_layout_details);
10127                            let end_x =
10128                                display_map.x_for_display_point(range.end, &text_layout_details);
10129                            start_x.min(end_x)..start_x.max(end_x)
10130                        };
10131
10132                    while row != end_row {
10133                        if above {
10134                            row.0 -= 1;
10135                        } else {
10136                            row.0 += 1;
10137                        }
10138
10139                        if let Some(new_selection) = self.selections.build_columnar_selection(
10140                            &display_map,
10141                            row,
10142                            &positions,
10143                            selection.reversed,
10144                            &text_layout_details,
10145                        ) {
10146                            state.stack.push(new_selection.id);
10147                            if above {
10148                                new_selections.push(new_selection);
10149                                new_selections.push(selection);
10150                            } else {
10151                                new_selections.push(selection);
10152                                new_selections.push(new_selection);
10153                            }
10154
10155                            continue 'outer;
10156                        }
10157                    }
10158                }
10159
10160                new_selections.push(selection);
10161            }
10162        } else {
10163            new_selections = selections;
10164            new_selections.retain(|s| s.id != last_added_selection);
10165            state.stack.pop();
10166        }
10167
10168        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10169            s.select(new_selections);
10170        });
10171        if state.stack.len() > 1 {
10172            self.add_selections_state = Some(state);
10173        }
10174    }
10175
10176    pub fn select_next_match_internal(
10177        &mut self,
10178        display_map: &DisplaySnapshot,
10179        replace_newest: bool,
10180        autoscroll: Option<Autoscroll>,
10181        window: &mut Window,
10182        cx: &mut Context<Self>,
10183    ) -> Result<()> {
10184        fn select_next_match_ranges(
10185            this: &mut Editor,
10186            range: Range<usize>,
10187            replace_newest: bool,
10188            auto_scroll: Option<Autoscroll>,
10189            window: &mut Window,
10190            cx: &mut Context<Editor>,
10191        ) {
10192            this.unfold_ranges(&[range.clone()], false, true, cx);
10193            this.change_selections(auto_scroll, window, cx, |s| {
10194                if replace_newest {
10195                    s.delete(s.newest_anchor().id);
10196                }
10197                s.insert_range(range.clone());
10198            });
10199        }
10200
10201        let buffer = &display_map.buffer_snapshot;
10202        let mut selections = self.selections.all::<usize>(cx);
10203        if let Some(mut select_next_state) = self.select_next_state.take() {
10204            let query = &select_next_state.query;
10205            if !select_next_state.done {
10206                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10207                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10208                let mut next_selected_range = None;
10209
10210                let bytes_after_last_selection =
10211                    buffer.bytes_in_range(last_selection.end..buffer.len());
10212                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10213                let query_matches = query
10214                    .stream_find_iter(bytes_after_last_selection)
10215                    .map(|result| (last_selection.end, result))
10216                    .chain(
10217                        query
10218                            .stream_find_iter(bytes_before_first_selection)
10219                            .map(|result| (0, result)),
10220                    );
10221
10222                for (start_offset, query_match) in query_matches {
10223                    let query_match = query_match.unwrap(); // can only fail due to I/O
10224                    let offset_range =
10225                        start_offset + query_match.start()..start_offset + query_match.end();
10226                    let display_range = offset_range.start.to_display_point(display_map)
10227                        ..offset_range.end.to_display_point(display_map);
10228
10229                    if !select_next_state.wordwise
10230                        || (!movement::is_inside_word(display_map, display_range.start)
10231                            && !movement::is_inside_word(display_map, display_range.end))
10232                    {
10233                        // TODO: This is n^2, because we might check all the selections
10234                        if !selections
10235                            .iter()
10236                            .any(|selection| selection.range().overlaps(&offset_range))
10237                        {
10238                            next_selected_range = Some(offset_range);
10239                            break;
10240                        }
10241                    }
10242                }
10243
10244                if let Some(next_selected_range) = next_selected_range {
10245                    select_next_match_ranges(
10246                        self,
10247                        next_selected_range,
10248                        replace_newest,
10249                        autoscroll,
10250                        window,
10251                        cx,
10252                    );
10253                } else {
10254                    select_next_state.done = true;
10255                }
10256            }
10257
10258            self.select_next_state = Some(select_next_state);
10259        } else {
10260            let mut only_carets = true;
10261            let mut same_text_selected = true;
10262            let mut selected_text = None;
10263
10264            let mut selections_iter = selections.iter().peekable();
10265            while let Some(selection) = selections_iter.next() {
10266                if selection.start != selection.end {
10267                    only_carets = false;
10268                }
10269
10270                if same_text_selected {
10271                    if selected_text.is_none() {
10272                        selected_text =
10273                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10274                    }
10275
10276                    if let Some(next_selection) = selections_iter.peek() {
10277                        if next_selection.range().len() == selection.range().len() {
10278                            let next_selected_text = buffer
10279                                .text_for_range(next_selection.range())
10280                                .collect::<String>();
10281                            if Some(next_selected_text) != selected_text {
10282                                same_text_selected = false;
10283                                selected_text = None;
10284                            }
10285                        } else {
10286                            same_text_selected = false;
10287                            selected_text = None;
10288                        }
10289                    }
10290                }
10291            }
10292
10293            if only_carets {
10294                for selection in &mut selections {
10295                    let word_range = movement::surrounding_word(
10296                        display_map,
10297                        selection.start.to_display_point(display_map),
10298                    );
10299                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
10300                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
10301                    selection.goal = SelectionGoal::None;
10302                    selection.reversed = false;
10303                    select_next_match_ranges(
10304                        self,
10305                        selection.start..selection.end,
10306                        replace_newest,
10307                        autoscroll,
10308                        window,
10309                        cx,
10310                    );
10311                }
10312
10313                if selections.len() == 1 {
10314                    let selection = selections
10315                        .last()
10316                        .expect("ensured that there's only one selection");
10317                    let query = buffer
10318                        .text_for_range(selection.start..selection.end)
10319                        .collect::<String>();
10320                    let is_empty = query.is_empty();
10321                    let select_state = SelectNextState {
10322                        query: AhoCorasick::new(&[query])?,
10323                        wordwise: true,
10324                        done: is_empty,
10325                    };
10326                    self.select_next_state = Some(select_state);
10327                } else {
10328                    self.select_next_state = None;
10329                }
10330            } else if let Some(selected_text) = selected_text {
10331                self.select_next_state = Some(SelectNextState {
10332                    query: AhoCorasick::new(&[selected_text])?,
10333                    wordwise: false,
10334                    done: false,
10335                });
10336                self.select_next_match_internal(
10337                    display_map,
10338                    replace_newest,
10339                    autoscroll,
10340                    window,
10341                    cx,
10342                )?;
10343            }
10344        }
10345        Ok(())
10346    }
10347
10348    pub fn select_all_matches(
10349        &mut self,
10350        _action: &SelectAllMatches,
10351        window: &mut Window,
10352        cx: &mut Context<Self>,
10353    ) -> Result<()> {
10354        self.push_to_selection_history();
10355        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10356
10357        self.select_next_match_internal(&display_map, false, None, window, cx)?;
10358        let Some(select_next_state) = self.select_next_state.as_mut() else {
10359            return Ok(());
10360        };
10361        if select_next_state.done {
10362            return Ok(());
10363        }
10364
10365        let mut new_selections = self.selections.all::<usize>(cx);
10366
10367        let buffer = &display_map.buffer_snapshot;
10368        let query_matches = select_next_state
10369            .query
10370            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10371
10372        for query_match in query_matches {
10373            let query_match = query_match.unwrap(); // can only fail due to I/O
10374            let offset_range = query_match.start()..query_match.end();
10375            let display_range = offset_range.start.to_display_point(&display_map)
10376                ..offset_range.end.to_display_point(&display_map);
10377
10378            if !select_next_state.wordwise
10379                || (!movement::is_inside_word(&display_map, display_range.start)
10380                    && !movement::is_inside_word(&display_map, display_range.end))
10381            {
10382                self.selections.change_with(cx, |selections| {
10383                    new_selections.push(Selection {
10384                        id: selections.new_selection_id(),
10385                        start: offset_range.start,
10386                        end: offset_range.end,
10387                        reversed: false,
10388                        goal: SelectionGoal::None,
10389                    });
10390                });
10391            }
10392        }
10393
10394        new_selections.sort_by_key(|selection| selection.start);
10395        let mut ix = 0;
10396        while ix + 1 < new_selections.len() {
10397            let current_selection = &new_selections[ix];
10398            let next_selection = &new_selections[ix + 1];
10399            if current_selection.range().overlaps(&next_selection.range()) {
10400                if current_selection.id < next_selection.id {
10401                    new_selections.remove(ix + 1);
10402                } else {
10403                    new_selections.remove(ix);
10404                }
10405            } else {
10406                ix += 1;
10407            }
10408        }
10409
10410        let reversed = self.selections.oldest::<usize>(cx).reversed;
10411
10412        for selection in new_selections.iter_mut() {
10413            selection.reversed = reversed;
10414        }
10415
10416        select_next_state.done = true;
10417        self.unfold_ranges(
10418            &new_selections
10419                .iter()
10420                .map(|selection| selection.range())
10421                .collect::<Vec<_>>(),
10422            false,
10423            false,
10424            cx,
10425        );
10426        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10427            selections.select(new_selections)
10428        });
10429
10430        Ok(())
10431    }
10432
10433    pub fn select_next(
10434        &mut self,
10435        action: &SelectNext,
10436        window: &mut Window,
10437        cx: &mut Context<Self>,
10438    ) -> Result<()> {
10439        self.push_to_selection_history();
10440        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10441        self.select_next_match_internal(
10442            &display_map,
10443            action.replace_newest,
10444            Some(Autoscroll::newest()),
10445            window,
10446            cx,
10447        )?;
10448        Ok(())
10449    }
10450
10451    pub fn select_previous(
10452        &mut self,
10453        action: &SelectPrevious,
10454        window: &mut Window,
10455        cx: &mut Context<Self>,
10456    ) -> Result<()> {
10457        self.push_to_selection_history();
10458        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10459        let buffer = &display_map.buffer_snapshot;
10460        let mut selections = self.selections.all::<usize>(cx);
10461        if let Some(mut select_prev_state) = self.select_prev_state.take() {
10462            let query = &select_prev_state.query;
10463            if !select_prev_state.done {
10464                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10465                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10466                let mut next_selected_range = None;
10467                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10468                let bytes_before_last_selection =
10469                    buffer.reversed_bytes_in_range(0..last_selection.start);
10470                let bytes_after_first_selection =
10471                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10472                let query_matches = query
10473                    .stream_find_iter(bytes_before_last_selection)
10474                    .map(|result| (last_selection.start, result))
10475                    .chain(
10476                        query
10477                            .stream_find_iter(bytes_after_first_selection)
10478                            .map(|result| (buffer.len(), result)),
10479                    );
10480                for (end_offset, query_match) in query_matches {
10481                    let query_match = query_match.unwrap(); // can only fail due to I/O
10482                    let offset_range =
10483                        end_offset - query_match.end()..end_offset - query_match.start();
10484                    let display_range = offset_range.start.to_display_point(&display_map)
10485                        ..offset_range.end.to_display_point(&display_map);
10486
10487                    if !select_prev_state.wordwise
10488                        || (!movement::is_inside_word(&display_map, display_range.start)
10489                            && !movement::is_inside_word(&display_map, display_range.end))
10490                    {
10491                        next_selected_range = Some(offset_range);
10492                        break;
10493                    }
10494                }
10495
10496                if let Some(next_selected_range) = next_selected_range {
10497                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10498                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10499                        if action.replace_newest {
10500                            s.delete(s.newest_anchor().id);
10501                        }
10502                        s.insert_range(next_selected_range);
10503                    });
10504                } else {
10505                    select_prev_state.done = true;
10506                }
10507            }
10508
10509            self.select_prev_state = Some(select_prev_state);
10510        } else {
10511            let mut only_carets = true;
10512            let mut same_text_selected = true;
10513            let mut selected_text = None;
10514
10515            let mut selections_iter = selections.iter().peekable();
10516            while let Some(selection) = selections_iter.next() {
10517                if selection.start != selection.end {
10518                    only_carets = false;
10519                }
10520
10521                if same_text_selected {
10522                    if selected_text.is_none() {
10523                        selected_text =
10524                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10525                    }
10526
10527                    if let Some(next_selection) = selections_iter.peek() {
10528                        if next_selection.range().len() == selection.range().len() {
10529                            let next_selected_text = buffer
10530                                .text_for_range(next_selection.range())
10531                                .collect::<String>();
10532                            if Some(next_selected_text) != selected_text {
10533                                same_text_selected = false;
10534                                selected_text = None;
10535                            }
10536                        } else {
10537                            same_text_selected = false;
10538                            selected_text = None;
10539                        }
10540                    }
10541                }
10542            }
10543
10544            if only_carets {
10545                for selection in &mut selections {
10546                    let word_range = movement::surrounding_word(
10547                        &display_map,
10548                        selection.start.to_display_point(&display_map),
10549                    );
10550                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10551                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10552                    selection.goal = SelectionGoal::None;
10553                    selection.reversed = false;
10554                }
10555                if selections.len() == 1 {
10556                    let selection = selections
10557                        .last()
10558                        .expect("ensured that there's only one selection");
10559                    let query = buffer
10560                        .text_for_range(selection.start..selection.end)
10561                        .collect::<String>();
10562                    let is_empty = query.is_empty();
10563                    let select_state = SelectNextState {
10564                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10565                        wordwise: true,
10566                        done: is_empty,
10567                    };
10568                    self.select_prev_state = Some(select_state);
10569                } else {
10570                    self.select_prev_state = None;
10571                }
10572
10573                self.unfold_ranges(
10574                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10575                    false,
10576                    true,
10577                    cx,
10578                );
10579                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10580                    s.select(selections);
10581                });
10582            } else if let Some(selected_text) = selected_text {
10583                self.select_prev_state = Some(SelectNextState {
10584                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10585                    wordwise: false,
10586                    done: false,
10587                });
10588                self.select_previous(action, window, cx)?;
10589            }
10590        }
10591        Ok(())
10592    }
10593
10594    pub fn toggle_comments(
10595        &mut self,
10596        action: &ToggleComments,
10597        window: &mut Window,
10598        cx: &mut Context<Self>,
10599    ) {
10600        if self.read_only(cx) {
10601            return;
10602        }
10603        let text_layout_details = &self.text_layout_details(window);
10604        self.transact(window, cx, |this, window, cx| {
10605            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10606            let mut edits = Vec::new();
10607            let mut selection_edit_ranges = Vec::new();
10608            let mut last_toggled_row = None;
10609            let snapshot = this.buffer.read(cx).read(cx);
10610            let empty_str: Arc<str> = Arc::default();
10611            let mut suffixes_inserted = Vec::new();
10612            let ignore_indent = action.ignore_indent;
10613
10614            fn comment_prefix_range(
10615                snapshot: &MultiBufferSnapshot,
10616                row: MultiBufferRow,
10617                comment_prefix: &str,
10618                comment_prefix_whitespace: &str,
10619                ignore_indent: bool,
10620            ) -> Range<Point> {
10621                let indent_size = if ignore_indent {
10622                    0
10623                } else {
10624                    snapshot.indent_size_for_line(row).len
10625                };
10626
10627                let start = Point::new(row.0, indent_size);
10628
10629                let mut line_bytes = snapshot
10630                    .bytes_in_range(start..snapshot.max_point())
10631                    .flatten()
10632                    .copied();
10633
10634                // If this line currently begins with the line comment prefix, then record
10635                // the range containing the prefix.
10636                if line_bytes
10637                    .by_ref()
10638                    .take(comment_prefix.len())
10639                    .eq(comment_prefix.bytes())
10640                {
10641                    // Include any whitespace that matches the comment prefix.
10642                    let matching_whitespace_len = line_bytes
10643                        .zip(comment_prefix_whitespace.bytes())
10644                        .take_while(|(a, b)| a == b)
10645                        .count() as u32;
10646                    let end = Point::new(
10647                        start.row,
10648                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10649                    );
10650                    start..end
10651                } else {
10652                    start..start
10653                }
10654            }
10655
10656            fn comment_suffix_range(
10657                snapshot: &MultiBufferSnapshot,
10658                row: MultiBufferRow,
10659                comment_suffix: &str,
10660                comment_suffix_has_leading_space: bool,
10661            ) -> Range<Point> {
10662                let end = Point::new(row.0, snapshot.line_len(row));
10663                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10664
10665                let mut line_end_bytes = snapshot
10666                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10667                    .flatten()
10668                    .copied();
10669
10670                let leading_space_len = if suffix_start_column > 0
10671                    && line_end_bytes.next() == Some(b' ')
10672                    && comment_suffix_has_leading_space
10673                {
10674                    1
10675                } else {
10676                    0
10677                };
10678
10679                // If this line currently begins with the line comment prefix, then record
10680                // the range containing the prefix.
10681                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10682                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
10683                    start..end
10684                } else {
10685                    end..end
10686                }
10687            }
10688
10689            // TODO: Handle selections that cross excerpts
10690            for selection in &mut selections {
10691                let start_column = snapshot
10692                    .indent_size_for_line(MultiBufferRow(selection.start.row))
10693                    .len;
10694                let language = if let Some(language) =
10695                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10696                {
10697                    language
10698                } else {
10699                    continue;
10700                };
10701
10702                selection_edit_ranges.clear();
10703
10704                // If multiple selections contain a given row, avoid processing that
10705                // row more than once.
10706                let mut start_row = MultiBufferRow(selection.start.row);
10707                if last_toggled_row == Some(start_row) {
10708                    start_row = start_row.next_row();
10709                }
10710                let end_row =
10711                    if selection.end.row > selection.start.row && selection.end.column == 0 {
10712                        MultiBufferRow(selection.end.row - 1)
10713                    } else {
10714                        MultiBufferRow(selection.end.row)
10715                    };
10716                last_toggled_row = Some(end_row);
10717
10718                if start_row > end_row {
10719                    continue;
10720                }
10721
10722                // If the language has line comments, toggle those.
10723                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10724
10725                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10726                if ignore_indent {
10727                    full_comment_prefixes = full_comment_prefixes
10728                        .into_iter()
10729                        .map(|s| Arc::from(s.trim_end()))
10730                        .collect();
10731                }
10732
10733                if !full_comment_prefixes.is_empty() {
10734                    let first_prefix = full_comment_prefixes
10735                        .first()
10736                        .expect("prefixes is non-empty");
10737                    let prefix_trimmed_lengths = full_comment_prefixes
10738                        .iter()
10739                        .map(|p| p.trim_end_matches(' ').len())
10740                        .collect::<SmallVec<[usize; 4]>>();
10741
10742                    let mut all_selection_lines_are_comments = true;
10743
10744                    for row in start_row.0..=end_row.0 {
10745                        let row = MultiBufferRow(row);
10746                        if start_row < end_row && snapshot.is_line_blank(row) {
10747                            continue;
10748                        }
10749
10750                        let prefix_range = full_comment_prefixes
10751                            .iter()
10752                            .zip(prefix_trimmed_lengths.iter().copied())
10753                            .map(|(prefix, trimmed_prefix_len)| {
10754                                comment_prefix_range(
10755                                    snapshot.deref(),
10756                                    row,
10757                                    &prefix[..trimmed_prefix_len],
10758                                    &prefix[trimmed_prefix_len..],
10759                                    ignore_indent,
10760                                )
10761                            })
10762                            .max_by_key(|range| range.end.column - range.start.column)
10763                            .expect("prefixes is non-empty");
10764
10765                        if prefix_range.is_empty() {
10766                            all_selection_lines_are_comments = false;
10767                        }
10768
10769                        selection_edit_ranges.push(prefix_range);
10770                    }
10771
10772                    if all_selection_lines_are_comments {
10773                        edits.extend(
10774                            selection_edit_ranges
10775                                .iter()
10776                                .cloned()
10777                                .map(|range| (range, empty_str.clone())),
10778                        );
10779                    } else {
10780                        let min_column = selection_edit_ranges
10781                            .iter()
10782                            .map(|range| range.start.column)
10783                            .min()
10784                            .unwrap_or(0);
10785                        edits.extend(selection_edit_ranges.iter().map(|range| {
10786                            let position = Point::new(range.start.row, min_column);
10787                            (position..position, first_prefix.clone())
10788                        }));
10789                    }
10790                } else if let Some((full_comment_prefix, comment_suffix)) =
10791                    language.block_comment_delimiters()
10792                {
10793                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10794                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10795                    let prefix_range = comment_prefix_range(
10796                        snapshot.deref(),
10797                        start_row,
10798                        comment_prefix,
10799                        comment_prefix_whitespace,
10800                        ignore_indent,
10801                    );
10802                    let suffix_range = comment_suffix_range(
10803                        snapshot.deref(),
10804                        end_row,
10805                        comment_suffix.trim_start_matches(' '),
10806                        comment_suffix.starts_with(' '),
10807                    );
10808
10809                    if prefix_range.is_empty() || suffix_range.is_empty() {
10810                        edits.push((
10811                            prefix_range.start..prefix_range.start,
10812                            full_comment_prefix.clone(),
10813                        ));
10814                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10815                        suffixes_inserted.push((end_row, comment_suffix.len()));
10816                    } else {
10817                        edits.push((prefix_range, empty_str.clone()));
10818                        edits.push((suffix_range, empty_str.clone()));
10819                    }
10820                } else {
10821                    continue;
10822                }
10823            }
10824
10825            drop(snapshot);
10826            this.buffer.update(cx, |buffer, cx| {
10827                buffer.edit(edits, None, cx);
10828            });
10829
10830            // Adjust selections so that they end before any comment suffixes that
10831            // were inserted.
10832            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10833            let mut selections = this.selections.all::<Point>(cx);
10834            let snapshot = this.buffer.read(cx).read(cx);
10835            for selection in &mut selections {
10836                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10837                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10838                        Ordering::Less => {
10839                            suffixes_inserted.next();
10840                            continue;
10841                        }
10842                        Ordering::Greater => break,
10843                        Ordering::Equal => {
10844                            if selection.end.column == snapshot.line_len(row) {
10845                                if selection.is_empty() {
10846                                    selection.start.column -= suffix_len as u32;
10847                                }
10848                                selection.end.column -= suffix_len as u32;
10849                            }
10850                            break;
10851                        }
10852                    }
10853                }
10854            }
10855
10856            drop(snapshot);
10857            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10858                s.select(selections)
10859            });
10860
10861            let selections = this.selections.all::<Point>(cx);
10862            let selections_on_single_row = selections.windows(2).all(|selections| {
10863                selections[0].start.row == selections[1].start.row
10864                    && selections[0].end.row == selections[1].end.row
10865                    && selections[0].start.row == selections[0].end.row
10866            });
10867            let selections_selecting = selections
10868                .iter()
10869                .any(|selection| selection.start != selection.end);
10870            let advance_downwards = action.advance_downwards
10871                && selections_on_single_row
10872                && !selections_selecting
10873                && !matches!(this.mode, EditorMode::SingleLine { .. });
10874
10875            if advance_downwards {
10876                let snapshot = this.buffer.read(cx).snapshot(cx);
10877
10878                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10879                    s.move_cursors_with(|display_snapshot, display_point, _| {
10880                        let mut point = display_point.to_point(display_snapshot);
10881                        point.row += 1;
10882                        point = snapshot.clip_point(point, Bias::Left);
10883                        let display_point = point.to_display_point(display_snapshot);
10884                        let goal = SelectionGoal::HorizontalPosition(
10885                            display_snapshot
10886                                .x_for_display_point(display_point, text_layout_details)
10887                                .into(),
10888                        );
10889                        (display_point, goal)
10890                    })
10891                });
10892            }
10893        });
10894    }
10895
10896    pub fn select_enclosing_symbol(
10897        &mut self,
10898        _: &SelectEnclosingSymbol,
10899        window: &mut Window,
10900        cx: &mut Context<Self>,
10901    ) {
10902        let buffer = self.buffer.read(cx).snapshot(cx);
10903        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10904
10905        fn update_selection(
10906            selection: &Selection<usize>,
10907            buffer_snap: &MultiBufferSnapshot,
10908        ) -> Option<Selection<usize>> {
10909            let cursor = selection.head();
10910            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10911            for symbol in symbols.iter().rev() {
10912                let start = symbol.range.start.to_offset(buffer_snap);
10913                let end = symbol.range.end.to_offset(buffer_snap);
10914                let new_range = start..end;
10915                if start < selection.start || end > selection.end {
10916                    return Some(Selection {
10917                        id: selection.id,
10918                        start: new_range.start,
10919                        end: new_range.end,
10920                        goal: SelectionGoal::None,
10921                        reversed: selection.reversed,
10922                    });
10923                }
10924            }
10925            None
10926        }
10927
10928        let mut selected_larger_symbol = false;
10929        let new_selections = old_selections
10930            .iter()
10931            .map(|selection| match update_selection(selection, &buffer) {
10932                Some(new_selection) => {
10933                    if new_selection.range() != selection.range() {
10934                        selected_larger_symbol = true;
10935                    }
10936                    new_selection
10937                }
10938                None => selection.clone(),
10939            })
10940            .collect::<Vec<_>>();
10941
10942        if selected_larger_symbol {
10943            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10944                s.select(new_selections);
10945            });
10946        }
10947    }
10948
10949    pub fn select_larger_syntax_node(
10950        &mut self,
10951        _: &SelectLargerSyntaxNode,
10952        window: &mut Window,
10953        cx: &mut Context<Self>,
10954    ) {
10955        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10956        let buffer = self.buffer.read(cx).snapshot(cx);
10957        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10958
10959        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10960        let mut selected_larger_node = false;
10961        let new_selections = old_selections
10962            .iter()
10963            .map(|selection| {
10964                let old_range = selection.start..selection.end;
10965                let mut new_range = old_range.clone();
10966                let mut new_node = None;
10967                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10968                {
10969                    new_node = Some(node);
10970                    new_range = match containing_range {
10971                        MultiOrSingleBufferOffsetRange::Single(_) => break,
10972                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
10973                    };
10974                    if !display_map.intersects_fold(new_range.start)
10975                        && !display_map.intersects_fold(new_range.end)
10976                    {
10977                        break;
10978                    }
10979                }
10980
10981                if let Some(node) = new_node {
10982                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10983                    // nodes. Parent and grandparent are also logged because this operation will not
10984                    // visit nodes that have the same range as their parent.
10985                    log::info!("Node: {node:?}");
10986                    let parent = node.parent();
10987                    log::info!("Parent: {parent:?}");
10988                    let grandparent = parent.and_then(|x| x.parent());
10989                    log::info!("Grandparent: {grandparent:?}");
10990                }
10991
10992                selected_larger_node |= new_range != old_range;
10993                Selection {
10994                    id: selection.id,
10995                    start: new_range.start,
10996                    end: new_range.end,
10997                    goal: SelectionGoal::None,
10998                    reversed: selection.reversed,
10999                }
11000            })
11001            .collect::<Vec<_>>();
11002
11003        if selected_larger_node {
11004            stack.push(old_selections);
11005            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11006                s.select(new_selections);
11007            });
11008        }
11009        self.select_larger_syntax_node_stack = stack;
11010    }
11011
11012    pub fn select_smaller_syntax_node(
11013        &mut self,
11014        _: &SelectSmallerSyntaxNode,
11015        window: &mut Window,
11016        cx: &mut Context<Self>,
11017    ) {
11018        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11019        if let Some(selections) = stack.pop() {
11020            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11021                s.select(selections.to_vec());
11022            });
11023        }
11024        self.select_larger_syntax_node_stack = stack;
11025    }
11026
11027    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
11028        if !EditorSettings::get_global(cx).gutter.runnables {
11029            self.clear_tasks();
11030            return Task::ready(());
11031        }
11032        let project = self.project.as_ref().map(Entity::downgrade);
11033        cx.spawn_in(window, |this, mut cx| async move {
11034            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
11035            let Some(project) = project.and_then(|p| p.upgrade()) else {
11036                return;
11037            };
11038            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
11039                this.display_map.update(cx, |map, cx| map.snapshot(cx))
11040            }) else {
11041                return;
11042            };
11043
11044            let hide_runnables = project
11045                .update(&mut cx, |project, cx| {
11046                    // Do not display any test indicators in non-dev server remote projects.
11047                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
11048                })
11049                .unwrap_or(true);
11050            if hide_runnables {
11051                return;
11052            }
11053            let new_rows =
11054                cx.background_spawn({
11055                    let snapshot = display_snapshot.clone();
11056                    async move {
11057                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
11058                    }
11059                })
11060                    .await;
11061
11062            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
11063            this.update(&mut cx, |this, _| {
11064                this.clear_tasks();
11065                for (key, value) in rows {
11066                    this.insert_tasks(key, value);
11067                }
11068            })
11069            .ok();
11070        })
11071    }
11072    fn fetch_runnable_ranges(
11073        snapshot: &DisplaySnapshot,
11074        range: Range<Anchor>,
11075    ) -> Vec<language::RunnableRange> {
11076        snapshot.buffer_snapshot.runnable_ranges(range).collect()
11077    }
11078
11079    fn runnable_rows(
11080        project: Entity<Project>,
11081        snapshot: DisplaySnapshot,
11082        runnable_ranges: Vec<RunnableRange>,
11083        mut cx: AsyncWindowContext,
11084    ) -> Vec<((BufferId, u32), RunnableTasks)> {
11085        runnable_ranges
11086            .into_iter()
11087            .filter_map(|mut runnable| {
11088                let tasks = cx
11089                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11090                    .ok()?;
11091                if tasks.is_empty() {
11092                    return None;
11093                }
11094
11095                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11096
11097                let row = snapshot
11098                    .buffer_snapshot
11099                    .buffer_line_for_row(MultiBufferRow(point.row))?
11100                    .1
11101                    .start
11102                    .row;
11103
11104                let context_range =
11105                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11106                Some((
11107                    (runnable.buffer_id, row),
11108                    RunnableTasks {
11109                        templates: tasks,
11110                        offset: snapshot
11111                            .buffer_snapshot
11112                            .anchor_before(runnable.run_range.start),
11113                        context_range,
11114                        column: point.column,
11115                        extra_variables: runnable.extra_captures,
11116                    },
11117                ))
11118            })
11119            .collect()
11120    }
11121
11122    fn templates_with_tags(
11123        project: &Entity<Project>,
11124        runnable: &mut Runnable,
11125        cx: &mut App,
11126    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11127        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11128            let (worktree_id, file) = project
11129                .buffer_for_id(runnable.buffer, cx)
11130                .and_then(|buffer| buffer.read(cx).file())
11131                .map(|file| (file.worktree_id(cx), file.clone()))
11132                .unzip();
11133
11134            (
11135                project.task_store().read(cx).task_inventory().cloned(),
11136                worktree_id,
11137                file,
11138            )
11139        });
11140
11141        let tags = mem::take(&mut runnable.tags);
11142        let mut tags: Vec<_> = tags
11143            .into_iter()
11144            .flat_map(|tag| {
11145                let tag = tag.0.clone();
11146                inventory
11147                    .as_ref()
11148                    .into_iter()
11149                    .flat_map(|inventory| {
11150                        inventory.read(cx).list_tasks(
11151                            file.clone(),
11152                            Some(runnable.language.clone()),
11153                            worktree_id,
11154                            cx,
11155                        )
11156                    })
11157                    .filter(move |(_, template)| {
11158                        template.tags.iter().any(|source_tag| source_tag == &tag)
11159                    })
11160            })
11161            .sorted_by_key(|(kind, _)| kind.to_owned())
11162            .collect();
11163        if let Some((leading_tag_source, _)) = tags.first() {
11164            // Strongest source wins; if we have worktree tag binding, prefer that to
11165            // global and language bindings;
11166            // if we have a global binding, prefer that to language binding.
11167            let first_mismatch = tags
11168                .iter()
11169                .position(|(tag_source, _)| tag_source != leading_tag_source);
11170            if let Some(index) = first_mismatch {
11171                tags.truncate(index);
11172            }
11173        }
11174
11175        tags
11176    }
11177
11178    pub fn move_to_enclosing_bracket(
11179        &mut self,
11180        _: &MoveToEnclosingBracket,
11181        window: &mut Window,
11182        cx: &mut Context<Self>,
11183    ) {
11184        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11185            s.move_offsets_with(|snapshot, selection| {
11186                let Some(enclosing_bracket_ranges) =
11187                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11188                else {
11189                    return;
11190                };
11191
11192                let mut best_length = usize::MAX;
11193                let mut best_inside = false;
11194                let mut best_in_bracket_range = false;
11195                let mut best_destination = None;
11196                for (open, close) in enclosing_bracket_ranges {
11197                    let close = close.to_inclusive();
11198                    let length = close.end() - open.start;
11199                    let inside = selection.start >= open.end && selection.end <= *close.start();
11200                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
11201                        || close.contains(&selection.head());
11202
11203                    // If best is next to a bracket and current isn't, skip
11204                    if !in_bracket_range && best_in_bracket_range {
11205                        continue;
11206                    }
11207
11208                    // Prefer smaller lengths unless best is inside and current isn't
11209                    if length > best_length && (best_inside || !inside) {
11210                        continue;
11211                    }
11212
11213                    best_length = length;
11214                    best_inside = inside;
11215                    best_in_bracket_range = in_bracket_range;
11216                    best_destination = Some(
11217                        if close.contains(&selection.start) && close.contains(&selection.end) {
11218                            if inside {
11219                                open.end
11220                            } else {
11221                                open.start
11222                            }
11223                        } else if inside {
11224                            *close.start()
11225                        } else {
11226                            *close.end()
11227                        },
11228                    );
11229                }
11230
11231                if let Some(destination) = best_destination {
11232                    selection.collapse_to(destination, SelectionGoal::None);
11233                }
11234            })
11235        });
11236    }
11237
11238    pub fn undo_selection(
11239        &mut self,
11240        _: &UndoSelection,
11241        window: &mut Window,
11242        cx: &mut Context<Self>,
11243    ) {
11244        self.end_selection(window, cx);
11245        self.selection_history.mode = SelectionHistoryMode::Undoing;
11246        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11247            self.change_selections(None, window, cx, |s| {
11248                s.select_anchors(entry.selections.to_vec())
11249            });
11250            self.select_next_state = entry.select_next_state;
11251            self.select_prev_state = entry.select_prev_state;
11252            self.add_selections_state = entry.add_selections_state;
11253            self.request_autoscroll(Autoscroll::newest(), cx);
11254        }
11255        self.selection_history.mode = SelectionHistoryMode::Normal;
11256    }
11257
11258    pub fn redo_selection(
11259        &mut self,
11260        _: &RedoSelection,
11261        window: &mut Window,
11262        cx: &mut Context<Self>,
11263    ) {
11264        self.end_selection(window, cx);
11265        self.selection_history.mode = SelectionHistoryMode::Redoing;
11266        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11267            self.change_selections(None, window, cx, |s| {
11268                s.select_anchors(entry.selections.to_vec())
11269            });
11270            self.select_next_state = entry.select_next_state;
11271            self.select_prev_state = entry.select_prev_state;
11272            self.add_selections_state = entry.add_selections_state;
11273            self.request_autoscroll(Autoscroll::newest(), cx);
11274        }
11275        self.selection_history.mode = SelectionHistoryMode::Normal;
11276    }
11277
11278    pub fn expand_excerpts(
11279        &mut self,
11280        action: &ExpandExcerpts,
11281        _: &mut Window,
11282        cx: &mut Context<Self>,
11283    ) {
11284        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11285    }
11286
11287    pub fn expand_excerpts_down(
11288        &mut self,
11289        action: &ExpandExcerptsDown,
11290        _: &mut Window,
11291        cx: &mut Context<Self>,
11292    ) {
11293        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11294    }
11295
11296    pub fn expand_excerpts_up(
11297        &mut self,
11298        action: &ExpandExcerptsUp,
11299        _: &mut Window,
11300        cx: &mut Context<Self>,
11301    ) {
11302        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11303    }
11304
11305    pub fn expand_excerpts_for_direction(
11306        &mut self,
11307        lines: u32,
11308        direction: ExpandExcerptDirection,
11309
11310        cx: &mut Context<Self>,
11311    ) {
11312        let selections = self.selections.disjoint_anchors();
11313
11314        let lines = if lines == 0 {
11315            EditorSettings::get_global(cx).expand_excerpt_lines
11316        } else {
11317            lines
11318        };
11319
11320        self.buffer.update(cx, |buffer, cx| {
11321            let snapshot = buffer.snapshot(cx);
11322            let mut excerpt_ids = selections
11323                .iter()
11324                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11325                .collect::<Vec<_>>();
11326            excerpt_ids.sort();
11327            excerpt_ids.dedup();
11328            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11329        })
11330    }
11331
11332    pub fn expand_excerpt(
11333        &mut self,
11334        excerpt: ExcerptId,
11335        direction: ExpandExcerptDirection,
11336        cx: &mut Context<Self>,
11337    ) {
11338        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11339        self.buffer.update(cx, |buffer, cx| {
11340            buffer.expand_excerpts([excerpt], lines, direction, cx)
11341        })
11342    }
11343
11344    pub fn go_to_singleton_buffer_point(
11345        &mut self,
11346        point: Point,
11347        window: &mut Window,
11348        cx: &mut Context<Self>,
11349    ) {
11350        self.go_to_singleton_buffer_range(point..point, window, cx);
11351    }
11352
11353    pub fn go_to_singleton_buffer_range(
11354        &mut self,
11355        range: Range<Point>,
11356        window: &mut Window,
11357        cx: &mut Context<Self>,
11358    ) {
11359        let multibuffer = self.buffer().read(cx);
11360        let Some(buffer) = multibuffer.as_singleton() else {
11361            return;
11362        };
11363        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11364            return;
11365        };
11366        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11367            return;
11368        };
11369        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11370            s.select_anchor_ranges([start..end])
11371        });
11372    }
11373
11374    fn go_to_diagnostic(
11375        &mut self,
11376        _: &GoToDiagnostic,
11377        window: &mut Window,
11378        cx: &mut Context<Self>,
11379    ) {
11380        self.go_to_diagnostic_impl(Direction::Next, window, cx)
11381    }
11382
11383    fn go_to_prev_diagnostic(
11384        &mut self,
11385        _: &GoToPreviousDiagnostic,
11386        window: &mut Window,
11387        cx: &mut Context<Self>,
11388    ) {
11389        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11390    }
11391
11392    pub fn go_to_diagnostic_impl(
11393        &mut self,
11394        direction: Direction,
11395        window: &mut Window,
11396        cx: &mut Context<Self>,
11397    ) {
11398        let buffer = self.buffer.read(cx).snapshot(cx);
11399        let selection = self.selections.newest::<usize>(cx);
11400
11401        // If there is an active Diagnostic Popover jump to its diagnostic instead.
11402        if direction == Direction::Next {
11403            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11404                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11405                    return;
11406                };
11407                self.activate_diagnostics(
11408                    buffer_id,
11409                    popover.local_diagnostic.diagnostic.group_id,
11410                    window,
11411                    cx,
11412                );
11413                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11414                    let primary_range_start = active_diagnostics.primary_range.start;
11415                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11416                        let mut new_selection = s.newest_anchor().clone();
11417                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11418                        s.select_anchors(vec![new_selection.clone()]);
11419                    });
11420                    self.refresh_inline_completion(false, true, window, cx);
11421                }
11422                return;
11423            }
11424        }
11425
11426        let active_group_id = self
11427            .active_diagnostics
11428            .as_ref()
11429            .map(|active_group| active_group.group_id);
11430        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11431            active_diagnostics
11432                .primary_range
11433                .to_offset(&buffer)
11434                .to_inclusive()
11435        });
11436        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11437            if active_primary_range.contains(&selection.head()) {
11438                *active_primary_range.start()
11439            } else {
11440                selection.head()
11441            }
11442        } else {
11443            selection.head()
11444        };
11445
11446        let snapshot = self.snapshot(window, cx);
11447        let primary_diagnostics_before = buffer
11448            .diagnostics_in_range::<usize>(0..search_start)
11449            .filter(|entry| entry.diagnostic.is_primary)
11450            .filter(|entry| entry.range.start != entry.range.end)
11451            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11452            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11453            .collect::<Vec<_>>();
11454        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11455            primary_diagnostics_before
11456                .iter()
11457                .position(|entry| entry.diagnostic.group_id == active_group_id)
11458        });
11459
11460        let primary_diagnostics_after = buffer
11461            .diagnostics_in_range::<usize>(search_start..buffer.len())
11462            .filter(|entry| entry.diagnostic.is_primary)
11463            .filter(|entry| entry.range.start != entry.range.end)
11464            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11465            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11466            .collect::<Vec<_>>();
11467        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11468            primary_diagnostics_after
11469                .iter()
11470                .enumerate()
11471                .rev()
11472                .find_map(|(i, entry)| {
11473                    if entry.diagnostic.group_id == active_group_id {
11474                        Some(i)
11475                    } else {
11476                        None
11477                    }
11478                })
11479        });
11480
11481        let next_primary_diagnostic = match direction {
11482            Direction::Prev => primary_diagnostics_before
11483                .iter()
11484                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11485                .rev()
11486                .next(),
11487            Direction::Next => primary_diagnostics_after
11488                .iter()
11489                .skip(
11490                    last_same_group_diagnostic_after
11491                        .map(|index| index + 1)
11492                        .unwrap_or(0),
11493                )
11494                .next(),
11495        };
11496
11497        // Cycle around to the start of the buffer, potentially moving back to the start of
11498        // the currently active diagnostic.
11499        let cycle_around = || match direction {
11500            Direction::Prev => primary_diagnostics_after
11501                .iter()
11502                .rev()
11503                .chain(primary_diagnostics_before.iter().rev())
11504                .next(),
11505            Direction::Next => primary_diagnostics_before
11506                .iter()
11507                .chain(primary_diagnostics_after.iter())
11508                .next(),
11509        };
11510
11511        if let Some((primary_range, group_id)) = next_primary_diagnostic
11512            .or_else(cycle_around)
11513            .map(|entry| (&entry.range, entry.diagnostic.group_id))
11514        {
11515            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11516                return;
11517            };
11518            self.activate_diagnostics(buffer_id, group_id, window, cx);
11519            if self.active_diagnostics.is_some() {
11520                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11521                    s.select(vec![Selection {
11522                        id: selection.id,
11523                        start: primary_range.start,
11524                        end: primary_range.start,
11525                        reversed: false,
11526                        goal: SelectionGoal::None,
11527                    }]);
11528                });
11529                self.refresh_inline_completion(false, true, window, cx);
11530            }
11531        }
11532    }
11533
11534    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11535        let snapshot = self.snapshot(window, cx);
11536        let selection = self.selections.newest::<Point>(cx);
11537        self.go_to_hunk_after_or_before_position(
11538            &snapshot,
11539            selection.head(),
11540            Direction::Next,
11541            window,
11542            cx,
11543        );
11544    }
11545
11546    fn go_to_hunk_after_or_before_position(
11547        &mut self,
11548        snapshot: &EditorSnapshot,
11549        position: Point,
11550        direction: Direction,
11551        window: &mut Window,
11552        cx: &mut Context<Editor>,
11553    ) {
11554        let row = if direction == Direction::Next {
11555            self.hunk_after_position(snapshot, position)
11556                .map(|hunk| hunk.row_range.start)
11557        } else {
11558            self.hunk_before_position(snapshot, position)
11559        };
11560
11561        if let Some(row) = row {
11562            let destination = Point::new(row.0, 0);
11563            let autoscroll = Autoscroll::center();
11564
11565            self.unfold_ranges(&[destination..destination], false, false, cx);
11566            self.change_selections(Some(autoscroll), window, cx, |s| {
11567                s.select_ranges([destination..destination]);
11568            });
11569        }
11570    }
11571
11572    fn hunk_after_position(
11573        &mut self,
11574        snapshot: &EditorSnapshot,
11575        position: Point,
11576    ) -> Option<MultiBufferDiffHunk> {
11577        snapshot
11578            .buffer_snapshot
11579            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11580            .find(|hunk| hunk.row_range.start.0 > position.row)
11581            .or_else(|| {
11582                snapshot
11583                    .buffer_snapshot
11584                    .diff_hunks_in_range(Point::zero()..position)
11585                    .find(|hunk| hunk.row_range.end.0 < position.row)
11586            })
11587    }
11588
11589    fn go_to_prev_hunk(
11590        &mut self,
11591        _: &GoToPreviousHunk,
11592        window: &mut Window,
11593        cx: &mut Context<Self>,
11594    ) {
11595        let snapshot = self.snapshot(window, cx);
11596        let selection = self.selections.newest::<Point>(cx);
11597        self.go_to_hunk_after_or_before_position(
11598            &snapshot,
11599            selection.head(),
11600            Direction::Prev,
11601            window,
11602            cx,
11603        );
11604    }
11605
11606    fn hunk_before_position(
11607        &mut self,
11608        snapshot: &EditorSnapshot,
11609        position: Point,
11610    ) -> Option<MultiBufferRow> {
11611        snapshot
11612            .buffer_snapshot
11613            .diff_hunk_before(position)
11614            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11615    }
11616
11617    pub fn go_to_definition(
11618        &mut self,
11619        _: &GoToDefinition,
11620        window: &mut Window,
11621        cx: &mut Context<Self>,
11622    ) -> Task<Result<Navigated>> {
11623        let definition =
11624            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11625        cx.spawn_in(window, |editor, mut cx| async move {
11626            if definition.await? == Navigated::Yes {
11627                return Ok(Navigated::Yes);
11628            }
11629            match editor.update_in(&mut cx, |editor, window, cx| {
11630                editor.find_all_references(&FindAllReferences, window, cx)
11631            })? {
11632                Some(references) => references.await,
11633                None => Ok(Navigated::No),
11634            }
11635        })
11636    }
11637
11638    pub fn go_to_declaration(
11639        &mut self,
11640        _: &GoToDeclaration,
11641        window: &mut Window,
11642        cx: &mut Context<Self>,
11643    ) -> Task<Result<Navigated>> {
11644        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11645    }
11646
11647    pub fn go_to_declaration_split(
11648        &mut self,
11649        _: &GoToDeclaration,
11650        window: &mut Window,
11651        cx: &mut Context<Self>,
11652    ) -> Task<Result<Navigated>> {
11653        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11654    }
11655
11656    pub fn go_to_implementation(
11657        &mut self,
11658        _: &GoToImplementation,
11659        window: &mut Window,
11660        cx: &mut Context<Self>,
11661    ) -> Task<Result<Navigated>> {
11662        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11663    }
11664
11665    pub fn go_to_implementation_split(
11666        &mut self,
11667        _: &GoToImplementationSplit,
11668        window: &mut Window,
11669        cx: &mut Context<Self>,
11670    ) -> Task<Result<Navigated>> {
11671        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11672    }
11673
11674    pub fn go_to_type_definition(
11675        &mut self,
11676        _: &GoToTypeDefinition,
11677        window: &mut Window,
11678        cx: &mut Context<Self>,
11679    ) -> Task<Result<Navigated>> {
11680        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11681    }
11682
11683    pub fn go_to_definition_split(
11684        &mut self,
11685        _: &GoToDefinitionSplit,
11686        window: &mut Window,
11687        cx: &mut Context<Self>,
11688    ) -> Task<Result<Navigated>> {
11689        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11690    }
11691
11692    pub fn go_to_type_definition_split(
11693        &mut self,
11694        _: &GoToTypeDefinitionSplit,
11695        window: &mut Window,
11696        cx: &mut Context<Self>,
11697    ) -> Task<Result<Navigated>> {
11698        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11699    }
11700
11701    fn go_to_definition_of_kind(
11702        &mut self,
11703        kind: GotoDefinitionKind,
11704        split: bool,
11705        window: &mut Window,
11706        cx: &mut Context<Self>,
11707    ) -> Task<Result<Navigated>> {
11708        let Some(provider) = self.semantics_provider.clone() else {
11709            return Task::ready(Ok(Navigated::No));
11710        };
11711        let head = self.selections.newest::<usize>(cx).head();
11712        let buffer = self.buffer.read(cx);
11713        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11714            text_anchor
11715        } else {
11716            return Task::ready(Ok(Navigated::No));
11717        };
11718
11719        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11720            return Task::ready(Ok(Navigated::No));
11721        };
11722
11723        cx.spawn_in(window, |editor, mut cx| async move {
11724            let definitions = definitions.await?;
11725            let navigated = editor
11726                .update_in(&mut cx, |editor, window, cx| {
11727                    editor.navigate_to_hover_links(
11728                        Some(kind),
11729                        definitions
11730                            .into_iter()
11731                            .filter(|location| {
11732                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11733                            })
11734                            .map(HoverLink::Text)
11735                            .collect::<Vec<_>>(),
11736                        split,
11737                        window,
11738                        cx,
11739                    )
11740                })?
11741                .await?;
11742            anyhow::Ok(navigated)
11743        })
11744    }
11745
11746    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11747        let selection = self.selections.newest_anchor();
11748        let head = selection.head();
11749        let tail = selection.tail();
11750
11751        let Some((buffer, start_position)) =
11752            self.buffer.read(cx).text_anchor_for_position(head, cx)
11753        else {
11754            return;
11755        };
11756
11757        let end_position = if head != tail {
11758            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11759                return;
11760            };
11761            Some(pos)
11762        } else {
11763            None
11764        };
11765
11766        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11767            let url = if let Some(end_pos) = end_position {
11768                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11769            } else {
11770                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11771            };
11772
11773            if let Some(url) = url {
11774                editor.update(&mut cx, |_, cx| {
11775                    cx.open_url(&url);
11776                })
11777            } else {
11778                Ok(())
11779            }
11780        });
11781
11782        url_finder.detach();
11783    }
11784
11785    pub fn open_selected_filename(
11786        &mut self,
11787        _: &OpenSelectedFilename,
11788        window: &mut Window,
11789        cx: &mut Context<Self>,
11790    ) {
11791        let Some(workspace) = self.workspace() else {
11792            return;
11793        };
11794
11795        let position = self.selections.newest_anchor().head();
11796
11797        let Some((buffer, buffer_position)) =
11798            self.buffer.read(cx).text_anchor_for_position(position, cx)
11799        else {
11800            return;
11801        };
11802
11803        let project = self.project.clone();
11804
11805        cx.spawn_in(window, |_, mut cx| async move {
11806            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11807
11808            if let Some((_, path)) = result {
11809                workspace
11810                    .update_in(&mut cx, |workspace, window, cx| {
11811                        workspace.open_resolved_path(path, window, cx)
11812                    })?
11813                    .await?;
11814            }
11815            anyhow::Ok(())
11816        })
11817        .detach();
11818    }
11819
11820    pub(crate) fn navigate_to_hover_links(
11821        &mut self,
11822        kind: Option<GotoDefinitionKind>,
11823        mut definitions: Vec<HoverLink>,
11824        split: bool,
11825        window: &mut Window,
11826        cx: &mut Context<Editor>,
11827    ) -> Task<Result<Navigated>> {
11828        // If there is one definition, just open it directly
11829        if definitions.len() == 1 {
11830            let definition = definitions.pop().unwrap();
11831
11832            enum TargetTaskResult {
11833                Location(Option<Location>),
11834                AlreadyNavigated,
11835            }
11836
11837            let target_task = match definition {
11838                HoverLink::Text(link) => {
11839                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11840                }
11841                HoverLink::InlayHint(lsp_location, server_id) => {
11842                    let computation =
11843                        self.compute_target_location(lsp_location, server_id, window, cx);
11844                    cx.background_spawn(async move {
11845                        let location = computation.await?;
11846                        Ok(TargetTaskResult::Location(location))
11847                    })
11848                }
11849                HoverLink::Url(url) => {
11850                    cx.open_url(&url);
11851                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11852                }
11853                HoverLink::File(path) => {
11854                    if let Some(workspace) = self.workspace() {
11855                        cx.spawn_in(window, |_, mut cx| async move {
11856                            workspace
11857                                .update_in(&mut cx, |workspace, window, cx| {
11858                                    workspace.open_resolved_path(path, window, cx)
11859                                })?
11860                                .await
11861                                .map(|_| TargetTaskResult::AlreadyNavigated)
11862                        })
11863                    } else {
11864                        Task::ready(Ok(TargetTaskResult::Location(None)))
11865                    }
11866                }
11867            };
11868            cx.spawn_in(window, |editor, mut cx| async move {
11869                let target = match target_task.await.context("target resolution task")? {
11870                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11871                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11872                    TargetTaskResult::Location(Some(target)) => target,
11873                };
11874
11875                editor.update_in(&mut cx, |editor, window, cx| {
11876                    let Some(workspace) = editor.workspace() else {
11877                        return Navigated::No;
11878                    };
11879                    let pane = workspace.read(cx).active_pane().clone();
11880
11881                    let range = target.range.to_point(target.buffer.read(cx));
11882                    let range = editor.range_for_match(&range);
11883                    let range = collapse_multiline_range(range);
11884
11885                    if !split
11886                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11887                    {
11888                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11889                    } else {
11890                        window.defer(cx, move |window, cx| {
11891                            let target_editor: Entity<Self> =
11892                                workspace.update(cx, |workspace, cx| {
11893                                    let pane = if split {
11894                                        workspace.adjacent_pane(window, cx)
11895                                    } else {
11896                                        workspace.active_pane().clone()
11897                                    };
11898
11899                                    workspace.open_project_item(
11900                                        pane,
11901                                        target.buffer.clone(),
11902                                        true,
11903                                        true,
11904                                        window,
11905                                        cx,
11906                                    )
11907                                });
11908                            target_editor.update(cx, |target_editor, cx| {
11909                                // When selecting a definition in a different buffer, disable the nav history
11910                                // to avoid creating a history entry at the previous cursor location.
11911                                pane.update(cx, |pane, _| pane.disable_history());
11912                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11913                                pane.update(cx, |pane, _| pane.enable_history());
11914                            });
11915                        });
11916                    }
11917                    Navigated::Yes
11918                })
11919            })
11920        } else if !definitions.is_empty() {
11921            cx.spawn_in(window, |editor, mut cx| async move {
11922                let (title, location_tasks, workspace) = editor
11923                    .update_in(&mut cx, |editor, window, cx| {
11924                        let tab_kind = match kind {
11925                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11926                            _ => "Definitions",
11927                        };
11928                        let title = definitions
11929                            .iter()
11930                            .find_map(|definition| match definition {
11931                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11932                                    let buffer = origin.buffer.read(cx);
11933                                    format!(
11934                                        "{} for {}",
11935                                        tab_kind,
11936                                        buffer
11937                                            .text_for_range(origin.range.clone())
11938                                            .collect::<String>()
11939                                    )
11940                                }),
11941                                HoverLink::InlayHint(_, _) => None,
11942                                HoverLink::Url(_) => None,
11943                                HoverLink::File(_) => None,
11944                            })
11945                            .unwrap_or(tab_kind.to_string());
11946                        let location_tasks = definitions
11947                            .into_iter()
11948                            .map(|definition| match definition {
11949                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11950                                HoverLink::InlayHint(lsp_location, server_id) => editor
11951                                    .compute_target_location(lsp_location, server_id, window, cx),
11952                                HoverLink::Url(_) => Task::ready(Ok(None)),
11953                                HoverLink::File(_) => Task::ready(Ok(None)),
11954                            })
11955                            .collect::<Vec<_>>();
11956                        (title, location_tasks, editor.workspace().clone())
11957                    })
11958                    .context("location tasks preparation")?;
11959
11960                let locations = future::join_all(location_tasks)
11961                    .await
11962                    .into_iter()
11963                    .filter_map(|location| location.transpose())
11964                    .collect::<Result<_>>()
11965                    .context("location tasks")?;
11966
11967                let Some(workspace) = workspace else {
11968                    return Ok(Navigated::No);
11969                };
11970                let opened = workspace
11971                    .update_in(&mut cx, |workspace, window, cx| {
11972                        Self::open_locations_in_multibuffer(
11973                            workspace,
11974                            locations,
11975                            title,
11976                            split,
11977                            MultibufferSelectionMode::First,
11978                            window,
11979                            cx,
11980                        )
11981                    })
11982                    .ok();
11983
11984                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11985            })
11986        } else {
11987            Task::ready(Ok(Navigated::No))
11988        }
11989    }
11990
11991    fn compute_target_location(
11992        &self,
11993        lsp_location: lsp::Location,
11994        server_id: LanguageServerId,
11995        window: &mut Window,
11996        cx: &mut Context<Self>,
11997    ) -> Task<anyhow::Result<Option<Location>>> {
11998        let Some(project) = self.project.clone() else {
11999            return Task::ready(Ok(None));
12000        };
12001
12002        cx.spawn_in(window, move |editor, mut cx| async move {
12003            let location_task = editor.update(&mut cx, |_, cx| {
12004                project.update(cx, |project, cx| {
12005                    let language_server_name = project
12006                        .language_server_statuses(cx)
12007                        .find(|(id, _)| server_id == *id)
12008                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
12009                    language_server_name.map(|language_server_name| {
12010                        project.open_local_buffer_via_lsp(
12011                            lsp_location.uri.clone(),
12012                            server_id,
12013                            language_server_name,
12014                            cx,
12015                        )
12016                    })
12017                })
12018            })?;
12019            let location = match location_task {
12020                Some(task) => Some({
12021                    let target_buffer_handle = task.await.context("open local buffer")?;
12022                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
12023                        let target_start = target_buffer
12024                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
12025                        let target_end = target_buffer
12026                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
12027                        target_buffer.anchor_after(target_start)
12028                            ..target_buffer.anchor_before(target_end)
12029                    })?;
12030                    Location {
12031                        buffer: target_buffer_handle,
12032                        range,
12033                    }
12034                }),
12035                None => None,
12036            };
12037            Ok(location)
12038        })
12039    }
12040
12041    pub fn find_all_references(
12042        &mut self,
12043        _: &FindAllReferences,
12044        window: &mut Window,
12045        cx: &mut Context<Self>,
12046    ) -> Option<Task<Result<Navigated>>> {
12047        let selection = self.selections.newest::<usize>(cx);
12048        let multi_buffer = self.buffer.read(cx);
12049        let head = selection.head();
12050
12051        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12052        let head_anchor = multi_buffer_snapshot.anchor_at(
12053            head,
12054            if head < selection.tail() {
12055                Bias::Right
12056            } else {
12057                Bias::Left
12058            },
12059        );
12060
12061        match self
12062            .find_all_references_task_sources
12063            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12064        {
12065            Ok(_) => {
12066                log::info!(
12067                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
12068                );
12069                return None;
12070            }
12071            Err(i) => {
12072                self.find_all_references_task_sources.insert(i, head_anchor);
12073            }
12074        }
12075
12076        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12077        let workspace = self.workspace()?;
12078        let project = workspace.read(cx).project().clone();
12079        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12080        Some(cx.spawn_in(window, |editor, mut cx| async move {
12081            let _cleanup = defer({
12082                let mut cx = cx.clone();
12083                move || {
12084                    let _ = editor.update(&mut cx, |editor, _| {
12085                        if let Ok(i) =
12086                            editor
12087                                .find_all_references_task_sources
12088                                .binary_search_by(|anchor| {
12089                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
12090                                })
12091                        {
12092                            editor.find_all_references_task_sources.remove(i);
12093                        }
12094                    });
12095                }
12096            });
12097
12098            let locations = references.await?;
12099            if locations.is_empty() {
12100                return anyhow::Ok(Navigated::No);
12101            }
12102
12103            workspace.update_in(&mut cx, |workspace, window, cx| {
12104                let title = locations
12105                    .first()
12106                    .as_ref()
12107                    .map(|location| {
12108                        let buffer = location.buffer.read(cx);
12109                        format!(
12110                            "References to `{}`",
12111                            buffer
12112                                .text_for_range(location.range.clone())
12113                                .collect::<String>()
12114                        )
12115                    })
12116                    .unwrap();
12117                Self::open_locations_in_multibuffer(
12118                    workspace,
12119                    locations,
12120                    title,
12121                    false,
12122                    MultibufferSelectionMode::First,
12123                    window,
12124                    cx,
12125                );
12126                Navigated::Yes
12127            })
12128        }))
12129    }
12130
12131    /// Opens a multibuffer with the given project locations in it
12132    pub fn open_locations_in_multibuffer(
12133        workspace: &mut Workspace,
12134        mut locations: Vec<Location>,
12135        title: String,
12136        split: bool,
12137        multibuffer_selection_mode: MultibufferSelectionMode,
12138        window: &mut Window,
12139        cx: &mut Context<Workspace>,
12140    ) {
12141        // If there are multiple definitions, open them in a multibuffer
12142        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12143        let mut locations = locations.into_iter().peekable();
12144        let mut ranges = Vec::new();
12145        let capability = workspace.project().read(cx).capability();
12146
12147        let excerpt_buffer = cx.new(|cx| {
12148            let mut multibuffer = MultiBuffer::new(capability);
12149            while let Some(location) = locations.next() {
12150                let buffer = location.buffer.read(cx);
12151                let mut ranges_for_buffer = Vec::new();
12152                let range = location.range.to_offset(buffer);
12153                ranges_for_buffer.push(range.clone());
12154
12155                while let Some(next_location) = locations.peek() {
12156                    if next_location.buffer == location.buffer {
12157                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
12158                        locations.next();
12159                    } else {
12160                        break;
12161                    }
12162                }
12163
12164                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12165                ranges.extend(multibuffer.push_excerpts_with_context_lines(
12166                    location.buffer.clone(),
12167                    ranges_for_buffer,
12168                    DEFAULT_MULTIBUFFER_CONTEXT,
12169                    cx,
12170                ))
12171            }
12172
12173            multibuffer.with_title(title)
12174        });
12175
12176        let editor = cx.new(|cx| {
12177            Editor::for_multibuffer(
12178                excerpt_buffer,
12179                Some(workspace.project().clone()),
12180                true,
12181                window,
12182                cx,
12183            )
12184        });
12185        editor.update(cx, |editor, cx| {
12186            match multibuffer_selection_mode {
12187                MultibufferSelectionMode::First => {
12188                    if let Some(first_range) = ranges.first() {
12189                        editor.change_selections(None, window, cx, |selections| {
12190                            selections.clear_disjoint();
12191                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12192                        });
12193                    }
12194                    editor.highlight_background::<Self>(
12195                        &ranges,
12196                        |theme| theme.editor_highlighted_line_background,
12197                        cx,
12198                    );
12199                }
12200                MultibufferSelectionMode::All => {
12201                    editor.change_selections(None, window, cx, |selections| {
12202                        selections.clear_disjoint();
12203                        selections.select_anchor_ranges(ranges);
12204                    });
12205                }
12206            }
12207            editor.register_buffers_with_language_servers(cx);
12208        });
12209
12210        let item = Box::new(editor);
12211        let item_id = item.item_id();
12212
12213        if split {
12214            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12215        } else {
12216            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12217                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12218                    pane.close_current_preview_item(window, cx)
12219                } else {
12220                    None
12221                }
12222            });
12223            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12224        }
12225        workspace.active_pane().update(cx, |pane, cx| {
12226            pane.set_preview_item_id(Some(item_id), cx);
12227        });
12228    }
12229
12230    pub fn rename(
12231        &mut self,
12232        _: &Rename,
12233        window: &mut Window,
12234        cx: &mut Context<Self>,
12235    ) -> Option<Task<Result<()>>> {
12236        use language::ToOffset as _;
12237
12238        let provider = self.semantics_provider.clone()?;
12239        let selection = self.selections.newest_anchor().clone();
12240        let (cursor_buffer, cursor_buffer_position) = self
12241            .buffer
12242            .read(cx)
12243            .text_anchor_for_position(selection.head(), cx)?;
12244        let (tail_buffer, cursor_buffer_position_end) = self
12245            .buffer
12246            .read(cx)
12247            .text_anchor_for_position(selection.tail(), cx)?;
12248        if tail_buffer != cursor_buffer {
12249            return None;
12250        }
12251
12252        let snapshot = cursor_buffer.read(cx).snapshot();
12253        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12254        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12255        let prepare_rename = provider
12256            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12257            .unwrap_or_else(|| Task::ready(Ok(None)));
12258        drop(snapshot);
12259
12260        Some(cx.spawn_in(window, |this, mut cx| async move {
12261            let rename_range = if let Some(range) = prepare_rename.await? {
12262                Some(range)
12263            } else {
12264                this.update(&mut cx, |this, cx| {
12265                    let buffer = this.buffer.read(cx).snapshot(cx);
12266                    let mut buffer_highlights = this
12267                        .document_highlights_for_position(selection.head(), &buffer)
12268                        .filter(|highlight| {
12269                            highlight.start.excerpt_id == selection.head().excerpt_id
12270                                && highlight.end.excerpt_id == selection.head().excerpt_id
12271                        });
12272                    buffer_highlights
12273                        .next()
12274                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12275                })?
12276            };
12277            if let Some(rename_range) = rename_range {
12278                this.update_in(&mut cx, |this, window, cx| {
12279                    let snapshot = cursor_buffer.read(cx).snapshot();
12280                    let rename_buffer_range = rename_range.to_offset(&snapshot);
12281                    let cursor_offset_in_rename_range =
12282                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12283                    let cursor_offset_in_rename_range_end =
12284                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12285
12286                    this.take_rename(false, window, cx);
12287                    let buffer = this.buffer.read(cx).read(cx);
12288                    let cursor_offset = selection.head().to_offset(&buffer);
12289                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12290                    let rename_end = rename_start + rename_buffer_range.len();
12291                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12292                    let mut old_highlight_id = None;
12293                    let old_name: Arc<str> = buffer
12294                        .chunks(rename_start..rename_end, true)
12295                        .map(|chunk| {
12296                            if old_highlight_id.is_none() {
12297                                old_highlight_id = chunk.syntax_highlight_id;
12298                            }
12299                            chunk.text
12300                        })
12301                        .collect::<String>()
12302                        .into();
12303
12304                    drop(buffer);
12305
12306                    // Position the selection in the rename editor so that it matches the current selection.
12307                    this.show_local_selections = false;
12308                    let rename_editor = cx.new(|cx| {
12309                        let mut editor = Editor::single_line(window, cx);
12310                        editor.buffer.update(cx, |buffer, cx| {
12311                            buffer.edit([(0..0, old_name.clone())], None, cx)
12312                        });
12313                        let rename_selection_range = match cursor_offset_in_rename_range
12314                            .cmp(&cursor_offset_in_rename_range_end)
12315                        {
12316                            Ordering::Equal => {
12317                                editor.select_all(&SelectAll, window, cx);
12318                                return editor;
12319                            }
12320                            Ordering::Less => {
12321                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12322                            }
12323                            Ordering::Greater => {
12324                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12325                            }
12326                        };
12327                        if rename_selection_range.end > old_name.len() {
12328                            editor.select_all(&SelectAll, window, cx);
12329                        } else {
12330                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12331                                s.select_ranges([rename_selection_range]);
12332                            });
12333                        }
12334                        editor
12335                    });
12336                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12337                        if e == &EditorEvent::Focused {
12338                            cx.emit(EditorEvent::FocusedIn)
12339                        }
12340                    })
12341                    .detach();
12342
12343                    let write_highlights =
12344                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12345                    let read_highlights =
12346                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
12347                    let ranges = write_highlights
12348                        .iter()
12349                        .flat_map(|(_, ranges)| ranges.iter())
12350                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12351                        .cloned()
12352                        .collect();
12353
12354                    this.highlight_text::<Rename>(
12355                        ranges,
12356                        HighlightStyle {
12357                            fade_out: Some(0.6),
12358                            ..Default::default()
12359                        },
12360                        cx,
12361                    );
12362                    let rename_focus_handle = rename_editor.focus_handle(cx);
12363                    window.focus(&rename_focus_handle);
12364                    let block_id = this.insert_blocks(
12365                        [BlockProperties {
12366                            style: BlockStyle::Flex,
12367                            placement: BlockPlacement::Below(range.start),
12368                            height: 1,
12369                            render: Arc::new({
12370                                let rename_editor = rename_editor.clone();
12371                                move |cx: &mut BlockContext| {
12372                                    let mut text_style = cx.editor_style.text.clone();
12373                                    if let Some(highlight_style) = old_highlight_id
12374                                        .and_then(|h| h.style(&cx.editor_style.syntax))
12375                                    {
12376                                        text_style = text_style.highlight(highlight_style);
12377                                    }
12378                                    div()
12379                                        .block_mouse_down()
12380                                        .pl(cx.anchor_x)
12381                                        .child(EditorElement::new(
12382                                            &rename_editor,
12383                                            EditorStyle {
12384                                                background: cx.theme().system().transparent,
12385                                                local_player: cx.editor_style.local_player,
12386                                                text: text_style,
12387                                                scrollbar_width: cx.editor_style.scrollbar_width,
12388                                                syntax: cx.editor_style.syntax.clone(),
12389                                                status: cx.editor_style.status.clone(),
12390                                                inlay_hints_style: HighlightStyle {
12391                                                    font_weight: Some(FontWeight::BOLD),
12392                                                    ..make_inlay_hints_style(cx.app)
12393                                                },
12394                                                inline_completion_styles: make_suggestion_styles(
12395                                                    cx.app,
12396                                                ),
12397                                                ..EditorStyle::default()
12398                                            },
12399                                        ))
12400                                        .into_any_element()
12401                                }
12402                            }),
12403                            priority: 0,
12404                        }],
12405                        Some(Autoscroll::fit()),
12406                        cx,
12407                    )[0];
12408                    this.pending_rename = Some(RenameState {
12409                        range,
12410                        old_name,
12411                        editor: rename_editor,
12412                        block_id,
12413                    });
12414                })?;
12415            }
12416
12417            Ok(())
12418        }))
12419    }
12420
12421    pub fn confirm_rename(
12422        &mut self,
12423        _: &ConfirmRename,
12424        window: &mut Window,
12425        cx: &mut Context<Self>,
12426    ) -> Option<Task<Result<()>>> {
12427        let rename = self.take_rename(false, window, cx)?;
12428        let workspace = self.workspace()?.downgrade();
12429        let (buffer, start) = self
12430            .buffer
12431            .read(cx)
12432            .text_anchor_for_position(rename.range.start, cx)?;
12433        let (end_buffer, _) = self
12434            .buffer
12435            .read(cx)
12436            .text_anchor_for_position(rename.range.end, cx)?;
12437        if buffer != end_buffer {
12438            return None;
12439        }
12440
12441        let old_name = rename.old_name;
12442        let new_name = rename.editor.read(cx).text(cx);
12443
12444        let rename = self.semantics_provider.as_ref()?.perform_rename(
12445            &buffer,
12446            start,
12447            new_name.clone(),
12448            cx,
12449        )?;
12450
12451        Some(cx.spawn_in(window, |editor, mut cx| async move {
12452            let project_transaction = rename.await?;
12453            Self::open_project_transaction(
12454                &editor,
12455                workspace,
12456                project_transaction,
12457                format!("Rename: {}{}", old_name, new_name),
12458                cx.clone(),
12459            )
12460            .await?;
12461
12462            editor.update(&mut cx, |editor, cx| {
12463                editor.refresh_document_highlights(cx);
12464            })?;
12465            Ok(())
12466        }))
12467    }
12468
12469    fn take_rename(
12470        &mut self,
12471        moving_cursor: bool,
12472        window: &mut Window,
12473        cx: &mut Context<Self>,
12474    ) -> Option<RenameState> {
12475        let rename = self.pending_rename.take()?;
12476        if rename.editor.focus_handle(cx).is_focused(window) {
12477            window.focus(&self.focus_handle);
12478        }
12479
12480        self.remove_blocks(
12481            [rename.block_id].into_iter().collect(),
12482            Some(Autoscroll::fit()),
12483            cx,
12484        );
12485        self.clear_highlights::<Rename>(cx);
12486        self.show_local_selections = true;
12487
12488        if moving_cursor {
12489            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12490                editor.selections.newest::<usize>(cx).head()
12491            });
12492
12493            // Update the selection to match the position of the selection inside
12494            // the rename editor.
12495            let snapshot = self.buffer.read(cx).read(cx);
12496            let rename_range = rename.range.to_offset(&snapshot);
12497            let cursor_in_editor = snapshot
12498                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12499                .min(rename_range.end);
12500            drop(snapshot);
12501
12502            self.change_selections(None, window, cx, |s| {
12503                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12504            });
12505        } else {
12506            self.refresh_document_highlights(cx);
12507        }
12508
12509        Some(rename)
12510    }
12511
12512    pub fn pending_rename(&self) -> Option<&RenameState> {
12513        self.pending_rename.as_ref()
12514    }
12515
12516    fn format(
12517        &mut self,
12518        _: &Format,
12519        window: &mut Window,
12520        cx: &mut Context<Self>,
12521    ) -> Option<Task<Result<()>>> {
12522        let project = match &self.project {
12523            Some(project) => project.clone(),
12524            None => return None,
12525        };
12526
12527        Some(self.perform_format(
12528            project,
12529            FormatTrigger::Manual,
12530            FormatTarget::Buffers,
12531            window,
12532            cx,
12533        ))
12534    }
12535
12536    fn format_selections(
12537        &mut self,
12538        _: &FormatSelections,
12539        window: &mut Window,
12540        cx: &mut Context<Self>,
12541    ) -> Option<Task<Result<()>>> {
12542        let project = match &self.project {
12543            Some(project) => project.clone(),
12544            None => return None,
12545        };
12546
12547        let ranges = self
12548            .selections
12549            .all_adjusted(cx)
12550            .into_iter()
12551            .map(|selection| selection.range())
12552            .collect_vec();
12553
12554        Some(self.perform_format(
12555            project,
12556            FormatTrigger::Manual,
12557            FormatTarget::Ranges(ranges),
12558            window,
12559            cx,
12560        ))
12561    }
12562
12563    fn perform_format(
12564        &mut self,
12565        project: Entity<Project>,
12566        trigger: FormatTrigger,
12567        target: FormatTarget,
12568        window: &mut Window,
12569        cx: &mut Context<Self>,
12570    ) -> Task<Result<()>> {
12571        let buffer = self.buffer.clone();
12572        let (buffers, target) = match target {
12573            FormatTarget::Buffers => {
12574                let mut buffers = buffer.read(cx).all_buffers();
12575                if trigger == FormatTrigger::Save {
12576                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
12577                }
12578                (buffers, LspFormatTarget::Buffers)
12579            }
12580            FormatTarget::Ranges(selection_ranges) => {
12581                let multi_buffer = buffer.read(cx);
12582                let snapshot = multi_buffer.read(cx);
12583                let mut buffers = HashSet::default();
12584                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12585                    BTreeMap::new();
12586                for selection_range in selection_ranges {
12587                    for (buffer, buffer_range, _) in
12588                        snapshot.range_to_buffer_ranges(selection_range)
12589                    {
12590                        let buffer_id = buffer.remote_id();
12591                        let start = buffer.anchor_before(buffer_range.start);
12592                        let end = buffer.anchor_after(buffer_range.end);
12593                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12594                        buffer_id_to_ranges
12595                            .entry(buffer_id)
12596                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12597                            .or_insert_with(|| vec![start..end]);
12598                    }
12599                }
12600                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12601            }
12602        };
12603
12604        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12605        let format = project.update(cx, |project, cx| {
12606            project.format(buffers, target, true, trigger, cx)
12607        });
12608
12609        cx.spawn_in(window, |_, mut cx| async move {
12610            let transaction = futures::select_biased! {
12611                () = timeout => {
12612                    log::warn!("timed out waiting for formatting");
12613                    None
12614                }
12615                transaction = format.log_err().fuse() => transaction,
12616            };
12617
12618            buffer
12619                .update(&mut cx, |buffer, cx| {
12620                    if let Some(transaction) = transaction {
12621                        if !buffer.is_singleton() {
12622                            buffer.push_transaction(&transaction.0, cx);
12623                        }
12624                    }
12625                    cx.notify();
12626                })
12627                .ok();
12628
12629            Ok(())
12630        })
12631    }
12632
12633    fn organize_imports(
12634        &mut self,
12635        _: &OrganizeImports,
12636        window: &mut Window,
12637        cx: &mut Context<Self>,
12638    ) -> Option<Task<Result<()>>> {
12639        let project = match &self.project {
12640            Some(project) => project.clone(),
12641            None => return None,
12642        };
12643        Some(self.perform_code_action_kind(
12644            project,
12645            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12646            window,
12647            cx,
12648        ))
12649    }
12650
12651    fn perform_code_action_kind(
12652        &mut self,
12653        project: Entity<Project>,
12654        kind: CodeActionKind,
12655        window: &mut Window,
12656        cx: &mut Context<Self>,
12657    ) -> Task<Result<()>> {
12658        let buffer = self.buffer.clone();
12659        let buffers = buffer.read(cx).all_buffers();
12660        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12661        let apply_action = project.update(cx, |project, cx| {
12662            project.apply_code_action_kind(buffers, kind, true, cx)
12663        });
12664        cx.spawn_in(window, |_, mut cx| async move {
12665            let transaction = futures::select_biased! {
12666                () = timeout => {
12667                    log::warn!("timed out waiting for executing code action");
12668                    None
12669                }
12670                transaction = apply_action.log_err().fuse() => transaction,
12671            };
12672            buffer
12673                .update(&mut cx, |buffer, cx| {
12674                    // check if we need this
12675                    if let Some(transaction) = transaction {
12676                        if !buffer.is_singleton() {
12677                            buffer.push_transaction(&transaction.0, cx);
12678                        }
12679                    }
12680                    cx.notify();
12681                })
12682                .ok();
12683            Ok(())
12684        })
12685    }
12686
12687    fn restart_language_server(
12688        &mut self,
12689        _: &RestartLanguageServer,
12690        _: &mut Window,
12691        cx: &mut Context<Self>,
12692    ) {
12693        if let Some(project) = self.project.clone() {
12694            self.buffer.update(cx, |multi_buffer, cx| {
12695                project.update(cx, |project, cx| {
12696                    project.restart_language_servers_for_buffers(
12697                        multi_buffer.all_buffers().into_iter().collect(),
12698                        cx,
12699                    );
12700                });
12701            })
12702        }
12703    }
12704
12705    fn cancel_language_server_work(
12706        workspace: &mut Workspace,
12707        _: &actions::CancelLanguageServerWork,
12708        _: &mut Window,
12709        cx: &mut Context<Workspace>,
12710    ) {
12711        let project = workspace.project();
12712        let buffers = workspace
12713            .active_item(cx)
12714            .and_then(|item| item.act_as::<Editor>(cx))
12715            .map_or(HashSet::default(), |editor| {
12716                editor.read(cx).buffer.read(cx).all_buffers()
12717            });
12718        project.update(cx, |project, cx| {
12719            project.cancel_language_server_work_for_buffers(buffers, cx);
12720        });
12721    }
12722
12723    fn show_character_palette(
12724        &mut self,
12725        _: &ShowCharacterPalette,
12726        window: &mut Window,
12727        _: &mut Context<Self>,
12728    ) {
12729        window.show_character_palette();
12730    }
12731
12732    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12733        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12734            let buffer = self.buffer.read(cx).snapshot(cx);
12735            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12736            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12737            let is_valid = buffer
12738                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12739                .any(|entry| {
12740                    entry.diagnostic.is_primary
12741                        && !entry.range.is_empty()
12742                        && entry.range.start == primary_range_start
12743                        && entry.diagnostic.message == active_diagnostics.primary_message
12744                });
12745
12746            if is_valid != active_diagnostics.is_valid {
12747                active_diagnostics.is_valid = is_valid;
12748                if is_valid {
12749                    let mut new_styles = HashMap::default();
12750                    for (block_id, diagnostic) in &active_diagnostics.blocks {
12751                        new_styles.insert(
12752                            *block_id,
12753                            diagnostic_block_renderer(diagnostic.clone(), None, true),
12754                        );
12755                    }
12756                    self.display_map.update(cx, |display_map, _cx| {
12757                        display_map.replace_blocks(new_styles);
12758                    });
12759                } else {
12760                    self.dismiss_diagnostics(cx);
12761                }
12762            }
12763        }
12764    }
12765
12766    fn activate_diagnostics(
12767        &mut self,
12768        buffer_id: BufferId,
12769        group_id: usize,
12770        window: &mut Window,
12771        cx: &mut Context<Self>,
12772    ) {
12773        self.dismiss_diagnostics(cx);
12774        let snapshot = self.snapshot(window, cx);
12775        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12776            let buffer = self.buffer.read(cx).snapshot(cx);
12777
12778            let mut primary_range = None;
12779            let mut primary_message = None;
12780            let diagnostic_group = buffer
12781                .diagnostic_group(buffer_id, group_id)
12782                .filter_map(|entry| {
12783                    let start = entry.range.start;
12784                    let end = entry.range.end;
12785                    if snapshot.is_line_folded(MultiBufferRow(start.row))
12786                        && (start.row == end.row
12787                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
12788                    {
12789                        return None;
12790                    }
12791                    if entry.diagnostic.is_primary {
12792                        primary_range = Some(entry.range.clone());
12793                        primary_message = Some(entry.diagnostic.message.clone());
12794                    }
12795                    Some(entry)
12796                })
12797                .collect::<Vec<_>>();
12798            let primary_range = primary_range?;
12799            let primary_message = primary_message?;
12800
12801            let blocks = display_map
12802                .insert_blocks(
12803                    diagnostic_group.iter().map(|entry| {
12804                        let diagnostic = entry.diagnostic.clone();
12805                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12806                        BlockProperties {
12807                            style: BlockStyle::Fixed,
12808                            placement: BlockPlacement::Below(
12809                                buffer.anchor_after(entry.range.start),
12810                            ),
12811                            height: message_height,
12812                            render: diagnostic_block_renderer(diagnostic, None, true),
12813                            priority: 0,
12814                        }
12815                    }),
12816                    cx,
12817                )
12818                .into_iter()
12819                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12820                .collect();
12821
12822            Some(ActiveDiagnosticGroup {
12823                primary_range: buffer.anchor_before(primary_range.start)
12824                    ..buffer.anchor_after(primary_range.end),
12825                primary_message,
12826                group_id,
12827                blocks,
12828                is_valid: true,
12829            })
12830        });
12831    }
12832
12833    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12834        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12835            self.display_map.update(cx, |display_map, cx| {
12836                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12837            });
12838            cx.notify();
12839        }
12840    }
12841
12842    /// Disable inline diagnostics rendering for this editor.
12843    pub fn disable_inline_diagnostics(&mut self) {
12844        self.inline_diagnostics_enabled = false;
12845        self.inline_diagnostics_update = Task::ready(());
12846        self.inline_diagnostics.clear();
12847    }
12848
12849    pub fn inline_diagnostics_enabled(&self) -> bool {
12850        self.inline_diagnostics_enabled
12851    }
12852
12853    pub fn show_inline_diagnostics(&self) -> bool {
12854        self.show_inline_diagnostics
12855    }
12856
12857    pub fn toggle_inline_diagnostics(
12858        &mut self,
12859        _: &ToggleInlineDiagnostics,
12860        window: &mut Window,
12861        cx: &mut Context<'_, Editor>,
12862    ) {
12863        self.show_inline_diagnostics = !self.show_inline_diagnostics;
12864        self.refresh_inline_diagnostics(false, window, cx);
12865    }
12866
12867    fn refresh_inline_diagnostics(
12868        &mut self,
12869        debounce: bool,
12870        window: &mut Window,
12871        cx: &mut Context<Self>,
12872    ) {
12873        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12874            self.inline_diagnostics_update = Task::ready(());
12875            self.inline_diagnostics.clear();
12876            return;
12877        }
12878
12879        let debounce_ms = ProjectSettings::get_global(cx)
12880            .diagnostics
12881            .inline
12882            .update_debounce_ms;
12883        let debounce = if debounce && debounce_ms > 0 {
12884            Some(Duration::from_millis(debounce_ms))
12885        } else {
12886            None
12887        };
12888        self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12889            if let Some(debounce) = debounce {
12890                cx.background_executor().timer(debounce).await;
12891            }
12892            let Some(snapshot) = editor
12893                .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12894                .ok()
12895            else {
12896                return;
12897            };
12898
12899            let new_inline_diagnostics = cx
12900                .background_spawn(async move {
12901                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12902                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12903                        let message = diagnostic_entry
12904                            .diagnostic
12905                            .message
12906                            .split_once('\n')
12907                            .map(|(line, _)| line)
12908                            .map(SharedString::new)
12909                            .unwrap_or_else(|| {
12910                                SharedString::from(diagnostic_entry.diagnostic.message)
12911                            });
12912                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12913                        let (Ok(i) | Err(i)) = inline_diagnostics
12914                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12915                        inline_diagnostics.insert(
12916                            i,
12917                            (
12918                                start_anchor,
12919                                InlineDiagnostic {
12920                                    message,
12921                                    group_id: diagnostic_entry.diagnostic.group_id,
12922                                    start: diagnostic_entry.range.start.to_point(&snapshot),
12923                                    is_primary: diagnostic_entry.diagnostic.is_primary,
12924                                    severity: diagnostic_entry.diagnostic.severity,
12925                                },
12926                            ),
12927                        );
12928                    }
12929                    inline_diagnostics
12930                })
12931                .await;
12932
12933            editor
12934                .update(&mut cx, |editor, cx| {
12935                    editor.inline_diagnostics = new_inline_diagnostics;
12936                    cx.notify();
12937                })
12938                .ok();
12939        });
12940    }
12941
12942    pub fn set_selections_from_remote(
12943        &mut self,
12944        selections: Vec<Selection<Anchor>>,
12945        pending_selection: Option<Selection<Anchor>>,
12946        window: &mut Window,
12947        cx: &mut Context<Self>,
12948    ) {
12949        let old_cursor_position = self.selections.newest_anchor().head();
12950        self.selections.change_with(cx, |s| {
12951            s.select_anchors(selections);
12952            if let Some(pending_selection) = pending_selection {
12953                s.set_pending(pending_selection, SelectMode::Character);
12954            } else {
12955                s.clear_pending();
12956            }
12957        });
12958        self.selections_did_change(false, &old_cursor_position, true, window, cx);
12959    }
12960
12961    fn push_to_selection_history(&mut self) {
12962        self.selection_history.push(SelectionHistoryEntry {
12963            selections: self.selections.disjoint_anchors(),
12964            select_next_state: self.select_next_state.clone(),
12965            select_prev_state: self.select_prev_state.clone(),
12966            add_selections_state: self.add_selections_state.clone(),
12967        });
12968    }
12969
12970    pub fn transact(
12971        &mut self,
12972        window: &mut Window,
12973        cx: &mut Context<Self>,
12974        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12975    ) -> Option<TransactionId> {
12976        self.start_transaction_at(Instant::now(), window, cx);
12977        update(self, window, cx);
12978        self.end_transaction_at(Instant::now(), cx)
12979    }
12980
12981    pub fn start_transaction_at(
12982        &mut self,
12983        now: Instant,
12984        window: &mut Window,
12985        cx: &mut Context<Self>,
12986    ) {
12987        self.end_selection(window, cx);
12988        if let Some(tx_id) = self
12989            .buffer
12990            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12991        {
12992            self.selection_history
12993                .insert_transaction(tx_id, self.selections.disjoint_anchors());
12994            cx.emit(EditorEvent::TransactionBegun {
12995                transaction_id: tx_id,
12996            })
12997        }
12998    }
12999
13000    pub fn end_transaction_at(
13001        &mut self,
13002        now: Instant,
13003        cx: &mut Context<Self>,
13004    ) -> Option<TransactionId> {
13005        if let Some(transaction_id) = self
13006            .buffer
13007            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
13008        {
13009            if let Some((_, end_selections)) =
13010                self.selection_history.transaction_mut(transaction_id)
13011            {
13012                *end_selections = Some(self.selections.disjoint_anchors());
13013            } else {
13014                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
13015            }
13016
13017            cx.emit(EditorEvent::Edited { transaction_id });
13018            Some(transaction_id)
13019        } else {
13020            None
13021        }
13022    }
13023
13024    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
13025        if self.selection_mark_mode {
13026            self.change_selections(None, window, cx, |s| {
13027                s.move_with(|_, sel| {
13028                    sel.collapse_to(sel.head(), SelectionGoal::None);
13029                });
13030            })
13031        }
13032        self.selection_mark_mode = true;
13033        cx.notify();
13034    }
13035
13036    pub fn swap_selection_ends(
13037        &mut self,
13038        _: &actions::SwapSelectionEnds,
13039        window: &mut Window,
13040        cx: &mut Context<Self>,
13041    ) {
13042        self.change_selections(None, window, cx, |s| {
13043            s.move_with(|_, sel| {
13044                if sel.start != sel.end {
13045                    sel.reversed = !sel.reversed
13046                }
13047            });
13048        });
13049        self.request_autoscroll(Autoscroll::newest(), cx);
13050        cx.notify();
13051    }
13052
13053    pub fn toggle_fold(
13054        &mut self,
13055        _: &actions::ToggleFold,
13056        window: &mut Window,
13057        cx: &mut Context<Self>,
13058    ) {
13059        if self.is_singleton(cx) {
13060            let selection = self.selections.newest::<Point>(cx);
13061
13062            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13063            let range = if selection.is_empty() {
13064                let point = selection.head().to_display_point(&display_map);
13065                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13066                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13067                    .to_point(&display_map);
13068                start..end
13069            } else {
13070                selection.range()
13071            };
13072            if display_map.folds_in_range(range).next().is_some() {
13073                self.unfold_lines(&Default::default(), window, cx)
13074            } else {
13075                self.fold(&Default::default(), window, cx)
13076            }
13077        } else {
13078            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13079            let buffer_ids: HashSet<_> = self
13080                .selections
13081                .disjoint_anchor_ranges()
13082                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13083                .collect();
13084
13085            let should_unfold = buffer_ids
13086                .iter()
13087                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13088
13089            for buffer_id in buffer_ids {
13090                if should_unfold {
13091                    self.unfold_buffer(buffer_id, cx);
13092                } else {
13093                    self.fold_buffer(buffer_id, cx);
13094                }
13095            }
13096        }
13097    }
13098
13099    pub fn toggle_fold_recursive(
13100        &mut self,
13101        _: &actions::ToggleFoldRecursive,
13102        window: &mut Window,
13103        cx: &mut Context<Self>,
13104    ) {
13105        let selection = self.selections.newest::<Point>(cx);
13106
13107        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13108        let range = if selection.is_empty() {
13109            let point = selection.head().to_display_point(&display_map);
13110            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13111            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13112                .to_point(&display_map);
13113            start..end
13114        } else {
13115            selection.range()
13116        };
13117        if display_map.folds_in_range(range).next().is_some() {
13118            self.unfold_recursive(&Default::default(), window, cx)
13119        } else {
13120            self.fold_recursive(&Default::default(), window, cx)
13121        }
13122    }
13123
13124    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13125        if self.is_singleton(cx) {
13126            let mut to_fold = Vec::new();
13127            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13128            let selections = self.selections.all_adjusted(cx);
13129
13130            for selection in selections {
13131                let range = selection.range().sorted();
13132                let buffer_start_row = range.start.row;
13133
13134                if range.start.row != range.end.row {
13135                    let mut found = false;
13136                    let mut row = range.start.row;
13137                    while row <= range.end.row {
13138                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13139                        {
13140                            found = true;
13141                            row = crease.range().end.row + 1;
13142                            to_fold.push(crease);
13143                        } else {
13144                            row += 1
13145                        }
13146                    }
13147                    if found {
13148                        continue;
13149                    }
13150                }
13151
13152                for row in (0..=range.start.row).rev() {
13153                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13154                        if crease.range().end.row >= buffer_start_row {
13155                            to_fold.push(crease);
13156                            if row <= range.start.row {
13157                                break;
13158                            }
13159                        }
13160                    }
13161                }
13162            }
13163
13164            self.fold_creases(to_fold, true, window, cx);
13165        } else {
13166            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13167            let buffer_ids = self
13168                .selections
13169                .disjoint_anchor_ranges()
13170                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13171                .collect::<HashSet<_>>();
13172            for buffer_id in buffer_ids {
13173                self.fold_buffer(buffer_id, cx);
13174            }
13175        }
13176    }
13177
13178    fn fold_at_level(
13179        &mut self,
13180        fold_at: &FoldAtLevel,
13181        window: &mut Window,
13182        cx: &mut Context<Self>,
13183    ) {
13184        if !self.buffer.read(cx).is_singleton() {
13185            return;
13186        }
13187
13188        let fold_at_level = fold_at.0;
13189        let snapshot = self.buffer.read(cx).snapshot(cx);
13190        let mut to_fold = Vec::new();
13191        let mut stack = vec![(0, snapshot.max_row().0, 1)];
13192
13193        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13194            while start_row < end_row {
13195                match self
13196                    .snapshot(window, cx)
13197                    .crease_for_buffer_row(MultiBufferRow(start_row))
13198                {
13199                    Some(crease) => {
13200                        let nested_start_row = crease.range().start.row + 1;
13201                        let nested_end_row = crease.range().end.row;
13202
13203                        if current_level < fold_at_level {
13204                            stack.push((nested_start_row, nested_end_row, current_level + 1));
13205                        } else if current_level == fold_at_level {
13206                            to_fold.push(crease);
13207                        }
13208
13209                        start_row = nested_end_row + 1;
13210                    }
13211                    None => start_row += 1,
13212                }
13213            }
13214        }
13215
13216        self.fold_creases(to_fold, true, window, cx);
13217    }
13218
13219    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13220        if self.buffer.read(cx).is_singleton() {
13221            let mut fold_ranges = Vec::new();
13222            let snapshot = self.buffer.read(cx).snapshot(cx);
13223
13224            for row in 0..snapshot.max_row().0 {
13225                if let Some(foldable_range) = self
13226                    .snapshot(window, cx)
13227                    .crease_for_buffer_row(MultiBufferRow(row))
13228                {
13229                    fold_ranges.push(foldable_range);
13230                }
13231            }
13232
13233            self.fold_creases(fold_ranges, true, window, cx);
13234        } else {
13235            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13236                editor
13237                    .update_in(&mut cx, |editor, _, cx| {
13238                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13239                            editor.fold_buffer(buffer_id, cx);
13240                        }
13241                    })
13242                    .ok();
13243            });
13244        }
13245    }
13246
13247    pub fn fold_function_bodies(
13248        &mut self,
13249        _: &actions::FoldFunctionBodies,
13250        window: &mut Window,
13251        cx: &mut Context<Self>,
13252    ) {
13253        let snapshot = self.buffer.read(cx).snapshot(cx);
13254
13255        let ranges = snapshot
13256            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13257            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13258            .collect::<Vec<_>>();
13259
13260        let creases = ranges
13261            .into_iter()
13262            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13263            .collect();
13264
13265        self.fold_creases(creases, true, window, cx);
13266    }
13267
13268    pub fn fold_recursive(
13269        &mut self,
13270        _: &actions::FoldRecursive,
13271        window: &mut Window,
13272        cx: &mut Context<Self>,
13273    ) {
13274        let mut to_fold = Vec::new();
13275        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13276        let selections = self.selections.all_adjusted(cx);
13277
13278        for selection in selections {
13279            let range = selection.range().sorted();
13280            let buffer_start_row = range.start.row;
13281
13282            if range.start.row != range.end.row {
13283                let mut found = false;
13284                for row in range.start.row..=range.end.row {
13285                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13286                        found = true;
13287                        to_fold.push(crease);
13288                    }
13289                }
13290                if found {
13291                    continue;
13292                }
13293            }
13294
13295            for row in (0..=range.start.row).rev() {
13296                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13297                    if crease.range().end.row >= buffer_start_row {
13298                        to_fold.push(crease);
13299                    } else {
13300                        break;
13301                    }
13302                }
13303            }
13304        }
13305
13306        self.fold_creases(to_fold, true, window, cx);
13307    }
13308
13309    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13310        let buffer_row = fold_at.buffer_row;
13311        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13312
13313        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13314            let autoscroll = self
13315                .selections
13316                .all::<Point>(cx)
13317                .iter()
13318                .any(|selection| crease.range().overlaps(&selection.range()));
13319
13320            self.fold_creases(vec![crease], autoscroll, window, cx);
13321        }
13322    }
13323
13324    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13325        if self.is_singleton(cx) {
13326            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13327            let buffer = &display_map.buffer_snapshot;
13328            let selections = self.selections.all::<Point>(cx);
13329            let ranges = selections
13330                .iter()
13331                .map(|s| {
13332                    let range = s.display_range(&display_map).sorted();
13333                    let mut start = range.start.to_point(&display_map);
13334                    let mut end = range.end.to_point(&display_map);
13335                    start.column = 0;
13336                    end.column = buffer.line_len(MultiBufferRow(end.row));
13337                    start..end
13338                })
13339                .collect::<Vec<_>>();
13340
13341            self.unfold_ranges(&ranges, true, true, cx);
13342        } else {
13343            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13344            let buffer_ids = self
13345                .selections
13346                .disjoint_anchor_ranges()
13347                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13348                .collect::<HashSet<_>>();
13349            for buffer_id in buffer_ids {
13350                self.unfold_buffer(buffer_id, cx);
13351            }
13352        }
13353    }
13354
13355    pub fn unfold_recursive(
13356        &mut self,
13357        _: &UnfoldRecursive,
13358        _window: &mut Window,
13359        cx: &mut Context<Self>,
13360    ) {
13361        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13362        let selections = self.selections.all::<Point>(cx);
13363        let ranges = selections
13364            .iter()
13365            .map(|s| {
13366                let mut range = s.display_range(&display_map).sorted();
13367                *range.start.column_mut() = 0;
13368                *range.end.column_mut() = display_map.line_len(range.end.row());
13369                let start = range.start.to_point(&display_map);
13370                let end = range.end.to_point(&display_map);
13371                start..end
13372            })
13373            .collect::<Vec<_>>();
13374
13375        self.unfold_ranges(&ranges, true, true, cx);
13376    }
13377
13378    pub fn unfold_at(
13379        &mut self,
13380        unfold_at: &UnfoldAt,
13381        _window: &mut Window,
13382        cx: &mut Context<Self>,
13383    ) {
13384        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13385
13386        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13387            ..Point::new(
13388                unfold_at.buffer_row.0,
13389                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13390            );
13391
13392        let autoscroll = self
13393            .selections
13394            .all::<Point>(cx)
13395            .iter()
13396            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13397
13398        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13399    }
13400
13401    pub fn unfold_all(
13402        &mut self,
13403        _: &actions::UnfoldAll,
13404        _window: &mut Window,
13405        cx: &mut Context<Self>,
13406    ) {
13407        if self.buffer.read(cx).is_singleton() {
13408            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13409            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13410        } else {
13411            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13412                editor
13413                    .update(&mut cx, |editor, cx| {
13414                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13415                            editor.unfold_buffer(buffer_id, cx);
13416                        }
13417                    })
13418                    .ok();
13419            });
13420        }
13421    }
13422
13423    pub fn fold_selected_ranges(
13424        &mut self,
13425        _: &FoldSelectedRanges,
13426        window: &mut Window,
13427        cx: &mut Context<Self>,
13428    ) {
13429        let selections = self.selections.all::<Point>(cx);
13430        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13431        let line_mode = self.selections.line_mode;
13432        let ranges = selections
13433            .into_iter()
13434            .map(|s| {
13435                if line_mode {
13436                    let start = Point::new(s.start.row, 0);
13437                    let end = Point::new(
13438                        s.end.row,
13439                        display_map
13440                            .buffer_snapshot
13441                            .line_len(MultiBufferRow(s.end.row)),
13442                    );
13443                    Crease::simple(start..end, display_map.fold_placeholder.clone())
13444                } else {
13445                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13446                }
13447            })
13448            .collect::<Vec<_>>();
13449        self.fold_creases(ranges, true, window, cx);
13450    }
13451
13452    pub fn fold_ranges<T: ToOffset + Clone>(
13453        &mut self,
13454        ranges: Vec<Range<T>>,
13455        auto_scroll: bool,
13456        window: &mut Window,
13457        cx: &mut Context<Self>,
13458    ) {
13459        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13460        let ranges = ranges
13461            .into_iter()
13462            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13463            .collect::<Vec<_>>();
13464        self.fold_creases(ranges, auto_scroll, window, cx);
13465    }
13466
13467    pub fn fold_creases<T: ToOffset + Clone>(
13468        &mut self,
13469        creases: Vec<Crease<T>>,
13470        auto_scroll: bool,
13471        window: &mut Window,
13472        cx: &mut Context<Self>,
13473    ) {
13474        if creases.is_empty() {
13475            return;
13476        }
13477
13478        let mut buffers_affected = HashSet::default();
13479        let multi_buffer = self.buffer().read(cx);
13480        for crease in &creases {
13481            if let Some((_, buffer, _)) =
13482                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13483            {
13484                buffers_affected.insert(buffer.read(cx).remote_id());
13485            };
13486        }
13487
13488        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13489
13490        if auto_scroll {
13491            self.request_autoscroll(Autoscroll::fit(), cx);
13492        }
13493
13494        cx.notify();
13495
13496        if let Some(active_diagnostics) = self.active_diagnostics.take() {
13497            // Clear diagnostics block when folding a range that contains it.
13498            let snapshot = self.snapshot(window, cx);
13499            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13500                drop(snapshot);
13501                self.active_diagnostics = Some(active_diagnostics);
13502                self.dismiss_diagnostics(cx);
13503            } else {
13504                self.active_diagnostics = Some(active_diagnostics);
13505            }
13506        }
13507
13508        self.scrollbar_marker_state.dirty = true;
13509    }
13510
13511    /// Removes any folds whose ranges intersect any of the given ranges.
13512    pub fn unfold_ranges<T: ToOffset + Clone>(
13513        &mut self,
13514        ranges: &[Range<T>],
13515        inclusive: bool,
13516        auto_scroll: bool,
13517        cx: &mut Context<Self>,
13518    ) {
13519        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13520            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13521        });
13522    }
13523
13524    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13525        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13526            return;
13527        }
13528        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13529        self.display_map.update(cx, |display_map, cx| {
13530            display_map.fold_buffers([buffer_id], cx)
13531        });
13532        cx.emit(EditorEvent::BufferFoldToggled {
13533            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13534            folded: true,
13535        });
13536        cx.notify();
13537    }
13538
13539    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13540        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13541            return;
13542        }
13543        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13544        self.display_map.update(cx, |display_map, cx| {
13545            display_map.unfold_buffers([buffer_id], cx);
13546        });
13547        cx.emit(EditorEvent::BufferFoldToggled {
13548            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13549            folded: false,
13550        });
13551        cx.notify();
13552    }
13553
13554    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13555        self.display_map.read(cx).is_buffer_folded(buffer)
13556    }
13557
13558    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13559        self.display_map.read(cx).folded_buffers()
13560    }
13561
13562    /// Removes any folds with the given ranges.
13563    pub fn remove_folds_with_type<T: ToOffset + Clone>(
13564        &mut self,
13565        ranges: &[Range<T>],
13566        type_id: TypeId,
13567        auto_scroll: bool,
13568        cx: &mut Context<Self>,
13569    ) {
13570        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13571            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13572        });
13573    }
13574
13575    fn remove_folds_with<T: ToOffset + Clone>(
13576        &mut self,
13577        ranges: &[Range<T>],
13578        auto_scroll: bool,
13579        cx: &mut Context<Self>,
13580        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13581    ) {
13582        if ranges.is_empty() {
13583            return;
13584        }
13585
13586        let mut buffers_affected = HashSet::default();
13587        let multi_buffer = self.buffer().read(cx);
13588        for range in ranges {
13589            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13590                buffers_affected.insert(buffer.read(cx).remote_id());
13591            };
13592        }
13593
13594        self.display_map.update(cx, update);
13595
13596        if auto_scroll {
13597            self.request_autoscroll(Autoscroll::fit(), cx);
13598        }
13599
13600        cx.notify();
13601        self.scrollbar_marker_state.dirty = true;
13602        self.active_indent_guides_state.dirty = true;
13603    }
13604
13605    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13606        self.display_map.read(cx).fold_placeholder.clone()
13607    }
13608
13609    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13610        self.buffer.update(cx, |buffer, cx| {
13611            buffer.set_all_diff_hunks_expanded(cx);
13612        });
13613    }
13614
13615    pub fn expand_all_diff_hunks(
13616        &mut self,
13617        _: &ExpandAllDiffHunks,
13618        _window: &mut Window,
13619        cx: &mut Context<Self>,
13620    ) {
13621        self.buffer.update(cx, |buffer, cx| {
13622            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13623        });
13624    }
13625
13626    pub fn toggle_selected_diff_hunks(
13627        &mut self,
13628        _: &ToggleSelectedDiffHunks,
13629        _window: &mut Window,
13630        cx: &mut Context<Self>,
13631    ) {
13632        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13633        self.toggle_diff_hunks_in_ranges(ranges, cx);
13634    }
13635
13636    pub fn diff_hunks_in_ranges<'a>(
13637        &'a self,
13638        ranges: &'a [Range<Anchor>],
13639        buffer: &'a MultiBufferSnapshot,
13640    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13641        ranges.iter().flat_map(move |range| {
13642            let end_excerpt_id = range.end.excerpt_id;
13643            let range = range.to_point(buffer);
13644            let mut peek_end = range.end;
13645            if range.end.row < buffer.max_row().0 {
13646                peek_end = Point::new(range.end.row + 1, 0);
13647            }
13648            buffer
13649                .diff_hunks_in_range(range.start..peek_end)
13650                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13651        })
13652    }
13653
13654    pub fn has_stageable_diff_hunks_in_ranges(
13655        &self,
13656        ranges: &[Range<Anchor>],
13657        snapshot: &MultiBufferSnapshot,
13658    ) -> bool {
13659        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13660        hunks.any(|hunk| hunk.status().has_secondary_hunk())
13661    }
13662
13663    pub fn toggle_staged_selected_diff_hunks(
13664        &mut self,
13665        _: &::git::ToggleStaged,
13666        _: &mut Window,
13667        cx: &mut Context<Self>,
13668    ) {
13669        let snapshot = self.buffer.read(cx).snapshot(cx);
13670        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13671        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13672        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13673    }
13674
13675    pub fn stage_and_next(
13676        &mut self,
13677        _: &::git::StageAndNext,
13678        window: &mut Window,
13679        cx: &mut Context<Self>,
13680    ) {
13681        self.do_stage_or_unstage_and_next(true, window, cx);
13682    }
13683
13684    pub fn unstage_and_next(
13685        &mut self,
13686        _: &::git::UnstageAndNext,
13687        window: &mut Window,
13688        cx: &mut Context<Self>,
13689    ) {
13690        self.do_stage_or_unstage_and_next(false, window, cx);
13691    }
13692
13693    pub fn stage_or_unstage_diff_hunks(
13694        &mut self,
13695        stage: bool,
13696        ranges: Vec<Range<Anchor>>,
13697        cx: &mut Context<Self>,
13698    ) {
13699        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
13700        cx.spawn(|this, mut cx| async move {
13701            task.await?;
13702            this.update(&mut cx, |this, cx| {
13703                let snapshot = this.buffer.read(cx).snapshot(cx);
13704                let chunk_by = this
13705                    .diff_hunks_in_ranges(&ranges, &snapshot)
13706                    .chunk_by(|hunk| hunk.buffer_id);
13707                for (buffer_id, hunks) in &chunk_by {
13708                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
13709                }
13710            })
13711        })
13712        .detach_and_log_err(cx);
13713    }
13714
13715    fn save_buffers_for_ranges_if_needed(
13716        &mut self,
13717        ranges: &[Range<Anchor>],
13718        cx: &mut Context<'_, Editor>,
13719    ) -> Task<Result<()>> {
13720        let multibuffer = self.buffer.read(cx);
13721        let snapshot = multibuffer.read(cx);
13722        let buffer_ids: HashSet<_> = ranges
13723            .iter()
13724            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
13725            .collect();
13726        drop(snapshot);
13727
13728        let mut buffers = HashSet::default();
13729        for buffer_id in buffer_ids {
13730            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
13731                let buffer = buffer_entity.read(cx);
13732                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
13733                {
13734                    buffers.insert(buffer_entity);
13735                }
13736            }
13737        }
13738
13739        if let Some(project) = &self.project {
13740            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
13741        } else {
13742            Task::ready(Ok(()))
13743        }
13744    }
13745
13746    fn do_stage_or_unstage_and_next(
13747        &mut self,
13748        stage: bool,
13749        window: &mut Window,
13750        cx: &mut Context<Self>,
13751    ) {
13752        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13753
13754        if ranges.iter().any(|range| range.start != range.end) {
13755            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13756            return;
13757        }
13758
13759        let snapshot = self.snapshot(window, cx);
13760        let newest_range = self.selections.newest::<Point>(cx).range();
13761
13762        let run_twice = snapshot
13763            .hunks_for_ranges([newest_range])
13764            .first()
13765            .is_some_and(|hunk| {
13766                let next_line = Point::new(hunk.row_range.end.0 + 1, 0);
13767                self.hunk_after_position(&snapshot, next_line)
13768                    .is_some_and(|other| other.row_range == hunk.row_range)
13769            });
13770
13771        if run_twice {
13772            self.go_to_next_hunk(&GoToHunk, window, cx);
13773        }
13774        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13775        self.go_to_next_hunk(&GoToHunk, window, cx);
13776    }
13777
13778    fn do_stage_or_unstage(
13779        &self,
13780        stage: bool,
13781        buffer_id: BufferId,
13782        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13783        cx: &mut App,
13784    ) -> Option<()> {
13785        let project = self.project.as_ref()?;
13786        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
13787        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
13788        let buffer_snapshot = buffer.read(cx).snapshot();
13789        let file_exists = buffer_snapshot
13790            .file()
13791            .is_some_and(|file| file.disk_state().exists());
13792        diff.update(cx, |diff, cx| {
13793            diff.stage_or_unstage_hunks(
13794                stage,
13795                &hunks
13796                    .map(|hunk| buffer_diff::DiffHunk {
13797                        buffer_range: hunk.buffer_range,
13798                        diff_base_byte_range: hunk.diff_base_byte_range,
13799                        secondary_status: hunk.secondary_status,
13800                        range: Point::zero()..Point::zero(), // unused
13801                    })
13802                    .collect::<Vec<_>>(),
13803                &buffer_snapshot,
13804                file_exists,
13805                cx,
13806            )
13807        });
13808        None
13809    }
13810
13811    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13812        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13813        self.buffer
13814            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13815    }
13816
13817    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13818        self.buffer.update(cx, |buffer, cx| {
13819            let ranges = vec![Anchor::min()..Anchor::max()];
13820            if !buffer.all_diff_hunks_expanded()
13821                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13822            {
13823                buffer.collapse_diff_hunks(ranges, cx);
13824                true
13825            } else {
13826                false
13827            }
13828        })
13829    }
13830
13831    fn toggle_diff_hunks_in_ranges(
13832        &mut self,
13833        ranges: Vec<Range<Anchor>>,
13834        cx: &mut Context<'_, Editor>,
13835    ) {
13836        self.buffer.update(cx, |buffer, cx| {
13837            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13838            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13839        })
13840    }
13841
13842    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13843        self.buffer.update(cx, |buffer, cx| {
13844            let snapshot = buffer.snapshot(cx);
13845            let excerpt_id = range.end.excerpt_id;
13846            let point_range = range.to_point(&snapshot);
13847            let expand = !buffer.single_hunk_is_expanded(range, cx);
13848            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13849        })
13850    }
13851
13852    pub(crate) fn apply_all_diff_hunks(
13853        &mut self,
13854        _: &ApplyAllDiffHunks,
13855        window: &mut Window,
13856        cx: &mut Context<Self>,
13857    ) {
13858        let buffers = self.buffer.read(cx).all_buffers();
13859        for branch_buffer in buffers {
13860            branch_buffer.update(cx, |branch_buffer, cx| {
13861                branch_buffer.merge_into_base(Vec::new(), cx);
13862            });
13863        }
13864
13865        if let Some(project) = self.project.clone() {
13866            self.save(true, project, window, cx).detach_and_log_err(cx);
13867        }
13868    }
13869
13870    pub(crate) fn apply_selected_diff_hunks(
13871        &mut self,
13872        _: &ApplyDiffHunk,
13873        window: &mut Window,
13874        cx: &mut Context<Self>,
13875    ) {
13876        let snapshot = self.snapshot(window, cx);
13877        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
13878        let mut ranges_by_buffer = HashMap::default();
13879        self.transact(window, cx, |editor, _window, cx| {
13880            for hunk in hunks {
13881                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13882                    ranges_by_buffer
13883                        .entry(buffer.clone())
13884                        .or_insert_with(Vec::new)
13885                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13886                }
13887            }
13888
13889            for (buffer, ranges) in ranges_by_buffer {
13890                buffer.update(cx, |buffer, cx| {
13891                    buffer.merge_into_base(ranges, cx);
13892                });
13893            }
13894        });
13895
13896        if let Some(project) = self.project.clone() {
13897            self.save(true, project, window, cx).detach_and_log_err(cx);
13898        }
13899    }
13900
13901    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13902        if hovered != self.gutter_hovered {
13903            self.gutter_hovered = hovered;
13904            cx.notify();
13905        }
13906    }
13907
13908    pub fn insert_blocks(
13909        &mut self,
13910        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13911        autoscroll: Option<Autoscroll>,
13912        cx: &mut Context<Self>,
13913    ) -> Vec<CustomBlockId> {
13914        let blocks = self
13915            .display_map
13916            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13917        if let Some(autoscroll) = autoscroll {
13918            self.request_autoscroll(autoscroll, cx);
13919        }
13920        cx.notify();
13921        blocks
13922    }
13923
13924    pub fn resize_blocks(
13925        &mut self,
13926        heights: HashMap<CustomBlockId, u32>,
13927        autoscroll: Option<Autoscroll>,
13928        cx: &mut Context<Self>,
13929    ) {
13930        self.display_map
13931            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13932        if let Some(autoscroll) = autoscroll {
13933            self.request_autoscroll(autoscroll, cx);
13934        }
13935        cx.notify();
13936    }
13937
13938    pub fn replace_blocks(
13939        &mut self,
13940        renderers: HashMap<CustomBlockId, RenderBlock>,
13941        autoscroll: Option<Autoscroll>,
13942        cx: &mut Context<Self>,
13943    ) {
13944        self.display_map
13945            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13946        if let Some(autoscroll) = autoscroll {
13947            self.request_autoscroll(autoscroll, cx);
13948        }
13949        cx.notify();
13950    }
13951
13952    pub fn remove_blocks(
13953        &mut self,
13954        block_ids: HashSet<CustomBlockId>,
13955        autoscroll: Option<Autoscroll>,
13956        cx: &mut Context<Self>,
13957    ) {
13958        self.display_map.update(cx, |display_map, cx| {
13959            display_map.remove_blocks(block_ids, cx)
13960        });
13961        if let Some(autoscroll) = autoscroll {
13962            self.request_autoscroll(autoscroll, cx);
13963        }
13964        cx.notify();
13965    }
13966
13967    pub fn row_for_block(
13968        &self,
13969        block_id: CustomBlockId,
13970        cx: &mut Context<Self>,
13971    ) -> Option<DisplayRow> {
13972        self.display_map
13973            .update(cx, |map, cx| map.row_for_block(block_id, cx))
13974    }
13975
13976    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13977        self.focused_block = Some(focused_block);
13978    }
13979
13980    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13981        self.focused_block.take()
13982    }
13983
13984    pub fn insert_creases(
13985        &mut self,
13986        creases: impl IntoIterator<Item = Crease<Anchor>>,
13987        cx: &mut Context<Self>,
13988    ) -> Vec<CreaseId> {
13989        self.display_map
13990            .update(cx, |map, cx| map.insert_creases(creases, cx))
13991    }
13992
13993    pub fn remove_creases(
13994        &mut self,
13995        ids: impl IntoIterator<Item = CreaseId>,
13996        cx: &mut Context<Self>,
13997    ) {
13998        self.display_map
13999            .update(cx, |map, cx| map.remove_creases(ids, cx));
14000    }
14001
14002    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
14003        self.display_map
14004            .update(cx, |map, cx| map.snapshot(cx))
14005            .longest_row()
14006    }
14007
14008    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
14009        self.display_map
14010            .update(cx, |map, cx| map.snapshot(cx))
14011            .max_point()
14012    }
14013
14014    pub fn text(&self, cx: &App) -> String {
14015        self.buffer.read(cx).read(cx).text()
14016    }
14017
14018    pub fn is_empty(&self, cx: &App) -> bool {
14019        self.buffer.read(cx).read(cx).is_empty()
14020    }
14021
14022    pub fn text_option(&self, cx: &App) -> Option<String> {
14023        let text = self.text(cx);
14024        let text = text.trim();
14025
14026        if text.is_empty() {
14027            return None;
14028        }
14029
14030        Some(text.to_string())
14031    }
14032
14033    pub fn set_text(
14034        &mut self,
14035        text: impl Into<Arc<str>>,
14036        window: &mut Window,
14037        cx: &mut Context<Self>,
14038    ) {
14039        self.transact(window, cx, |this, _, cx| {
14040            this.buffer
14041                .read(cx)
14042                .as_singleton()
14043                .expect("you can only call set_text on editors for singleton buffers")
14044                .update(cx, |buffer, cx| buffer.set_text(text, cx));
14045        });
14046    }
14047
14048    pub fn display_text(&self, cx: &mut App) -> String {
14049        self.display_map
14050            .update(cx, |map, cx| map.snapshot(cx))
14051            .text()
14052    }
14053
14054    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
14055        let mut wrap_guides = smallvec::smallvec![];
14056
14057        if self.show_wrap_guides == Some(false) {
14058            return wrap_guides;
14059        }
14060
14061        let settings = self.buffer.read(cx).language_settings(cx);
14062        if settings.show_wrap_guides {
14063            match self.soft_wrap_mode(cx) {
14064                SoftWrap::Column(soft_wrap) => {
14065                    wrap_guides.push((soft_wrap as usize, true));
14066                }
14067                SoftWrap::Bounded(soft_wrap) => {
14068                    wrap_guides.push((soft_wrap as usize, true));
14069                }
14070                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
14071            }
14072            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14073        }
14074
14075        wrap_guides
14076    }
14077
14078    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14079        let settings = self.buffer.read(cx).language_settings(cx);
14080        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14081        match mode {
14082            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14083                SoftWrap::None
14084            }
14085            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14086            language_settings::SoftWrap::PreferredLineLength => {
14087                SoftWrap::Column(settings.preferred_line_length)
14088            }
14089            language_settings::SoftWrap::Bounded => {
14090                SoftWrap::Bounded(settings.preferred_line_length)
14091            }
14092        }
14093    }
14094
14095    pub fn set_soft_wrap_mode(
14096        &mut self,
14097        mode: language_settings::SoftWrap,
14098
14099        cx: &mut Context<Self>,
14100    ) {
14101        self.soft_wrap_mode_override = Some(mode);
14102        cx.notify();
14103    }
14104
14105    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14106        self.text_style_refinement = Some(style);
14107    }
14108
14109    /// called by the Element so we know what style we were most recently rendered with.
14110    pub(crate) fn set_style(
14111        &mut self,
14112        style: EditorStyle,
14113        window: &mut Window,
14114        cx: &mut Context<Self>,
14115    ) {
14116        let rem_size = window.rem_size();
14117        self.display_map.update(cx, |map, cx| {
14118            map.set_font(
14119                style.text.font(),
14120                style.text.font_size.to_pixels(rem_size),
14121                cx,
14122            )
14123        });
14124        self.style = Some(style);
14125    }
14126
14127    pub fn style(&self) -> Option<&EditorStyle> {
14128        self.style.as_ref()
14129    }
14130
14131    // Called by the element. This method is not designed to be called outside of the editor
14132    // element's layout code because it does not notify when rewrapping is computed synchronously.
14133    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14134        self.display_map
14135            .update(cx, |map, cx| map.set_wrap_width(width, cx))
14136    }
14137
14138    pub fn set_soft_wrap(&mut self) {
14139        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14140    }
14141
14142    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14143        if self.soft_wrap_mode_override.is_some() {
14144            self.soft_wrap_mode_override.take();
14145        } else {
14146            let soft_wrap = match self.soft_wrap_mode(cx) {
14147                SoftWrap::GitDiff => return,
14148                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14149                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14150                    language_settings::SoftWrap::None
14151                }
14152            };
14153            self.soft_wrap_mode_override = Some(soft_wrap);
14154        }
14155        cx.notify();
14156    }
14157
14158    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14159        let Some(workspace) = self.workspace() else {
14160            return;
14161        };
14162        let fs = workspace.read(cx).app_state().fs.clone();
14163        let current_show = TabBarSettings::get_global(cx).show;
14164        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14165            setting.show = Some(!current_show);
14166        });
14167    }
14168
14169    pub fn toggle_indent_guides(
14170        &mut self,
14171        _: &ToggleIndentGuides,
14172        _: &mut Window,
14173        cx: &mut Context<Self>,
14174    ) {
14175        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14176            self.buffer
14177                .read(cx)
14178                .language_settings(cx)
14179                .indent_guides
14180                .enabled
14181        });
14182        self.show_indent_guides = Some(!currently_enabled);
14183        cx.notify();
14184    }
14185
14186    fn should_show_indent_guides(&self) -> Option<bool> {
14187        self.show_indent_guides
14188    }
14189
14190    pub fn toggle_line_numbers(
14191        &mut self,
14192        _: &ToggleLineNumbers,
14193        _: &mut Window,
14194        cx: &mut Context<Self>,
14195    ) {
14196        let mut editor_settings = EditorSettings::get_global(cx).clone();
14197        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14198        EditorSettings::override_global(editor_settings, cx);
14199    }
14200
14201    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14202        self.use_relative_line_numbers
14203            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14204    }
14205
14206    pub fn toggle_relative_line_numbers(
14207        &mut self,
14208        _: &ToggleRelativeLineNumbers,
14209        _: &mut Window,
14210        cx: &mut Context<Self>,
14211    ) {
14212        let is_relative = self.should_use_relative_line_numbers(cx);
14213        self.set_relative_line_number(Some(!is_relative), cx)
14214    }
14215
14216    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14217        self.use_relative_line_numbers = is_relative;
14218        cx.notify();
14219    }
14220
14221    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14222        self.show_gutter = show_gutter;
14223        cx.notify();
14224    }
14225
14226    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14227        self.show_scrollbars = show_scrollbars;
14228        cx.notify();
14229    }
14230
14231    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14232        self.show_line_numbers = Some(show_line_numbers);
14233        cx.notify();
14234    }
14235
14236    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14237        self.show_git_diff_gutter = Some(show_git_diff_gutter);
14238        cx.notify();
14239    }
14240
14241    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14242        self.show_code_actions = Some(show_code_actions);
14243        cx.notify();
14244    }
14245
14246    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14247        self.show_runnables = Some(show_runnables);
14248        cx.notify();
14249    }
14250
14251    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14252        if self.display_map.read(cx).masked != masked {
14253            self.display_map.update(cx, |map, _| map.masked = masked);
14254        }
14255        cx.notify()
14256    }
14257
14258    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14259        self.show_wrap_guides = Some(show_wrap_guides);
14260        cx.notify();
14261    }
14262
14263    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14264        self.show_indent_guides = Some(show_indent_guides);
14265        cx.notify();
14266    }
14267
14268    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14269        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14270            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14271                if let Some(dir) = file.abs_path(cx).parent() {
14272                    return Some(dir.to_owned());
14273                }
14274            }
14275
14276            if let Some(project_path) = buffer.read(cx).project_path(cx) {
14277                return Some(project_path.path.to_path_buf());
14278            }
14279        }
14280
14281        None
14282    }
14283
14284    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14285        self.active_excerpt(cx)?
14286            .1
14287            .read(cx)
14288            .file()
14289            .and_then(|f| f.as_local())
14290    }
14291
14292    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14293        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14294            let buffer = buffer.read(cx);
14295            if let Some(project_path) = buffer.project_path(cx) {
14296                let project = self.project.as_ref()?.read(cx);
14297                project.absolute_path(&project_path, cx)
14298            } else {
14299                buffer
14300                    .file()
14301                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14302            }
14303        })
14304    }
14305
14306    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14307        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14308            let project_path = buffer.read(cx).project_path(cx)?;
14309            let project = self.project.as_ref()?.read(cx);
14310            let entry = project.entry_for_path(&project_path, cx)?;
14311            let path = entry.path.to_path_buf();
14312            Some(path)
14313        })
14314    }
14315
14316    pub fn reveal_in_finder(
14317        &mut self,
14318        _: &RevealInFileManager,
14319        _window: &mut Window,
14320        cx: &mut Context<Self>,
14321    ) {
14322        if let Some(target) = self.target_file(cx) {
14323            cx.reveal_path(&target.abs_path(cx));
14324        }
14325    }
14326
14327    pub fn copy_path(
14328        &mut self,
14329        _: &zed_actions::workspace::CopyPath,
14330        _window: &mut Window,
14331        cx: &mut Context<Self>,
14332    ) {
14333        if let Some(path) = self.target_file_abs_path(cx) {
14334            if let Some(path) = path.to_str() {
14335                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14336            }
14337        }
14338    }
14339
14340    pub fn copy_relative_path(
14341        &mut self,
14342        _: &zed_actions::workspace::CopyRelativePath,
14343        _window: &mut Window,
14344        cx: &mut Context<Self>,
14345    ) {
14346        if let Some(path) = self.target_file_path(cx) {
14347            if let Some(path) = path.to_str() {
14348                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14349            }
14350        }
14351    }
14352
14353    pub fn copy_file_name_without_extension(
14354        &mut self,
14355        _: &CopyFileNameWithoutExtension,
14356        _: &mut Window,
14357        cx: &mut Context<Self>,
14358    ) {
14359        if let Some(file) = self.target_file(cx) {
14360            if let Some(file_stem) = file.path().file_stem() {
14361                if let Some(name) = file_stem.to_str() {
14362                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14363                }
14364            }
14365        }
14366    }
14367
14368    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14369        if let Some(file) = self.target_file(cx) {
14370            if let Some(file_name) = file.path().file_name() {
14371                if let Some(name) = file_name.to_str() {
14372                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14373                }
14374            }
14375        }
14376    }
14377
14378    pub fn toggle_git_blame(
14379        &mut self,
14380        _: &ToggleGitBlame,
14381        window: &mut Window,
14382        cx: &mut Context<Self>,
14383    ) {
14384        self.show_git_blame_gutter = !self.show_git_blame_gutter;
14385
14386        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14387            self.start_git_blame(true, window, cx);
14388        }
14389
14390        cx.notify();
14391    }
14392
14393    pub fn toggle_git_blame_inline(
14394        &mut self,
14395        _: &ToggleGitBlameInline,
14396        window: &mut Window,
14397        cx: &mut Context<Self>,
14398    ) {
14399        self.toggle_git_blame_inline_internal(true, window, cx);
14400        cx.notify();
14401    }
14402
14403    pub fn git_blame_inline_enabled(&self) -> bool {
14404        self.git_blame_inline_enabled
14405    }
14406
14407    pub fn toggle_selection_menu(
14408        &mut self,
14409        _: &ToggleSelectionMenu,
14410        _: &mut Window,
14411        cx: &mut Context<Self>,
14412    ) {
14413        self.show_selection_menu = self
14414            .show_selection_menu
14415            .map(|show_selections_menu| !show_selections_menu)
14416            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14417
14418        cx.notify();
14419    }
14420
14421    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14422        self.show_selection_menu
14423            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14424    }
14425
14426    fn start_git_blame(
14427        &mut self,
14428        user_triggered: bool,
14429        window: &mut Window,
14430        cx: &mut Context<Self>,
14431    ) {
14432        if let Some(project) = self.project.as_ref() {
14433            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14434                return;
14435            };
14436
14437            if buffer.read(cx).file().is_none() {
14438                return;
14439            }
14440
14441            let focused = self.focus_handle(cx).contains_focused(window, cx);
14442
14443            let project = project.clone();
14444            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14445            self.blame_subscription =
14446                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14447            self.blame = Some(blame);
14448        }
14449    }
14450
14451    fn toggle_git_blame_inline_internal(
14452        &mut self,
14453        user_triggered: bool,
14454        window: &mut Window,
14455        cx: &mut Context<Self>,
14456    ) {
14457        if self.git_blame_inline_enabled {
14458            self.git_blame_inline_enabled = false;
14459            self.show_git_blame_inline = false;
14460            self.show_git_blame_inline_delay_task.take();
14461        } else {
14462            self.git_blame_inline_enabled = true;
14463            self.start_git_blame_inline(user_triggered, window, cx);
14464        }
14465
14466        cx.notify();
14467    }
14468
14469    fn start_git_blame_inline(
14470        &mut self,
14471        user_triggered: bool,
14472        window: &mut Window,
14473        cx: &mut Context<Self>,
14474    ) {
14475        self.start_git_blame(user_triggered, window, cx);
14476
14477        if ProjectSettings::get_global(cx)
14478            .git
14479            .inline_blame_delay()
14480            .is_some()
14481        {
14482            self.start_inline_blame_timer(window, cx);
14483        } else {
14484            self.show_git_blame_inline = true
14485        }
14486    }
14487
14488    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14489        self.blame.as_ref()
14490    }
14491
14492    pub fn show_git_blame_gutter(&self) -> bool {
14493        self.show_git_blame_gutter
14494    }
14495
14496    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14497        self.show_git_blame_gutter && self.has_blame_entries(cx)
14498    }
14499
14500    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14501        self.show_git_blame_inline
14502            && (self.focus_handle.is_focused(window)
14503                || self
14504                    .git_blame_inline_tooltip
14505                    .as_ref()
14506                    .and_then(|t| t.upgrade())
14507                    .is_some())
14508            && !self.newest_selection_head_on_empty_line(cx)
14509            && self.has_blame_entries(cx)
14510    }
14511
14512    fn has_blame_entries(&self, cx: &App) -> bool {
14513        self.blame()
14514            .map_or(false, |blame| blame.read(cx).has_generated_entries())
14515    }
14516
14517    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14518        let cursor_anchor = self.selections.newest_anchor().head();
14519
14520        let snapshot = self.buffer.read(cx).snapshot(cx);
14521        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14522
14523        snapshot.line_len(buffer_row) == 0
14524    }
14525
14526    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14527        let buffer_and_selection = maybe!({
14528            let selection = self.selections.newest::<Point>(cx);
14529            let selection_range = selection.range();
14530
14531            let multi_buffer = self.buffer().read(cx);
14532            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14533            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14534
14535            let (buffer, range, _) = if selection.reversed {
14536                buffer_ranges.first()
14537            } else {
14538                buffer_ranges.last()
14539            }?;
14540
14541            let selection = text::ToPoint::to_point(&range.start, &buffer).row
14542                ..text::ToPoint::to_point(&range.end, &buffer).row;
14543            Some((
14544                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14545                selection,
14546            ))
14547        });
14548
14549        let Some((buffer, selection)) = buffer_and_selection else {
14550            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14551        };
14552
14553        let Some(project) = self.project.as_ref() else {
14554            return Task::ready(Err(anyhow!("editor does not have project")));
14555        };
14556
14557        project.update(cx, |project, cx| {
14558            project.get_permalink_to_line(&buffer, selection, cx)
14559        })
14560    }
14561
14562    pub fn copy_permalink_to_line(
14563        &mut self,
14564        _: &CopyPermalinkToLine,
14565        window: &mut Window,
14566        cx: &mut Context<Self>,
14567    ) {
14568        let permalink_task = self.get_permalink_to_line(cx);
14569        let workspace = self.workspace();
14570
14571        cx.spawn_in(window, |_, mut cx| async move {
14572            match permalink_task.await {
14573                Ok(permalink) => {
14574                    cx.update(|_, cx| {
14575                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14576                    })
14577                    .ok();
14578                }
14579                Err(err) => {
14580                    let message = format!("Failed to copy permalink: {err}");
14581
14582                    Err::<(), anyhow::Error>(err).log_err();
14583
14584                    if let Some(workspace) = workspace {
14585                        workspace
14586                            .update_in(&mut cx, |workspace, _, cx| {
14587                                struct CopyPermalinkToLine;
14588
14589                                workspace.show_toast(
14590                                    Toast::new(
14591                                        NotificationId::unique::<CopyPermalinkToLine>(),
14592                                        message,
14593                                    ),
14594                                    cx,
14595                                )
14596                            })
14597                            .ok();
14598                    }
14599                }
14600            }
14601        })
14602        .detach();
14603    }
14604
14605    pub fn copy_file_location(
14606        &mut self,
14607        _: &CopyFileLocation,
14608        _: &mut Window,
14609        cx: &mut Context<Self>,
14610    ) {
14611        let selection = self.selections.newest::<Point>(cx).start.row + 1;
14612        if let Some(file) = self.target_file(cx) {
14613            if let Some(path) = file.path().to_str() {
14614                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14615            }
14616        }
14617    }
14618
14619    pub fn open_permalink_to_line(
14620        &mut self,
14621        _: &OpenPermalinkToLine,
14622        window: &mut Window,
14623        cx: &mut Context<Self>,
14624    ) {
14625        let permalink_task = self.get_permalink_to_line(cx);
14626        let workspace = self.workspace();
14627
14628        cx.spawn_in(window, |_, mut cx| async move {
14629            match permalink_task.await {
14630                Ok(permalink) => {
14631                    cx.update(|_, cx| {
14632                        cx.open_url(permalink.as_ref());
14633                    })
14634                    .ok();
14635                }
14636                Err(err) => {
14637                    let message = format!("Failed to open permalink: {err}");
14638
14639                    Err::<(), anyhow::Error>(err).log_err();
14640
14641                    if let Some(workspace) = workspace {
14642                        workspace
14643                            .update(&mut cx, |workspace, cx| {
14644                                struct OpenPermalinkToLine;
14645
14646                                workspace.show_toast(
14647                                    Toast::new(
14648                                        NotificationId::unique::<OpenPermalinkToLine>(),
14649                                        message,
14650                                    ),
14651                                    cx,
14652                                )
14653                            })
14654                            .ok();
14655                    }
14656                }
14657            }
14658        })
14659        .detach();
14660    }
14661
14662    pub fn insert_uuid_v4(
14663        &mut self,
14664        _: &InsertUuidV4,
14665        window: &mut Window,
14666        cx: &mut Context<Self>,
14667    ) {
14668        self.insert_uuid(UuidVersion::V4, window, cx);
14669    }
14670
14671    pub fn insert_uuid_v7(
14672        &mut self,
14673        _: &InsertUuidV7,
14674        window: &mut Window,
14675        cx: &mut Context<Self>,
14676    ) {
14677        self.insert_uuid(UuidVersion::V7, window, cx);
14678    }
14679
14680    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14681        self.transact(window, cx, |this, window, cx| {
14682            let edits = this
14683                .selections
14684                .all::<Point>(cx)
14685                .into_iter()
14686                .map(|selection| {
14687                    let uuid = match version {
14688                        UuidVersion::V4 => uuid::Uuid::new_v4(),
14689                        UuidVersion::V7 => uuid::Uuid::now_v7(),
14690                    };
14691
14692                    (selection.range(), uuid.to_string())
14693                });
14694            this.edit(edits, cx);
14695            this.refresh_inline_completion(true, false, window, cx);
14696        });
14697    }
14698
14699    pub fn open_selections_in_multibuffer(
14700        &mut self,
14701        _: &OpenSelectionsInMultibuffer,
14702        window: &mut Window,
14703        cx: &mut Context<Self>,
14704    ) {
14705        let multibuffer = self.buffer.read(cx);
14706
14707        let Some(buffer) = multibuffer.as_singleton() else {
14708            return;
14709        };
14710
14711        let Some(workspace) = self.workspace() else {
14712            return;
14713        };
14714
14715        let locations = self
14716            .selections
14717            .disjoint_anchors()
14718            .iter()
14719            .map(|range| Location {
14720                buffer: buffer.clone(),
14721                range: range.start.text_anchor..range.end.text_anchor,
14722            })
14723            .collect::<Vec<_>>();
14724
14725        let title = multibuffer.title(cx).to_string();
14726
14727        cx.spawn_in(window, |_, mut cx| async move {
14728            workspace.update_in(&mut cx, |workspace, window, cx| {
14729                Self::open_locations_in_multibuffer(
14730                    workspace,
14731                    locations,
14732                    format!("Selections for '{title}'"),
14733                    false,
14734                    MultibufferSelectionMode::All,
14735                    window,
14736                    cx,
14737                );
14738            })
14739        })
14740        .detach();
14741    }
14742
14743    /// Adds a row highlight for the given range. If a row has multiple highlights, the
14744    /// last highlight added will be used.
14745    ///
14746    /// If the range ends at the beginning of a line, then that line will not be highlighted.
14747    pub fn highlight_rows<T: 'static>(
14748        &mut self,
14749        range: Range<Anchor>,
14750        color: Hsla,
14751        should_autoscroll: bool,
14752        cx: &mut Context<Self>,
14753    ) {
14754        let snapshot = self.buffer().read(cx).snapshot(cx);
14755        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14756        let ix = row_highlights.binary_search_by(|highlight| {
14757            Ordering::Equal
14758                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14759                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14760        });
14761
14762        if let Err(mut ix) = ix {
14763            let index = post_inc(&mut self.highlight_order);
14764
14765            // If this range intersects with the preceding highlight, then merge it with
14766            // the preceding highlight. Otherwise insert a new highlight.
14767            let mut merged = false;
14768            if ix > 0 {
14769                let prev_highlight = &mut row_highlights[ix - 1];
14770                if prev_highlight
14771                    .range
14772                    .end
14773                    .cmp(&range.start, &snapshot)
14774                    .is_ge()
14775                {
14776                    ix -= 1;
14777                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14778                        prev_highlight.range.end = range.end;
14779                    }
14780                    merged = true;
14781                    prev_highlight.index = index;
14782                    prev_highlight.color = color;
14783                    prev_highlight.should_autoscroll = should_autoscroll;
14784                }
14785            }
14786
14787            if !merged {
14788                row_highlights.insert(
14789                    ix,
14790                    RowHighlight {
14791                        range: range.clone(),
14792                        index,
14793                        color,
14794                        should_autoscroll,
14795                    },
14796                );
14797            }
14798
14799            // If any of the following highlights intersect with this one, merge them.
14800            while let Some(next_highlight) = row_highlights.get(ix + 1) {
14801                let highlight = &row_highlights[ix];
14802                if next_highlight
14803                    .range
14804                    .start
14805                    .cmp(&highlight.range.end, &snapshot)
14806                    .is_le()
14807                {
14808                    if next_highlight
14809                        .range
14810                        .end
14811                        .cmp(&highlight.range.end, &snapshot)
14812                        .is_gt()
14813                    {
14814                        row_highlights[ix].range.end = next_highlight.range.end;
14815                    }
14816                    row_highlights.remove(ix + 1);
14817                } else {
14818                    break;
14819                }
14820            }
14821        }
14822    }
14823
14824    /// Remove any highlighted row ranges of the given type that intersect the
14825    /// given ranges.
14826    pub fn remove_highlighted_rows<T: 'static>(
14827        &mut self,
14828        ranges_to_remove: Vec<Range<Anchor>>,
14829        cx: &mut Context<Self>,
14830    ) {
14831        let snapshot = self.buffer().read(cx).snapshot(cx);
14832        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14833        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14834        row_highlights.retain(|highlight| {
14835            while let Some(range_to_remove) = ranges_to_remove.peek() {
14836                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14837                    Ordering::Less | Ordering::Equal => {
14838                        ranges_to_remove.next();
14839                    }
14840                    Ordering::Greater => {
14841                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14842                            Ordering::Less | Ordering::Equal => {
14843                                return false;
14844                            }
14845                            Ordering::Greater => break,
14846                        }
14847                    }
14848                }
14849            }
14850
14851            true
14852        })
14853    }
14854
14855    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14856    pub fn clear_row_highlights<T: 'static>(&mut self) {
14857        self.highlighted_rows.remove(&TypeId::of::<T>());
14858    }
14859
14860    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14861    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14862        self.highlighted_rows
14863            .get(&TypeId::of::<T>())
14864            .map_or(&[] as &[_], |vec| vec.as_slice())
14865            .iter()
14866            .map(|highlight| (highlight.range.clone(), highlight.color))
14867    }
14868
14869    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14870    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14871    /// Allows to ignore certain kinds of highlights.
14872    pub fn highlighted_display_rows(
14873        &self,
14874        window: &mut Window,
14875        cx: &mut App,
14876    ) -> BTreeMap<DisplayRow, Background> {
14877        let snapshot = self.snapshot(window, cx);
14878        let mut used_highlight_orders = HashMap::default();
14879        self.highlighted_rows
14880            .iter()
14881            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14882            .fold(
14883                BTreeMap::<DisplayRow, Background>::new(),
14884                |mut unique_rows, highlight| {
14885                    let start = highlight.range.start.to_display_point(&snapshot);
14886                    let end = highlight.range.end.to_display_point(&snapshot);
14887                    let start_row = start.row().0;
14888                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14889                        && end.column() == 0
14890                    {
14891                        end.row().0.saturating_sub(1)
14892                    } else {
14893                        end.row().0
14894                    };
14895                    for row in start_row..=end_row {
14896                        let used_index =
14897                            used_highlight_orders.entry(row).or_insert(highlight.index);
14898                        if highlight.index >= *used_index {
14899                            *used_index = highlight.index;
14900                            unique_rows.insert(DisplayRow(row), highlight.color.into());
14901                        }
14902                    }
14903                    unique_rows
14904                },
14905            )
14906    }
14907
14908    pub fn highlighted_display_row_for_autoscroll(
14909        &self,
14910        snapshot: &DisplaySnapshot,
14911    ) -> Option<DisplayRow> {
14912        self.highlighted_rows
14913            .values()
14914            .flat_map(|highlighted_rows| highlighted_rows.iter())
14915            .filter_map(|highlight| {
14916                if highlight.should_autoscroll {
14917                    Some(highlight.range.start.to_display_point(snapshot).row())
14918                } else {
14919                    None
14920                }
14921            })
14922            .min()
14923    }
14924
14925    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14926        self.highlight_background::<SearchWithinRange>(
14927            ranges,
14928            |colors| colors.editor_document_highlight_read_background,
14929            cx,
14930        )
14931    }
14932
14933    pub fn set_breadcrumb_header(&mut self, new_header: String) {
14934        self.breadcrumb_header = Some(new_header);
14935    }
14936
14937    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14938        self.clear_background_highlights::<SearchWithinRange>(cx);
14939    }
14940
14941    pub fn highlight_background<T: 'static>(
14942        &mut self,
14943        ranges: &[Range<Anchor>],
14944        color_fetcher: fn(&ThemeColors) -> Hsla,
14945        cx: &mut Context<Self>,
14946    ) {
14947        self.background_highlights
14948            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14949        self.scrollbar_marker_state.dirty = true;
14950        cx.notify();
14951    }
14952
14953    pub fn clear_background_highlights<T: 'static>(
14954        &mut self,
14955        cx: &mut Context<Self>,
14956    ) -> Option<BackgroundHighlight> {
14957        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14958        if !text_highlights.1.is_empty() {
14959            self.scrollbar_marker_state.dirty = true;
14960            cx.notify();
14961        }
14962        Some(text_highlights)
14963    }
14964
14965    pub fn highlight_gutter<T: 'static>(
14966        &mut self,
14967        ranges: &[Range<Anchor>],
14968        color_fetcher: fn(&App) -> Hsla,
14969        cx: &mut Context<Self>,
14970    ) {
14971        self.gutter_highlights
14972            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14973        cx.notify();
14974    }
14975
14976    pub fn clear_gutter_highlights<T: 'static>(
14977        &mut self,
14978        cx: &mut Context<Self>,
14979    ) -> Option<GutterHighlight> {
14980        cx.notify();
14981        self.gutter_highlights.remove(&TypeId::of::<T>())
14982    }
14983
14984    #[cfg(feature = "test-support")]
14985    pub fn all_text_background_highlights(
14986        &self,
14987        window: &mut Window,
14988        cx: &mut Context<Self>,
14989    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14990        let snapshot = self.snapshot(window, cx);
14991        let buffer = &snapshot.buffer_snapshot;
14992        let start = buffer.anchor_before(0);
14993        let end = buffer.anchor_after(buffer.len());
14994        let theme = cx.theme().colors();
14995        self.background_highlights_in_range(start..end, &snapshot, theme)
14996    }
14997
14998    #[cfg(feature = "test-support")]
14999    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
15000        let snapshot = self.buffer().read(cx).snapshot(cx);
15001
15002        let highlights = self
15003            .background_highlights
15004            .get(&TypeId::of::<items::BufferSearchHighlights>());
15005
15006        if let Some((_color, ranges)) = highlights {
15007            ranges
15008                .iter()
15009                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
15010                .collect_vec()
15011        } else {
15012            vec![]
15013        }
15014    }
15015
15016    fn document_highlights_for_position<'a>(
15017        &'a self,
15018        position: Anchor,
15019        buffer: &'a MultiBufferSnapshot,
15020    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
15021        let read_highlights = self
15022            .background_highlights
15023            .get(&TypeId::of::<DocumentHighlightRead>())
15024            .map(|h| &h.1);
15025        let write_highlights = self
15026            .background_highlights
15027            .get(&TypeId::of::<DocumentHighlightWrite>())
15028            .map(|h| &h.1);
15029        let left_position = position.bias_left(buffer);
15030        let right_position = position.bias_right(buffer);
15031        read_highlights
15032            .into_iter()
15033            .chain(write_highlights)
15034            .flat_map(move |ranges| {
15035                let start_ix = match ranges.binary_search_by(|probe| {
15036                    let cmp = probe.end.cmp(&left_position, buffer);
15037                    if cmp.is_ge() {
15038                        Ordering::Greater
15039                    } else {
15040                        Ordering::Less
15041                    }
15042                }) {
15043                    Ok(i) | Err(i) => i,
15044                };
15045
15046                ranges[start_ix..]
15047                    .iter()
15048                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
15049            })
15050    }
15051
15052    pub fn has_background_highlights<T: 'static>(&self) -> bool {
15053        self.background_highlights
15054            .get(&TypeId::of::<T>())
15055            .map_or(false, |(_, highlights)| !highlights.is_empty())
15056    }
15057
15058    pub fn background_highlights_in_range(
15059        &self,
15060        search_range: Range<Anchor>,
15061        display_snapshot: &DisplaySnapshot,
15062        theme: &ThemeColors,
15063    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15064        let mut results = Vec::new();
15065        for (color_fetcher, ranges) in self.background_highlights.values() {
15066            let color = color_fetcher(theme);
15067            let start_ix = match ranges.binary_search_by(|probe| {
15068                let cmp = probe
15069                    .end
15070                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15071                if cmp.is_gt() {
15072                    Ordering::Greater
15073                } else {
15074                    Ordering::Less
15075                }
15076            }) {
15077                Ok(i) | Err(i) => i,
15078            };
15079            for range in &ranges[start_ix..] {
15080                if range
15081                    .start
15082                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15083                    .is_ge()
15084                {
15085                    break;
15086                }
15087
15088                let start = range.start.to_display_point(display_snapshot);
15089                let end = range.end.to_display_point(display_snapshot);
15090                results.push((start..end, color))
15091            }
15092        }
15093        results
15094    }
15095
15096    pub fn background_highlight_row_ranges<T: 'static>(
15097        &self,
15098        search_range: Range<Anchor>,
15099        display_snapshot: &DisplaySnapshot,
15100        count: usize,
15101    ) -> Vec<RangeInclusive<DisplayPoint>> {
15102        let mut results = Vec::new();
15103        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15104            return vec![];
15105        };
15106
15107        let start_ix = match ranges.binary_search_by(|probe| {
15108            let cmp = probe
15109                .end
15110                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15111            if cmp.is_gt() {
15112                Ordering::Greater
15113            } else {
15114                Ordering::Less
15115            }
15116        }) {
15117            Ok(i) | Err(i) => i,
15118        };
15119        let mut push_region = |start: Option<Point>, end: Option<Point>| {
15120            if let (Some(start_display), Some(end_display)) = (start, end) {
15121                results.push(
15122                    start_display.to_display_point(display_snapshot)
15123                        ..=end_display.to_display_point(display_snapshot),
15124                );
15125            }
15126        };
15127        let mut start_row: Option<Point> = None;
15128        let mut end_row: Option<Point> = None;
15129        if ranges.len() > count {
15130            return Vec::new();
15131        }
15132        for range in &ranges[start_ix..] {
15133            if range
15134                .start
15135                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15136                .is_ge()
15137            {
15138                break;
15139            }
15140            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15141            if let Some(current_row) = &end_row {
15142                if end.row == current_row.row {
15143                    continue;
15144                }
15145            }
15146            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15147            if start_row.is_none() {
15148                assert_eq!(end_row, None);
15149                start_row = Some(start);
15150                end_row = Some(end);
15151                continue;
15152            }
15153            if let Some(current_end) = end_row.as_mut() {
15154                if start.row > current_end.row + 1 {
15155                    push_region(start_row, end_row);
15156                    start_row = Some(start);
15157                    end_row = Some(end);
15158                } else {
15159                    // Merge two hunks.
15160                    *current_end = end;
15161                }
15162            } else {
15163                unreachable!();
15164            }
15165        }
15166        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15167        push_region(start_row, end_row);
15168        results
15169    }
15170
15171    pub fn gutter_highlights_in_range(
15172        &self,
15173        search_range: Range<Anchor>,
15174        display_snapshot: &DisplaySnapshot,
15175        cx: &App,
15176    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15177        let mut results = Vec::new();
15178        for (color_fetcher, ranges) in self.gutter_highlights.values() {
15179            let color = color_fetcher(cx);
15180            let start_ix = match ranges.binary_search_by(|probe| {
15181                let cmp = probe
15182                    .end
15183                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15184                if cmp.is_gt() {
15185                    Ordering::Greater
15186                } else {
15187                    Ordering::Less
15188                }
15189            }) {
15190                Ok(i) | Err(i) => i,
15191            };
15192            for range in &ranges[start_ix..] {
15193                if range
15194                    .start
15195                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15196                    .is_ge()
15197                {
15198                    break;
15199                }
15200
15201                let start = range.start.to_display_point(display_snapshot);
15202                let end = range.end.to_display_point(display_snapshot);
15203                results.push((start..end, color))
15204            }
15205        }
15206        results
15207    }
15208
15209    /// Get the text ranges corresponding to the redaction query
15210    pub fn redacted_ranges(
15211        &self,
15212        search_range: Range<Anchor>,
15213        display_snapshot: &DisplaySnapshot,
15214        cx: &App,
15215    ) -> Vec<Range<DisplayPoint>> {
15216        display_snapshot
15217            .buffer_snapshot
15218            .redacted_ranges(search_range, |file| {
15219                if let Some(file) = file {
15220                    file.is_private()
15221                        && EditorSettings::get(
15222                            Some(SettingsLocation {
15223                                worktree_id: file.worktree_id(cx),
15224                                path: file.path().as_ref(),
15225                            }),
15226                            cx,
15227                        )
15228                        .redact_private_values
15229                } else {
15230                    false
15231                }
15232            })
15233            .map(|range| {
15234                range.start.to_display_point(display_snapshot)
15235                    ..range.end.to_display_point(display_snapshot)
15236            })
15237            .collect()
15238    }
15239
15240    pub fn highlight_text<T: 'static>(
15241        &mut self,
15242        ranges: Vec<Range<Anchor>>,
15243        style: HighlightStyle,
15244        cx: &mut Context<Self>,
15245    ) {
15246        self.display_map.update(cx, |map, _| {
15247            map.highlight_text(TypeId::of::<T>(), ranges, style)
15248        });
15249        cx.notify();
15250    }
15251
15252    pub(crate) fn highlight_inlays<T: 'static>(
15253        &mut self,
15254        highlights: Vec<InlayHighlight>,
15255        style: HighlightStyle,
15256        cx: &mut Context<Self>,
15257    ) {
15258        self.display_map.update(cx, |map, _| {
15259            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15260        });
15261        cx.notify();
15262    }
15263
15264    pub fn text_highlights<'a, T: 'static>(
15265        &'a self,
15266        cx: &'a App,
15267    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15268        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15269    }
15270
15271    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15272        let cleared = self
15273            .display_map
15274            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15275        if cleared {
15276            cx.notify();
15277        }
15278    }
15279
15280    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15281        (self.read_only(cx) || self.blink_manager.read(cx).visible())
15282            && self.focus_handle.is_focused(window)
15283    }
15284
15285    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15286        self.show_cursor_when_unfocused = is_enabled;
15287        cx.notify();
15288    }
15289
15290    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15291        cx.notify();
15292    }
15293
15294    fn on_buffer_event(
15295        &mut self,
15296        multibuffer: &Entity<MultiBuffer>,
15297        event: &multi_buffer::Event,
15298        window: &mut Window,
15299        cx: &mut Context<Self>,
15300    ) {
15301        match event {
15302            multi_buffer::Event::Edited {
15303                singleton_buffer_edited,
15304                edited_buffer: buffer_edited,
15305            } => {
15306                self.scrollbar_marker_state.dirty = true;
15307                self.active_indent_guides_state.dirty = true;
15308                self.refresh_active_diagnostics(cx);
15309                self.refresh_code_actions(window, cx);
15310                if self.has_active_inline_completion() {
15311                    self.update_visible_inline_completion(window, cx);
15312                }
15313                if let Some(buffer) = buffer_edited {
15314                    let buffer_id = buffer.read(cx).remote_id();
15315                    if !self.registered_buffers.contains_key(&buffer_id) {
15316                        if let Some(project) = self.project.as_ref() {
15317                            project.update(cx, |project, cx| {
15318                                self.registered_buffers.insert(
15319                                    buffer_id,
15320                                    project.register_buffer_with_language_servers(&buffer, cx),
15321                                );
15322                            })
15323                        }
15324                    }
15325                }
15326                cx.emit(EditorEvent::BufferEdited);
15327                cx.emit(SearchEvent::MatchesInvalidated);
15328                if *singleton_buffer_edited {
15329                    if let Some(project) = &self.project {
15330                        #[allow(clippy::mutable_key_type)]
15331                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15332                            multibuffer
15333                                .all_buffers()
15334                                .into_iter()
15335                                .filter_map(|buffer| {
15336                                    buffer.update(cx, |buffer, cx| {
15337                                        let language = buffer.language()?;
15338                                        let should_discard = project.update(cx, |project, cx| {
15339                                            project.is_local()
15340                                                && !project.has_language_servers_for(buffer, cx)
15341                                        });
15342                                        should_discard.not().then_some(language.clone())
15343                                    })
15344                                })
15345                                .collect::<HashSet<_>>()
15346                        });
15347                        if !languages_affected.is_empty() {
15348                            self.refresh_inlay_hints(
15349                                InlayHintRefreshReason::BufferEdited(languages_affected),
15350                                cx,
15351                            );
15352                        }
15353                    }
15354                }
15355
15356                let Some(project) = &self.project else { return };
15357                let (telemetry, is_via_ssh) = {
15358                    let project = project.read(cx);
15359                    let telemetry = project.client().telemetry().clone();
15360                    let is_via_ssh = project.is_via_ssh();
15361                    (telemetry, is_via_ssh)
15362                };
15363                refresh_linked_ranges(self, window, cx);
15364                telemetry.log_edit_event("editor", is_via_ssh);
15365            }
15366            multi_buffer::Event::ExcerptsAdded {
15367                buffer,
15368                predecessor,
15369                excerpts,
15370            } => {
15371                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15372                let buffer_id = buffer.read(cx).remote_id();
15373                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15374                    if let Some(project) = &self.project {
15375                        get_uncommitted_diff_for_buffer(
15376                            project,
15377                            [buffer.clone()],
15378                            self.buffer.clone(),
15379                            cx,
15380                        )
15381                        .detach();
15382                    }
15383                }
15384                cx.emit(EditorEvent::ExcerptsAdded {
15385                    buffer: buffer.clone(),
15386                    predecessor: *predecessor,
15387                    excerpts: excerpts.clone(),
15388                });
15389                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15390            }
15391            multi_buffer::Event::ExcerptsRemoved { ids } => {
15392                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15393                let buffer = self.buffer.read(cx);
15394                self.registered_buffers
15395                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15396                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15397            }
15398            multi_buffer::Event::ExcerptsEdited {
15399                excerpt_ids,
15400                buffer_ids,
15401            } => {
15402                self.display_map.update(cx, |map, cx| {
15403                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
15404                });
15405                cx.emit(EditorEvent::ExcerptsEdited {
15406                    ids: excerpt_ids.clone(),
15407                })
15408            }
15409            multi_buffer::Event::ExcerptsExpanded { ids } => {
15410                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15411                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15412            }
15413            multi_buffer::Event::Reparsed(buffer_id) => {
15414                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15415
15416                cx.emit(EditorEvent::Reparsed(*buffer_id));
15417            }
15418            multi_buffer::Event::DiffHunksToggled => {
15419                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15420            }
15421            multi_buffer::Event::LanguageChanged(buffer_id) => {
15422                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15423                cx.emit(EditorEvent::Reparsed(*buffer_id));
15424                cx.notify();
15425            }
15426            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15427            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15428            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15429                cx.emit(EditorEvent::TitleChanged)
15430            }
15431            // multi_buffer::Event::DiffBaseChanged => {
15432            //     self.scrollbar_marker_state.dirty = true;
15433            //     cx.emit(EditorEvent::DiffBaseChanged);
15434            //     cx.notify();
15435            // }
15436            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15437            multi_buffer::Event::DiagnosticsUpdated => {
15438                self.refresh_active_diagnostics(cx);
15439                self.refresh_inline_diagnostics(true, window, cx);
15440                self.scrollbar_marker_state.dirty = true;
15441                cx.notify();
15442            }
15443            _ => {}
15444        };
15445    }
15446
15447    fn on_display_map_changed(
15448        &mut self,
15449        _: Entity<DisplayMap>,
15450        _: &mut Window,
15451        cx: &mut Context<Self>,
15452    ) {
15453        cx.notify();
15454    }
15455
15456    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15457        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15458        self.update_edit_prediction_settings(cx);
15459        self.refresh_inline_completion(true, false, window, cx);
15460        self.refresh_inlay_hints(
15461            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15462                self.selections.newest_anchor().head(),
15463                &self.buffer.read(cx).snapshot(cx),
15464                cx,
15465            )),
15466            cx,
15467        );
15468
15469        let old_cursor_shape = self.cursor_shape;
15470
15471        {
15472            let editor_settings = EditorSettings::get_global(cx);
15473            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15474            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15475            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15476        }
15477
15478        if old_cursor_shape != self.cursor_shape {
15479            cx.emit(EditorEvent::CursorShapeChanged);
15480        }
15481
15482        let project_settings = ProjectSettings::get_global(cx);
15483        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15484
15485        if self.mode == EditorMode::Full {
15486            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15487            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15488            if self.show_inline_diagnostics != show_inline_diagnostics {
15489                self.show_inline_diagnostics = show_inline_diagnostics;
15490                self.refresh_inline_diagnostics(false, window, cx);
15491            }
15492
15493            if self.git_blame_inline_enabled != inline_blame_enabled {
15494                self.toggle_git_blame_inline_internal(false, window, cx);
15495            }
15496        }
15497
15498        cx.notify();
15499    }
15500
15501    pub fn set_searchable(&mut self, searchable: bool) {
15502        self.searchable = searchable;
15503    }
15504
15505    pub fn searchable(&self) -> bool {
15506        self.searchable
15507    }
15508
15509    fn open_proposed_changes_editor(
15510        &mut self,
15511        _: &OpenProposedChangesEditor,
15512        window: &mut Window,
15513        cx: &mut Context<Self>,
15514    ) {
15515        let Some(workspace) = self.workspace() else {
15516            cx.propagate();
15517            return;
15518        };
15519
15520        let selections = self.selections.all::<usize>(cx);
15521        let multi_buffer = self.buffer.read(cx);
15522        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15523        let mut new_selections_by_buffer = HashMap::default();
15524        for selection in selections {
15525            for (buffer, range, _) in
15526                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15527            {
15528                let mut range = range.to_point(buffer);
15529                range.start.column = 0;
15530                range.end.column = buffer.line_len(range.end.row);
15531                new_selections_by_buffer
15532                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15533                    .or_insert(Vec::new())
15534                    .push(range)
15535            }
15536        }
15537
15538        let proposed_changes_buffers = new_selections_by_buffer
15539            .into_iter()
15540            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15541            .collect::<Vec<_>>();
15542        let proposed_changes_editor = cx.new(|cx| {
15543            ProposedChangesEditor::new(
15544                "Proposed changes",
15545                proposed_changes_buffers,
15546                self.project.clone(),
15547                window,
15548                cx,
15549            )
15550        });
15551
15552        window.defer(cx, move |window, cx| {
15553            workspace.update(cx, |workspace, cx| {
15554                workspace.active_pane().update(cx, |pane, cx| {
15555                    pane.add_item(
15556                        Box::new(proposed_changes_editor),
15557                        true,
15558                        true,
15559                        None,
15560                        window,
15561                        cx,
15562                    );
15563                });
15564            });
15565        });
15566    }
15567
15568    pub fn open_excerpts_in_split(
15569        &mut self,
15570        _: &OpenExcerptsSplit,
15571        window: &mut Window,
15572        cx: &mut Context<Self>,
15573    ) {
15574        self.open_excerpts_common(None, true, window, cx)
15575    }
15576
15577    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15578        self.open_excerpts_common(None, false, window, cx)
15579    }
15580
15581    fn open_excerpts_common(
15582        &mut self,
15583        jump_data: Option<JumpData>,
15584        split: bool,
15585        window: &mut Window,
15586        cx: &mut Context<Self>,
15587    ) {
15588        let Some(workspace) = self.workspace() else {
15589            cx.propagate();
15590            return;
15591        };
15592
15593        if self.buffer.read(cx).is_singleton() {
15594            cx.propagate();
15595            return;
15596        }
15597
15598        let mut new_selections_by_buffer = HashMap::default();
15599        match &jump_data {
15600            Some(JumpData::MultiBufferPoint {
15601                excerpt_id,
15602                position,
15603                anchor,
15604                line_offset_from_top,
15605            }) => {
15606                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15607                if let Some(buffer) = multi_buffer_snapshot
15608                    .buffer_id_for_excerpt(*excerpt_id)
15609                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15610                {
15611                    let buffer_snapshot = buffer.read(cx).snapshot();
15612                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15613                        language::ToPoint::to_point(anchor, &buffer_snapshot)
15614                    } else {
15615                        buffer_snapshot.clip_point(*position, Bias::Left)
15616                    };
15617                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15618                    new_selections_by_buffer.insert(
15619                        buffer,
15620                        (
15621                            vec![jump_to_offset..jump_to_offset],
15622                            Some(*line_offset_from_top),
15623                        ),
15624                    );
15625                }
15626            }
15627            Some(JumpData::MultiBufferRow {
15628                row,
15629                line_offset_from_top,
15630            }) => {
15631                let point = MultiBufferPoint::new(row.0, 0);
15632                if let Some((buffer, buffer_point, _)) =
15633                    self.buffer.read(cx).point_to_buffer_point(point, cx)
15634                {
15635                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15636                    new_selections_by_buffer
15637                        .entry(buffer)
15638                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
15639                        .0
15640                        .push(buffer_offset..buffer_offset)
15641                }
15642            }
15643            None => {
15644                let selections = self.selections.all::<usize>(cx);
15645                let multi_buffer = self.buffer.read(cx);
15646                for selection in selections {
15647                    for (snapshot, range, _, anchor) in multi_buffer
15648                        .snapshot(cx)
15649                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15650                    {
15651                        if let Some(anchor) = anchor {
15652                            // selection is in a deleted hunk
15653                            let Some(buffer_id) = anchor.buffer_id else {
15654                                continue;
15655                            };
15656                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15657                                continue;
15658                            };
15659                            let offset = text::ToOffset::to_offset(
15660                                &anchor.text_anchor,
15661                                &buffer_handle.read(cx).snapshot(),
15662                            );
15663                            let range = offset..offset;
15664                            new_selections_by_buffer
15665                                .entry(buffer_handle)
15666                                .or_insert((Vec::new(), None))
15667                                .0
15668                                .push(range)
15669                        } else {
15670                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15671                            else {
15672                                continue;
15673                            };
15674                            new_selections_by_buffer
15675                                .entry(buffer_handle)
15676                                .or_insert((Vec::new(), None))
15677                                .0
15678                                .push(range)
15679                        }
15680                    }
15681                }
15682            }
15683        }
15684
15685        if new_selections_by_buffer.is_empty() {
15686            return;
15687        }
15688
15689        // We defer the pane interaction because we ourselves are a workspace item
15690        // and activating a new item causes the pane to call a method on us reentrantly,
15691        // which panics if we're on the stack.
15692        window.defer(cx, move |window, cx| {
15693            workspace.update(cx, |workspace, cx| {
15694                let pane = if split {
15695                    workspace.adjacent_pane(window, cx)
15696                } else {
15697                    workspace.active_pane().clone()
15698                };
15699
15700                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15701                    let editor = buffer
15702                        .read(cx)
15703                        .file()
15704                        .is_none()
15705                        .then(|| {
15706                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15707                            // so `workspace.open_project_item` will never find them, always opening a new editor.
15708                            // Instead, we try to activate the existing editor in the pane first.
15709                            let (editor, pane_item_index) =
15710                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
15711                                    let editor = item.downcast::<Editor>()?;
15712                                    let singleton_buffer =
15713                                        editor.read(cx).buffer().read(cx).as_singleton()?;
15714                                    if singleton_buffer == buffer {
15715                                        Some((editor, i))
15716                                    } else {
15717                                        None
15718                                    }
15719                                })?;
15720                            pane.update(cx, |pane, cx| {
15721                                pane.activate_item(pane_item_index, true, true, window, cx)
15722                            });
15723                            Some(editor)
15724                        })
15725                        .flatten()
15726                        .unwrap_or_else(|| {
15727                            workspace.open_project_item::<Self>(
15728                                pane.clone(),
15729                                buffer,
15730                                true,
15731                                true,
15732                                window,
15733                                cx,
15734                            )
15735                        });
15736
15737                    editor.update(cx, |editor, cx| {
15738                        let autoscroll = match scroll_offset {
15739                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15740                            None => Autoscroll::newest(),
15741                        };
15742                        let nav_history = editor.nav_history.take();
15743                        editor.change_selections(Some(autoscroll), window, cx, |s| {
15744                            s.select_ranges(ranges);
15745                        });
15746                        editor.nav_history = nav_history;
15747                    });
15748                }
15749            })
15750        });
15751    }
15752
15753    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15754        let snapshot = self.buffer.read(cx).read(cx);
15755        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15756        Some(
15757            ranges
15758                .iter()
15759                .map(move |range| {
15760                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15761                })
15762                .collect(),
15763        )
15764    }
15765
15766    fn selection_replacement_ranges(
15767        &self,
15768        range: Range<OffsetUtf16>,
15769        cx: &mut App,
15770    ) -> Vec<Range<OffsetUtf16>> {
15771        let selections = self.selections.all::<OffsetUtf16>(cx);
15772        let newest_selection = selections
15773            .iter()
15774            .max_by_key(|selection| selection.id)
15775            .unwrap();
15776        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15777        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15778        let snapshot = self.buffer.read(cx).read(cx);
15779        selections
15780            .into_iter()
15781            .map(|mut selection| {
15782                selection.start.0 =
15783                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
15784                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15785                snapshot.clip_offset_utf16(selection.start, Bias::Left)
15786                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15787            })
15788            .collect()
15789    }
15790
15791    fn report_editor_event(
15792        &self,
15793        event_type: &'static str,
15794        file_extension: Option<String>,
15795        cx: &App,
15796    ) {
15797        if cfg!(any(test, feature = "test-support")) {
15798            return;
15799        }
15800
15801        let Some(project) = &self.project else { return };
15802
15803        // If None, we are in a file without an extension
15804        let file = self
15805            .buffer
15806            .read(cx)
15807            .as_singleton()
15808            .and_then(|b| b.read(cx).file());
15809        let file_extension = file_extension.or(file
15810            .as_ref()
15811            .and_then(|file| Path::new(file.file_name(cx)).extension())
15812            .and_then(|e| e.to_str())
15813            .map(|a| a.to_string()));
15814
15815        let vim_mode = cx
15816            .global::<SettingsStore>()
15817            .raw_user_settings()
15818            .get("vim_mode")
15819            == Some(&serde_json::Value::Bool(true));
15820
15821        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15822        let copilot_enabled = edit_predictions_provider
15823            == language::language_settings::EditPredictionProvider::Copilot;
15824        let copilot_enabled_for_language = self
15825            .buffer
15826            .read(cx)
15827            .language_settings(cx)
15828            .show_edit_predictions;
15829
15830        let project = project.read(cx);
15831        telemetry::event!(
15832            event_type,
15833            file_extension,
15834            vim_mode,
15835            copilot_enabled,
15836            copilot_enabled_for_language,
15837            edit_predictions_provider,
15838            is_via_ssh = project.is_via_ssh(),
15839        );
15840    }
15841
15842    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15843    /// with each line being an array of {text, highlight} objects.
15844    fn copy_highlight_json(
15845        &mut self,
15846        _: &CopyHighlightJson,
15847        window: &mut Window,
15848        cx: &mut Context<Self>,
15849    ) {
15850        #[derive(Serialize)]
15851        struct Chunk<'a> {
15852            text: String,
15853            highlight: Option<&'a str>,
15854        }
15855
15856        let snapshot = self.buffer.read(cx).snapshot(cx);
15857        let range = self
15858            .selected_text_range(false, window, cx)
15859            .and_then(|selection| {
15860                if selection.range.is_empty() {
15861                    None
15862                } else {
15863                    Some(selection.range)
15864                }
15865            })
15866            .unwrap_or_else(|| 0..snapshot.len());
15867
15868        let chunks = snapshot.chunks(range, true);
15869        let mut lines = Vec::new();
15870        let mut line: VecDeque<Chunk> = VecDeque::new();
15871
15872        let Some(style) = self.style.as_ref() else {
15873            return;
15874        };
15875
15876        for chunk in chunks {
15877            let highlight = chunk
15878                .syntax_highlight_id
15879                .and_then(|id| id.name(&style.syntax));
15880            let mut chunk_lines = chunk.text.split('\n').peekable();
15881            while let Some(text) = chunk_lines.next() {
15882                let mut merged_with_last_token = false;
15883                if let Some(last_token) = line.back_mut() {
15884                    if last_token.highlight == highlight {
15885                        last_token.text.push_str(text);
15886                        merged_with_last_token = true;
15887                    }
15888                }
15889
15890                if !merged_with_last_token {
15891                    line.push_back(Chunk {
15892                        text: text.into(),
15893                        highlight,
15894                    });
15895                }
15896
15897                if chunk_lines.peek().is_some() {
15898                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
15899                        line.pop_front();
15900                    }
15901                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
15902                        line.pop_back();
15903                    }
15904
15905                    lines.push(mem::take(&mut line));
15906                }
15907            }
15908        }
15909
15910        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15911            return;
15912        };
15913        cx.write_to_clipboard(ClipboardItem::new_string(lines));
15914    }
15915
15916    pub fn open_context_menu(
15917        &mut self,
15918        _: &OpenContextMenu,
15919        window: &mut Window,
15920        cx: &mut Context<Self>,
15921    ) {
15922        self.request_autoscroll(Autoscroll::newest(), cx);
15923        let position = self.selections.newest_display(cx).start;
15924        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15925    }
15926
15927    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15928        &self.inlay_hint_cache
15929    }
15930
15931    pub fn replay_insert_event(
15932        &mut self,
15933        text: &str,
15934        relative_utf16_range: Option<Range<isize>>,
15935        window: &mut Window,
15936        cx: &mut Context<Self>,
15937    ) {
15938        if !self.input_enabled {
15939            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15940            return;
15941        }
15942        if let Some(relative_utf16_range) = relative_utf16_range {
15943            let selections = self.selections.all::<OffsetUtf16>(cx);
15944            self.change_selections(None, window, cx, |s| {
15945                let new_ranges = selections.into_iter().map(|range| {
15946                    let start = OffsetUtf16(
15947                        range
15948                            .head()
15949                            .0
15950                            .saturating_add_signed(relative_utf16_range.start),
15951                    );
15952                    let end = OffsetUtf16(
15953                        range
15954                            .head()
15955                            .0
15956                            .saturating_add_signed(relative_utf16_range.end),
15957                    );
15958                    start..end
15959                });
15960                s.select_ranges(new_ranges);
15961            });
15962        }
15963
15964        self.handle_input(text, window, cx);
15965    }
15966
15967    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15968        let Some(provider) = self.semantics_provider.as_ref() else {
15969            return false;
15970        };
15971
15972        let mut supports = false;
15973        self.buffer().update(cx, |this, cx| {
15974            this.for_each_buffer(|buffer| {
15975                supports |= provider.supports_inlay_hints(buffer, cx);
15976            });
15977        });
15978
15979        supports
15980    }
15981
15982    pub fn is_focused(&self, window: &Window) -> bool {
15983        self.focus_handle.is_focused(window)
15984    }
15985
15986    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15987        cx.emit(EditorEvent::Focused);
15988
15989        if let Some(descendant) = self
15990            .last_focused_descendant
15991            .take()
15992            .and_then(|descendant| descendant.upgrade())
15993        {
15994            window.focus(&descendant);
15995        } else {
15996            if let Some(blame) = self.blame.as_ref() {
15997                blame.update(cx, GitBlame::focus)
15998            }
15999
16000            self.blink_manager.update(cx, BlinkManager::enable);
16001            self.show_cursor_names(window, cx);
16002            self.buffer.update(cx, |buffer, cx| {
16003                buffer.finalize_last_transaction(cx);
16004                if self.leader_peer_id.is_none() {
16005                    buffer.set_active_selections(
16006                        &self.selections.disjoint_anchors(),
16007                        self.selections.line_mode,
16008                        self.cursor_shape,
16009                        cx,
16010                    );
16011                }
16012            });
16013        }
16014    }
16015
16016    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16017        cx.emit(EditorEvent::FocusedIn)
16018    }
16019
16020    fn handle_focus_out(
16021        &mut self,
16022        event: FocusOutEvent,
16023        _window: &mut Window,
16024        cx: &mut Context<Self>,
16025    ) {
16026        if event.blurred != self.focus_handle {
16027            self.last_focused_descendant = Some(event.blurred);
16028        }
16029        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
16030    }
16031
16032    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16033        self.blink_manager.update(cx, BlinkManager::disable);
16034        self.buffer
16035            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
16036
16037        if let Some(blame) = self.blame.as_ref() {
16038            blame.update(cx, GitBlame::blur)
16039        }
16040        if !self.hover_state.focused(window, cx) {
16041            hide_hover(self, cx);
16042        }
16043        if !self
16044            .context_menu
16045            .borrow()
16046            .as_ref()
16047            .is_some_and(|context_menu| context_menu.focused(window, cx))
16048        {
16049            self.hide_context_menu(window, cx);
16050        }
16051        self.discard_inline_completion(false, cx);
16052        cx.emit(EditorEvent::Blurred);
16053        cx.notify();
16054    }
16055
16056    pub fn register_action<A: Action>(
16057        &mut self,
16058        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
16059    ) -> Subscription {
16060        let id = self.next_editor_action_id.post_inc();
16061        let listener = Arc::new(listener);
16062        self.editor_actions.borrow_mut().insert(
16063            id,
16064            Box::new(move |window, _| {
16065                let listener = listener.clone();
16066                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
16067                    let action = action.downcast_ref().unwrap();
16068                    if phase == DispatchPhase::Bubble {
16069                        listener(action, window, cx)
16070                    }
16071                })
16072            }),
16073        );
16074
16075        let editor_actions = self.editor_actions.clone();
16076        Subscription::new(move || {
16077            editor_actions.borrow_mut().remove(&id);
16078        })
16079    }
16080
16081    pub fn file_header_size(&self) -> u32 {
16082        FILE_HEADER_HEIGHT
16083    }
16084
16085    pub fn restore(
16086        &mut self,
16087        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16088        window: &mut Window,
16089        cx: &mut Context<Self>,
16090    ) {
16091        let workspace = self.workspace();
16092        let project = self.project.as_ref();
16093        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16094            let mut tasks = Vec::new();
16095            for (buffer_id, changes) in revert_changes {
16096                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16097                    buffer.update(cx, |buffer, cx| {
16098                        buffer.edit(
16099                            changes
16100                                .into_iter()
16101                                .map(|(range, text)| (range, text.to_string())),
16102                            None,
16103                            cx,
16104                        );
16105                    });
16106
16107                    if let Some(project) =
16108                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16109                    {
16110                        project.update(cx, |project, cx| {
16111                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16112                        })
16113                    }
16114                }
16115            }
16116            tasks
16117        });
16118        cx.spawn_in(window, |_, mut cx| async move {
16119            for (buffer, task) in save_tasks {
16120                let result = task.await;
16121                if result.is_err() {
16122                    let Some(path) = buffer
16123                        .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16124                        .ok()
16125                    else {
16126                        continue;
16127                    };
16128                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16129                        let Some(task) = cx
16130                            .update_window_entity(&workspace, |workspace, window, cx| {
16131                                workspace
16132                                    .open_path_preview(path, None, false, false, false, window, cx)
16133                            })
16134                            .ok()
16135                        else {
16136                            continue;
16137                        };
16138                        task.await.log_err();
16139                    }
16140                }
16141            }
16142        })
16143        .detach();
16144        self.change_selections(None, window, cx, |selections| selections.refresh());
16145    }
16146
16147    pub fn to_pixel_point(
16148        &self,
16149        source: multi_buffer::Anchor,
16150        editor_snapshot: &EditorSnapshot,
16151        window: &mut Window,
16152    ) -> Option<gpui::Point<Pixels>> {
16153        let source_point = source.to_display_point(editor_snapshot);
16154        self.display_to_pixel_point(source_point, editor_snapshot, window)
16155    }
16156
16157    pub fn display_to_pixel_point(
16158        &self,
16159        source: DisplayPoint,
16160        editor_snapshot: &EditorSnapshot,
16161        window: &mut Window,
16162    ) -> Option<gpui::Point<Pixels>> {
16163        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16164        let text_layout_details = self.text_layout_details(window);
16165        let scroll_top = text_layout_details
16166            .scroll_anchor
16167            .scroll_position(editor_snapshot)
16168            .y;
16169
16170        if source.row().as_f32() < scroll_top.floor() {
16171            return None;
16172        }
16173        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16174        let source_y = line_height * (source.row().as_f32() - scroll_top);
16175        Some(gpui::Point::new(source_x, source_y))
16176    }
16177
16178    pub fn has_visible_completions_menu(&self) -> bool {
16179        !self.edit_prediction_preview_is_active()
16180            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16181                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16182            })
16183    }
16184
16185    pub fn register_addon<T: Addon>(&mut self, instance: T) {
16186        self.addons
16187            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16188    }
16189
16190    pub fn unregister_addon<T: Addon>(&mut self) {
16191        self.addons.remove(&std::any::TypeId::of::<T>());
16192    }
16193
16194    pub fn addon<T: Addon>(&self) -> Option<&T> {
16195        let type_id = std::any::TypeId::of::<T>();
16196        self.addons
16197            .get(&type_id)
16198            .and_then(|item| item.to_any().downcast_ref::<T>())
16199    }
16200
16201    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16202        let text_layout_details = self.text_layout_details(window);
16203        let style = &text_layout_details.editor_style;
16204        let font_id = window.text_system().resolve_font(&style.text.font());
16205        let font_size = style.text.font_size.to_pixels(window.rem_size());
16206        let line_height = style.text.line_height_in_pixels(window.rem_size());
16207        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16208
16209        gpui::Size::new(em_width, line_height)
16210    }
16211
16212    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16213        self.load_diff_task.clone()
16214    }
16215
16216    fn read_selections_from_db(
16217        &mut self,
16218        item_id: u64,
16219        workspace_id: WorkspaceId,
16220        window: &mut Window,
16221        cx: &mut Context<Editor>,
16222    ) {
16223        if !self.is_singleton(cx)
16224            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16225        {
16226            return;
16227        }
16228        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16229            return;
16230        };
16231        if selections.is_empty() {
16232            return;
16233        }
16234
16235        let snapshot = self.buffer.read(cx).snapshot(cx);
16236        self.change_selections(None, window, cx, |s| {
16237            s.select_ranges(selections.into_iter().map(|(start, end)| {
16238                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16239            }));
16240        });
16241    }
16242}
16243
16244fn insert_extra_newline_brackets(
16245    buffer: &MultiBufferSnapshot,
16246    range: Range<usize>,
16247    language: &language::LanguageScope,
16248) -> bool {
16249    let leading_whitespace_len = buffer
16250        .reversed_chars_at(range.start)
16251        .take_while(|c| c.is_whitespace() && *c != '\n')
16252        .map(|c| c.len_utf8())
16253        .sum::<usize>();
16254    let trailing_whitespace_len = buffer
16255        .chars_at(range.end)
16256        .take_while(|c| c.is_whitespace() && *c != '\n')
16257        .map(|c| c.len_utf8())
16258        .sum::<usize>();
16259    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16260
16261    language.brackets().any(|(pair, enabled)| {
16262        let pair_start = pair.start.trim_end();
16263        let pair_end = pair.end.trim_start();
16264
16265        enabled
16266            && pair.newline
16267            && buffer.contains_str_at(range.end, pair_end)
16268            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16269    })
16270}
16271
16272fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16273    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16274        [(buffer, range, _)] => (*buffer, range.clone()),
16275        _ => return false,
16276    };
16277    let pair = {
16278        let mut result: Option<BracketMatch> = None;
16279
16280        for pair in buffer
16281            .all_bracket_ranges(range.clone())
16282            .filter(move |pair| {
16283                pair.open_range.start <= range.start && pair.close_range.end >= range.end
16284            })
16285        {
16286            let len = pair.close_range.end - pair.open_range.start;
16287
16288            if let Some(existing) = &result {
16289                let existing_len = existing.close_range.end - existing.open_range.start;
16290                if len > existing_len {
16291                    continue;
16292                }
16293            }
16294
16295            result = Some(pair);
16296        }
16297
16298        result
16299    };
16300    let Some(pair) = pair else {
16301        return false;
16302    };
16303    pair.newline_only
16304        && buffer
16305            .chars_for_range(pair.open_range.end..range.start)
16306            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16307            .all(|c| c.is_whitespace() && c != '\n')
16308}
16309
16310fn get_uncommitted_diff_for_buffer(
16311    project: &Entity<Project>,
16312    buffers: impl IntoIterator<Item = Entity<Buffer>>,
16313    buffer: Entity<MultiBuffer>,
16314    cx: &mut App,
16315) -> Task<()> {
16316    let mut tasks = Vec::new();
16317    project.update(cx, |project, cx| {
16318        for buffer in buffers {
16319            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16320        }
16321    });
16322    cx.spawn(|mut cx| async move {
16323        let diffs = future::join_all(tasks).await;
16324        buffer
16325            .update(&mut cx, |buffer, cx| {
16326                for diff in diffs.into_iter().flatten() {
16327                    buffer.add_diff(diff, cx);
16328                }
16329            })
16330            .ok();
16331    })
16332}
16333
16334fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16335    let tab_size = tab_size.get() as usize;
16336    let mut width = offset;
16337
16338    for ch in text.chars() {
16339        width += if ch == '\t' {
16340            tab_size - (width % tab_size)
16341        } else {
16342            1
16343        };
16344    }
16345
16346    width - offset
16347}
16348
16349#[cfg(test)]
16350mod tests {
16351    use super::*;
16352
16353    #[test]
16354    fn test_string_size_with_expanded_tabs() {
16355        let nz = |val| NonZeroU32::new(val).unwrap();
16356        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16357        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16358        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16359        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16360        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16361        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16362        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16363        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16364    }
16365}
16366
16367/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16368struct WordBreakingTokenizer<'a> {
16369    input: &'a str,
16370}
16371
16372impl<'a> WordBreakingTokenizer<'a> {
16373    fn new(input: &'a str) -> Self {
16374        Self { input }
16375    }
16376}
16377
16378fn is_char_ideographic(ch: char) -> bool {
16379    use unicode_script::Script::*;
16380    use unicode_script::UnicodeScript;
16381    matches!(ch.script(), Han | Tangut | Yi)
16382}
16383
16384fn is_grapheme_ideographic(text: &str) -> bool {
16385    text.chars().any(is_char_ideographic)
16386}
16387
16388fn is_grapheme_whitespace(text: &str) -> bool {
16389    text.chars().any(|x| x.is_whitespace())
16390}
16391
16392fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16393    text.chars().next().map_or(false, |ch| {
16394        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16395    })
16396}
16397
16398#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16399struct WordBreakToken<'a> {
16400    token: &'a str,
16401    grapheme_len: usize,
16402    is_whitespace: bool,
16403}
16404
16405impl<'a> Iterator for WordBreakingTokenizer<'a> {
16406    /// Yields a span, the count of graphemes in the token, and whether it was
16407    /// whitespace. Note that it also breaks at word boundaries.
16408    type Item = WordBreakToken<'a>;
16409
16410    fn next(&mut self) -> Option<Self::Item> {
16411        use unicode_segmentation::UnicodeSegmentation;
16412        if self.input.is_empty() {
16413            return None;
16414        }
16415
16416        let mut iter = self.input.graphemes(true).peekable();
16417        let mut offset = 0;
16418        let mut graphemes = 0;
16419        if let Some(first_grapheme) = iter.next() {
16420            let is_whitespace = is_grapheme_whitespace(first_grapheme);
16421            offset += first_grapheme.len();
16422            graphemes += 1;
16423            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16424                if let Some(grapheme) = iter.peek().copied() {
16425                    if should_stay_with_preceding_ideograph(grapheme) {
16426                        offset += grapheme.len();
16427                        graphemes += 1;
16428                    }
16429                }
16430            } else {
16431                let mut words = self.input[offset..].split_word_bound_indices().peekable();
16432                let mut next_word_bound = words.peek().copied();
16433                if next_word_bound.map_or(false, |(i, _)| i == 0) {
16434                    next_word_bound = words.next();
16435                }
16436                while let Some(grapheme) = iter.peek().copied() {
16437                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
16438                        break;
16439                    };
16440                    if is_grapheme_whitespace(grapheme) != is_whitespace {
16441                        break;
16442                    };
16443                    offset += grapheme.len();
16444                    graphemes += 1;
16445                    iter.next();
16446                }
16447            }
16448            let token = &self.input[..offset];
16449            self.input = &self.input[offset..];
16450            if is_whitespace {
16451                Some(WordBreakToken {
16452                    token: " ",
16453                    grapheme_len: 1,
16454                    is_whitespace: true,
16455                })
16456            } else {
16457                Some(WordBreakToken {
16458                    token,
16459                    grapheme_len: graphemes,
16460                    is_whitespace: false,
16461                })
16462            }
16463        } else {
16464            None
16465        }
16466    }
16467}
16468
16469#[test]
16470fn test_word_breaking_tokenizer() {
16471    let tests: &[(&str, &[(&str, usize, bool)])] = &[
16472        ("", &[]),
16473        ("  ", &[(" ", 1, true)]),
16474        ("Ʒ", &[("Ʒ", 1, false)]),
16475        ("Ǽ", &[("Ǽ", 1, false)]),
16476        ("", &[("", 1, false)]),
16477        ("⋑⋑", &[("⋑⋑", 2, false)]),
16478        (
16479            "原理,进而",
16480            &[
16481                ("", 1, false),
16482                ("理,", 2, false),
16483                ("", 1, false),
16484                ("", 1, false),
16485            ],
16486        ),
16487        (
16488            "hello world",
16489            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16490        ),
16491        (
16492            "hello, world",
16493            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16494        ),
16495        (
16496            "  hello world",
16497            &[
16498                (" ", 1, true),
16499                ("hello", 5, false),
16500                (" ", 1, true),
16501                ("world", 5, false),
16502            ],
16503        ),
16504        (
16505            "这是什么 \n 钢笔",
16506            &[
16507                ("", 1, false),
16508                ("", 1, false),
16509                ("", 1, false),
16510                ("", 1, false),
16511                (" ", 1, true),
16512                ("", 1, false),
16513                ("", 1, false),
16514            ],
16515        ),
16516        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16517    ];
16518
16519    for (input, result) in tests {
16520        assert_eq!(
16521            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16522            result
16523                .iter()
16524                .copied()
16525                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16526                    token,
16527                    grapheme_len,
16528                    is_whitespace,
16529                })
16530                .collect::<Vec<_>>()
16531        );
16532    }
16533}
16534
16535fn wrap_with_prefix(
16536    line_prefix: String,
16537    unwrapped_text: String,
16538    wrap_column: usize,
16539    tab_size: NonZeroU32,
16540) -> String {
16541    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16542    let mut wrapped_text = String::new();
16543    let mut current_line = line_prefix.clone();
16544
16545    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16546    let mut current_line_len = line_prefix_len;
16547    for WordBreakToken {
16548        token,
16549        grapheme_len,
16550        is_whitespace,
16551    } in tokenizer
16552    {
16553        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16554            wrapped_text.push_str(current_line.trim_end());
16555            wrapped_text.push('\n');
16556            current_line.truncate(line_prefix.len());
16557            current_line_len = line_prefix_len;
16558            if !is_whitespace {
16559                current_line.push_str(token);
16560                current_line_len += grapheme_len;
16561            }
16562        } else if !is_whitespace {
16563            current_line.push_str(token);
16564            current_line_len += grapheme_len;
16565        } else if current_line_len != line_prefix_len {
16566            current_line.push(' ');
16567            current_line_len += 1;
16568        }
16569    }
16570
16571    if !current_line.is_empty() {
16572        wrapped_text.push_str(&current_line);
16573    }
16574    wrapped_text
16575}
16576
16577#[test]
16578fn test_wrap_with_prefix() {
16579    assert_eq!(
16580        wrap_with_prefix(
16581            "# ".to_string(),
16582            "abcdefg".to_string(),
16583            4,
16584            NonZeroU32::new(4).unwrap()
16585        ),
16586        "# abcdefg"
16587    );
16588    assert_eq!(
16589        wrap_with_prefix(
16590            "".to_string(),
16591            "\thello world".to_string(),
16592            8,
16593            NonZeroU32::new(4).unwrap()
16594        ),
16595        "hello\nworld"
16596    );
16597    assert_eq!(
16598        wrap_with_prefix(
16599            "// ".to_string(),
16600            "xx \nyy zz aa bb cc".to_string(),
16601            12,
16602            NonZeroU32::new(4).unwrap()
16603        ),
16604        "// xx yy zz\n// aa bb cc"
16605    );
16606    assert_eq!(
16607        wrap_with_prefix(
16608            String::new(),
16609            "这是什么 \n 钢笔".to_string(),
16610            3,
16611            NonZeroU32::new(4).unwrap()
16612        ),
16613        "这是什\n么 钢\n"
16614    );
16615}
16616
16617pub trait CollaborationHub {
16618    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16619    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16620    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16621}
16622
16623impl CollaborationHub for Entity<Project> {
16624    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16625        self.read(cx).collaborators()
16626    }
16627
16628    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16629        self.read(cx).user_store().read(cx).participant_indices()
16630    }
16631
16632    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16633        let this = self.read(cx);
16634        let user_ids = this.collaborators().values().map(|c| c.user_id);
16635        this.user_store().read_with(cx, |user_store, cx| {
16636            user_store.participant_names(user_ids, cx)
16637        })
16638    }
16639}
16640
16641pub trait SemanticsProvider {
16642    fn hover(
16643        &self,
16644        buffer: &Entity<Buffer>,
16645        position: text::Anchor,
16646        cx: &mut App,
16647    ) -> Option<Task<Vec<project::Hover>>>;
16648
16649    fn inlay_hints(
16650        &self,
16651        buffer_handle: Entity<Buffer>,
16652        range: Range<text::Anchor>,
16653        cx: &mut App,
16654    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16655
16656    fn resolve_inlay_hint(
16657        &self,
16658        hint: InlayHint,
16659        buffer_handle: Entity<Buffer>,
16660        server_id: LanguageServerId,
16661        cx: &mut App,
16662    ) -> Option<Task<anyhow::Result<InlayHint>>>;
16663
16664    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16665
16666    fn document_highlights(
16667        &self,
16668        buffer: &Entity<Buffer>,
16669        position: text::Anchor,
16670        cx: &mut App,
16671    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16672
16673    fn definitions(
16674        &self,
16675        buffer: &Entity<Buffer>,
16676        position: text::Anchor,
16677        kind: GotoDefinitionKind,
16678        cx: &mut App,
16679    ) -> Option<Task<Result<Vec<LocationLink>>>>;
16680
16681    fn range_for_rename(
16682        &self,
16683        buffer: &Entity<Buffer>,
16684        position: text::Anchor,
16685        cx: &mut App,
16686    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16687
16688    fn perform_rename(
16689        &self,
16690        buffer: &Entity<Buffer>,
16691        position: text::Anchor,
16692        new_name: String,
16693        cx: &mut App,
16694    ) -> Option<Task<Result<ProjectTransaction>>>;
16695}
16696
16697pub trait CompletionProvider {
16698    fn completions(
16699        &self,
16700        buffer: &Entity<Buffer>,
16701        buffer_position: text::Anchor,
16702        trigger: CompletionContext,
16703        window: &mut Window,
16704        cx: &mut Context<Editor>,
16705    ) -> Task<Result<Vec<Completion>>>;
16706
16707    fn resolve_completions(
16708        &self,
16709        buffer: Entity<Buffer>,
16710        completion_indices: Vec<usize>,
16711        completions: Rc<RefCell<Box<[Completion]>>>,
16712        cx: &mut Context<Editor>,
16713    ) -> Task<Result<bool>>;
16714
16715    fn apply_additional_edits_for_completion(
16716        &self,
16717        _buffer: Entity<Buffer>,
16718        _completions: Rc<RefCell<Box<[Completion]>>>,
16719        _completion_index: usize,
16720        _push_to_history: bool,
16721        _cx: &mut Context<Editor>,
16722    ) -> Task<Result<Option<language::Transaction>>> {
16723        Task::ready(Ok(None))
16724    }
16725
16726    fn is_completion_trigger(
16727        &self,
16728        buffer: &Entity<Buffer>,
16729        position: language::Anchor,
16730        text: &str,
16731        trigger_in_words: bool,
16732        cx: &mut Context<Editor>,
16733    ) -> bool;
16734
16735    fn sort_completions(&self) -> bool {
16736        true
16737    }
16738}
16739
16740pub trait CodeActionProvider {
16741    fn id(&self) -> Arc<str>;
16742
16743    fn code_actions(
16744        &self,
16745        buffer: &Entity<Buffer>,
16746        range: Range<text::Anchor>,
16747        window: &mut Window,
16748        cx: &mut App,
16749    ) -> Task<Result<Vec<CodeAction>>>;
16750
16751    fn apply_code_action(
16752        &self,
16753        buffer_handle: Entity<Buffer>,
16754        action: CodeAction,
16755        excerpt_id: ExcerptId,
16756        push_to_history: bool,
16757        window: &mut Window,
16758        cx: &mut App,
16759    ) -> Task<Result<ProjectTransaction>>;
16760}
16761
16762impl CodeActionProvider for Entity<Project> {
16763    fn id(&self) -> Arc<str> {
16764        "project".into()
16765    }
16766
16767    fn code_actions(
16768        &self,
16769        buffer: &Entity<Buffer>,
16770        range: Range<text::Anchor>,
16771        _window: &mut Window,
16772        cx: &mut App,
16773    ) -> Task<Result<Vec<CodeAction>>> {
16774        self.update(cx, |project, cx| {
16775            project.code_actions(buffer, range, None, cx)
16776        })
16777    }
16778
16779    fn apply_code_action(
16780        &self,
16781        buffer_handle: Entity<Buffer>,
16782        action: CodeAction,
16783        _excerpt_id: ExcerptId,
16784        push_to_history: bool,
16785        _window: &mut Window,
16786        cx: &mut App,
16787    ) -> Task<Result<ProjectTransaction>> {
16788        self.update(cx, |project, cx| {
16789            project.apply_code_action(buffer_handle, action, push_to_history, cx)
16790        })
16791    }
16792}
16793
16794fn snippet_completions(
16795    project: &Project,
16796    buffer: &Entity<Buffer>,
16797    buffer_position: text::Anchor,
16798    cx: &mut App,
16799) -> Task<Result<Vec<Completion>>> {
16800    let language = buffer.read(cx).language_at(buffer_position);
16801    let language_name = language.as_ref().map(|language| language.lsp_id());
16802    let snippet_store = project.snippets().read(cx);
16803    let snippets = snippet_store.snippets_for(language_name, cx);
16804
16805    if snippets.is_empty() {
16806        return Task::ready(Ok(vec![]));
16807    }
16808    let snapshot = buffer.read(cx).text_snapshot();
16809    let chars: String = snapshot
16810        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16811        .collect();
16812
16813    let scope = language.map(|language| language.default_scope());
16814    let executor = cx.background_executor().clone();
16815
16816    cx.background_spawn(async move {
16817        let classifier = CharClassifier::new(scope).for_completion(true);
16818        let mut last_word = chars
16819            .chars()
16820            .take_while(|c| classifier.is_word(*c))
16821            .collect::<String>();
16822        last_word = last_word.chars().rev().collect();
16823
16824        if last_word.is_empty() {
16825            return Ok(vec![]);
16826        }
16827
16828        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16829        let to_lsp = |point: &text::Anchor| {
16830            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16831            point_to_lsp(end)
16832        };
16833        let lsp_end = to_lsp(&buffer_position);
16834
16835        let candidates = snippets
16836            .iter()
16837            .enumerate()
16838            .flat_map(|(ix, snippet)| {
16839                snippet
16840                    .prefix
16841                    .iter()
16842                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16843            })
16844            .collect::<Vec<StringMatchCandidate>>();
16845
16846        let mut matches = fuzzy::match_strings(
16847            &candidates,
16848            &last_word,
16849            last_word.chars().any(|c| c.is_uppercase()),
16850            100,
16851            &Default::default(),
16852            executor,
16853        )
16854        .await;
16855
16856        // Remove all candidates where the query's start does not match the start of any word in the candidate
16857        if let Some(query_start) = last_word.chars().next() {
16858            matches.retain(|string_match| {
16859                split_words(&string_match.string).any(|word| {
16860                    // Check that the first codepoint of the word as lowercase matches the first
16861                    // codepoint of the query as lowercase
16862                    word.chars()
16863                        .flat_map(|codepoint| codepoint.to_lowercase())
16864                        .zip(query_start.to_lowercase())
16865                        .all(|(word_cp, query_cp)| word_cp == query_cp)
16866                })
16867            });
16868        }
16869
16870        let matched_strings = matches
16871            .into_iter()
16872            .map(|m| m.string)
16873            .collect::<HashSet<_>>();
16874
16875        let result: Vec<Completion> = snippets
16876            .into_iter()
16877            .filter_map(|snippet| {
16878                let matching_prefix = snippet
16879                    .prefix
16880                    .iter()
16881                    .find(|prefix| matched_strings.contains(*prefix))?;
16882                let start = as_offset - last_word.len();
16883                let start = snapshot.anchor_before(start);
16884                let range = start..buffer_position;
16885                let lsp_start = to_lsp(&start);
16886                let lsp_range = lsp::Range {
16887                    start: lsp_start,
16888                    end: lsp_end,
16889                };
16890                Some(Completion {
16891                    old_range: range,
16892                    new_text: snippet.body.clone(),
16893                    resolved: false,
16894                    label: CodeLabel {
16895                        text: matching_prefix.clone(),
16896                        runs: vec![],
16897                        filter_range: 0..matching_prefix.len(),
16898                    },
16899                    server_id: LanguageServerId(usize::MAX),
16900                    documentation: snippet
16901                        .description
16902                        .clone()
16903                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
16904                    lsp_completion: lsp::CompletionItem {
16905                        label: snippet.prefix.first().unwrap().clone(),
16906                        kind: Some(CompletionItemKind::SNIPPET),
16907                        label_details: snippet.description.as_ref().map(|description| {
16908                            lsp::CompletionItemLabelDetails {
16909                                detail: Some(description.clone()),
16910                                description: None,
16911                            }
16912                        }),
16913                        insert_text_format: Some(InsertTextFormat::SNIPPET),
16914                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16915                            lsp::InsertReplaceEdit {
16916                                new_text: snippet.body.clone(),
16917                                insert: lsp_range,
16918                                replace: lsp_range,
16919                            },
16920                        )),
16921                        filter_text: Some(snippet.body.clone()),
16922                        sort_text: Some(char::MAX.to_string()),
16923                        ..Default::default()
16924                    },
16925                    confirm: None,
16926                })
16927            })
16928            .collect();
16929
16930        Ok(result)
16931    })
16932}
16933
16934impl CompletionProvider for Entity<Project> {
16935    fn completions(
16936        &self,
16937        buffer: &Entity<Buffer>,
16938        buffer_position: text::Anchor,
16939        options: CompletionContext,
16940        _window: &mut Window,
16941        cx: &mut Context<Editor>,
16942    ) -> Task<Result<Vec<Completion>>> {
16943        self.update(cx, |project, cx| {
16944            let snippets = snippet_completions(project, buffer, buffer_position, cx);
16945            let project_completions = project.completions(buffer, buffer_position, options, cx);
16946            cx.background_spawn(async move {
16947                let mut completions = project_completions.await?;
16948                let snippets_completions = snippets.await?;
16949                completions.extend(snippets_completions);
16950                Ok(completions)
16951            })
16952        })
16953    }
16954
16955    fn resolve_completions(
16956        &self,
16957        buffer: Entity<Buffer>,
16958        completion_indices: Vec<usize>,
16959        completions: Rc<RefCell<Box<[Completion]>>>,
16960        cx: &mut Context<Editor>,
16961    ) -> Task<Result<bool>> {
16962        self.update(cx, |project, cx| {
16963            project.lsp_store().update(cx, |lsp_store, cx| {
16964                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16965            })
16966        })
16967    }
16968
16969    fn apply_additional_edits_for_completion(
16970        &self,
16971        buffer: Entity<Buffer>,
16972        completions: Rc<RefCell<Box<[Completion]>>>,
16973        completion_index: usize,
16974        push_to_history: bool,
16975        cx: &mut Context<Editor>,
16976    ) -> Task<Result<Option<language::Transaction>>> {
16977        self.update(cx, |project, cx| {
16978            project.lsp_store().update(cx, |lsp_store, cx| {
16979                lsp_store.apply_additional_edits_for_completion(
16980                    buffer,
16981                    completions,
16982                    completion_index,
16983                    push_to_history,
16984                    cx,
16985                )
16986            })
16987        })
16988    }
16989
16990    fn is_completion_trigger(
16991        &self,
16992        buffer: &Entity<Buffer>,
16993        position: language::Anchor,
16994        text: &str,
16995        trigger_in_words: bool,
16996        cx: &mut Context<Editor>,
16997    ) -> bool {
16998        let mut chars = text.chars();
16999        let char = if let Some(char) = chars.next() {
17000            char
17001        } else {
17002            return false;
17003        };
17004        if chars.next().is_some() {
17005            return false;
17006        }
17007
17008        let buffer = buffer.read(cx);
17009        let snapshot = buffer.snapshot();
17010        if !snapshot.settings_at(position, cx).show_completions_on_input {
17011            return false;
17012        }
17013        let classifier = snapshot.char_classifier_at(position).for_completion(true);
17014        if trigger_in_words && classifier.is_word(char) {
17015            return true;
17016        }
17017
17018        buffer.completion_triggers().contains(text)
17019    }
17020}
17021
17022impl SemanticsProvider for Entity<Project> {
17023    fn hover(
17024        &self,
17025        buffer: &Entity<Buffer>,
17026        position: text::Anchor,
17027        cx: &mut App,
17028    ) -> Option<Task<Vec<project::Hover>>> {
17029        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
17030    }
17031
17032    fn document_highlights(
17033        &self,
17034        buffer: &Entity<Buffer>,
17035        position: text::Anchor,
17036        cx: &mut App,
17037    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
17038        Some(self.update(cx, |project, cx| {
17039            project.document_highlights(buffer, position, cx)
17040        }))
17041    }
17042
17043    fn definitions(
17044        &self,
17045        buffer: &Entity<Buffer>,
17046        position: text::Anchor,
17047        kind: GotoDefinitionKind,
17048        cx: &mut App,
17049    ) -> Option<Task<Result<Vec<LocationLink>>>> {
17050        Some(self.update(cx, |project, cx| match kind {
17051            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
17052            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
17053            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
17054            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
17055        }))
17056    }
17057
17058    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
17059        // TODO: make this work for remote projects
17060        self.update(cx, |this, cx| {
17061            buffer.update(cx, |buffer, cx| {
17062                this.any_language_server_supports_inlay_hints(buffer, cx)
17063            })
17064        })
17065    }
17066
17067    fn inlay_hints(
17068        &self,
17069        buffer_handle: Entity<Buffer>,
17070        range: Range<text::Anchor>,
17071        cx: &mut App,
17072    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
17073        Some(self.update(cx, |project, cx| {
17074            project.inlay_hints(buffer_handle, range, cx)
17075        }))
17076    }
17077
17078    fn resolve_inlay_hint(
17079        &self,
17080        hint: InlayHint,
17081        buffer_handle: Entity<Buffer>,
17082        server_id: LanguageServerId,
17083        cx: &mut App,
17084    ) -> Option<Task<anyhow::Result<InlayHint>>> {
17085        Some(self.update(cx, |project, cx| {
17086            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
17087        }))
17088    }
17089
17090    fn range_for_rename(
17091        &self,
17092        buffer: &Entity<Buffer>,
17093        position: text::Anchor,
17094        cx: &mut App,
17095    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17096        Some(self.update(cx, |project, cx| {
17097            let buffer = buffer.clone();
17098            let task = project.prepare_rename(buffer.clone(), position, cx);
17099            cx.spawn(|_, mut cx| async move {
17100                Ok(match task.await? {
17101                    PrepareRenameResponse::Success(range) => Some(range),
17102                    PrepareRenameResponse::InvalidPosition => None,
17103                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17104                        // Fallback on using TreeSitter info to determine identifier range
17105                        buffer.update(&mut cx, |buffer, _| {
17106                            let snapshot = buffer.snapshot();
17107                            let (range, kind) = snapshot.surrounding_word(position);
17108                            if kind != Some(CharKind::Word) {
17109                                return None;
17110                            }
17111                            Some(
17112                                snapshot.anchor_before(range.start)
17113                                    ..snapshot.anchor_after(range.end),
17114                            )
17115                        })?
17116                    }
17117                })
17118            })
17119        }))
17120    }
17121
17122    fn perform_rename(
17123        &self,
17124        buffer: &Entity<Buffer>,
17125        position: text::Anchor,
17126        new_name: String,
17127        cx: &mut App,
17128    ) -> Option<Task<Result<ProjectTransaction>>> {
17129        Some(self.update(cx, |project, cx| {
17130            project.perform_rename(buffer.clone(), position, new_name, cx)
17131        }))
17132    }
17133}
17134
17135fn inlay_hint_settings(
17136    location: Anchor,
17137    snapshot: &MultiBufferSnapshot,
17138    cx: &mut Context<Editor>,
17139) -> InlayHintSettings {
17140    let file = snapshot.file_at(location);
17141    let language = snapshot.language_at(location).map(|l| l.name());
17142    language_settings(language, file, cx).inlay_hints
17143}
17144
17145fn consume_contiguous_rows(
17146    contiguous_row_selections: &mut Vec<Selection<Point>>,
17147    selection: &Selection<Point>,
17148    display_map: &DisplaySnapshot,
17149    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17150) -> (MultiBufferRow, MultiBufferRow) {
17151    contiguous_row_selections.push(selection.clone());
17152    let start_row = MultiBufferRow(selection.start.row);
17153    let mut end_row = ending_row(selection, display_map);
17154
17155    while let Some(next_selection) = selections.peek() {
17156        if next_selection.start.row <= end_row.0 {
17157            end_row = ending_row(next_selection, display_map);
17158            contiguous_row_selections.push(selections.next().unwrap().clone());
17159        } else {
17160            break;
17161        }
17162    }
17163    (start_row, end_row)
17164}
17165
17166fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17167    if next_selection.end.column > 0 || next_selection.is_empty() {
17168        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17169    } else {
17170        MultiBufferRow(next_selection.end.row)
17171    }
17172}
17173
17174impl EditorSnapshot {
17175    pub fn remote_selections_in_range<'a>(
17176        &'a self,
17177        range: &'a Range<Anchor>,
17178        collaboration_hub: &dyn CollaborationHub,
17179        cx: &'a App,
17180    ) -> impl 'a + Iterator<Item = RemoteSelection> {
17181        let participant_names = collaboration_hub.user_names(cx);
17182        let participant_indices = collaboration_hub.user_participant_indices(cx);
17183        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17184        let collaborators_by_replica_id = collaborators_by_peer_id
17185            .iter()
17186            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17187            .collect::<HashMap<_, _>>();
17188        self.buffer_snapshot
17189            .selections_in_range(range, false)
17190            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17191                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17192                let participant_index = participant_indices.get(&collaborator.user_id).copied();
17193                let user_name = participant_names.get(&collaborator.user_id).cloned();
17194                Some(RemoteSelection {
17195                    replica_id,
17196                    selection,
17197                    cursor_shape,
17198                    line_mode,
17199                    participant_index,
17200                    peer_id: collaborator.peer_id,
17201                    user_name,
17202                })
17203            })
17204    }
17205
17206    pub fn hunks_for_ranges(
17207        &self,
17208        ranges: impl IntoIterator<Item = Range<Point>>,
17209    ) -> Vec<MultiBufferDiffHunk> {
17210        let mut hunks = Vec::new();
17211        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17212            HashMap::default();
17213        for query_range in ranges {
17214            let query_rows =
17215                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17216            for hunk in self.buffer_snapshot.diff_hunks_in_range(
17217                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17218            ) {
17219                // Include deleted hunks that are adjacent to the query range, because
17220                // otherwise they would be missed.
17221                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
17222                if hunk.status().is_deleted() {
17223                    intersects_range |= hunk.row_range.start == query_rows.end;
17224                    intersects_range |= hunk.row_range.end == query_rows.start;
17225                }
17226                if intersects_range {
17227                    if !processed_buffer_rows
17228                        .entry(hunk.buffer_id)
17229                        .or_default()
17230                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17231                    {
17232                        continue;
17233                    }
17234                    hunks.push(hunk);
17235                }
17236            }
17237        }
17238
17239        hunks
17240    }
17241
17242    fn display_diff_hunks_for_rows<'a>(
17243        &'a self,
17244        display_rows: Range<DisplayRow>,
17245        folded_buffers: &'a HashSet<BufferId>,
17246    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17247        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17248        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17249
17250        self.buffer_snapshot
17251            .diff_hunks_in_range(buffer_start..buffer_end)
17252            .filter_map(|hunk| {
17253                if folded_buffers.contains(&hunk.buffer_id) {
17254                    return None;
17255                }
17256
17257                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17258                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17259
17260                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17261                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17262
17263                let display_hunk = if hunk_display_start.column() != 0 {
17264                    DisplayDiffHunk::Folded {
17265                        display_row: hunk_display_start.row(),
17266                    }
17267                } else {
17268                    let mut end_row = hunk_display_end.row();
17269                    if hunk_display_end.column() > 0 {
17270                        end_row.0 += 1;
17271                    }
17272                    DisplayDiffHunk::Unfolded {
17273                        status: hunk.status(),
17274                        diff_base_byte_range: hunk.diff_base_byte_range,
17275                        display_row_range: hunk_display_start.row()..end_row,
17276                        multi_buffer_range: Anchor::range_in_buffer(
17277                            hunk.excerpt_id,
17278                            hunk.buffer_id,
17279                            hunk.buffer_range,
17280                        ),
17281                    }
17282                };
17283
17284                Some(display_hunk)
17285            })
17286    }
17287
17288    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17289        self.display_snapshot.buffer_snapshot.language_at(position)
17290    }
17291
17292    pub fn is_focused(&self) -> bool {
17293        self.is_focused
17294    }
17295
17296    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17297        self.placeholder_text.as_ref()
17298    }
17299
17300    pub fn scroll_position(&self) -> gpui::Point<f32> {
17301        self.scroll_anchor.scroll_position(&self.display_snapshot)
17302    }
17303
17304    fn gutter_dimensions(
17305        &self,
17306        font_id: FontId,
17307        font_size: Pixels,
17308        max_line_number_width: Pixels,
17309        cx: &App,
17310    ) -> Option<GutterDimensions> {
17311        if !self.show_gutter {
17312            return None;
17313        }
17314
17315        let descent = cx.text_system().descent(font_id, font_size);
17316        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17317        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17318
17319        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17320            matches!(
17321                ProjectSettings::get_global(cx).git.git_gutter,
17322                Some(GitGutterSetting::TrackedFiles)
17323            )
17324        });
17325        let gutter_settings = EditorSettings::get_global(cx).gutter;
17326        let show_line_numbers = self
17327            .show_line_numbers
17328            .unwrap_or(gutter_settings.line_numbers);
17329        let line_gutter_width = if show_line_numbers {
17330            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17331            let min_width_for_number_on_gutter = em_advance * 4.0;
17332            max_line_number_width.max(min_width_for_number_on_gutter)
17333        } else {
17334            0.0.into()
17335        };
17336
17337        let show_code_actions = self
17338            .show_code_actions
17339            .unwrap_or(gutter_settings.code_actions);
17340
17341        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17342
17343        let git_blame_entries_width =
17344            self.git_blame_gutter_max_author_length
17345                .map(|max_author_length| {
17346                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17347
17348                    /// The number of characters to dedicate to gaps and margins.
17349                    const SPACING_WIDTH: usize = 4;
17350
17351                    let max_char_count = max_author_length
17352                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17353                        + ::git::SHORT_SHA_LENGTH
17354                        + MAX_RELATIVE_TIMESTAMP.len()
17355                        + SPACING_WIDTH;
17356
17357                    em_advance * max_char_count
17358                });
17359
17360        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17361        left_padding += if show_code_actions || show_runnables {
17362            em_width * 3.0
17363        } else if show_git_gutter && show_line_numbers {
17364            em_width * 2.0
17365        } else if show_git_gutter || show_line_numbers {
17366            em_width
17367        } else {
17368            px(0.)
17369        };
17370
17371        let right_padding = if gutter_settings.folds && show_line_numbers {
17372            em_width * 4.0
17373        } else if gutter_settings.folds {
17374            em_width * 3.0
17375        } else if show_line_numbers {
17376            em_width
17377        } else {
17378            px(0.)
17379        };
17380
17381        Some(GutterDimensions {
17382            left_padding,
17383            right_padding,
17384            width: line_gutter_width + left_padding + right_padding,
17385            margin: -descent,
17386            git_blame_entries_width,
17387        })
17388    }
17389
17390    pub fn render_crease_toggle(
17391        &self,
17392        buffer_row: MultiBufferRow,
17393        row_contains_cursor: bool,
17394        editor: Entity<Editor>,
17395        window: &mut Window,
17396        cx: &mut App,
17397    ) -> Option<AnyElement> {
17398        let folded = self.is_line_folded(buffer_row);
17399        let mut is_foldable = false;
17400
17401        if let Some(crease) = self
17402            .crease_snapshot
17403            .query_row(buffer_row, &self.buffer_snapshot)
17404        {
17405            is_foldable = true;
17406            match crease {
17407                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17408                    if let Some(render_toggle) = render_toggle {
17409                        let toggle_callback =
17410                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17411                                if folded {
17412                                    editor.update(cx, |editor, cx| {
17413                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17414                                    });
17415                                } else {
17416                                    editor.update(cx, |editor, cx| {
17417                                        editor.unfold_at(
17418                                            &crate::UnfoldAt { buffer_row },
17419                                            window,
17420                                            cx,
17421                                        )
17422                                    });
17423                                }
17424                            });
17425                        return Some((render_toggle)(
17426                            buffer_row,
17427                            folded,
17428                            toggle_callback,
17429                            window,
17430                            cx,
17431                        ));
17432                    }
17433                }
17434            }
17435        }
17436
17437        is_foldable |= self.starts_indent(buffer_row);
17438
17439        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17440            Some(
17441                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17442                    .toggle_state(folded)
17443                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17444                        if folded {
17445                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17446                        } else {
17447                            this.fold_at(&FoldAt { buffer_row }, window, cx);
17448                        }
17449                    }))
17450                    .into_any_element(),
17451            )
17452        } else {
17453            None
17454        }
17455    }
17456
17457    pub fn render_crease_trailer(
17458        &self,
17459        buffer_row: MultiBufferRow,
17460        window: &mut Window,
17461        cx: &mut App,
17462    ) -> Option<AnyElement> {
17463        let folded = self.is_line_folded(buffer_row);
17464        if let Crease::Inline { render_trailer, .. } = self
17465            .crease_snapshot
17466            .query_row(buffer_row, &self.buffer_snapshot)?
17467        {
17468            let render_trailer = render_trailer.as_ref()?;
17469            Some(render_trailer(buffer_row, folded, window, cx))
17470        } else {
17471            None
17472        }
17473    }
17474}
17475
17476impl Deref for EditorSnapshot {
17477    type Target = DisplaySnapshot;
17478
17479    fn deref(&self) -> &Self::Target {
17480        &self.display_snapshot
17481    }
17482}
17483
17484#[derive(Clone, Debug, PartialEq, Eq)]
17485pub enum EditorEvent {
17486    InputIgnored {
17487        text: Arc<str>,
17488    },
17489    InputHandled {
17490        utf16_range_to_replace: Option<Range<isize>>,
17491        text: Arc<str>,
17492    },
17493    ExcerptsAdded {
17494        buffer: Entity<Buffer>,
17495        predecessor: ExcerptId,
17496        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17497    },
17498    ExcerptsRemoved {
17499        ids: Vec<ExcerptId>,
17500    },
17501    BufferFoldToggled {
17502        ids: Vec<ExcerptId>,
17503        folded: bool,
17504    },
17505    ExcerptsEdited {
17506        ids: Vec<ExcerptId>,
17507    },
17508    ExcerptsExpanded {
17509        ids: Vec<ExcerptId>,
17510    },
17511    BufferEdited,
17512    Edited {
17513        transaction_id: clock::Lamport,
17514    },
17515    Reparsed(BufferId),
17516    Focused,
17517    FocusedIn,
17518    Blurred,
17519    DirtyChanged,
17520    Saved,
17521    TitleChanged,
17522    DiffBaseChanged,
17523    SelectionsChanged {
17524        local: bool,
17525    },
17526    ScrollPositionChanged {
17527        local: bool,
17528        autoscroll: bool,
17529    },
17530    Closed,
17531    TransactionUndone {
17532        transaction_id: clock::Lamport,
17533    },
17534    TransactionBegun {
17535        transaction_id: clock::Lamport,
17536    },
17537    Reloaded,
17538    CursorShapeChanged,
17539}
17540
17541impl EventEmitter<EditorEvent> for Editor {}
17542
17543impl Focusable for Editor {
17544    fn focus_handle(&self, _cx: &App) -> FocusHandle {
17545        self.focus_handle.clone()
17546    }
17547}
17548
17549impl Render for Editor {
17550    fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17551        let settings = ThemeSettings::get_global(cx);
17552
17553        let mut text_style = match self.mode {
17554            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17555                color: cx.theme().colors().editor_foreground,
17556                font_family: settings.ui_font.family.clone(),
17557                font_features: settings.ui_font.features.clone(),
17558                font_fallbacks: settings.ui_font.fallbacks.clone(),
17559                font_size: rems(0.875).into(),
17560                font_weight: settings.ui_font.weight,
17561                line_height: relative(settings.buffer_line_height.value()),
17562                ..Default::default()
17563            },
17564            EditorMode::Full => TextStyle {
17565                color: cx.theme().colors().editor_foreground,
17566                font_family: settings.buffer_font.family.clone(),
17567                font_features: settings.buffer_font.features.clone(),
17568                font_fallbacks: settings.buffer_font.fallbacks.clone(),
17569                font_size: settings.buffer_font_size(cx).into(),
17570                font_weight: settings.buffer_font.weight,
17571                line_height: relative(settings.buffer_line_height.value()),
17572                ..Default::default()
17573            },
17574        };
17575        if let Some(text_style_refinement) = &self.text_style_refinement {
17576            text_style.refine(text_style_refinement)
17577        }
17578
17579        let background = match self.mode {
17580            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17581            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17582            EditorMode::Full => cx.theme().colors().editor_background,
17583        };
17584
17585        EditorElement::new(
17586            &cx.entity(),
17587            EditorStyle {
17588                background,
17589                local_player: cx.theme().players().local(),
17590                text: text_style,
17591                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17592                syntax: cx.theme().syntax().clone(),
17593                status: cx.theme().status().clone(),
17594                inlay_hints_style: make_inlay_hints_style(cx),
17595                inline_completion_styles: make_suggestion_styles(cx),
17596                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17597            },
17598        )
17599    }
17600}
17601
17602impl EntityInputHandler for Editor {
17603    fn text_for_range(
17604        &mut self,
17605        range_utf16: Range<usize>,
17606        adjusted_range: &mut Option<Range<usize>>,
17607        _: &mut Window,
17608        cx: &mut Context<Self>,
17609    ) -> Option<String> {
17610        let snapshot = self.buffer.read(cx).read(cx);
17611        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17612        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17613        if (start.0..end.0) != range_utf16 {
17614            adjusted_range.replace(start.0..end.0);
17615        }
17616        Some(snapshot.text_for_range(start..end).collect())
17617    }
17618
17619    fn selected_text_range(
17620        &mut self,
17621        ignore_disabled_input: bool,
17622        _: &mut Window,
17623        cx: &mut Context<Self>,
17624    ) -> Option<UTF16Selection> {
17625        // Prevent the IME menu from appearing when holding down an alphabetic key
17626        // while input is disabled.
17627        if !ignore_disabled_input && !self.input_enabled {
17628            return None;
17629        }
17630
17631        let selection = self.selections.newest::<OffsetUtf16>(cx);
17632        let range = selection.range();
17633
17634        Some(UTF16Selection {
17635            range: range.start.0..range.end.0,
17636            reversed: selection.reversed,
17637        })
17638    }
17639
17640    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17641        let snapshot = self.buffer.read(cx).read(cx);
17642        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17643        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17644    }
17645
17646    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17647        self.clear_highlights::<InputComposition>(cx);
17648        self.ime_transaction.take();
17649    }
17650
17651    fn replace_text_in_range(
17652        &mut self,
17653        range_utf16: Option<Range<usize>>,
17654        text: &str,
17655        window: &mut Window,
17656        cx: &mut Context<Self>,
17657    ) {
17658        if !self.input_enabled {
17659            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17660            return;
17661        }
17662
17663        self.transact(window, cx, |this, window, cx| {
17664            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17665                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17666                Some(this.selection_replacement_ranges(range_utf16, cx))
17667            } else {
17668                this.marked_text_ranges(cx)
17669            };
17670
17671            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17672                let newest_selection_id = this.selections.newest_anchor().id;
17673                this.selections
17674                    .all::<OffsetUtf16>(cx)
17675                    .iter()
17676                    .zip(ranges_to_replace.iter())
17677                    .find_map(|(selection, range)| {
17678                        if selection.id == newest_selection_id {
17679                            Some(
17680                                (range.start.0 as isize - selection.head().0 as isize)
17681                                    ..(range.end.0 as isize - selection.head().0 as isize),
17682                            )
17683                        } else {
17684                            None
17685                        }
17686                    })
17687            });
17688
17689            cx.emit(EditorEvent::InputHandled {
17690                utf16_range_to_replace: range_to_replace,
17691                text: text.into(),
17692            });
17693
17694            if let Some(new_selected_ranges) = new_selected_ranges {
17695                this.change_selections(None, window, cx, |selections| {
17696                    selections.select_ranges(new_selected_ranges)
17697                });
17698                this.backspace(&Default::default(), window, cx);
17699            }
17700
17701            this.handle_input(text, window, cx);
17702        });
17703
17704        if let Some(transaction) = self.ime_transaction {
17705            self.buffer.update(cx, |buffer, cx| {
17706                buffer.group_until_transaction(transaction, cx);
17707            });
17708        }
17709
17710        self.unmark_text(window, cx);
17711    }
17712
17713    fn replace_and_mark_text_in_range(
17714        &mut self,
17715        range_utf16: Option<Range<usize>>,
17716        text: &str,
17717        new_selected_range_utf16: Option<Range<usize>>,
17718        window: &mut Window,
17719        cx: &mut Context<Self>,
17720    ) {
17721        if !self.input_enabled {
17722            return;
17723        }
17724
17725        let transaction = self.transact(window, cx, |this, window, cx| {
17726            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17727                let snapshot = this.buffer.read(cx).read(cx);
17728                if let Some(relative_range_utf16) = range_utf16.as_ref() {
17729                    for marked_range in &mut marked_ranges {
17730                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17731                        marked_range.start.0 += relative_range_utf16.start;
17732                        marked_range.start =
17733                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17734                        marked_range.end =
17735                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17736                    }
17737                }
17738                Some(marked_ranges)
17739            } else if let Some(range_utf16) = range_utf16 {
17740                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17741                Some(this.selection_replacement_ranges(range_utf16, cx))
17742            } else {
17743                None
17744            };
17745
17746            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17747                let newest_selection_id = this.selections.newest_anchor().id;
17748                this.selections
17749                    .all::<OffsetUtf16>(cx)
17750                    .iter()
17751                    .zip(ranges_to_replace.iter())
17752                    .find_map(|(selection, range)| {
17753                        if selection.id == newest_selection_id {
17754                            Some(
17755                                (range.start.0 as isize - selection.head().0 as isize)
17756                                    ..(range.end.0 as isize - selection.head().0 as isize),
17757                            )
17758                        } else {
17759                            None
17760                        }
17761                    })
17762            });
17763
17764            cx.emit(EditorEvent::InputHandled {
17765                utf16_range_to_replace: range_to_replace,
17766                text: text.into(),
17767            });
17768
17769            if let Some(ranges) = ranges_to_replace {
17770                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17771            }
17772
17773            let marked_ranges = {
17774                let snapshot = this.buffer.read(cx).read(cx);
17775                this.selections
17776                    .disjoint_anchors()
17777                    .iter()
17778                    .map(|selection| {
17779                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17780                    })
17781                    .collect::<Vec<_>>()
17782            };
17783
17784            if text.is_empty() {
17785                this.unmark_text(window, cx);
17786            } else {
17787                this.highlight_text::<InputComposition>(
17788                    marked_ranges.clone(),
17789                    HighlightStyle {
17790                        underline: Some(UnderlineStyle {
17791                            thickness: px(1.),
17792                            color: None,
17793                            wavy: false,
17794                        }),
17795                        ..Default::default()
17796                    },
17797                    cx,
17798                );
17799            }
17800
17801            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17802            let use_autoclose = this.use_autoclose;
17803            let use_auto_surround = this.use_auto_surround;
17804            this.set_use_autoclose(false);
17805            this.set_use_auto_surround(false);
17806            this.handle_input(text, window, cx);
17807            this.set_use_autoclose(use_autoclose);
17808            this.set_use_auto_surround(use_auto_surround);
17809
17810            if let Some(new_selected_range) = new_selected_range_utf16 {
17811                let snapshot = this.buffer.read(cx).read(cx);
17812                let new_selected_ranges = marked_ranges
17813                    .into_iter()
17814                    .map(|marked_range| {
17815                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17816                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17817                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17818                        snapshot.clip_offset_utf16(new_start, Bias::Left)
17819                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17820                    })
17821                    .collect::<Vec<_>>();
17822
17823                drop(snapshot);
17824                this.change_selections(None, window, cx, |selections| {
17825                    selections.select_ranges(new_selected_ranges)
17826                });
17827            }
17828        });
17829
17830        self.ime_transaction = self.ime_transaction.or(transaction);
17831        if let Some(transaction) = self.ime_transaction {
17832            self.buffer.update(cx, |buffer, cx| {
17833                buffer.group_until_transaction(transaction, cx);
17834            });
17835        }
17836
17837        if self.text_highlights::<InputComposition>(cx).is_none() {
17838            self.ime_transaction.take();
17839        }
17840    }
17841
17842    fn bounds_for_range(
17843        &mut self,
17844        range_utf16: Range<usize>,
17845        element_bounds: gpui::Bounds<Pixels>,
17846        window: &mut Window,
17847        cx: &mut Context<Self>,
17848    ) -> Option<gpui::Bounds<Pixels>> {
17849        let text_layout_details = self.text_layout_details(window);
17850        let gpui::Size {
17851            width: em_width,
17852            height: line_height,
17853        } = self.character_size(window);
17854
17855        let snapshot = self.snapshot(window, cx);
17856        let scroll_position = snapshot.scroll_position();
17857        let scroll_left = scroll_position.x * em_width;
17858
17859        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17860        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17861            + self.gutter_dimensions.width
17862            + self.gutter_dimensions.margin;
17863        let y = line_height * (start.row().as_f32() - scroll_position.y);
17864
17865        Some(Bounds {
17866            origin: element_bounds.origin + point(x, y),
17867            size: size(em_width, line_height),
17868        })
17869    }
17870
17871    fn character_index_for_point(
17872        &mut self,
17873        point: gpui::Point<Pixels>,
17874        _window: &mut Window,
17875        _cx: &mut Context<Self>,
17876    ) -> Option<usize> {
17877        let position_map = self.last_position_map.as_ref()?;
17878        if !position_map.text_hitbox.contains(&point) {
17879            return None;
17880        }
17881        let display_point = position_map.point_for_position(point).previous_valid;
17882        let anchor = position_map
17883            .snapshot
17884            .display_point_to_anchor(display_point, Bias::Left);
17885        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17886        Some(utf16_offset.0)
17887    }
17888}
17889
17890trait SelectionExt {
17891    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17892    fn spanned_rows(
17893        &self,
17894        include_end_if_at_line_start: bool,
17895        map: &DisplaySnapshot,
17896    ) -> Range<MultiBufferRow>;
17897}
17898
17899impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17900    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17901        let start = self
17902            .start
17903            .to_point(&map.buffer_snapshot)
17904            .to_display_point(map);
17905        let end = self
17906            .end
17907            .to_point(&map.buffer_snapshot)
17908            .to_display_point(map);
17909        if self.reversed {
17910            end..start
17911        } else {
17912            start..end
17913        }
17914    }
17915
17916    fn spanned_rows(
17917        &self,
17918        include_end_if_at_line_start: bool,
17919        map: &DisplaySnapshot,
17920    ) -> Range<MultiBufferRow> {
17921        let start = self.start.to_point(&map.buffer_snapshot);
17922        let mut end = self.end.to_point(&map.buffer_snapshot);
17923        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17924            end.row -= 1;
17925        }
17926
17927        let buffer_start = map.prev_line_boundary(start).0;
17928        let buffer_end = map.next_line_boundary(end).0;
17929        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17930    }
17931}
17932
17933impl<T: InvalidationRegion> InvalidationStack<T> {
17934    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17935    where
17936        S: Clone + ToOffset,
17937    {
17938        while let Some(region) = self.last() {
17939            let all_selections_inside_invalidation_ranges =
17940                if selections.len() == region.ranges().len() {
17941                    selections
17942                        .iter()
17943                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17944                        .all(|(selection, invalidation_range)| {
17945                            let head = selection.head().to_offset(buffer);
17946                            invalidation_range.start <= head && invalidation_range.end >= head
17947                        })
17948                } else {
17949                    false
17950                };
17951
17952            if all_selections_inside_invalidation_ranges {
17953                break;
17954            } else {
17955                self.pop();
17956            }
17957        }
17958    }
17959}
17960
17961impl<T> Default for InvalidationStack<T> {
17962    fn default() -> Self {
17963        Self(Default::default())
17964    }
17965}
17966
17967impl<T> Deref for InvalidationStack<T> {
17968    type Target = Vec<T>;
17969
17970    fn deref(&self) -> &Self::Target {
17971        &self.0
17972    }
17973}
17974
17975impl<T> DerefMut for InvalidationStack<T> {
17976    fn deref_mut(&mut self) -> &mut Self::Target {
17977        &mut self.0
17978    }
17979}
17980
17981impl InvalidationRegion for SnippetState {
17982    fn ranges(&self) -> &[Range<Anchor>] {
17983        &self.ranges[self.active_index]
17984    }
17985}
17986
17987pub fn diagnostic_block_renderer(
17988    diagnostic: Diagnostic,
17989    max_message_rows: Option<u8>,
17990    allow_closing: bool,
17991) -> RenderBlock {
17992    let (text_without_backticks, code_ranges) =
17993        highlight_diagnostic_message(&diagnostic, max_message_rows);
17994
17995    Arc::new(move |cx: &mut BlockContext| {
17996        let group_id: SharedString = cx.block_id.to_string().into();
17997
17998        let mut text_style = cx.window.text_style().clone();
17999        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
18000        let theme_settings = ThemeSettings::get_global(cx);
18001        text_style.font_family = theme_settings.buffer_font.family.clone();
18002        text_style.font_style = theme_settings.buffer_font.style;
18003        text_style.font_features = theme_settings.buffer_font.features.clone();
18004        text_style.font_weight = theme_settings.buffer_font.weight;
18005
18006        let multi_line_diagnostic = diagnostic.message.contains('\n');
18007
18008        let buttons = |diagnostic: &Diagnostic| {
18009            if multi_line_diagnostic {
18010                v_flex()
18011            } else {
18012                h_flex()
18013            }
18014            .when(allow_closing, |div| {
18015                div.children(diagnostic.is_primary.then(|| {
18016                    IconButton::new("close-block", IconName::XCircle)
18017                        .icon_color(Color::Muted)
18018                        .size(ButtonSize::Compact)
18019                        .style(ButtonStyle::Transparent)
18020                        .visible_on_hover(group_id.clone())
18021                        .on_click(move |_click, window, cx| {
18022                            window.dispatch_action(Box::new(Cancel), cx)
18023                        })
18024                        .tooltip(|window, cx| {
18025                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
18026                        })
18027                }))
18028            })
18029            .child(
18030                IconButton::new("copy-block", IconName::Copy)
18031                    .icon_color(Color::Muted)
18032                    .size(ButtonSize::Compact)
18033                    .style(ButtonStyle::Transparent)
18034                    .visible_on_hover(group_id.clone())
18035                    .on_click({
18036                        let message = diagnostic.message.clone();
18037                        move |_click, _, cx| {
18038                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
18039                        }
18040                    })
18041                    .tooltip(Tooltip::text("Copy diagnostic message")),
18042            )
18043        };
18044
18045        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
18046            AvailableSpace::min_size(),
18047            cx.window,
18048            cx.app,
18049        );
18050
18051        h_flex()
18052            .id(cx.block_id)
18053            .group(group_id.clone())
18054            .relative()
18055            .size_full()
18056            .block_mouse_down()
18057            .pl(cx.gutter_dimensions.width)
18058            .w(cx.max_width - cx.gutter_dimensions.full_width())
18059            .child(
18060                div()
18061                    .flex()
18062                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
18063                    .flex_shrink(),
18064            )
18065            .child(buttons(&diagnostic))
18066            .child(div().flex().flex_shrink_0().child(
18067                StyledText::new(text_without_backticks.clone()).with_default_highlights(
18068                    &text_style,
18069                    code_ranges.iter().map(|range| {
18070                        (
18071                            range.clone(),
18072                            HighlightStyle {
18073                                font_weight: Some(FontWeight::BOLD),
18074                                ..Default::default()
18075                            },
18076                        )
18077                    }),
18078                ),
18079            ))
18080            .into_any_element()
18081    })
18082}
18083
18084fn inline_completion_edit_text(
18085    current_snapshot: &BufferSnapshot,
18086    edits: &[(Range<Anchor>, String)],
18087    edit_preview: &EditPreview,
18088    include_deletions: bool,
18089    cx: &App,
18090) -> HighlightedText {
18091    let edits = edits
18092        .iter()
18093        .map(|(anchor, text)| {
18094            (
18095                anchor.start.text_anchor..anchor.end.text_anchor,
18096                text.clone(),
18097            )
18098        })
18099        .collect::<Vec<_>>();
18100
18101    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18102}
18103
18104pub fn highlight_diagnostic_message(
18105    diagnostic: &Diagnostic,
18106    mut max_message_rows: Option<u8>,
18107) -> (SharedString, Vec<Range<usize>>) {
18108    let mut text_without_backticks = String::new();
18109    let mut code_ranges = Vec::new();
18110
18111    if let Some(source) = &diagnostic.source {
18112        text_without_backticks.push_str(source);
18113        code_ranges.push(0..source.len());
18114        text_without_backticks.push_str(": ");
18115    }
18116
18117    let mut prev_offset = 0;
18118    let mut in_code_block = false;
18119    let has_row_limit = max_message_rows.is_some();
18120    let mut newline_indices = diagnostic
18121        .message
18122        .match_indices('\n')
18123        .filter(|_| has_row_limit)
18124        .map(|(ix, _)| ix)
18125        .fuse()
18126        .peekable();
18127
18128    for (quote_ix, _) in diagnostic
18129        .message
18130        .match_indices('`')
18131        .chain([(diagnostic.message.len(), "")])
18132    {
18133        let mut first_newline_ix = None;
18134        let mut last_newline_ix = None;
18135        while let Some(newline_ix) = newline_indices.peek() {
18136            if *newline_ix < quote_ix {
18137                if first_newline_ix.is_none() {
18138                    first_newline_ix = Some(*newline_ix);
18139                }
18140                last_newline_ix = Some(*newline_ix);
18141
18142                if let Some(rows_left) = &mut max_message_rows {
18143                    if *rows_left == 0 {
18144                        break;
18145                    } else {
18146                        *rows_left -= 1;
18147                    }
18148                }
18149                let _ = newline_indices.next();
18150            } else {
18151                break;
18152            }
18153        }
18154        let prev_len = text_without_backticks.len();
18155        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18156        text_without_backticks.push_str(new_text);
18157        if in_code_block {
18158            code_ranges.push(prev_len..text_without_backticks.len());
18159        }
18160        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18161        in_code_block = !in_code_block;
18162        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18163            text_without_backticks.push_str("...");
18164            break;
18165        }
18166    }
18167
18168    (text_without_backticks.into(), code_ranges)
18169}
18170
18171fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18172    match severity {
18173        DiagnosticSeverity::ERROR => colors.error,
18174        DiagnosticSeverity::WARNING => colors.warning,
18175        DiagnosticSeverity::INFORMATION => colors.info,
18176        DiagnosticSeverity::HINT => colors.info,
18177        _ => colors.ignored,
18178    }
18179}
18180
18181pub fn styled_runs_for_code_label<'a>(
18182    label: &'a CodeLabel,
18183    syntax_theme: &'a theme::SyntaxTheme,
18184) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18185    let fade_out = HighlightStyle {
18186        fade_out: Some(0.35),
18187        ..Default::default()
18188    };
18189
18190    let mut prev_end = label.filter_range.end;
18191    label
18192        .runs
18193        .iter()
18194        .enumerate()
18195        .flat_map(move |(ix, (range, highlight_id))| {
18196            let style = if let Some(style) = highlight_id.style(syntax_theme) {
18197                style
18198            } else {
18199                return Default::default();
18200            };
18201            let mut muted_style = style;
18202            muted_style.highlight(fade_out);
18203
18204            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18205            if range.start >= label.filter_range.end {
18206                if range.start > prev_end {
18207                    runs.push((prev_end..range.start, fade_out));
18208                }
18209                runs.push((range.clone(), muted_style));
18210            } else if range.end <= label.filter_range.end {
18211                runs.push((range.clone(), style));
18212            } else {
18213                runs.push((range.start..label.filter_range.end, style));
18214                runs.push((label.filter_range.end..range.end, muted_style));
18215            }
18216            prev_end = cmp::max(prev_end, range.end);
18217
18218            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18219                runs.push((prev_end..label.text.len(), fade_out));
18220            }
18221
18222            runs
18223        })
18224}
18225
18226pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18227    let mut prev_index = 0;
18228    let mut prev_codepoint: Option<char> = None;
18229    text.char_indices()
18230        .chain([(text.len(), '\0')])
18231        .filter_map(move |(index, codepoint)| {
18232            let prev_codepoint = prev_codepoint.replace(codepoint)?;
18233            let is_boundary = index == text.len()
18234                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18235                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18236            if is_boundary {
18237                let chunk = &text[prev_index..index];
18238                prev_index = index;
18239                Some(chunk)
18240            } else {
18241                None
18242            }
18243        })
18244}
18245
18246pub trait RangeToAnchorExt: Sized {
18247    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18248
18249    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18250        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18251        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18252    }
18253}
18254
18255impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18256    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18257        let start_offset = self.start.to_offset(snapshot);
18258        let end_offset = self.end.to_offset(snapshot);
18259        if start_offset == end_offset {
18260            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18261        } else {
18262            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18263        }
18264    }
18265}
18266
18267pub trait RowExt {
18268    fn as_f32(&self) -> f32;
18269
18270    fn next_row(&self) -> Self;
18271
18272    fn previous_row(&self) -> Self;
18273
18274    fn minus(&self, other: Self) -> u32;
18275}
18276
18277impl RowExt for DisplayRow {
18278    fn as_f32(&self) -> f32 {
18279        self.0 as f32
18280    }
18281
18282    fn next_row(&self) -> Self {
18283        Self(self.0 + 1)
18284    }
18285
18286    fn previous_row(&self) -> Self {
18287        Self(self.0.saturating_sub(1))
18288    }
18289
18290    fn minus(&self, other: Self) -> u32 {
18291        self.0 - other.0
18292    }
18293}
18294
18295impl RowExt for MultiBufferRow {
18296    fn as_f32(&self) -> f32 {
18297        self.0 as f32
18298    }
18299
18300    fn next_row(&self) -> Self {
18301        Self(self.0 + 1)
18302    }
18303
18304    fn previous_row(&self) -> Self {
18305        Self(self.0.saturating_sub(1))
18306    }
18307
18308    fn minus(&self, other: Self) -> u32 {
18309        self.0 - other.0
18310    }
18311}
18312
18313trait RowRangeExt {
18314    type Row;
18315
18316    fn len(&self) -> usize;
18317
18318    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18319}
18320
18321impl RowRangeExt for Range<MultiBufferRow> {
18322    type Row = MultiBufferRow;
18323
18324    fn len(&self) -> usize {
18325        (self.end.0 - self.start.0) as usize
18326    }
18327
18328    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18329        (self.start.0..self.end.0).map(MultiBufferRow)
18330    }
18331}
18332
18333impl RowRangeExt for Range<DisplayRow> {
18334    type Row = DisplayRow;
18335
18336    fn len(&self) -> usize {
18337        (self.end.0 - self.start.0) as usize
18338    }
18339
18340    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18341        (self.start.0..self.end.0).map(DisplayRow)
18342    }
18343}
18344
18345/// If select range has more than one line, we
18346/// just point the cursor to range.start.
18347fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18348    if range.start.row == range.end.row {
18349        range
18350    } else {
18351        range.start..range.start
18352    }
18353}
18354pub struct KillRing(ClipboardItem);
18355impl Global for KillRing {}
18356
18357const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18358
18359fn all_edits_insertions_or_deletions(
18360    edits: &Vec<(Range<Anchor>, String)>,
18361    snapshot: &MultiBufferSnapshot,
18362) -> bool {
18363    let mut all_insertions = true;
18364    let mut all_deletions = true;
18365
18366    for (range, new_text) in edits.iter() {
18367        let range_is_empty = range.to_offset(&snapshot).is_empty();
18368        let text_is_empty = new_text.is_empty();
18369
18370        if range_is_empty != text_is_empty {
18371            if range_is_empty {
18372                all_deletions = false;
18373            } else {
18374                all_insertions = false;
18375            }
18376        } else {
18377            return false;
18378        }
18379
18380        if !all_insertions && !all_deletions {
18381            return false;
18382        }
18383    }
18384    all_insertions || all_deletions
18385}
18386
18387struct MissingEditPredictionKeybindingTooltip;
18388
18389impl Render for MissingEditPredictionKeybindingTooltip {
18390    fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18391        ui::tooltip_container(window, cx, |container, _, cx| {
18392            container
18393                .flex_shrink_0()
18394                .max_w_80()
18395                .min_h(rems_from_px(124.))
18396                .justify_between()
18397                .child(
18398                    v_flex()
18399                        .flex_1()
18400                        .text_ui_sm(cx)
18401                        .child(Label::new("Conflict with Accept Keybinding"))
18402                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
18403                )
18404                .child(
18405                    h_flex()
18406                        .pb_1()
18407                        .gap_1()
18408                        .items_end()
18409                        .w_full()
18410                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
18411                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
18412                        }))
18413                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
18414                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
18415                        })),
18416                )
18417        })
18418    }
18419}