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 jsx_tag_auto_close;
   32mod linked_editing_ranges;
   33mod lsp_ext;
   34mod mouse_context_menu;
   35pub mod movement;
   36mod persistence;
   37mod proposed_changes_editor;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45#[cfg(test)]
   46mod inline_completion_tests;
   47mod signature_help;
   48#[cfg(any(test, feature = "test-support"))]
   49pub mod test;
   50
   51pub(crate) use actions::*;
   52pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   53use aho_corasick::AhoCorasick;
   54use anyhow::{anyhow, Context as _, Result};
   55use blink_manager::BlinkManager;
   56use buffer_diff::DiffHunkStatus;
   57use client::{Collaborator, ParticipantIndex};
   58use clock::ReplicaId;
   59use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   60use convert_case::{Case, Casing};
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   65};
   66pub use editor_settings_controls::*;
   67use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use futures::{
   72    future::{self, join, Shared},
   73    FutureExt,
   74};
   75use fuzzy::StringMatchCandidate;
   76
   77use ::git::Restore;
   78use code_context_menus::{
   79    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   80    CompletionsMenu, ContextMenuOrigin,
   81};
   82use git::blame::GitBlame;
   83use gpui::{
   84    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   85    AnimationExt, AnyElement, App, AppContext, AsyncWindowContext, AvailableSpace, Background,
   86    Bounds, ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity,
   87    EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight,
   88    Global, HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
   89    ParentElement, Pixels, Render, SharedString, Size, Stateful, Styled, StyledText, Subscription,
   90    Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   91    WeakEntity, WeakFocusHandle, Window,
   92};
   93use highlight_matching_bracket::refresh_matching_bracket_highlights;
   94use hover_popover::{hide_hover, HoverState};
   95use indent_guides::ActiveIndentGuidesState;
   96use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   97pub use inline_completion::Direction;
   98use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   99pub use items::MAX_TAB_TITLE_LEN;
  100use itertools::Itertools;
  101use language::{
  102    language_settings::{
  103        self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
  104        WordsCompletionMode,
  105    },
  106    point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
  107    Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, EditPredictionsMode,
  108    EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
  109    Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions, WordsQuery,
  110};
  111use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  112use linked_editing_ranges::refresh_linked_ranges;
  113use mouse_context_menu::MouseContextMenu;
  114use persistence::DB;
  115pub use proposed_changes_editor::{
  116    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  117};
  118use smallvec::smallvec;
  119use std::iter::Peekable;
  120use task::{ResolvedTask, TaskTemplate, TaskVariables};
  121
  122use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  123pub use lsp::CompletionContext;
  124use lsp::{
  125    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  126    InsertTextFormat, LanguageServerId, LanguageServerName,
  127};
  128
  129use language::BufferSnapshot;
  130use movement::TextLayoutDetails;
  131pub use multi_buffer::{
  132    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  133    ToOffset, ToPoint,
  134};
  135use multi_buffer::{
  136    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  137    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  138};
  139use project::{
  140    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  141    project_settings::{GitGutterSetting, ProjectSettings},
  142    CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
  143    Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
  144    TaskSourceKind,
  145};
  146use rand::prelude::*;
  147use rpc::{proto::*, ErrorExt};
  148use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  149use selections_collection::{
  150    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  151};
  152use serde::{Deserialize, Serialize};
  153use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  154use smallvec::SmallVec;
  155use snippet::Snippet;
  156use std::{
  157    any::TypeId,
  158    borrow::Cow,
  159    cell::RefCell,
  160    cmp::{self, Ordering, Reverse},
  161    mem,
  162    num::NonZeroU32,
  163    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  164    path::{Path, PathBuf},
  165    rc::Rc,
  166    sync::Arc,
  167    time::{Duration, Instant},
  168};
  169pub use sum_tree::Bias;
  170use sum_tree::TreeMap;
  171use text::{BufferId, OffsetUtf16, Rope};
  172use theme::{
  173    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  174    ThemeColors, ThemeSettings,
  175};
  176use ui::{
  177    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  178    Tooltip,
  179};
  180use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  181use workspace::{
  182    item::{ItemHandle, PreviewTabsSettings},
  183    ItemId, RestoreOnStartupBehavior,
  184};
  185use workspace::{
  186    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  187    WorkspaceSettings,
  188};
  189use workspace::{
  190    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  191};
  192use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  193
  194use crate::hover_links::{find_url, find_url_from_range};
  195use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  196
  197pub const FILE_HEADER_HEIGHT: u32 = 2;
  198pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  199pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  200const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  201const MAX_LINE_LEN: usize = 1024;
  202const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  203const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  204pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  205#[doc(hidden)]
  206pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  207
  208pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  209pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  210pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  211
  212pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  213pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  214pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
  215
  216const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  217    alt: true,
  218    shift: true,
  219    control: false,
  220    platform: false,
  221    function: false,
  222};
  223
  224#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  225pub enum InlayId {
  226    InlineCompletion(usize),
  227    Hint(usize),
  228}
  229
  230impl InlayId {
  231    fn id(&self) -> usize {
  232        match self {
  233            Self::InlineCompletion(id) => *id,
  234            Self::Hint(id) => *id,
  235        }
  236    }
  237}
  238
  239enum DocumentHighlightRead {}
  240enum DocumentHighlightWrite {}
  241enum InputComposition {}
  242enum SelectedTextHighlight {}
  243
  244#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  245pub enum Navigated {
  246    Yes,
  247    No,
  248}
  249
  250impl Navigated {
  251    pub fn from_bool(yes: bool) -> Navigated {
  252        if yes {
  253            Navigated::Yes
  254        } else {
  255            Navigated::No
  256        }
  257    }
  258}
  259
  260#[derive(Debug, Clone, PartialEq, Eq)]
  261enum DisplayDiffHunk {
  262    Folded {
  263        display_row: DisplayRow,
  264    },
  265    Unfolded {
  266        is_created_file: bool,
  267        diff_base_byte_range: Range<usize>,
  268        display_row_range: Range<DisplayRow>,
  269        multi_buffer_range: Range<Anchor>,
  270        status: DiffHunkStatus,
  271    },
  272}
  273
  274pub fn init_settings(cx: &mut App) {
  275    EditorSettings::register(cx);
  276}
  277
  278pub fn init(cx: &mut App) {
  279    init_settings(cx);
  280
  281    workspace::register_project_item::<Editor>(cx);
  282    workspace::FollowableViewRegistry::register::<Editor>(cx);
  283    workspace::register_serializable_item::<Editor>(cx);
  284
  285    cx.observe_new(
  286        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  287            workspace.register_action(Editor::new_file);
  288            workspace.register_action(Editor::new_file_vertical);
  289            workspace.register_action(Editor::new_file_horizontal);
  290            workspace.register_action(Editor::cancel_language_server_work);
  291        },
  292    )
  293    .detach();
  294
  295    cx.on_action(move |_: &workspace::NewFile, cx| {
  296        let app_state = workspace::AppState::global(cx);
  297        if let Some(app_state) = app_state.upgrade() {
  298            workspace::open_new(
  299                Default::default(),
  300                app_state,
  301                cx,
  302                |workspace, window, cx| {
  303                    Editor::new_file(workspace, &Default::default(), window, cx)
  304                },
  305            )
  306            .detach();
  307        }
  308    });
  309    cx.on_action(move |_: &workspace::NewWindow, cx| {
  310        let app_state = workspace::AppState::global(cx);
  311        if let Some(app_state) = app_state.upgrade() {
  312            workspace::open_new(
  313                Default::default(),
  314                app_state,
  315                cx,
  316                |workspace, window, cx| {
  317                    cx.activate(true);
  318                    Editor::new_file(workspace, &Default::default(), window, cx)
  319                },
  320            )
  321            .detach();
  322        }
  323    });
  324}
  325
  326pub struct SearchWithinRange;
  327
  328trait InvalidationRegion {
  329    fn ranges(&self) -> &[Range<Anchor>];
  330}
  331
  332#[derive(Clone, Debug, PartialEq)]
  333pub enum SelectPhase {
  334    Begin {
  335        position: DisplayPoint,
  336        add: bool,
  337        click_count: usize,
  338    },
  339    BeginColumnar {
  340        position: DisplayPoint,
  341        reset: bool,
  342        goal_column: u32,
  343    },
  344    Extend {
  345        position: DisplayPoint,
  346        click_count: usize,
  347    },
  348    Update {
  349        position: DisplayPoint,
  350        goal_column: u32,
  351        scroll_delta: gpui::Point<f32>,
  352    },
  353    End,
  354}
  355
  356#[derive(Clone, Debug)]
  357pub enum SelectMode {
  358    Character,
  359    Word(Range<Anchor>),
  360    Line(Range<Anchor>),
  361    All,
  362}
  363
  364#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  365pub enum EditorMode {
  366    SingleLine { auto_width: bool },
  367    AutoHeight { max_lines: usize },
  368    Full,
  369}
  370
  371#[derive(Copy, Clone, Debug)]
  372pub enum SoftWrap {
  373    /// Prefer not to wrap at all.
  374    ///
  375    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  376    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  377    GitDiff,
  378    /// Prefer a single line generally, unless an overly long line is encountered.
  379    None,
  380    /// Soft wrap lines that exceed the editor width.
  381    EditorWidth,
  382    /// Soft wrap lines at the preferred line length.
  383    Column(u32),
  384    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  385    Bounded(u32),
  386}
  387
  388#[derive(Clone)]
  389pub struct EditorStyle {
  390    pub background: Hsla,
  391    pub local_player: PlayerColor,
  392    pub text: TextStyle,
  393    pub scrollbar_width: Pixels,
  394    pub syntax: Arc<SyntaxTheme>,
  395    pub status: StatusColors,
  396    pub inlay_hints_style: HighlightStyle,
  397    pub inline_completion_styles: InlineCompletionStyles,
  398    pub unnecessary_code_fade: f32,
  399}
  400
  401impl Default for EditorStyle {
  402    fn default() -> Self {
  403        Self {
  404            background: Hsla::default(),
  405            local_player: PlayerColor::default(),
  406            text: TextStyle::default(),
  407            scrollbar_width: Pixels::default(),
  408            syntax: Default::default(),
  409            // HACK: Status colors don't have a real default.
  410            // We should look into removing the status colors from the editor
  411            // style and retrieve them directly from the theme.
  412            status: StatusColors::dark(),
  413            inlay_hints_style: HighlightStyle::default(),
  414            inline_completion_styles: InlineCompletionStyles {
  415                insertion: HighlightStyle::default(),
  416                whitespace: HighlightStyle::default(),
  417            },
  418            unnecessary_code_fade: Default::default(),
  419        }
  420    }
  421}
  422
  423pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  424    let show_background = language_settings::language_settings(None, None, cx)
  425        .inlay_hints
  426        .show_background;
  427
  428    HighlightStyle {
  429        color: Some(cx.theme().status().hint),
  430        background_color: show_background.then(|| cx.theme().status().hint_background),
  431        ..HighlightStyle::default()
  432    }
  433}
  434
  435pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  436    InlineCompletionStyles {
  437        insertion: HighlightStyle {
  438            color: Some(cx.theme().status().predictive),
  439            ..HighlightStyle::default()
  440        },
  441        whitespace: HighlightStyle {
  442            background_color: Some(cx.theme().status().created_background),
  443            ..HighlightStyle::default()
  444        },
  445    }
  446}
  447
  448type CompletionId = usize;
  449
  450pub(crate) enum EditDisplayMode {
  451    TabAccept,
  452    DiffPopover,
  453    Inline,
  454}
  455
  456enum InlineCompletion {
  457    Edit {
  458        edits: Vec<(Range<Anchor>, String)>,
  459        edit_preview: Option<EditPreview>,
  460        display_mode: EditDisplayMode,
  461        snapshot: BufferSnapshot,
  462    },
  463    Move {
  464        target: Anchor,
  465        snapshot: BufferSnapshot,
  466    },
  467}
  468
  469struct InlineCompletionState {
  470    inlay_ids: Vec<InlayId>,
  471    completion: InlineCompletion,
  472    completion_id: Option<SharedString>,
  473    invalidation_range: Range<Anchor>,
  474}
  475
  476enum EditPredictionSettings {
  477    Disabled,
  478    Enabled {
  479        show_in_menu: bool,
  480        preview_requires_modifier: bool,
  481    },
  482}
  483
  484enum InlineCompletionHighlight {}
  485
  486#[derive(Debug, Clone)]
  487struct InlineDiagnostic {
  488    message: SharedString,
  489    group_id: usize,
  490    is_primary: bool,
  491    start: Point,
  492    severity: DiagnosticSeverity,
  493}
  494
  495pub enum MenuInlineCompletionsPolicy {
  496    Never,
  497    ByProvider,
  498}
  499
  500pub enum EditPredictionPreview {
  501    /// Modifier is not pressed
  502    Inactive { released_too_fast: bool },
  503    /// Modifier pressed
  504    Active {
  505        since: Instant,
  506        previous_scroll_position: Option<ScrollAnchor>,
  507    },
  508}
  509
  510impl EditPredictionPreview {
  511    pub fn released_too_fast(&self) -> bool {
  512        match self {
  513            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  514            EditPredictionPreview::Active { .. } => false,
  515        }
  516    }
  517
  518    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  519        if let EditPredictionPreview::Active {
  520            previous_scroll_position,
  521            ..
  522        } = self
  523        {
  524            *previous_scroll_position = scroll_position;
  525        }
  526    }
  527}
  528
  529#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  530struct EditorActionId(usize);
  531
  532impl EditorActionId {
  533    pub fn post_inc(&mut self) -> Self {
  534        let answer = self.0;
  535
  536        *self = Self(answer + 1);
  537
  538        Self(answer)
  539    }
  540}
  541
  542// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  543// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  544
  545type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  546type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  547
  548#[derive(Default)]
  549struct ScrollbarMarkerState {
  550    scrollbar_size: Size<Pixels>,
  551    dirty: bool,
  552    markers: Arc<[PaintQuad]>,
  553    pending_refresh: Option<Task<Result<()>>>,
  554}
  555
  556impl ScrollbarMarkerState {
  557    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  558        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  559    }
  560}
  561
  562#[derive(Clone, Debug)]
  563struct RunnableTasks {
  564    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  565    offset: multi_buffer::Anchor,
  566    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  567    column: u32,
  568    // Values of all named captures, including those starting with '_'
  569    extra_variables: HashMap<String, String>,
  570    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  571    context_range: Range<BufferOffset>,
  572}
  573
  574impl RunnableTasks {
  575    fn resolve<'a>(
  576        &'a self,
  577        cx: &'a task::TaskContext,
  578    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  579        self.templates.iter().filter_map(|(kind, template)| {
  580            template
  581                .resolve_task(&kind.to_id_base(), cx)
  582                .map(|task| (kind.clone(), task))
  583        })
  584    }
  585}
  586
  587#[derive(Clone)]
  588struct ResolvedTasks {
  589    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  590    position: Anchor,
  591}
  592#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  593struct BufferOffset(usize);
  594
  595// Addons allow storing per-editor state in other crates (e.g. Vim)
  596pub trait Addon: 'static {
  597    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  598
  599    fn render_buffer_header_controls(
  600        &self,
  601        _: &ExcerptInfo,
  602        _: &Window,
  603        _: &App,
  604    ) -> Option<AnyElement> {
  605        None
  606    }
  607
  608    fn to_any(&self) -> &dyn std::any::Any;
  609}
  610
  611/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  612///
  613/// See the [module level documentation](self) for more information.
  614pub struct Editor {
  615    focus_handle: FocusHandle,
  616    last_focused_descendant: Option<WeakFocusHandle>,
  617    /// The text buffer being edited
  618    buffer: Entity<MultiBuffer>,
  619    /// Map of how text in the buffer should be displayed.
  620    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  621    pub display_map: Entity<DisplayMap>,
  622    pub selections: SelectionsCollection,
  623    pub scroll_manager: ScrollManager,
  624    /// When inline assist editors are linked, they all render cursors because
  625    /// typing enters text into each of them, even the ones that aren't focused.
  626    pub(crate) show_cursor_when_unfocused: bool,
  627    columnar_selection_tail: Option<Anchor>,
  628    add_selections_state: Option<AddSelectionsState>,
  629    select_next_state: Option<SelectNextState>,
  630    select_prev_state: Option<SelectNextState>,
  631    selection_history: SelectionHistory,
  632    autoclose_regions: Vec<AutocloseRegion>,
  633    snippet_stack: InvalidationStack<SnippetState>,
  634    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  635    ime_transaction: Option<TransactionId>,
  636    active_diagnostics: Option<ActiveDiagnosticGroup>,
  637    show_inline_diagnostics: bool,
  638    inline_diagnostics_update: Task<()>,
  639    inline_diagnostics_enabled: bool,
  640    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  641    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  642    hard_wrap: Option<usize>,
  643
  644    // TODO: make this a access method
  645    pub project: Option<Entity<Project>>,
  646    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  647    completion_provider: Option<Box<dyn CompletionProvider>>,
  648    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  649    blink_manager: Entity<BlinkManager>,
  650    show_cursor_names: bool,
  651    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  652    pub show_local_selections: bool,
  653    mode: EditorMode,
  654    show_breadcrumbs: bool,
  655    show_gutter: bool,
  656    show_scrollbars: bool,
  657    show_line_numbers: Option<bool>,
  658    use_relative_line_numbers: Option<bool>,
  659    show_git_diff_gutter: Option<bool>,
  660    show_code_actions: Option<bool>,
  661    show_runnables: Option<bool>,
  662    show_wrap_guides: Option<bool>,
  663    show_indent_guides: Option<bool>,
  664    placeholder_text: Option<Arc<str>>,
  665    highlight_order: usize,
  666    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  667    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  668    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  669    scrollbar_marker_state: ScrollbarMarkerState,
  670    active_indent_guides_state: ActiveIndentGuidesState,
  671    nav_history: Option<ItemNavHistory>,
  672    context_menu: RefCell<Option<CodeContextMenu>>,
  673    mouse_context_menu: Option<MouseContextMenu>,
  674    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  675    signature_help_state: SignatureHelpState,
  676    auto_signature_help: Option<bool>,
  677    find_all_references_task_sources: Vec<Anchor>,
  678    next_completion_id: CompletionId,
  679    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  680    code_actions_task: Option<Task<Result<()>>>,
  681    selection_highlight_task: Option<Task<()>>,
  682    document_highlights_task: Option<Task<()>>,
  683    linked_editing_range_task: Option<Task<Option<()>>>,
  684    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  685    pending_rename: Option<RenameState>,
  686    searchable: bool,
  687    cursor_shape: CursorShape,
  688    current_line_highlight: Option<CurrentLineHighlight>,
  689    collapse_matches: bool,
  690    autoindent_mode: Option<AutoindentMode>,
  691    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  692    input_enabled: bool,
  693    use_modal_editing: bool,
  694    read_only: bool,
  695    leader_peer_id: Option<PeerId>,
  696    remote_id: Option<ViewId>,
  697    hover_state: HoverState,
  698    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  699    gutter_hovered: bool,
  700    hovered_link_state: Option<HoveredLinkState>,
  701    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  702    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  703    active_inline_completion: Option<InlineCompletionState>,
  704    /// Used to prevent flickering as the user types while the menu is open
  705    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  706    edit_prediction_settings: EditPredictionSettings,
  707    inline_completions_hidden_for_vim_mode: bool,
  708    show_inline_completions_override: Option<bool>,
  709    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  710    edit_prediction_preview: EditPredictionPreview,
  711    edit_prediction_indent_conflict: bool,
  712    edit_prediction_requires_modifier_in_indent_conflict: bool,
  713    inlay_hint_cache: InlayHintCache,
  714    next_inlay_id: usize,
  715    _subscriptions: Vec<Subscription>,
  716    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  717    gutter_dimensions: GutterDimensions,
  718    style: Option<EditorStyle>,
  719    text_style_refinement: Option<TextStyleRefinement>,
  720    next_editor_action_id: EditorActionId,
  721    editor_actions:
  722        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  723    use_autoclose: bool,
  724    use_auto_surround: bool,
  725    auto_replace_emoji_shortcode: bool,
  726    jsx_tag_auto_close_enabled_in_any_buffer: 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 indentation of the first line when this content was originally copied.
 1014    pub first_line_indent: 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            window,
 1096            cx,
 1097        )
 1098    }
 1099
 1100    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1101        let buffer = cx.new(|cx| Buffer::local("", cx));
 1102        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1103        Self::new(EditorMode::Full, buffer, None, window, cx)
 1104    }
 1105
 1106    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1107        let buffer = cx.new(|cx| Buffer::local("", cx));
 1108        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1109        Self::new(
 1110            EditorMode::SingleLine { auto_width: true },
 1111            buffer,
 1112            None,
 1113            window,
 1114            cx,
 1115        )
 1116    }
 1117
 1118    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1119        let buffer = cx.new(|cx| Buffer::local("", cx));
 1120        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1121        Self::new(
 1122            EditorMode::AutoHeight { max_lines },
 1123            buffer,
 1124            None,
 1125            window,
 1126            cx,
 1127        )
 1128    }
 1129
 1130    pub fn for_buffer(
 1131        buffer: Entity<Buffer>,
 1132        project: Option<Entity<Project>>,
 1133        window: &mut Window,
 1134        cx: &mut Context<Self>,
 1135    ) -> Self {
 1136        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1137        Self::new(EditorMode::Full, buffer, project, window, cx)
 1138    }
 1139
 1140    pub fn for_multibuffer(
 1141        buffer: Entity<MultiBuffer>,
 1142        project: Option<Entity<Project>>,
 1143        window: &mut Window,
 1144        cx: &mut Context<Self>,
 1145    ) -> Self {
 1146        Self::new(EditorMode::Full, buffer, project, window, cx)
 1147    }
 1148
 1149    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1150        let mut clone = Self::new(
 1151            self.mode,
 1152            self.buffer.clone(),
 1153            self.project.clone(),
 1154            window,
 1155            cx,
 1156        );
 1157        self.display_map.update(cx, |display_map, cx| {
 1158            let snapshot = display_map.snapshot(cx);
 1159            clone.display_map.update(cx, |display_map, cx| {
 1160                display_map.set_state(&snapshot, cx);
 1161            });
 1162        });
 1163        clone.selections.clone_state(&self.selections);
 1164        clone.scroll_manager.clone_state(&self.scroll_manager);
 1165        clone.searchable = self.searchable;
 1166        clone
 1167    }
 1168
 1169    pub fn new(
 1170        mode: EditorMode,
 1171        buffer: Entity<MultiBuffer>,
 1172        project: Option<Entity<Project>>,
 1173        window: &mut Window,
 1174        cx: &mut Context<Self>,
 1175    ) -> Self {
 1176        let style = window.text_style();
 1177        let font_size = style.font_size.to_pixels(window.rem_size());
 1178        let editor = cx.entity().downgrade();
 1179        let fold_placeholder = FoldPlaceholder {
 1180            constrain_width: true,
 1181            render: Arc::new(move |fold_id, fold_range, cx| {
 1182                let editor = editor.clone();
 1183                div()
 1184                    .id(fold_id)
 1185                    .bg(cx.theme().colors().ghost_element_background)
 1186                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1187                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1188                    .rounded_xs()
 1189                    .size_full()
 1190                    .cursor_pointer()
 1191                    .child("")
 1192                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1193                    .on_click(move |_, _window, cx| {
 1194                        editor
 1195                            .update(cx, |editor, cx| {
 1196                                editor.unfold_ranges(
 1197                                    &[fold_range.start..fold_range.end],
 1198                                    true,
 1199                                    false,
 1200                                    cx,
 1201                                );
 1202                                cx.stop_propagation();
 1203                            })
 1204                            .ok();
 1205                    })
 1206                    .into_any()
 1207            }),
 1208            merge_adjacent: true,
 1209            ..Default::default()
 1210        };
 1211        let display_map = cx.new(|cx| {
 1212            DisplayMap::new(
 1213                buffer.clone(),
 1214                style.font(),
 1215                font_size,
 1216                None,
 1217                FILE_HEADER_HEIGHT,
 1218                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1219                fold_placeholder,
 1220                cx,
 1221            )
 1222        });
 1223
 1224        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1225
 1226        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1227
 1228        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1229            .then(|| language_settings::SoftWrap::None);
 1230
 1231        let mut project_subscriptions = Vec::new();
 1232        if mode == EditorMode::Full {
 1233            if let Some(project) = project.as_ref() {
 1234                project_subscriptions.push(cx.subscribe_in(
 1235                    project,
 1236                    window,
 1237                    |editor, _, event, window, cx| match event {
 1238                        project::Event::RefreshCodeLens => {
 1239                            // we always query lens with actions, without storing them, always refreshing them
 1240                        }
 1241                        project::Event::RefreshInlayHints => {
 1242                            editor
 1243                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1244                        }
 1245                        project::Event::SnippetEdit(id, snippet_edits) => {
 1246                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1247                                let focus_handle = editor.focus_handle(cx);
 1248                                if focus_handle.is_focused(window) {
 1249                                    let snapshot = buffer.read(cx).snapshot();
 1250                                    for (range, snippet) in snippet_edits {
 1251                                        let editor_range =
 1252                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1253                                        editor
 1254                                            .insert_snippet(
 1255                                                &[editor_range],
 1256                                                snippet.clone(),
 1257                                                window,
 1258                                                cx,
 1259                                            )
 1260                                            .ok();
 1261                                    }
 1262                                }
 1263                            }
 1264                        }
 1265                        _ => {}
 1266                    },
 1267                ));
 1268                if let Some(task_inventory) = project
 1269                    .read(cx)
 1270                    .task_store()
 1271                    .read(cx)
 1272                    .task_inventory()
 1273                    .cloned()
 1274                {
 1275                    project_subscriptions.push(cx.observe_in(
 1276                        &task_inventory,
 1277                        window,
 1278                        |editor, _, window, cx| {
 1279                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1280                        },
 1281                    ));
 1282                }
 1283            }
 1284        }
 1285
 1286        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1287
 1288        let inlay_hint_settings =
 1289            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1290        let focus_handle = cx.focus_handle();
 1291        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1292            .detach();
 1293        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1294            .detach();
 1295        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1296            .detach();
 1297        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1298            .detach();
 1299
 1300        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1301            Some(false)
 1302        } else {
 1303            None
 1304        };
 1305
 1306        let mut code_action_providers = Vec::new();
 1307        let mut load_uncommitted_diff = None;
 1308        if let Some(project) = project.clone() {
 1309            load_uncommitted_diff = Some(
 1310                get_uncommitted_diff_for_buffer(
 1311                    &project,
 1312                    buffer.read(cx).all_buffers(),
 1313                    buffer.clone(),
 1314                    cx,
 1315                )
 1316                .shared(),
 1317            );
 1318            code_action_providers.push(Rc::new(project) as Rc<_>);
 1319        }
 1320
 1321        let mut this = Self {
 1322            focus_handle,
 1323            show_cursor_when_unfocused: false,
 1324            last_focused_descendant: None,
 1325            buffer: buffer.clone(),
 1326            display_map: display_map.clone(),
 1327            selections,
 1328            scroll_manager: ScrollManager::new(cx),
 1329            columnar_selection_tail: None,
 1330            add_selections_state: None,
 1331            select_next_state: None,
 1332            select_prev_state: None,
 1333            selection_history: Default::default(),
 1334            autoclose_regions: Default::default(),
 1335            snippet_stack: Default::default(),
 1336            select_larger_syntax_node_stack: Vec::new(),
 1337            ime_transaction: Default::default(),
 1338            active_diagnostics: None,
 1339            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1340            inline_diagnostics_update: Task::ready(()),
 1341            inline_diagnostics: Vec::new(),
 1342            soft_wrap_mode_override,
 1343            hard_wrap: None,
 1344            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1345            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1346            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1347            project,
 1348            blink_manager: blink_manager.clone(),
 1349            show_local_selections: true,
 1350            show_scrollbars: true,
 1351            mode,
 1352            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1353            show_gutter: mode == EditorMode::Full,
 1354            show_line_numbers: None,
 1355            use_relative_line_numbers: None,
 1356            show_git_diff_gutter: None,
 1357            show_code_actions: None,
 1358            show_runnables: None,
 1359            show_wrap_guides: None,
 1360            show_indent_guides,
 1361            placeholder_text: None,
 1362            highlight_order: 0,
 1363            highlighted_rows: HashMap::default(),
 1364            background_highlights: Default::default(),
 1365            gutter_highlights: TreeMap::default(),
 1366            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1367            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1368            nav_history: None,
 1369            context_menu: RefCell::new(None),
 1370            mouse_context_menu: None,
 1371            completion_tasks: Default::default(),
 1372            signature_help_state: SignatureHelpState::default(),
 1373            auto_signature_help: None,
 1374            find_all_references_task_sources: Vec::new(),
 1375            next_completion_id: 0,
 1376            next_inlay_id: 0,
 1377            code_action_providers,
 1378            available_code_actions: Default::default(),
 1379            code_actions_task: Default::default(),
 1380            selection_highlight_task: Default::default(),
 1381            document_highlights_task: Default::default(),
 1382            linked_editing_range_task: Default::default(),
 1383            pending_rename: Default::default(),
 1384            searchable: true,
 1385            cursor_shape: EditorSettings::get_global(cx)
 1386                .cursor_shape
 1387                .unwrap_or_default(),
 1388            current_line_highlight: None,
 1389            autoindent_mode: Some(AutoindentMode::EachLine),
 1390            collapse_matches: false,
 1391            workspace: None,
 1392            input_enabled: true,
 1393            use_modal_editing: mode == EditorMode::Full,
 1394            read_only: false,
 1395            use_autoclose: true,
 1396            use_auto_surround: true,
 1397            auto_replace_emoji_shortcode: false,
 1398            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1399            leader_peer_id: None,
 1400            remote_id: None,
 1401            hover_state: Default::default(),
 1402            pending_mouse_down: None,
 1403            hovered_link_state: Default::default(),
 1404            edit_prediction_provider: None,
 1405            active_inline_completion: None,
 1406            stale_inline_completion_in_menu: None,
 1407            edit_prediction_preview: EditPredictionPreview::Inactive {
 1408                released_too_fast: false,
 1409            },
 1410            inline_diagnostics_enabled: mode == EditorMode::Full,
 1411            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1412
 1413            gutter_hovered: false,
 1414            pixel_position_of_newest_cursor: None,
 1415            last_bounds: None,
 1416            last_position_map: None,
 1417            expect_bounds_change: None,
 1418            gutter_dimensions: GutterDimensions::default(),
 1419            style: None,
 1420            show_cursor_names: false,
 1421            hovered_cursors: Default::default(),
 1422            next_editor_action_id: EditorActionId::default(),
 1423            editor_actions: Rc::default(),
 1424            inline_completions_hidden_for_vim_mode: false,
 1425            show_inline_completions_override: None,
 1426            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1427            edit_prediction_settings: EditPredictionSettings::Disabled,
 1428            edit_prediction_indent_conflict: false,
 1429            edit_prediction_requires_modifier_in_indent_conflict: true,
 1430            custom_context_menu: None,
 1431            show_git_blame_gutter: false,
 1432            show_git_blame_inline: false,
 1433            show_selection_menu: None,
 1434            show_git_blame_inline_delay_task: None,
 1435            git_blame_inline_tooltip: None,
 1436            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1437            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1438                .session
 1439                .restore_unsaved_buffers,
 1440            blame: None,
 1441            blame_subscription: None,
 1442            tasks: Default::default(),
 1443            _subscriptions: vec![
 1444                cx.observe(&buffer, Self::on_buffer_changed),
 1445                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1446                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1447                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1448                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1449                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1450                cx.observe_window_activation(window, |editor, window, cx| {
 1451                    let active = window.is_window_active();
 1452                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1453                        if active {
 1454                            blink_manager.enable(cx);
 1455                        } else {
 1456                            blink_manager.disable(cx);
 1457                        }
 1458                    });
 1459                }),
 1460            ],
 1461            tasks_update_task: None,
 1462            linked_edit_ranges: Default::default(),
 1463            in_project_search: false,
 1464            previous_search_ranges: None,
 1465            breadcrumb_header: None,
 1466            focused_block: None,
 1467            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1468            addons: HashMap::default(),
 1469            registered_buffers: HashMap::default(),
 1470            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1471            selection_mark_mode: false,
 1472            toggle_fold_multiple_buffers: Task::ready(()),
 1473            serialize_selections: Task::ready(()),
 1474            text_style_refinement: None,
 1475            load_diff_task: load_uncommitted_diff,
 1476        };
 1477        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1478        this._subscriptions.extend(project_subscriptions);
 1479
 1480        this.end_selection(window, cx);
 1481        this.scroll_manager.show_scrollbar(window, cx);
 1482        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1483
 1484        if mode == EditorMode::Full {
 1485            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1486            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1487
 1488            if this.git_blame_inline_enabled {
 1489                this.git_blame_inline_enabled = true;
 1490                this.start_git_blame_inline(false, window, cx);
 1491            }
 1492
 1493            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1494                if let Some(project) = this.project.as_ref() {
 1495                    let handle = project.update(cx, |project, cx| {
 1496                        project.register_buffer_with_language_servers(&buffer, cx)
 1497                    });
 1498                    this.registered_buffers
 1499                        .insert(buffer.read(cx).remote_id(), handle);
 1500                }
 1501            }
 1502        }
 1503
 1504        this.report_editor_event("Editor Opened", None, cx);
 1505        this
 1506    }
 1507
 1508    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1509        self.mouse_context_menu
 1510            .as_ref()
 1511            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1512    }
 1513
 1514    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1515        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1516    }
 1517
 1518    fn key_context_internal(
 1519        &self,
 1520        has_active_edit_prediction: bool,
 1521        window: &Window,
 1522        cx: &App,
 1523    ) -> KeyContext {
 1524        let mut key_context = KeyContext::new_with_defaults();
 1525        key_context.add("Editor");
 1526        let mode = match self.mode {
 1527            EditorMode::SingleLine { .. } => "single_line",
 1528            EditorMode::AutoHeight { .. } => "auto_height",
 1529            EditorMode::Full => "full",
 1530        };
 1531
 1532        if EditorSettings::jupyter_enabled(cx) {
 1533            key_context.add("jupyter");
 1534        }
 1535
 1536        key_context.set("mode", mode);
 1537        if self.pending_rename.is_some() {
 1538            key_context.add("renaming");
 1539        }
 1540
 1541        match self.context_menu.borrow().as_ref() {
 1542            Some(CodeContextMenu::Completions(_)) => {
 1543                key_context.add("menu");
 1544                key_context.add("showing_completions");
 1545            }
 1546            Some(CodeContextMenu::CodeActions(_)) => {
 1547                key_context.add("menu");
 1548                key_context.add("showing_code_actions")
 1549            }
 1550            None => {}
 1551        }
 1552
 1553        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1554        if !self.focus_handle(cx).contains_focused(window, cx)
 1555            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1556        {
 1557            for addon in self.addons.values() {
 1558                addon.extend_key_context(&mut key_context, cx)
 1559            }
 1560        }
 1561
 1562        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1563            if let Some(extension) = singleton_buffer
 1564                .read(cx)
 1565                .file()
 1566                .and_then(|file| file.path().extension()?.to_str())
 1567            {
 1568                key_context.set("extension", extension.to_string());
 1569            }
 1570        } else {
 1571            key_context.add("multibuffer");
 1572        }
 1573
 1574        if has_active_edit_prediction {
 1575            if self.edit_prediction_in_conflict() {
 1576                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1577            } else {
 1578                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1579                key_context.add("copilot_suggestion");
 1580            }
 1581        }
 1582
 1583        if self.selection_mark_mode {
 1584            key_context.add("selection_mode");
 1585        }
 1586
 1587        key_context
 1588    }
 1589
 1590    pub fn edit_prediction_in_conflict(&self) -> bool {
 1591        if !self.show_edit_predictions_in_menu() {
 1592            return false;
 1593        }
 1594
 1595        let showing_completions = self
 1596            .context_menu
 1597            .borrow()
 1598            .as_ref()
 1599            .map_or(false, |context| {
 1600                matches!(context, CodeContextMenu::Completions(_))
 1601            });
 1602
 1603        showing_completions
 1604            || self.edit_prediction_requires_modifier()
 1605            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1606            // bindings to insert tab characters.
 1607            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1608    }
 1609
 1610    pub fn accept_edit_prediction_keybind(
 1611        &self,
 1612        window: &Window,
 1613        cx: &App,
 1614    ) -> AcceptEditPredictionBinding {
 1615        let key_context = self.key_context_internal(true, window, cx);
 1616        let in_conflict = self.edit_prediction_in_conflict();
 1617
 1618        AcceptEditPredictionBinding(
 1619            window
 1620                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1621                .into_iter()
 1622                .filter(|binding| {
 1623                    !in_conflict
 1624                        || binding
 1625                            .keystrokes()
 1626                            .first()
 1627                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1628                })
 1629                .rev()
 1630                .min_by_key(|binding| {
 1631                    binding
 1632                        .keystrokes()
 1633                        .first()
 1634                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1635                }),
 1636        )
 1637    }
 1638
 1639    pub fn new_file(
 1640        workspace: &mut Workspace,
 1641        _: &workspace::NewFile,
 1642        window: &mut Window,
 1643        cx: &mut Context<Workspace>,
 1644    ) {
 1645        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1646            "Failed to create buffer",
 1647            window,
 1648            cx,
 1649            |e, _, _| match e.error_code() {
 1650                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1651                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1652                e.error_tag("required").unwrap_or("the latest version")
 1653            )),
 1654                _ => None,
 1655            },
 1656        );
 1657    }
 1658
 1659    pub fn new_in_workspace(
 1660        workspace: &mut Workspace,
 1661        window: &mut Window,
 1662        cx: &mut Context<Workspace>,
 1663    ) -> Task<Result<Entity<Editor>>> {
 1664        let project = workspace.project().clone();
 1665        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1666
 1667        cx.spawn_in(window, |workspace, mut cx| async move {
 1668            let buffer = create.await?;
 1669            workspace.update_in(&mut cx, |workspace, window, cx| {
 1670                let editor =
 1671                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1672                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1673                editor
 1674            })
 1675        })
 1676    }
 1677
 1678    fn new_file_vertical(
 1679        workspace: &mut Workspace,
 1680        _: &workspace::NewFileSplitVertical,
 1681        window: &mut Window,
 1682        cx: &mut Context<Workspace>,
 1683    ) {
 1684        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1685    }
 1686
 1687    fn new_file_horizontal(
 1688        workspace: &mut Workspace,
 1689        _: &workspace::NewFileSplitHorizontal,
 1690        window: &mut Window,
 1691        cx: &mut Context<Workspace>,
 1692    ) {
 1693        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1694    }
 1695
 1696    fn new_file_in_direction(
 1697        workspace: &mut Workspace,
 1698        direction: SplitDirection,
 1699        window: &mut Window,
 1700        cx: &mut Context<Workspace>,
 1701    ) {
 1702        let project = workspace.project().clone();
 1703        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1704
 1705        cx.spawn_in(window, |workspace, mut cx| async move {
 1706            let buffer = create.await?;
 1707            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1708                workspace.split_item(
 1709                    direction,
 1710                    Box::new(
 1711                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1712                    ),
 1713                    window,
 1714                    cx,
 1715                )
 1716            })?;
 1717            anyhow::Ok(())
 1718        })
 1719        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1720            match e.error_code() {
 1721                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1722                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1723                e.error_tag("required").unwrap_or("the latest version")
 1724            )),
 1725                _ => None,
 1726            }
 1727        });
 1728    }
 1729
 1730    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1731        self.leader_peer_id
 1732    }
 1733
 1734    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1735        &self.buffer
 1736    }
 1737
 1738    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1739        self.workspace.as_ref()?.0.upgrade()
 1740    }
 1741
 1742    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1743        self.buffer().read(cx).title(cx)
 1744    }
 1745
 1746    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1747        let git_blame_gutter_max_author_length = self
 1748            .render_git_blame_gutter(cx)
 1749            .then(|| {
 1750                if let Some(blame) = self.blame.as_ref() {
 1751                    let max_author_length =
 1752                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1753                    Some(max_author_length)
 1754                } else {
 1755                    None
 1756                }
 1757            })
 1758            .flatten();
 1759
 1760        EditorSnapshot {
 1761            mode: self.mode,
 1762            show_gutter: self.show_gutter,
 1763            show_line_numbers: self.show_line_numbers,
 1764            show_git_diff_gutter: self.show_git_diff_gutter,
 1765            show_code_actions: self.show_code_actions,
 1766            show_runnables: self.show_runnables,
 1767            git_blame_gutter_max_author_length,
 1768            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1769            scroll_anchor: self.scroll_manager.anchor(),
 1770            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1771            placeholder_text: self.placeholder_text.clone(),
 1772            is_focused: self.focus_handle.is_focused(window),
 1773            current_line_highlight: self
 1774                .current_line_highlight
 1775                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1776            gutter_hovered: self.gutter_hovered,
 1777        }
 1778    }
 1779
 1780    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1781        self.buffer.read(cx).language_at(point, cx)
 1782    }
 1783
 1784    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1785        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1786    }
 1787
 1788    pub fn active_excerpt(
 1789        &self,
 1790        cx: &App,
 1791    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1792        self.buffer
 1793            .read(cx)
 1794            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1795    }
 1796
 1797    pub fn mode(&self) -> EditorMode {
 1798        self.mode
 1799    }
 1800
 1801    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1802        self.collaboration_hub.as_deref()
 1803    }
 1804
 1805    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1806        self.collaboration_hub = Some(hub);
 1807    }
 1808
 1809    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1810        self.in_project_search = in_project_search;
 1811    }
 1812
 1813    pub fn set_custom_context_menu(
 1814        &mut self,
 1815        f: impl 'static
 1816            + Fn(
 1817                &mut Self,
 1818                DisplayPoint,
 1819                &mut Window,
 1820                &mut Context<Self>,
 1821            ) -> Option<Entity<ui::ContextMenu>>,
 1822    ) {
 1823        self.custom_context_menu = Some(Box::new(f))
 1824    }
 1825
 1826    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1827        self.completion_provider = provider;
 1828    }
 1829
 1830    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1831        self.semantics_provider.clone()
 1832    }
 1833
 1834    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1835        self.semantics_provider = provider;
 1836    }
 1837
 1838    pub fn set_edit_prediction_provider<T>(
 1839        &mut self,
 1840        provider: Option<Entity<T>>,
 1841        window: &mut Window,
 1842        cx: &mut Context<Self>,
 1843    ) where
 1844        T: EditPredictionProvider,
 1845    {
 1846        self.edit_prediction_provider =
 1847            provider.map(|provider| RegisteredInlineCompletionProvider {
 1848                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1849                    if this.focus_handle.is_focused(window) {
 1850                        this.update_visible_inline_completion(window, cx);
 1851                    }
 1852                }),
 1853                provider: Arc::new(provider),
 1854            });
 1855        self.update_edit_prediction_settings(cx);
 1856        self.refresh_inline_completion(false, false, window, cx);
 1857    }
 1858
 1859    pub fn placeholder_text(&self) -> Option<&str> {
 1860        self.placeholder_text.as_deref()
 1861    }
 1862
 1863    pub fn set_placeholder_text(
 1864        &mut self,
 1865        placeholder_text: impl Into<Arc<str>>,
 1866        cx: &mut Context<Self>,
 1867    ) {
 1868        let placeholder_text = Some(placeholder_text.into());
 1869        if self.placeholder_text != placeholder_text {
 1870            self.placeholder_text = placeholder_text;
 1871            cx.notify();
 1872        }
 1873    }
 1874
 1875    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1876        self.cursor_shape = cursor_shape;
 1877
 1878        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1879        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1880
 1881        cx.notify();
 1882    }
 1883
 1884    pub fn set_current_line_highlight(
 1885        &mut self,
 1886        current_line_highlight: Option<CurrentLineHighlight>,
 1887    ) {
 1888        self.current_line_highlight = current_line_highlight;
 1889    }
 1890
 1891    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1892        self.collapse_matches = collapse_matches;
 1893    }
 1894
 1895    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1896        let buffers = self.buffer.read(cx).all_buffers();
 1897        let Some(project) = self.project.as_ref() else {
 1898            return;
 1899        };
 1900        project.update(cx, |project, cx| {
 1901            for buffer in buffers {
 1902                self.registered_buffers
 1903                    .entry(buffer.read(cx).remote_id())
 1904                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1905            }
 1906        })
 1907    }
 1908
 1909    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1910        if self.collapse_matches {
 1911            return range.start..range.start;
 1912        }
 1913        range.clone()
 1914    }
 1915
 1916    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1917        if self.display_map.read(cx).clip_at_line_ends != clip {
 1918            self.display_map
 1919                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1920        }
 1921    }
 1922
 1923    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1924        self.input_enabled = input_enabled;
 1925    }
 1926
 1927    pub fn set_inline_completions_hidden_for_vim_mode(
 1928        &mut self,
 1929        hidden: bool,
 1930        window: &mut Window,
 1931        cx: &mut Context<Self>,
 1932    ) {
 1933        if hidden != self.inline_completions_hidden_for_vim_mode {
 1934            self.inline_completions_hidden_for_vim_mode = hidden;
 1935            if hidden {
 1936                self.update_visible_inline_completion(window, cx);
 1937            } else {
 1938                self.refresh_inline_completion(true, false, window, cx);
 1939            }
 1940        }
 1941    }
 1942
 1943    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1944        self.menu_inline_completions_policy = value;
 1945    }
 1946
 1947    pub fn set_autoindent(&mut self, autoindent: bool) {
 1948        if autoindent {
 1949            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1950        } else {
 1951            self.autoindent_mode = None;
 1952        }
 1953    }
 1954
 1955    pub fn read_only(&self, cx: &App) -> bool {
 1956        self.read_only || self.buffer.read(cx).read_only()
 1957    }
 1958
 1959    pub fn set_read_only(&mut self, read_only: bool) {
 1960        self.read_only = read_only;
 1961    }
 1962
 1963    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1964        self.use_autoclose = autoclose;
 1965    }
 1966
 1967    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1968        self.use_auto_surround = auto_surround;
 1969    }
 1970
 1971    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1972        self.auto_replace_emoji_shortcode = auto_replace;
 1973    }
 1974
 1975    pub fn toggle_edit_predictions(
 1976        &mut self,
 1977        _: &ToggleEditPrediction,
 1978        window: &mut Window,
 1979        cx: &mut Context<Self>,
 1980    ) {
 1981        if self.show_inline_completions_override.is_some() {
 1982            self.set_show_edit_predictions(None, window, cx);
 1983        } else {
 1984            let show_edit_predictions = !self.edit_predictions_enabled();
 1985            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1986        }
 1987    }
 1988
 1989    pub fn set_show_edit_predictions(
 1990        &mut self,
 1991        show_edit_predictions: Option<bool>,
 1992        window: &mut Window,
 1993        cx: &mut Context<Self>,
 1994    ) {
 1995        self.show_inline_completions_override = show_edit_predictions;
 1996        self.update_edit_prediction_settings(cx);
 1997
 1998        if let Some(false) = show_edit_predictions {
 1999            self.discard_inline_completion(false, cx);
 2000        } else {
 2001            self.refresh_inline_completion(false, true, window, cx);
 2002        }
 2003    }
 2004
 2005    fn inline_completions_disabled_in_scope(
 2006        &self,
 2007        buffer: &Entity<Buffer>,
 2008        buffer_position: language::Anchor,
 2009        cx: &App,
 2010    ) -> bool {
 2011        let snapshot = buffer.read(cx).snapshot();
 2012        let settings = snapshot.settings_at(buffer_position, cx);
 2013
 2014        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2015            return false;
 2016        };
 2017
 2018        scope.override_name().map_or(false, |scope_name| {
 2019            settings
 2020                .edit_predictions_disabled_in
 2021                .iter()
 2022                .any(|s| s == scope_name)
 2023        })
 2024    }
 2025
 2026    pub fn set_use_modal_editing(&mut self, to: bool) {
 2027        self.use_modal_editing = to;
 2028    }
 2029
 2030    pub fn use_modal_editing(&self) -> bool {
 2031        self.use_modal_editing
 2032    }
 2033
 2034    fn selections_did_change(
 2035        &mut self,
 2036        local: bool,
 2037        old_cursor_position: &Anchor,
 2038        show_completions: bool,
 2039        window: &mut Window,
 2040        cx: &mut Context<Self>,
 2041    ) {
 2042        window.invalidate_character_coordinates();
 2043
 2044        // Copy selections to primary selection buffer
 2045        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2046        if local {
 2047            let selections = self.selections.all::<usize>(cx);
 2048            let buffer_handle = self.buffer.read(cx).read(cx);
 2049
 2050            let mut text = String::new();
 2051            for (index, selection) in selections.iter().enumerate() {
 2052                let text_for_selection = buffer_handle
 2053                    .text_for_range(selection.start..selection.end)
 2054                    .collect::<String>();
 2055
 2056                text.push_str(&text_for_selection);
 2057                if index != selections.len() - 1 {
 2058                    text.push('\n');
 2059                }
 2060            }
 2061
 2062            if !text.is_empty() {
 2063                cx.write_to_primary(ClipboardItem::new_string(text));
 2064            }
 2065        }
 2066
 2067        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2068            self.buffer.update(cx, |buffer, cx| {
 2069                buffer.set_active_selections(
 2070                    &self.selections.disjoint_anchors(),
 2071                    self.selections.line_mode,
 2072                    self.cursor_shape,
 2073                    cx,
 2074                )
 2075            });
 2076        }
 2077        let display_map = self
 2078            .display_map
 2079            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2080        let buffer = &display_map.buffer_snapshot;
 2081        self.add_selections_state = None;
 2082        self.select_next_state = None;
 2083        self.select_prev_state = None;
 2084        self.select_larger_syntax_node_stack.clear();
 2085        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2086        self.snippet_stack
 2087            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2088        self.take_rename(false, window, cx);
 2089
 2090        let new_cursor_position = self.selections.newest_anchor().head();
 2091
 2092        self.push_to_nav_history(
 2093            *old_cursor_position,
 2094            Some(new_cursor_position.to_point(buffer)),
 2095            cx,
 2096        );
 2097
 2098        if local {
 2099            let new_cursor_position = self.selections.newest_anchor().head();
 2100            let mut context_menu = self.context_menu.borrow_mut();
 2101            let completion_menu = match context_menu.as_ref() {
 2102                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2103                _ => {
 2104                    *context_menu = None;
 2105                    None
 2106                }
 2107            };
 2108            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2109                if !self.registered_buffers.contains_key(&buffer_id) {
 2110                    if let Some(project) = self.project.as_ref() {
 2111                        project.update(cx, |project, cx| {
 2112                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2113                                return;
 2114                            };
 2115                            self.registered_buffers.insert(
 2116                                buffer_id,
 2117                                project.register_buffer_with_language_servers(&buffer, cx),
 2118                            );
 2119                        })
 2120                    }
 2121                }
 2122            }
 2123
 2124            if let Some(completion_menu) = completion_menu {
 2125                let cursor_position = new_cursor_position.to_offset(buffer);
 2126                let (word_range, kind) =
 2127                    buffer.surrounding_word(completion_menu.initial_position, true);
 2128                if kind == Some(CharKind::Word)
 2129                    && word_range.to_inclusive().contains(&cursor_position)
 2130                {
 2131                    let mut completion_menu = completion_menu.clone();
 2132                    drop(context_menu);
 2133
 2134                    let query = Self::completion_query(buffer, cursor_position);
 2135                    cx.spawn(move |this, mut cx| async move {
 2136                        completion_menu
 2137                            .filter(query.as_deref(), cx.background_executor().clone())
 2138                            .await;
 2139
 2140                        this.update(&mut cx, |this, cx| {
 2141                            let mut context_menu = this.context_menu.borrow_mut();
 2142                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2143                            else {
 2144                                return;
 2145                            };
 2146
 2147                            if menu.id > completion_menu.id {
 2148                                return;
 2149                            }
 2150
 2151                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2152                            drop(context_menu);
 2153                            cx.notify();
 2154                        })
 2155                    })
 2156                    .detach();
 2157
 2158                    if show_completions {
 2159                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2160                    }
 2161                } else {
 2162                    drop(context_menu);
 2163                    self.hide_context_menu(window, cx);
 2164                }
 2165            } else {
 2166                drop(context_menu);
 2167            }
 2168
 2169            hide_hover(self, cx);
 2170
 2171            if old_cursor_position.to_display_point(&display_map).row()
 2172                != new_cursor_position.to_display_point(&display_map).row()
 2173            {
 2174                self.available_code_actions.take();
 2175            }
 2176            self.refresh_code_actions(window, cx);
 2177            self.refresh_document_highlights(cx);
 2178            self.refresh_selected_text_highlights(window, cx);
 2179            refresh_matching_bracket_highlights(self, window, cx);
 2180            self.update_visible_inline_completion(window, cx);
 2181            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2182            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2183            if self.git_blame_inline_enabled {
 2184                self.start_inline_blame_timer(window, cx);
 2185            }
 2186        }
 2187
 2188        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2189        cx.emit(EditorEvent::SelectionsChanged { local });
 2190
 2191        let selections = &self.selections.disjoint;
 2192        if selections.len() == 1 {
 2193            cx.emit(SearchEvent::ActiveMatchChanged)
 2194        }
 2195        if local
 2196            && self.is_singleton(cx)
 2197            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2198        {
 2199            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2200                let background_executor = cx.background_executor().clone();
 2201                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2202                let snapshot = self.buffer().read(cx).snapshot(cx);
 2203                let selections = selections.clone();
 2204                self.serialize_selections = cx.background_spawn(async move {
 2205                    background_executor.timer(Duration::from_millis(100)).await;
 2206                    let selections = selections
 2207                        .iter()
 2208                        .map(|selection| {
 2209                            (
 2210                                selection.start.to_offset(&snapshot),
 2211                                selection.end.to_offset(&snapshot),
 2212                            )
 2213                        })
 2214                        .collect();
 2215                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2216                        .await
 2217                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2218                        .log_err();
 2219                });
 2220            }
 2221        }
 2222
 2223        cx.notify();
 2224    }
 2225
 2226    pub fn sync_selections(
 2227        &mut self,
 2228        other: Entity<Editor>,
 2229        cx: &mut Context<Self>,
 2230    ) -> gpui::Subscription {
 2231        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2232        self.selections.change_with(cx, |selections| {
 2233            selections.select_anchors(other_selections);
 2234        });
 2235
 2236        let other_subscription =
 2237            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2238                EditorEvent::SelectionsChanged { local: true } => {
 2239                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2240                    if other_selections.is_empty() {
 2241                        return;
 2242                    }
 2243                    this.selections.change_with(cx, |selections| {
 2244                        selections.select_anchors(other_selections);
 2245                    });
 2246                }
 2247                _ => {}
 2248            });
 2249
 2250        let this_subscription =
 2251            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2252                EditorEvent::SelectionsChanged { local: true } => {
 2253                    let these_selections = this.selections.disjoint.to_vec();
 2254                    if these_selections.is_empty() {
 2255                        return;
 2256                    }
 2257                    other.update(cx, |other_editor, cx| {
 2258                        other_editor.selections.change_with(cx, |selections| {
 2259                            selections.select_anchors(these_selections);
 2260                        })
 2261                    });
 2262                }
 2263                _ => {}
 2264            });
 2265
 2266        Subscription::join(other_subscription, this_subscription)
 2267    }
 2268
 2269    pub fn change_selections<R>(
 2270        &mut self,
 2271        autoscroll: Option<Autoscroll>,
 2272        window: &mut Window,
 2273        cx: &mut Context<Self>,
 2274        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2275    ) -> R {
 2276        self.change_selections_inner(autoscroll, true, window, cx, change)
 2277    }
 2278
 2279    fn change_selections_inner<R>(
 2280        &mut self,
 2281        autoscroll: Option<Autoscroll>,
 2282        request_completions: bool,
 2283        window: &mut Window,
 2284        cx: &mut Context<Self>,
 2285        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2286    ) -> R {
 2287        let old_cursor_position = self.selections.newest_anchor().head();
 2288        self.push_to_selection_history();
 2289
 2290        let (changed, result) = self.selections.change_with(cx, change);
 2291
 2292        if changed {
 2293            if let Some(autoscroll) = autoscroll {
 2294                self.request_autoscroll(autoscroll, cx);
 2295            }
 2296            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2297
 2298            if self.should_open_signature_help_automatically(
 2299                &old_cursor_position,
 2300                self.signature_help_state.backspace_pressed(),
 2301                cx,
 2302            ) {
 2303                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2304            }
 2305            self.signature_help_state.set_backspace_pressed(false);
 2306        }
 2307
 2308        result
 2309    }
 2310
 2311    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2312    where
 2313        I: IntoIterator<Item = (Range<S>, T)>,
 2314        S: ToOffset,
 2315        T: Into<Arc<str>>,
 2316    {
 2317        if self.read_only(cx) {
 2318            return;
 2319        }
 2320
 2321        self.buffer
 2322            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2323    }
 2324
 2325    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2326    where
 2327        I: IntoIterator<Item = (Range<S>, T)>,
 2328        S: ToOffset,
 2329        T: Into<Arc<str>>,
 2330    {
 2331        if self.read_only(cx) {
 2332            return;
 2333        }
 2334
 2335        self.buffer.update(cx, |buffer, cx| {
 2336            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2337        });
 2338    }
 2339
 2340    pub fn edit_with_block_indent<I, S, T>(
 2341        &mut self,
 2342        edits: I,
 2343        original_indent_columns: Vec<Option<u32>>,
 2344        cx: &mut Context<Self>,
 2345    ) where
 2346        I: IntoIterator<Item = (Range<S>, T)>,
 2347        S: ToOffset,
 2348        T: Into<Arc<str>>,
 2349    {
 2350        if self.read_only(cx) {
 2351            return;
 2352        }
 2353
 2354        self.buffer.update(cx, |buffer, cx| {
 2355            buffer.edit(
 2356                edits,
 2357                Some(AutoindentMode::Block {
 2358                    original_indent_columns,
 2359                }),
 2360                cx,
 2361            )
 2362        });
 2363    }
 2364
 2365    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2366        self.hide_context_menu(window, cx);
 2367
 2368        match phase {
 2369            SelectPhase::Begin {
 2370                position,
 2371                add,
 2372                click_count,
 2373            } => self.begin_selection(position, add, click_count, window, cx),
 2374            SelectPhase::BeginColumnar {
 2375                position,
 2376                goal_column,
 2377                reset,
 2378            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2379            SelectPhase::Extend {
 2380                position,
 2381                click_count,
 2382            } => self.extend_selection(position, click_count, window, cx),
 2383            SelectPhase::Update {
 2384                position,
 2385                goal_column,
 2386                scroll_delta,
 2387            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2388            SelectPhase::End => self.end_selection(window, cx),
 2389        }
 2390    }
 2391
 2392    fn extend_selection(
 2393        &mut self,
 2394        position: DisplayPoint,
 2395        click_count: usize,
 2396        window: &mut Window,
 2397        cx: &mut Context<Self>,
 2398    ) {
 2399        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2400        let tail = self.selections.newest::<usize>(cx).tail();
 2401        self.begin_selection(position, false, click_count, window, cx);
 2402
 2403        let position = position.to_offset(&display_map, Bias::Left);
 2404        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2405
 2406        let mut pending_selection = self
 2407            .selections
 2408            .pending_anchor()
 2409            .expect("extend_selection not called with pending selection");
 2410        if position >= tail {
 2411            pending_selection.start = tail_anchor;
 2412        } else {
 2413            pending_selection.end = tail_anchor;
 2414            pending_selection.reversed = true;
 2415        }
 2416
 2417        let mut pending_mode = self.selections.pending_mode().unwrap();
 2418        match &mut pending_mode {
 2419            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2420            _ => {}
 2421        }
 2422
 2423        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2424            s.set_pending(pending_selection, pending_mode)
 2425        });
 2426    }
 2427
 2428    fn begin_selection(
 2429        &mut self,
 2430        position: DisplayPoint,
 2431        add: bool,
 2432        click_count: usize,
 2433        window: &mut Window,
 2434        cx: &mut Context<Self>,
 2435    ) {
 2436        if !self.focus_handle.is_focused(window) {
 2437            self.last_focused_descendant = None;
 2438            window.focus(&self.focus_handle);
 2439        }
 2440
 2441        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2442        let buffer = &display_map.buffer_snapshot;
 2443        let newest_selection = self.selections.newest_anchor().clone();
 2444        let position = display_map.clip_point(position, Bias::Left);
 2445
 2446        let start;
 2447        let end;
 2448        let mode;
 2449        let mut auto_scroll;
 2450        match click_count {
 2451            1 => {
 2452                start = buffer.anchor_before(position.to_point(&display_map));
 2453                end = start;
 2454                mode = SelectMode::Character;
 2455                auto_scroll = true;
 2456            }
 2457            2 => {
 2458                let range = movement::surrounding_word(&display_map, position);
 2459                start = buffer.anchor_before(range.start.to_point(&display_map));
 2460                end = buffer.anchor_before(range.end.to_point(&display_map));
 2461                mode = SelectMode::Word(start..end);
 2462                auto_scroll = true;
 2463            }
 2464            3 => {
 2465                let position = display_map
 2466                    .clip_point(position, Bias::Left)
 2467                    .to_point(&display_map);
 2468                let line_start = display_map.prev_line_boundary(position).0;
 2469                let next_line_start = buffer.clip_point(
 2470                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2471                    Bias::Left,
 2472                );
 2473                start = buffer.anchor_before(line_start);
 2474                end = buffer.anchor_before(next_line_start);
 2475                mode = SelectMode::Line(start..end);
 2476                auto_scroll = true;
 2477            }
 2478            _ => {
 2479                start = buffer.anchor_before(0);
 2480                end = buffer.anchor_before(buffer.len());
 2481                mode = SelectMode::All;
 2482                auto_scroll = false;
 2483            }
 2484        }
 2485        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2486
 2487        let point_to_delete: Option<usize> = {
 2488            let selected_points: Vec<Selection<Point>> =
 2489                self.selections.disjoint_in_range(start..end, cx);
 2490
 2491            if !add || click_count > 1 {
 2492                None
 2493            } else if !selected_points.is_empty() {
 2494                Some(selected_points[0].id)
 2495            } else {
 2496                let clicked_point_already_selected =
 2497                    self.selections.disjoint.iter().find(|selection| {
 2498                        selection.start.to_point(buffer) == start.to_point(buffer)
 2499                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2500                    });
 2501
 2502                clicked_point_already_selected.map(|selection| selection.id)
 2503            }
 2504        };
 2505
 2506        let selections_count = self.selections.count();
 2507
 2508        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2509            if let Some(point_to_delete) = point_to_delete {
 2510                s.delete(point_to_delete);
 2511
 2512                if selections_count == 1 {
 2513                    s.set_pending_anchor_range(start..end, mode);
 2514                }
 2515            } else {
 2516                if !add {
 2517                    s.clear_disjoint();
 2518                } else if click_count > 1 {
 2519                    s.delete(newest_selection.id)
 2520                }
 2521
 2522                s.set_pending_anchor_range(start..end, mode);
 2523            }
 2524        });
 2525    }
 2526
 2527    fn begin_columnar_selection(
 2528        &mut self,
 2529        position: DisplayPoint,
 2530        goal_column: u32,
 2531        reset: bool,
 2532        window: &mut Window,
 2533        cx: &mut Context<Self>,
 2534    ) {
 2535        if !self.focus_handle.is_focused(window) {
 2536            self.last_focused_descendant = None;
 2537            window.focus(&self.focus_handle);
 2538        }
 2539
 2540        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2541
 2542        if reset {
 2543            let pointer_position = display_map
 2544                .buffer_snapshot
 2545                .anchor_before(position.to_point(&display_map));
 2546
 2547            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2548                s.clear_disjoint();
 2549                s.set_pending_anchor_range(
 2550                    pointer_position..pointer_position,
 2551                    SelectMode::Character,
 2552                );
 2553            });
 2554        }
 2555
 2556        let tail = self.selections.newest::<Point>(cx).tail();
 2557        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2558
 2559        if !reset {
 2560            self.select_columns(
 2561                tail.to_display_point(&display_map),
 2562                position,
 2563                goal_column,
 2564                &display_map,
 2565                window,
 2566                cx,
 2567            );
 2568        }
 2569    }
 2570
 2571    fn update_selection(
 2572        &mut self,
 2573        position: DisplayPoint,
 2574        goal_column: u32,
 2575        scroll_delta: gpui::Point<f32>,
 2576        window: &mut Window,
 2577        cx: &mut Context<Self>,
 2578    ) {
 2579        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2580
 2581        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2582            let tail = tail.to_display_point(&display_map);
 2583            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2584        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2585            let buffer = self.buffer.read(cx).snapshot(cx);
 2586            let head;
 2587            let tail;
 2588            let mode = self.selections.pending_mode().unwrap();
 2589            match &mode {
 2590                SelectMode::Character => {
 2591                    head = position.to_point(&display_map);
 2592                    tail = pending.tail().to_point(&buffer);
 2593                }
 2594                SelectMode::Word(original_range) => {
 2595                    let original_display_range = original_range.start.to_display_point(&display_map)
 2596                        ..original_range.end.to_display_point(&display_map);
 2597                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2598                        ..original_display_range.end.to_point(&display_map);
 2599                    if movement::is_inside_word(&display_map, position)
 2600                        || original_display_range.contains(&position)
 2601                    {
 2602                        let word_range = movement::surrounding_word(&display_map, position);
 2603                        if word_range.start < original_display_range.start {
 2604                            head = word_range.start.to_point(&display_map);
 2605                        } else {
 2606                            head = word_range.end.to_point(&display_map);
 2607                        }
 2608                    } else {
 2609                        head = position.to_point(&display_map);
 2610                    }
 2611
 2612                    if head <= original_buffer_range.start {
 2613                        tail = original_buffer_range.end;
 2614                    } else {
 2615                        tail = original_buffer_range.start;
 2616                    }
 2617                }
 2618                SelectMode::Line(original_range) => {
 2619                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2620
 2621                    let position = display_map
 2622                        .clip_point(position, Bias::Left)
 2623                        .to_point(&display_map);
 2624                    let line_start = display_map.prev_line_boundary(position).0;
 2625                    let next_line_start = buffer.clip_point(
 2626                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2627                        Bias::Left,
 2628                    );
 2629
 2630                    if line_start < original_range.start {
 2631                        head = line_start
 2632                    } else {
 2633                        head = next_line_start
 2634                    }
 2635
 2636                    if head <= original_range.start {
 2637                        tail = original_range.end;
 2638                    } else {
 2639                        tail = original_range.start;
 2640                    }
 2641                }
 2642                SelectMode::All => {
 2643                    return;
 2644                }
 2645            };
 2646
 2647            if head < tail {
 2648                pending.start = buffer.anchor_before(head);
 2649                pending.end = buffer.anchor_before(tail);
 2650                pending.reversed = true;
 2651            } else {
 2652                pending.start = buffer.anchor_before(tail);
 2653                pending.end = buffer.anchor_before(head);
 2654                pending.reversed = false;
 2655            }
 2656
 2657            self.change_selections(None, window, cx, |s| {
 2658                s.set_pending(pending, mode);
 2659            });
 2660        } else {
 2661            log::error!("update_selection dispatched with no pending selection");
 2662            return;
 2663        }
 2664
 2665        self.apply_scroll_delta(scroll_delta, window, cx);
 2666        cx.notify();
 2667    }
 2668
 2669    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2670        self.columnar_selection_tail.take();
 2671        if self.selections.pending_anchor().is_some() {
 2672            let selections = self.selections.all::<usize>(cx);
 2673            self.change_selections(None, window, cx, |s| {
 2674                s.select(selections);
 2675                s.clear_pending();
 2676            });
 2677        }
 2678    }
 2679
 2680    fn select_columns(
 2681        &mut self,
 2682        tail: DisplayPoint,
 2683        head: DisplayPoint,
 2684        goal_column: u32,
 2685        display_map: &DisplaySnapshot,
 2686        window: &mut Window,
 2687        cx: &mut Context<Self>,
 2688    ) {
 2689        let start_row = cmp::min(tail.row(), head.row());
 2690        let end_row = cmp::max(tail.row(), head.row());
 2691        let start_column = cmp::min(tail.column(), goal_column);
 2692        let end_column = cmp::max(tail.column(), goal_column);
 2693        let reversed = start_column < tail.column();
 2694
 2695        let selection_ranges = (start_row.0..=end_row.0)
 2696            .map(DisplayRow)
 2697            .filter_map(|row| {
 2698                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2699                    let start = display_map
 2700                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2701                        .to_point(display_map);
 2702                    let end = display_map
 2703                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2704                        .to_point(display_map);
 2705                    if reversed {
 2706                        Some(end..start)
 2707                    } else {
 2708                        Some(start..end)
 2709                    }
 2710                } else {
 2711                    None
 2712                }
 2713            })
 2714            .collect::<Vec<_>>();
 2715
 2716        self.change_selections(None, window, cx, |s| {
 2717            s.select_ranges(selection_ranges);
 2718        });
 2719        cx.notify();
 2720    }
 2721
 2722    pub fn has_pending_nonempty_selection(&self) -> bool {
 2723        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2724            Some(Selection { start, end, .. }) => start != end,
 2725            None => false,
 2726        };
 2727
 2728        pending_nonempty_selection
 2729            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2730    }
 2731
 2732    pub fn has_pending_selection(&self) -> bool {
 2733        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2734    }
 2735
 2736    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2737        self.selection_mark_mode = false;
 2738
 2739        if self.clear_expanded_diff_hunks(cx) {
 2740            cx.notify();
 2741            return;
 2742        }
 2743        if self.dismiss_menus_and_popups(true, window, cx) {
 2744            return;
 2745        }
 2746
 2747        if self.mode == EditorMode::Full
 2748            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2749        {
 2750            return;
 2751        }
 2752
 2753        cx.propagate();
 2754    }
 2755
 2756    pub fn dismiss_menus_and_popups(
 2757        &mut self,
 2758        is_user_requested: bool,
 2759        window: &mut Window,
 2760        cx: &mut Context<Self>,
 2761    ) -> bool {
 2762        if self.take_rename(false, window, cx).is_some() {
 2763            return true;
 2764        }
 2765
 2766        if hide_hover(self, cx) {
 2767            return true;
 2768        }
 2769
 2770        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2771            return true;
 2772        }
 2773
 2774        if self.hide_context_menu(window, cx).is_some() {
 2775            return true;
 2776        }
 2777
 2778        if self.mouse_context_menu.take().is_some() {
 2779            return true;
 2780        }
 2781
 2782        if is_user_requested && self.discard_inline_completion(true, cx) {
 2783            return true;
 2784        }
 2785
 2786        if self.snippet_stack.pop().is_some() {
 2787            return true;
 2788        }
 2789
 2790        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2791            self.dismiss_diagnostics(cx);
 2792            return true;
 2793        }
 2794
 2795        false
 2796    }
 2797
 2798    fn linked_editing_ranges_for(
 2799        &self,
 2800        selection: Range<text::Anchor>,
 2801        cx: &App,
 2802    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2803        if self.linked_edit_ranges.is_empty() {
 2804            return None;
 2805        }
 2806        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2807            selection.end.buffer_id.and_then(|end_buffer_id| {
 2808                if selection.start.buffer_id != Some(end_buffer_id) {
 2809                    return None;
 2810                }
 2811                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2812                let snapshot = buffer.read(cx).snapshot();
 2813                self.linked_edit_ranges
 2814                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2815                    .map(|ranges| (ranges, snapshot, buffer))
 2816            })?;
 2817        use text::ToOffset as TO;
 2818        // find offset from the start of current range to current cursor position
 2819        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2820
 2821        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2822        let start_difference = start_offset - start_byte_offset;
 2823        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2824        let end_difference = end_offset - start_byte_offset;
 2825        // Current range has associated linked ranges.
 2826        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2827        for range in linked_ranges.iter() {
 2828            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2829            let end_offset = start_offset + end_difference;
 2830            let start_offset = start_offset + start_difference;
 2831            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2832                continue;
 2833            }
 2834            if self.selections.disjoint_anchor_ranges().any(|s| {
 2835                if s.start.buffer_id != selection.start.buffer_id
 2836                    || s.end.buffer_id != selection.end.buffer_id
 2837                {
 2838                    return false;
 2839                }
 2840                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2841                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2842            }) {
 2843                continue;
 2844            }
 2845            let start = buffer_snapshot.anchor_after(start_offset);
 2846            let end = buffer_snapshot.anchor_after(end_offset);
 2847            linked_edits
 2848                .entry(buffer.clone())
 2849                .or_default()
 2850                .push(start..end);
 2851        }
 2852        Some(linked_edits)
 2853    }
 2854
 2855    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2856        let text: Arc<str> = text.into();
 2857
 2858        if self.read_only(cx) {
 2859            return;
 2860        }
 2861
 2862        let selections = self.selections.all_adjusted(cx);
 2863        let mut bracket_inserted = false;
 2864        let mut edits = Vec::new();
 2865        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2866        let mut new_selections = Vec::with_capacity(selections.len());
 2867        let mut new_autoclose_regions = Vec::new();
 2868        let snapshot = self.buffer.read(cx).read(cx);
 2869
 2870        for (selection, autoclose_region) in
 2871            self.selections_with_autoclose_regions(selections, &snapshot)
 2872        {
 2873            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2874                // Determine if the inserted text matches the opening or closing
 2875                // bracket of any of this language's bracket pairs.
 2876                let mut bracket_pair = None;
 2877                let mut is_bracket_pair_start = false;
 2878                let mut is_bracket_pair_end = false;
 2879                if !text.is_empty() {
 2880                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2881                    //  and they are removing the character that triggered IME popup.
 2882                    for (pair, enabled) in scope.brackets() {
 2883                        if !pair.close && !pair.surround {
 2884                            continue;
 2885                        }
 2886
 2887                        if enabled && pair.start.ends_with(text.as_ref()) {
 2888                            let prefix_len = pair.start.len() - text.len();
 2889                            let preceding_text_matches_prefix = prefix_len == 0
 2890                                || (selection.start.column >= (prefix_len as u32)
 2891                                    && snapshot.contains_str_at(
 2892                                        Point::new(
 2893                                            selection.start.row,
 2894                                            selection.start.column - (prefix_len as u32),
 2895                                        ),
 2896                                        &pair.start[..prefix_len],
 2897                                    ));
 2898                            if preceding_text_matches_prefix {
 2899                                bracket_pair = Some(pair.clone());
 2900                                is_bracket_pair_start = true;
 2901                                break;
 2902                            }
 2903                        }
 2904                        if pair.end.as_str() == text.as_ref() {
 2905                            bracket_pair = Some(pair.clone());
 2906                            is_bracket_pair_end = true;
 2907                            break;
 2908                        }
 2909                    }
 2910                }
 2911
 2912                if let Some(bracket_pair) = bracket_pair {
 2913                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 2914                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2915                    let auto_surround =
 2916                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2917                    if selection.is_empty() {
 2918                        if is_bracket_pair_start {
 2919                            // If the inserted text is a suffix of an opening bracket and the
 2920                            // selection is preceded by the rest of the opening bracket, then
 2921                            // insert the closing bracket.
 2922                            let following_text_allows_autoclose = snapshot
 2923                                .chars_at(selection.start)
 2924                                .next()
 2925                                .map_or(true, |c| scope.should_autoclose_before(c));
 2926
 2927                            let preceding_text_allows_autoclose = selection.start.column == 0
 2928                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 2929                                    true,
 2930                                    |c| {
 2931                                        bracket_pair.start != bracket_pair.end
 2932                                            || !snapshot
 2933                                                .char_classifier_at(selection.start)
 2934                                                .is_word(c)
 2935                                    },
 2936                                );
 2937
 2938                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2939                                && bracket_pair.start.len() == 1
 2940                            {
 2941                                let target = bracket_pair.start.chars().next().unwrap();
 2942                                let current_line_count = snapshot
 2943                                    .reversed_chars_at(selection.start)
 2944                                    .take_while(|&c| c != '\n')
 2945                                    .filter(|&c| c == target)
 2946                                    .count();
 2947                                current_line_count % 2 == 1
 2948                            } else {
 2949                                false
 2950                            };
 2951
 2952                            if autoclose
 2953                                && bracket_pair.close
 2954                                && following_text_allows_autoclose
 2955                                && preceding_text_allows_autoclose
 2956                                && !is_closing_quote
 2957                            {
 2958                                let anchor = snapshot.anchor_before(selection.end);
 2959                                new_selections.push((selection.map(|_| anchor), text.len()));
 2960                                new_autoclose_regions.push((
 2961                                    anchor,
 2962                                    text.len(),
 2963                                    selection.id,
 2964                                    bracket_pair.clone(),
 2965                                ));
 2966                                edits.push((
 2967                                    selection.range(),
 2968                                    format!("{}{}", text, bracket_pair.end).into(),
 2969                                ));
 2970                                bracket_inserted = true;
 2971                                continue;
 2972                            }
 2973                        }
 2974
 2975                        if let Some(region) = autoclose_region {
 2976                            // If the selection is followed by an auto-inserted closing bracket,
 2977                            // then don't insert that closing bracket again; just move the selection
 2978                            // past the closing bracket.
 2979                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2980                                && text.as_ref() == region.pair.end.as_str();
 2981                            if should_skip {
 2982                                let anchor = snapshot.anchor_after(selection.end);
 2983                                new_selections
 2984                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2985                                continue;
 2986                            }
 2987                        }
 2988
 2989                        let always_treat_brackets_as_autoclosed = snapshot
 2990                            .language_settings_at(selection.start, cx)
 2991                            .always_treat_brackets_as_autoclosed;
 2992                        if always_treat_brackets_as_autoclosed
 2993                            && is_bracket_pair_end
 2994                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2995                        {
 2996                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2997                            // and the inserted text is a closing bracket and the selection is followed
 2998                            // by the closing bracket then move the selection past the closing bracket.
 2999                            let anchor = snapshot.anchor_after(selection.end);
 3000                            new_selections.push((selection.map(|_| anchor), text.len()));
 3001                            continue;
 3002                        }
 3003                    }
 3004                    // If an opening bracket is 1 character long and is typed while
 3005                    // text is selected, then surround that text with the bracket pair.
 3006                    else if auto_surround
 3007                        && bracket_pair.surround
 3008                        && is_bracket_pair_start
 3009                        && bracket_pair.start.chars().count() == 1
 3010                    {
 3011                        edits.push((selection.start..selection.start, text.clone()));
 3012                        edits.push((
 3013                            selection.end..selection.end,
 3014                            bracket_pair.end.as_str().into(),
 3015                        ));
 3016                        bracket_inserted = true;
 3017                        new_selections.push((
 3018                            Selection {
 3019                                id: selection.id,
 3020                                start: snapshot.anchor_after(selection.start),
 3021                                end: snapshot.anchor_before(selection.end),
 3022                                reversed: selection.reversed,
 3023                                goal: selection.goal,
 3024                            },
 3025                            0,
 3026                        ));
 3027                        continue;
 3028                    }
 3029                }
 3030            }
 3031
 3032            if self.auto_replace_emoji_shortcode
 3033                && selection.is_empty()
 3034                && text.as_ref().ends_with(':')
 3035            {
 3036                if let Some(possible_emoji_short_code) =
 3037                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3038                {
 3039                    if !possible_emoji_short_code.is_empty() {
 3040                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3041                            let emoji_shortcode_start = Point::new(
 3042                                selection.start.row,
 3043                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3044                            );
 3045
 3046                            // Remove shortcode from buffer
 3047                            edits.push((
 3048                                emoji_shortcode_start..selection.start,
 3049                                "".to_string().into(),
 3050                            ));
 3051                            new_selections.push((
 3052                                Selection {
 3053                                    id: selection.id,
 3054                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3055                                    end: snapshot.anchor_before(selection.start),
 3056                                    reversed: selection.reversed,
 3057                                    goal: selection.goal,
 3058                                },
 3059                                0,
 3060                            ));
 3061
 3062                            // Insert emoji
 3063                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3064                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3065                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3066
 3067                            continue;
 3068                        }
 3069                    }
 3070                }
 3071            }
 3072
 3073            // If not handling any auto-close operation, then just replace the selected
 3074            // text with the given input and move the selection to the end of the
 3075            // newly inserted text.
 3076            let anchor = snapshot.anchor_after(selection.end);
 3077            if !self.linked_edit_ranges.is_empty() {
 3078                let start_anchor = snapshot.anchor_before(selection.start);
 3079
 3080                let is_word_char = text.chars().next().map_or(true, |char| {
 3081                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3082                    classifier.is_word(char)
 3083                });
 3084
 3085                if is_word_char {
 3086                    if let Some(ranges) = self
 3087                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3088                    {
 3089                        for (buffer, edits) in ranges {
 3090                            linked_edits
 3091                                .entry(buffer.clone())
 3092                                .or_default()
 3093                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3094                        }
 3095                    }
 3096                }
 3097            }
 3098
 3099            new_selections.push((selection.map(|_| anchor), 0));
 3100            edits.push((selection.start..selection.end, text.clone()));
 3101        }
 3102
 3103        drop(snapshot);
 3104
 3105        self.transact(window, cx, |this, window, cx| {
 3106            let initial_buffer_versions =
 3107                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3108
 3109            this.buffer.update(cx, |buffer, cx| {
 3110                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3111            });
 3112            for (buffer, edits) in linked_edits {
 3113                buffer.update(cx, |buffer, cx| {
 3114                    let snapshot = buffer.snapshot();
 3115                    let edits = edits
 3116                        .into_iter()
 3117                        .map(|(range, text)| {
 3118                            use text::ToPoint as TP;
 3119                            let end_point = TP::to_point(&range.end, &snapshot);
 3120                            let start_point = TP::to_point(&range.start, &snapshot);
 3121                            (start_point..end_point, text)
 3122                        })
 3123                        .sorted_by_key(|(range, _)| range.start)
 3124                        .collect::<Vec<_>>();
 3125                    buffer.edit(edits, None, cx);
 3126                })
 3127            }
 3128            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3129            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3130            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3131            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3132                .zip(new_selection_deltas)
 3133                .map(|(selection, delta)| Selection {
 3134                    id: selection.id,
 3135                    start: selection.start + delta,
 3136                    end: selection.end + delta,
 3137                    reversed: selection.reversed,
 3138                    goal: SelectionGoal::None,
 3139                })
 3140                .collect::<Vec<_>>();
 3141
 3142            let mut i = 0;
 3143            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3144                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3145                let start = map.buffer_snapshot.anchor_before(position);
 3146                let end = map.buffer_snapshot.anchor_after(position);
 3147                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3148                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3149                        Ordering::Less => i += 1,
 3150                        Ordering::Greater => break,
 3151                        Ordering::Equal => {
 3152                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3153                                Ordering::Less => i += 1,
 3154                                Ordering::Equal => break,
 3155                                Ordering::Greater => break,
 3156                            }
 3157                        }
 3158                    }
 3159                }
 3160                this.autoclose_regions.insert(
 3161                    i,
 3162                    AutocloseRegion {
 3163                        selection_id,
 3164                        range: start..end,
 3165                        pair,
 3166                    },
 3167                );
 3168            }
 3169
 3170            let had_active_inline_completion = this.has_active_inline_completion();
 3171            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3172                s.select(new_selections)
 3173            });
 3174
 3175            if !bracket_inserted {
 3176                if let Some(on_type_format_task) =
 3177                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3178                {
 3179                    on_type_format_task.detach_and_log_err(cx);
 3180                }
 3181            }
 3182
 3183            let editor_settings = EditorSettings::get_global(cx);
 3184            if bracket_inserted
 3185                && (editor_settings.auto_signature_help
 3186                    || editor_settings.show_signature_help_after_edits)
 3187            {
 3188                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3189            }
 3190
 3191            let trigger_in_words =
 3192                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3193            if this.hard_wrap.is_some() {
 3194                let latest: Range<Point> = this.selections.newest(cx).range();
 3195                if latest.is_empty()
 3196                    && this
 3197                        .buffer()
 3198                        .read(cx)
 3199                        .snapshot(cx)
 3200                        .line_len(MultiBufferRow(latest.start.row))
 3201                        == latest.start.column
 3202                {
 3203                    this.rewrap_impl(true, cx)
 3204                }
 3205            }
 3206            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3207            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3208            this.refresh_inline_completion(true, false, window, cx);
 3209            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3210        });
 3211    }
 3212
 3213    fn find_possible_emoji_shortcode_at_position(
 3214        snapshot: &MultiBufferSnapshot,
 3215        position: Point,
 3216    ) -> Option<String> {
 3217        let mut chars = Vec::new();
 3218        let mut found_colon = false;
 3219        for char in snapshot.reversed_chars_at(position).take(100) {
 3220            // Found a possible emoji shortcode in the middle of the buffer
 3221            if found_colon {
 3222                if char.is_whitespace() {
 3223                    chars.reverse();
 3224                    return Some(chars.iter().collect());
 3225                }
 3226                // If the previous character is not a whitespace, we are in the middle of a word
 3227                // and we only want to complete the shortcode if the word is made up of other emojis
 3228                let mut containing_word = String::new();
 3229                for ch in snapshot
 3230                    .reversed_chars_at(position)
 3231                    .skip(chars.len() + 1)
 3232                    .take(100)
 3233                {
 3234                    if ch.is_whitespace() {
 3235                        break;
 3236                    }
 3237                    containing_word.push(ch);
 3238                }
 3239                let containing_word = containing_word.chars().rev().collect::<String>();
 3240                if util::word_consists_of_emojis(containing_word.as_str()) {
 3241                    chars.reverse();
 3242                    return Some(chars.iter().collect());
 3243                }
 3244            }
 3245
 3246            if char.is_whitespace() || !char.is_ascii() {
 3247                return None;
 3248            }
 3249            if char == ':' {
 3250                found_colon = true;
 3251            } else {
 3252                chars.push(char);
 3253            }
 3254        }
 3255        // Found a possible emoji shortcode at the beginning of the buffer
 3256        chars.reverse();
 3257        Some(chars.iter().collect())
 3258    }
 3259
 3260    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3261        self.transact(window, cx, |this, window, cx| {
 3262            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3263                let selections = this.selections.all::<usize>(cx);
 3264                let multi_buffer = this.buffer.read(cx);
 3265                let buffer = multi_buffer.snapshot(cx);
 3266                selections
 3267                    .iter()
 3268                    .map(|selection| {
 3269                        let start_point = selection.start.to_point(&buffer);
 3270                        let mut indent =
 3271                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3272                        indent.len = cmp::min(indent.len, start_point.column);
 3273                        let start = selection.start;
 3274                        let end = selection.end;
 3275                        let selection_is_empty = start == end;
 3276                        let language_scope = buffer.language_scope_at(start);
 3277                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3278                            &language_scope
 3279                        {
 3280                            let insert_extra_newline =
 3281                                insert_extra_newline_brackets(&buffer, start..end, language)
 3282                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3283
 3284                            // Comment extension on newline is allowed only for cursor selections
 3285                            let comment_delimiter = maybe!({
 3286                                if !selection_is_empty {
 3287                                    return None;
 3288                                }
 3289
 3290                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3291                                    return None;
 3292                                }
 3293
 3294                                let delimiters = language.line_comment_prefixes();
 3295                                let max_len_of_delimiter =
 3296                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3297                                let (snapshot, range) =
 3298                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3299
 3300                                let mut index_of_first_non_whitespace = 0;
 3301                                let comment_candidate = snapshot
 3302                                    .chars_for_range(range)
 3303                                    .skip_while(|c| {
 3304                                        let should_skip = c.is_whitespace();
 3305                                        if should_skip {
 3306                                            index_of_first_non_whitespace += 1;
 3307                                        }
 3308                                        should_skip
 3309                                    })
 3310                                    .take(max_len_of_delimiter)
 3311                                    .collect::<String>();
 3312                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3313                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3314                                })?;
 3315                                let cursor_is_placed_after_comment_marker =
 3316                                    index_of_first_non_whitespace + comment_prefix.len()
 3317                                        <= start_point.column as usize;
 3318                                if cursor_is_placed_after_comment_marker {
 3319                                    Some(comment_prefix.clone())
 3320                                } else {
 3321                                    None
 3322                                }
 3323                            });
 3324                            (comment_delimiter, insert_extra_newline)
 3325                        } else {
 3326                            (None, false)
 3327                        };
 3328
 3329                        let capacity_for_delimiter = comment_delimiter
 3330                            .as_deref()
 3331                            .map(str::len)
 3332                            .unwrap_or_default();
 3333                        let mut new_text =
 3334                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3335                        new_text.push('\n');
 3336                        new_text.extend(indent.chars());
 3337                        if let Some(delimiter) = &comment_delimiter {
 3338                            new_text.push_str(delimiter);
 3339                        }
 3340                        if insert_extra_newline {
 3341                            new_text = new_text.repeat(2);
 3342                        }
 3343
 3344                        let anchor = buffer.anchor_after(end);
 3345                        let new_selection = selection.map(|_| anchor);
 3346                        (
 3347                            (start..end, new_text),
 3348                            (insert_extra_newline, new_selection),
 3349                        )
 3350                    })
 3351                    .unzip()
 3352            };
 3353
 3354            this.edit_with_autoindent(edits, cx);
 3355            let buffer = this.buffer.read(cx).snapshot(cx);
 3356            let new_selections = selection_fixup_info
 3357                .into_iter()
 3358                .map(|(extra_newline_inserted, new_selection)| {
 3359                    let mut cursor = new_selection.end.to_point(&buffer);
 3360                    if extra_newline_inserted {
 3361                        cursor.row -= 1;
 3362                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3363                    }
 3364                    new_selection.map(|_| cursor)
 3365                })
 3366                .collect();
 3367
 3368            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3369                s.select(new_selections)
 3370            });
 3371            this.refresh_inline_completion(true, false, window, cx);
 3372        });
 3373    }
 3374
 3375    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3376        let buffer = self.buffer.read(cx);
 3377        let snapshot = buffer.snapshot(cx);
 3378
 3379        let mut edits = Vec::new();
 3380        let mut rows = Vec::new();
 3381
 3382        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3383            let cursor = selection.head();
 3384            let row = cursor.row;
 3385
 3386            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3387
 3388            let newline = "\n".to_string();
 3389            edits.push((start_of_line..start_of_line, newline));
 3390
 3391            rows.push(row + rows_inserted as u32);
 3392        }
 3393
 3394        self.transact(window, cx, |editor, window, cx| {
 3395            editor.edit(edits, cx);
 3396
 3397            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3398                let mut index = 0;
 3399                s.move_cursors_with(|map, _, _| {
 3400                    let row = rows[index];
 3401                    index += 1;
 3402
 3403                    let point = Point::new(row, 0);
 3404                    let boundary = map.next_line_boundary(point).1;
 3405                    let clipped = map.clip_point(boundary, Bias::Left);
 3406
 3407                    (clipped, SelectionGoal::None)
 3408                });
 3409            });
 3410
 3411            let mut indent_edits = Vec::new();
 3412            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3413            for row in rows {
 3414                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3415                for (row, indent) in indents {
 3416                    if indent.len == 0 {
 3417                        continue;
 3418                    }
 3419
 3420                    let text = match indent.kind {
 3421                        IndentKind::Space => " ".repeat(indent.len as usize),
 3422                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3423                    };
 3424                    let point = Point::new(row.0, 0);
 3425                    indent_edits.push((point..point, text));
 3426                }
 3427            }
 3428            editor.edit(indent_edits, cx);
 3429        });
 3430    }
 3431
 3432    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3433        let buffer = self.buffer.read(cx);
 3434        let snapshot = buffer.snapshot(cx);
 3435
 3436        let mut edits = Vec::new();
 3437        let mut rows = Vec::new();
 3438        let mut rows_inserted = 0;
 3439
 3440        for selection in self.selections.all_adjusted(cx) {
 3441            let cursor = selection.head();
 3442            let row = cursor.row;
 3443
 3444            let point = Point::new(row + 1, 0);
 3445            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3446
 3447            let newline = "\n".to_string();
 3448            edits.push((start_of_line..start_of_line, newline));
 3449
 3450            rows_inserted += 1;
 3451            rows.push(row + rows_inserted);
 3452        }
 3453
 3454        self.transact(window, cx, |editor, window, cx| {
 3455            editor.edit(edits, cx);
 3456
 3457            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3458                let mut index = 0;
 3459                s.move_cursors_with(|map, _, _| {
 3460                    let row = rows[index];
 3461                    index += 1;
 3462
 3463                    let point = Point::new(row, 0);
 3464                    let boundary = map.next_line_boundary(point).1;
 3465                    let clipped = map.clip_point(boundary, Bias::Left);
 3466
 3467                    (clipped, SelectionGoal::None)
 3468                });
 3469            });
 3470
 3471            let mut indent_edits = Vec::new();
 3472            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3473            for row in rows {
 3474                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3475                for (row, indent) in indents {
 3476                    if indent.len == 0 {
 3477                        continue;
 3478                    }
 3479
 3480                    let text = match indent.kind {
 3481                        IndentKind::Space => " ".repeat(indent.len as usize),
 3482                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3483                    };
 3484                    let point = Point::new(row.0, 0);
 3485                    indent_edits.push((point..point, text));
 3486                }
 3487            }
 3488            editor.edit(indent_edits, cx);
 3489        });
 3490    }
 3491
 3492    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3493        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3494            original_indent_columns: Vec::new(),
 3495        });
 3496        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3497    }
 3498
 3499    fn insert_with_autoindent_mode(
 3500        &mut self,
 3501        text: &str,
 3502        autoindent_mode: Option<AutoindentMode>,
 3503        window: &mut Window,
 3504        cx: &mut Context<Self>,
 3505    ) {
 3506        if self.read_only(cx) {
 3507            return;
 3508        }
 3509
 3510        let text: Arc<str> = text.into();
 3511        self.transact(window, cx, |this, window, cx| {
 3512            let old_selections = this.selections.all_adjusted(cx);
 3513            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3514                let anchors = {
 3515                    let snapshot = buffer.read(cx);
 3516                    old_selections
 3517                        .iter()
 3518                        .map(|s| {
 3519                            let anchor = snapshot.anchor_after(s.head());
 3520                            s.map(|_| anchor)
 3521                        })
 3522                        .collect::<Vec<_>>()
 3523                };
 3524                buffer.edit(
 3525                    old_selections
 3526                        .iter()
 3527                        .map(|s| (s.start..s.end, text.clone())),
 3528                    autoindent_mode,
 3529                    cx,
 3530                );
 3531                anchors
 3532            });
 3533
 3534            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3535                s.select_anchors(selection_anchors);
 3536            });
 3537
 3538            cx.notify();
 3539        });
 3540    }
 3541
 3542    fn trigger_completion_on_input(
 3543        &mut self,
 3544        text: &str,
 3545        trigger_in_words: bool,
 3546        window: &mut Window,
 3547        cx: &mut Context<Self>,
 3548    ) {
 3549        let ignore_completion_provider = self
 3550            .context_menu
 3551            .borrow()
 3552            .as_ref()
 3553            .map(|menu| match menu {
 3554                CodeContextMenu::Completions(completions_menu) => {
 3555                    completions_menu.ignore_completion_provider
 3556                }
 3557                CodeContextMenu::CodeActions(_) => false,
 3558            })
 3559            .unwrap_or(false);
 3560
 3561        if ignore_completion_provider {
 3562            self.show_word_completions(&ShowWordCompletions, window, cx);
 3563        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 3564            self.show_completions(
 3565                &ShowCompletions {
 3566                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3567                },
 3568                window,
 3569                cx,
 3570            );
 3571        } else {
 3572            self.hide_context_menu(window, cx);
 3573        }
 3574    }
 3575
 3576    fn is_completion_trigger(
 3577        &self,
 3578        text: &str,
 3579        trigger_in_words: bool,
 3580        cx: &mut Context<Self>,
 3581    ) -> bool {
 3582        let position = self.selections.newest_anchor().head();
 3583        let multibuffer = self.buffer.read(cx);
 3584        let Some(buffer) = position
 3585            .buffer_id
 3586            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3587        else {
 3588            return false;
 3589        };
 3590
 3591        if let Some(completion_provider) = &self.completion_provider {
 3592            completion_provider.is_completion_trigger(
 3593                &buffer,
 3594                position.text_anchor,
 3595                text,
 3596                trigger_in_words,
 3597                cx,
 3598            )
 3599        } else {
 3600            false
 3601        }
 3602    }
 3603
 3604    /// If any empty selections is touching the start of its innermost containing autoclose
 3605    /// region, expand it to select the brackets.
 3606    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3607        let selections = self.selections.all::<usize>(cx);
 3608        let buffer = self.buffer.read(cx).read(cx);
 3609        let new_selections = self
 3610            .selections_with_autoclose_regions(selections, &buffer)
 3611            .map(|(mut selection, region)| {
 3612                if !selection.is_empty() {
 3613                    return selection;
 3614                }
 3615
 3616                if let Some(region) = region {
 3617                    let mut range = region.range.to_offset(&buffer);
 3618                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3619                        range.start -= region.pair.start.len();
 3620                        if buffer.contains_str_at(range.start, &region.pair.start)
 3621                            && buffer.contains_str_at(range.end, &region.pair.end)
 3622                        {
 3623                            range.end += region.pair.end.len();
 3624                            selection.start = range.start;
 3625                            selection.end = range.end;
 3626
 3627                            return selection;
 3628                        }
 3629                    }
 3630                }
 3631
 3632                let always_treat_brackets_as_autoclosed = buffer
 3633                    .language_settings_at(selection.start, cx)
 3634                    .always_treat_brackets_as_autoclosed;
 3635
 3636                if !always_treat_brackets_as_autoclosed {
 3637                    return selection;
 3638                }
 3639
 3640                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3641                    for (pair, enabled) in scope.brackets() {
 3642                        if !enabled || !pair.close {
 3643                            continue;
 3644                        }
 3645
 3646                        if buffer.contains_str_at(selection.start, &pair.end) {
 3647                            let pair_start_len = pair.start.len();
 3648                            if buffer.contains_str_at(
 3649                                selection.start.saturating_sub(pair_start_len),
 3650                                &pair.start,
 3651                            ) {
 3652                                selection.start -= pair_start_len;
 3653                                selection.end += pair.end.len();
 3654
 3655                                return selection;
 3656                            }
 3657                        }
 3658                    }
 3659                }
 3660
 3661                selection
 3662            })
 3663            .collect();
 3664
 3665        drop(buffer);
 3666        self.change_selections(None, window, cx, |selections| {
 3667            selections.select(new_selections)
 3668        });
 3669    }
 3670
 3671    /// Iterate the given selections, and for each one, find the smallest surrounding
 3672    /// autoclose region. This uses the ordering of the selections and the autoclose
 3673    /// regions to avoid repeated comparisons.
 3674    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3675        &'a self,
 3676        selections: impl IntoIterator<Item = Selection<D>>,
 3677        buffer: &'a MultiBufferSnapshot,
 3678    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3679        let mut i = 0;
 3680        let mut regions = self.autoclose_regions.as_slice();
 3681        selections.into_iter().map(move |selection| {
 3682            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3683
 3684            let mut enclosing = None;
 3685            while let Some(pair_state) = regions.get(i) {
 3686                if pair_state.range.end.to_offset(buffer) < range.start {
 3687                    regions = &regions[i + 1..];
 3688                    i = 0;
 3689                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3690                    break;
 3691                } else {
 3692                    if pair_state.selection_id == selection.id {
 3693                        enclosing = Some(pair_state);
 3694                    }
 3695                    i += 1;
 3696                }
 3697            }
 3698
 3699            (selection, enclosing)
 3700        })
 3701    }
 3702
 3703    /// Remove any autoclose regions that no longer contain their selection.
 3704    fn invalidate_autoclose_regions(
 3705        &mut self,
 3706        mut selections: &[Selection<Anchor>],
 3707        buffer: &MultiBufferSnapshot,
 3708    ) {
 3709        self.autoclose_regions.retain(|state| {
 3710            let mut i = 0;
 3711            while let Some(selection) = selections.get(i) {
 3712                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3713                    selections = &selections[1..];
 3714                    continue;
 3715                }
 3716                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3717                    break;
 3718                }
 3719                if selection.id == state.selection_id {
 3720                    return true;
 3721                } else {
 3722                    i += 1;
 3723                }
 3724            }
 3725            false
 3726        });
 3727    }
 3728
 3729    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3730        let offset = position.to_offset(buffer);
 3731        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3732        if offset > word_range.start && kind == Some(CharKind::Word) {
 3733            Some(
 3734                buffer
 3735                    .text_for_range(word_range.start..offset)
 3736                    .collect::<String>(),
 3737            )
 3738        } else {
 3739            None
 3740        }
 3741    }
 3742
 3743    pub fn toggle_inlay_hints(
 3744        &mut self,
 3745        _: &ToggleInlayHints,
 3746        _: &mut Window,
 3747        cx: &mut Context<Self>,
 3748    ) {
 3749        self.refresh_inlay_hints(
 3750            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 3751            cx,
 3752        );
 3753    }
 3754
 3755    pub fn inlay_hints_enabled(&self) -> bool {
 3756        self.inlay_hint_cache.enabled
 3757    }
 3758
 3759    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3760        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3761            return;
 3762        }
 3763
 3764        let reason_description = reason.description();
 3765        let ignore_debounce = matches!(
 3766            reason,
 3767            InlayHintRefreshReason::SettingsChange(_)
 3768                | InlayHintRefreshReason::Toggle(_)
 3769                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3770                | InlayHintRefreshReason::ModifiersChanged(_)
 3771        );
 3772        let (invalidate_cache, required_languages) = match reason {
 3773            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 3774                match self.inlay_hint_cache.modifiers_override(enabled) {
 3775                    Some(enabled) => {
 3776                        if enabled {
 3777                            (InvalidationStrategy::RefreshRequested, None)
 3778                        } else {
 3779                            self.splice_inlays(
 3780                                &self
 3781                                    .visible_inlay_hints(cx)
 3782                                    .iter()
 3783                                    .map(|inlay| inlay.id)
 3784                                    .collect::<Vec<InlayId>>(),
 3785                                Vec::new(),
 3786                                cx,
 3787                            );
 3788                            return;
 3789                        }
 3790                    }
 3791                    None => return,
 3792                }
 3793            }
 3794            InlayHintRefreshReason::Toggle(enabled) => {
 3795                if self.inlay_hint_cache.toggle(enabled) {
 3796                    if enabled {
 3797                        (InvalidationStrategy::RefreshRequested, None)
 3798                    } else {
 3799                        self.splice_inlays(
 3800                            &self
 3801                                .visible_inlay_hints(cx)
 3802                                .iter()
 3803                                .map(|inlay| inlay.id)
 3804                                .collect::<Vec<InlayId>>(),
 3805                            Vec::new(),
 3806                            cx,
 3807                        );
 3808                        return;
 3809                    }
 3810                } else {
 3811                    return;
 3812                }
 3813            }
 3814            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3815                match self.inlay_hint_cache.update_settings(
 3816                    &self.buffer,
 3817                    new_settings,
 3818                    self.visible_inlay_hints(cx),
 3819                    cx,
 3820                ) {
 3821                    ControlFlow::Break(Some(InlaySplice {
 3822                        to_remove,
 3823                        to_insert,
 3824                    })) => {
 3825                        self.splice_inlays(&to_remove, to_insert, cx);
 3826                        return;
 3827                    }
 3828                    ControlFlow::Break(None) => return,
 3829                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3830                }
 3831            }
 3832            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3833                if let Some(InlaySplice {
 3834                    to_remove,
 3835                    to_insert,
 3836                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3837                {
 3838                    self.splice_inlays(&to_remove, to_insert, cx);
 3839                }
 3840                return;
 3841            }
 3842            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3843            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3844                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3845            }
 3846            InlayHintRefreshReason::RefreshRequested => {
 3847                (InvalidationStrategy::RefreshRequested, None)
 3848            }
 3849        };
 3850
 3851        if let Some(InlaySplice {
 3852            to_remove,
 3853            to_insert,
 3854        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3855            reason_description,
 3856            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3857            invalidate_cache,
 3858            ignore_debounce,
 3859            cx,
 3860        ) {
 3861            self.splice_inlays(&to_remove, to_insert, cx);
 3862        }
 3863    }
 3864
 3865    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3866        self.display_map
 3867            .read(cx)
 3868            .current_inlays()
 3869            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3870            .cloned()
 3871            .collect()
 3872    }
 3873
 3874    pub fn excerpts_for_inlay_hints_query(
 3875        &self,
 3876        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3877        cx: &mut Context<Editor>,
 3878    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3879        let Some(project) = self.project.as_ref() else {
 3880            return HashMap::default();
 3881        };
 3882        let project = project.read(cx);
 3883        let multi_buffer = self.buffer().read(cx);
 3884        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3885        let multi_buffer_visible_start = self
 3886            .scroll_manager
 3887            .anchor()
 3888            .anchor
 3889            .to_point(&multi_buffer_snapshot);
 3890        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3891            multi_buffer_visible_start
 3892                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3893            Bias::Left,
 3894        );
 3895        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3896        multi_buffer_snapshot
 3897            .range_to_buffer_ranges(multi_buffer_visible_range)
 3898            .into_iter()
 3899            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3900            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3901                let buffer_file = project::File::from_dyn(buffer.file())?;
 3902                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3903                let worktree_entry = buffer_worktree
 3904                    .read(cx)
 3905                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3906                if worktree_entry.is_ignored {
 3907                    return None;
 3908                }
 3909
 3910                let language = buffer.language()?;
 3911                if let Some(restrict_to_languages) = restrict_to_languages {
 3912                    if !restrict_to_languages.contains(language) {
 3913                        return None;
 3914                    }
 3915                }
 3916                Some((
 3917                    excerpt_id,
 3918                    (
 3919                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3920                        buffer.version().clone(),
 3921                        excerpt_visible_range,
 3922                    ),
 3923                ))
 3924            })
 3925            .collect()
 3926    }
 3927
 3928    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3929        TextLayoutDetails {
 3930            text_system: window.text_system().clone(),
 3931            editor_style: self.style.clone().unwrap(),
 3932            rem_size: window.rem_size(),
 3933            scroll_anchor: self.scroll_manager.anchor(),
 3934            visible_rows: self.visible_line_count(),
 3935            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3936        }
 3937    }
 3938
 3939    pub fn splice_inlays(
 3940        &self,
 3941        to_remove: &[InlayId],
 3942        to_insert: Vec<Inlay>,
 3943        cx: &mut Context<Self>,
 3944    ) {
 3945        self.display_map.update(cx, |display_map, cx| {
 3946            display_map.splice_inlays(to_remove, to_insert, cx)
 3947        });
 3948        cx.notify();
 3949    }
 3950
 3951    fn trigger_on_type_formatting(
 3952        &self,
 3953        input: String,
 3954        window: &mut Window,
 3955        cx: &mut Context<Self>,
 3956    ) -> Option<Task<Result<()>>> {
 3957        if input.len() != 1 {
 3958            return None;
 3959        }
 3960
 3961        let project = self.project.as_ref()?;
 3962        let position = self.selections.newest_anchor().head();
 3963        let (buffer, buffer_position) = self
 3964            .buffer
 3965            .read(cx)
 3966            .text_anchor_for_position(position, cx)?;
 3967
 3968        let settings = language_settings::language_settings(
 3969            buffer
 3970                .read(cx)
 3971                .language_at(buffer_position)
 3972                .map(|l| l.name()),
 3973            buffer.read(cx).file(),
 3974            cx,
 3975        );
 3976        if !settings.use_on_type_format {
 3977            return None;
 3978        }
 3979
 3980        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3981        // hence we do LSP request & edit on host side only — add formats to host's history.
 3982        let push_to_lsp_host_history = true;
 3983        // If this is not the host, append its history with new edits.
 3984        let push_to_client_history = project.read(cx).is_via_collab();
 3985
 3986        let on_type_formatting = project.update(cx, |project, cx| {
 3987            project.on_type_format(
 3988                buffer.clone(),
 3989                buffer_position,
 3990                input,
 3991                push_to_lsp_host_history,
 3992                cx,
 3993            )
 3994        });
 3995        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3996            if let Some(transaction) = on_type_formatting.await? {
 3997                if push_to_client_history {
 3998                    buffer
 3999                        .update(&mut cx, |buffer, _| {
 4000                            buffer.push_transaction(transaction, Instant::now());
 4001                        })
 4002                        .ok();
 4003                }
 4004                editor.update(&mut cx, |editor, cx| {
 4005                    editor.refresh_document_highlights(cx);
 4006                })?;
 4007            }
 4008            Ok(())
 4009        }))
 4010    }
 4011
 4012    pub fn show_word_completions(
 4013        &mut self,
 4014        _: &ShowWordCompletions,
 4015        window: &mut Window,
 4016        cx: &mut Context<Self>,
 4017    ) {
 4018        self.open_completions_menu(true, None, window, cx);
 4019    }
 4020
 4021    pub fn show_completions(
 4022        &mut self,
 4023        options: &ShowCompletions,
 4024        window: &mut Window,
 4025        cx: &mut Context<Self>,
 4026    ) {
 4027        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4028    }
 4029
 4030    fn open_completions_menu(
 4031        &mut self,
 4032        ignore_completion_provider: bool,
 4033        trigger: Option<&str>,
 4034        window: &mut Window,
 4035        cx: &mut Context<Self>,
 4036    ) {
 4037        if self.pending_rename.is_some() {
 4038            return;
 4039        }
 4040        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4041            return;
 4042        }
 4043
 4044        let position = self.selections.newest_anchor().head();
 4045        if position.diff_base_anchor.is_some() {
 4046            return;
 4047        }
 4048        let (buffer, buffer_position) =
 4049            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4050                output
 4051            } else {
 4052                return;
 4053            };
 4054        let buffer_snapshot = buffer.read(cx).snapshot();
 4055        let show_completion_documentation = buffer_snapshot
 4056            .settings_at(buffer_position, cx)
 4057            .show_completion_documentation;
 4058
 4059        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4060
 4061        let trigger_kind = match trigger {
 4062            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4063                CompletionTriggerKind::TRIGGER_CHARACTER
 4064            }
 4065            _ => CompletionTriggerKind::INVOKED,
 4066        };
 4067        let completion_context = CompletionContext {
 4068            trigger_character: trigger.and_then(|trigger| {
 4069                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4070                    Some(String::from(trigger))
 4071                } else {
 4072                    None
 4073                }
 4074            }),
 4075            trigger_kind,
 4076        };
 4077
 4078        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4079        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4080            let word_to_exclude = buffer_snapshot
 4081                .text_for_range(old_range.clone())
 4082                .collect::<String>();
 4083            (
 4084                buffer_snapshot.anchor_before(old_range.start)
 4085                    ..buffer_snapshot.anchor_after(old_range.end),
 4086                Some(word_to_exclude),
 4087            )
 4088        } else {
 4089            (buffer_position..buffer_position, None)
 4090        };
 4091
 4092        let completion_settings = language_settings(
 4093            buffer_snapshot
 4094                .language_at(buffer_position)
 4095                .map(|language| language.name()),
 4096            buffer_snapshot.file(),
 4097            cx,
 4098        )
 4099        .completions;
 4100
 4101        // The document can be large, so stay in reasonable bounds when searching for words,
 4102        // otherwise completion pop-up might be slow to appear.
 4103        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4104        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4105        let min_word_search = buffer_snapshot.clip_point(
 4106            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4107            Bias::Left,
 4108        );
 4109        let max_word_search = buffer_snapshot.clip_point(
 4110            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4111            Bias::Right,
 4112        );
 4113        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4114            ..buffer_snapshot.point_to_offset(max_word_search);
 4115
 4116        let provider = self
 4117            .completion_provider
 4118            .as_ref()
 4119            .filter(|_| !ignore_completion_provider);
 4120        let skip_digits = query
 4121            .as_ref()
 4122            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4123
 4124        let (mut words, provided_completions) = match provider {
 4125            Some(provider) => {
 4126                let completions =
 4127                    provider.completions(&buffer, buffer_position, completion_context, window, cx);
 4128
 4129                let words = match completion_settings.words {
 4130                    WordsCompletionMode::Disabled => Task::ready(HashMap::default()),
 4131                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4132                        .background_spawn(async move {
 4133                            buffer_snapshot.words_in_range(WordsQuery {
 4134                                fuzzy_contents: None,
 4135                                range: word_search_range,
 4136                                skip_digits,
 4137                            })
 4138                        }),
 4139                };
 4140
 4141                (words, completions)
 4142            }
 4143            None => (
 4144                cx.background_spawn(async move {
 4145                    buffer_snapshot.words_in_range(WordsQuery {
 4146                        fuzzy_contents: None,
 4147                        range: word_search_range,
 4148                        skip_digits,
 4149                    })
 4150                }),
 4151                Task::ready(Ok(None)),
 4152            ),
 4153        };
 4154
 4155        let sort_completions = provider
 4156            .as_ref()
 4157            .map_or(true, |provider| provider.sort_completions());
 4158
 4159        let id = post_inc(&mut self.next_completion_id);
 4160        let task = cx.spawn_in(window, |editor, mut cx| {
 4161            async move {
 4162                editor.update(&mut cx, |this, _| {
 4163                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4164                })?;
 4165
 4166                let mut completions = Vec::new();
 4167                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4168                    completions.extend(provided_completions);
 4169                    if completion_settings.words == WordsCompletionMode::Fallback {
 4170                        words = Task::ready(HashMap::default());
 4171                    }
 4172                }
 4173
 4174                let mut words = words.await;
 4175                if let Some(word_to_exclude) = &word_to_exclude {
 4176                    words.remove(word_to_exclude);
 4177                }
 4178                for lsp_completion in &completions {
 4179                    words.remove(&lsp_completion.new_text);
 4180                }
 4181                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4182                    old_range: old_range.clone(),
 4183                    new_text: word.clone(),
 4184                    label: CodeLabel::plain(word, None),
 4185                    documentation: None,
 4186                    source: CompletionSource::BufferWord {
 4187                        word_range,
 4188                        resolved: false,
 4189                    },
 4190                    confirm: None,
 4191                }));
 4192
 4193                let menu = if completions.is_empty() {
 4194                    None
 4195                } else {
 4196                    let mut menu = CompletionsMenu::new(
 4197                        id,
 4198                        sort_completions,
 4199                        show_completion_documentation,
 4200                        ignore_completion_provider,
 4201                        position,
 4202                        buffer.clone(),
 4203                        completions.into(),
 4204                    );
 4205
 4206                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4207                        .await;
 4208
 4209                    menu.visible().then_some(menu)
 4210                };
 4211
 4212                editor.update_in(&mut cx, |editor, window, cx| {
 4213                    match editor.context_menu.borrow().as_ref() {
 4214                        None => {}
 4215                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4216                            if prev_menu.id > id {
 4217                                return;
 4218                            }
 4219                        }
 4220                        _ => return,
 4221                    }
 4222
 4223                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4224                        let mut menu = menu.unwrap();
 4225                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4226
 4227                        *editor.context_menu.borrow_mut() =
 4228                            Some(CodeContextMenu::Completions(menu));
 4229
 4230                        if editor.show_edit_predictions_in_menu() {
 4231                            editor.update_visible_inline_completion(window, cx);
 4232                        } else {
 4233                            editor.discard_inline_completion(false, cx);
 4234                        }
 4235
 4236                        cx.notify();
 4237                    } else if editor.completion_tasks.len() <= 1 {
 4238                        // If there are no more completion tasks and the last menu was
 4239                        // empty, we should hide it.
 4240                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4241                        // If it was already hidden and we don't show inline
 4242                        // completions in the menu, we should also show the
 4243                        // inline-completion when available.
 4244                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4245                            editor.update_visible_inline_completion(window, cx);
 4246                        }
 4247                    }
 4248                })?;
 4249
 4250                anyhow::Ok(())
 4251            }
 4252            .log_err()
 4253        });
 4254
 4255        self.completion_tasks.push((id, task));
 4256    }
 4257
 4258    pub fn confirm_completion(
 4259        &mut self,
 4260        action: &ConfirmCompletion,
 4261        window: &mut Window,
 4262        cx: &mut Context<Self>,
 4263    ) -> Option<Task<Result<()>>> {
 4264        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4265    }
 4266
 4267    pub fn compose_completion(
 4268        &mut self,
 4269        action: &ComposeCompletion,
 4270        window: &mut Window,
 4271        cx: &mut Context<Self>,
 4272    ) -> Option<Task<Result<()>>> {
 4273        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4274    }
 4275
 4276    fn do_completion(
 4277        &mut self,
 4278        item_ix: Option<usize>,
 4279        intent: CompletionIntent,
 4280        window: &mut Window,
 4281        cx: &mut Context<Editor>,
 4282    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4283        use language::ToOffset as _;
 4284
 4285        let completions_menu =
 4286            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4287                menu
 4288            } else {
 4289                return None;
 4290            };
 4291
 4292        let entries = completions_menu.entries.borrow();
 4293        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4294        if self.show_edit_predictions_in_menu() {
 4295            self.discard_inline_completion(true, cx);
 4296        }
 4297        let candidate_id = mat.candidate_id;
 4298        drop(entries);
 4299
 4300        let buffer_handle = completions_menu.buffer;
 4301        let completion = completions_menu
 4302            .completions
 4303            .borrow()
 4304            .get(candidate_id)?
 4305            .clone();
 4306        cx.stop_propagation();
 4307
 4308        let snippet;
 4309        let text;
 4310
 4311        if completion.is_snippet() {
 4312            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4313            text = snippet.as_ref().unwrap().text.clone();
 4314        } else {
 4315            snippet = None;
 4316            text = completion.new_text.clone();
 4317        };
 4318        let selections = self.selections.all::<usize>(cx);
 4319        let buffer = buffer_handle.read(cx);
 4320        let old_range = completion.old_range.to_offset(buffer);
 4321        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4322
 4323        let newest_selection = self.selections.newest_anchor();
 4324        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4325            return None;
 4326        }
 4327
 4328        let lookbehind = newest_selection
 4329            .start
 4330            .text_anchor
 4331            .to_offset(buffer)
 4332            .saturating_sub(old_range.start);
 4333        let lookahead = old_range
 4334            .end
 4335            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4336        let mut common_prefix_len = old_text
 4337            .bytes()
 4338            .zip(text.bytes())
 4339            .take_while(|(a, b)| a == b)
 4340            .count();
 4341
 4342        let snapshot = self.buffer.read(cx).snapshot(cx);
 4343        let mut range_to_replace: Option<Range<isize>> = None;
 4344        let mut ranges = Vec::new();
 4345        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4346        for selection in &selections {
 4347            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4348                let start = selection.start.saturating_sub(lookbehind);
 4349                let end = selection.end + lookahead;
 4350                if selection.id == newest_selection.id {
 4351                    range_to_replace = Some(
 4352                        ((start + common_prefix_len) as isize - selection.start as isize)
 4353                            ..(end as isize - selection.start as isize),
 4354                    );
 4355                }
 4356                ranges.push(start + common_prefix_len..end);
 4357            } else {
 4358                common_prefix_len = 0;
 4359                ranges.clear();
 4360                ranges.extend(selections.iter().map(|s| {
 4361                    if s.id == newest_selection.id {
 4362                        range_to_replace = Some(
 4363                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4364                                - selection.start as isize
 4365                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4366                                    - selection.start as isize,
 4367                        );
 4368                        old_range.clone()
 4369                    } else {
 4370                        s.start..s.end
 4371                    }
 4372                }));
 4373                break;
 4374            }
 4375            if !self.linked_edit_ranges.is_empty() {
 4376                let start_anchor = snapshot.anchor_before(selection.head());
 4377                let end_anchor = snapshot.anchor_after(selection.tail());
 4378                if let Some(ranges) = self
 4379                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4380                {
 4381                    for (buffer, edits) in ranges {
 4382                        linked_edits.entry(buffer.clone()).or_default().extend(
 4383                            edits
 4384                                .into_iter()
 4385                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4386                        );
 4387                    }
 4388                }
 4389            }
 4390        }
 4391        let text = &text[common_prefix_len..];
 4392
 4393        cx.emit(EditorEvent::InputHandled {
 4394            utf16_range_to_replace: range_to_replace,
 4395            text: text.into(),
 4396        });
 4397
 4398        self.transact(window, cx, |this, window, cx| {
 4399            if let Some(mut snippet) = snippet {
 4400                snippet.text = text.to_string();
 4401                for tabstop in snippet
 4402                    .tabstops
 4403                    .iter_mut()
 4404                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4405                {
 4406                    tabstop.start -= common_prefix_len as isize;
 4407                    tabstop.end -= common_prefix_len as isize;
 4408                }
 4409
 4410                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4411            } else {
 4412                this.buffer.update(cx, |buffer, cx| {
 4413                    buffer.edit(
 4414                        ranges.iter().map(|range| (range.clone(), text)),
 4415                        this.autoindent_mode.clone(),
 4416                        cx,
 4417                    );
 4418                });
 4419            }
 4420            for (buffer, edits) in linked_edits {
 4421                buffer.update(cx, |buffer, cx| {
 4422                    let snapshot = buffer.snapshot();
 4423                    let edits = edits
 4424                        .into_iter()
 4425                        .map(|(range, text)| {
 4426                            use text::ToPoint as TP;
 4427                            let end_point = TP::to_point(&range.end, &snapshot);
 4428                            let start_point = TP::to_point(&range.start, &snapshot);
 4429                            (start_point..end_point, text)
 4430                        })
 4431                        .sorted_by_key(|(range, _)| range.start)
 4432                        .collect::<Vec<_>>();
 4433                    buffer.edit(edits, None, cx);
 4434                })
 4435            }
 4436
 4437            this.refresh_inline_completion(true, false, window, cx);
 4438        });
 4439
 4440        let show_new_completions_on_confirm = completion
 4441            .confirm
 4442            .as_ref()
 4443            .map_or(false, |confirm| confirm(intent, window, cx));
 4444        if show_new_completions_on_confirm {
 4445            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4446        }
 4447
 4448        let provider = self.completion_provider.as_ref()?;
 4449        drop(completion);
 4450        let apply_edits = provider.apply_additional_edits_for_completion(
 4451            buffer_handle,
 4452            completions_menu.completions.clone(),
 4453            candidate_id,
 4454            true,
 4455            cx,
 4456        );
 4457
 4458        let editor_settings = EditorSettings::get_global(cx);
 4459        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4460            // After the code completion is finished, users often want to know what signatures are needed.
 4461            // so we should automatically call signature_help
 4462            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4463        }
 4464
 4465        Some(cx.foreground_executor().spawn(async move {
 4466            apply_edits.await?;
 4467            Ok(())
 4468        }))
 4469    }
 4470
 4471    pub fn toggle_code_actions(
 4472        &mut self,
 4473        action: &ToggleCodeActions,
 4474        window: &mut Window,
 4475        cx: &mut Context<Self>,
 4476    ) {
 4477        let mut context_menu = self.context_menu.borrow_mut();
 4478        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4479            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4480                // Toggle if we're selecting the same one
 4481                *context_menu = None;
 4482                cx.notify();
 4483                return;
 4484            } else {
 4485                // Otherwise, clear it and start a new one
 4486                *context_menu = None;
 4487                cx.notify();
 4488            }
 4489        }
 4490        drop(context_menu);
 4491        let snapshot = self.snapshot(window, cx);
 4492        let deployed_from_indicator = action.deployed_from_indicator;
 4493        let mut task = self.code_actions_task.take();
 4494        let action = action.clone();
 4495        cx.spawn_in(window, |editor, mut cx| async move {
 4496            while let Some(prev_task) = task {
 4497                prev_task.await.log_err();
 4498                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4499            }
 4500
 4501            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4502                if editor.focus_handle.is_focused(window) {
 4503                    let multibuffer_point = action
 4504                        .deployed_from_indicator
 4505                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4506                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4507                    let (buffer, buffer_row) = snapshot
 4508                        .buffer_snapshot
 4509                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4510                        .and_then(|(buffer_snapshot, range)| {
 4511                            editor
 4512                                .buffer
 4513                                .read(cx)
 4514                                .buffer(buffer_snapshot.remote_id())
 4515                                .map(|buffer| (buffer, range.start.row))
 4516                        })?;
 4517                    let (_, code_actions) = editor
 4518                        .available_code_actions
 4519                        .clone()
 4520                        .and_then(|(location, code_actions)| {
 4521                            let snapshot = location.buffer.read(cx).snapshot();
 4522                            let point_range = location.range.to_point(&snapshot);
 4523                            let point_range = point_range.start.row..=point_range.end.row;
 4524                            if point_range.contains(&buffer_row) {
 4525                                Some((location, code_actions))
 4526                            } else {
 4527                                None
 4528                            }
 4529                        })
 4530                        .unzip();
 4531                    let buffer_id = buffer.read(cx).remote_id();
 4532                    let tasks = editor
 4533                        .tasks
 4534                        .get(&(buffer_id, buffer_row))
 4535                        .map(|t| Arc::new(t.to_owned()));
 4536                    if tasks.is_none() && code_actions.is_none() {
 4537                        return None;
 4538                    }
 4539
 4540                    editor.completion_tasks.clear();
 4541                    editor.discard_inline_completion(false, cx);
 4542                    let task_context =
 4543                        tasks
 4544                            .as_ref()
 4545                            .zip(editor.project.clone())
 4546                            .map(|(tasks, project)| {
 4547                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4548                            });
 4549
 4550                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4551                        let task_context = match task_context {
 4552                            Some(task_context) => task_context.await,
 4553                            None => None,
 4554                        };
 4555                        let resolved_tasks =
 4556                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4557                                Rc::new(ResolvedTasks {
 4558                                    templates: tasks.resolve(&task_context).collect(),
 4559                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4560                                        multibuffer_point.row,
 4561                                        tasks.column,
 4562                                    )),
 4563                                })
 4564                            });
 4565                        let spawn_straight_away = resolved_tasks
 4566                            .as_ref()
 4567                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4568                            && code_actions
 4569                                .as_ref()
 4570                                .map_or(true, |actions| actions.is_empty());
 4571                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4572                            *editor.context_menu.borrow_mut() =
 4573                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4574                                    buffer,
 4575                                    actions: CodeActionContents {
 4576                                        tasks: resolved_tasks,
 4577                                        actions: code_actions,
 4578                                    },
 4579                                    selected_item: Default::default(),
 4580                                    scroll_handle: UniformListScrollHandle::default(),
 4581                                    deployed_from_indicator,
 4582                                }));
 4583                            if spawn_straight_away {
 4584                                if let Some(task) = editor.confirm_code_action(
 4585                                    &ConfirmCodeAction { item_ix: Some(0) },
 4586                                    window,
 4587                                    cx,
 4588                                ) {
 4589                                    cx.notify();
 4590                                    return task;
 4591                                }
 4592                            }
 4593                            cx.notify();
 4594                            Task::ready(Ok(()))
 4595                        }) {
 4596                            task.await
 4597                        } else {
 4598                            Ok(())
 4599                        }
 4600                    }))
 4601                } else {
 4602                    Some(Task::ready(Ok(())))
 4603                }
 4604            })?;
 4605            if let Some(task) = spawned_test_task {
 4606                task.await?;
 4607            }
 4608
 4609            Ok::<_, anyhow::Error>(())
 4610        })
 4611        .detach_and_log_err(cx);
 4612    }
 4613
 4614    pub fn confirm_code_action(
 4615        &mut self,
 4616        action: &ConfirmCodeAction,
 4617        window: &mut Window,
 4618        cx: &mut Context<Self>,
 4619    ) -> Option<Task<Result<()>>> {
 4620        let actions_menu =
 4621            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4622                menu
 4623            } else {
 4624                return None;
 4625            };
 4626        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4627        let action = actions_menu.actions.get(action_ix)?;
 4628        let title = action.label();
 4629        let buffer = actions_menu.buffer;
 4630        let workspace = self.workspace()?;
 4631
 4632        match action {
 4633            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4634                workspace.update(cx, |workspace, cx| {
 4635                    workspace::tasks::schedule_resolved_task(
 4636                        workspace,
 4637                        task_source_kind,
 4638                        resolved_task,
 4639                        false,
 4640                        cx,
 4641                    );
 4642
 4643                    Some(Task::ready(Ok(())))
 4644                })
 4645            }
 4646            CodeActionsItem::CodeAction {
 4647                excerpt_id,
 4648                action,
 4649                provider,
 4650            } => {
 4651                let apply_code_action =
 4652                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4653                let workspace = workspace.downgrade();
 4654                Some(cx.spawn_in(window, |editor, cx| async move {
 4655                    let project_transaction = apply_code_action.await?;
 4656                    Self::open_project_transaction(
 4657                        &editor,
 4658                        workspace,
 4659                        project_transaction,
 4660                        title,
 4661                        cx,
 4662                    )
 4663                    .await
 4664                }))
 4665            }
 4666        }
 4667    }
 4668
 4669    pub async fn open_project_transaction(
 4670        this: &WeakEntity<Editor>,
 4671        workspace: WeakEntity<Workspace>,
 4672        transaction: ProjectTransaction,
 4673        title: String,
 4674        mut cx: AsyncWindowContext,
 4675    ) -> Result<()> {
 4676        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4677        cx.update(|_, cx| {
 4678            entries.sort_unstable_by_key(|(buffer, _)| {
 4679                buffer.read(cx).file().map(|f| f.path().clone())
 4680            });
 4681        })?;
 4682
 4683        // If the project transaction's edits are all contained within this editor, then
 4684        // avoid opening a new editor to display them.
 4685
 4686        if let Some((buffer, transaction)) = entries.first() {
 4687            if entries.len() == 1 {
 4688                let excerpt = this.update(&mut cx, |editor, cx| {
 4689                    editor
 4690                        .buffer()
 4691                        .read(cx)
 4692                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4693                })?;
 4694                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4695                    if excerpted_buffer == *buffer {
 4696                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4697                            let excerpt_range = excerpt_range.to_offset(buffer);
 4698                            buffer
 4699                                .edited_ranges_for_transaction::<usize>(transaction)
 4700                                .all(|range| {
 4701                                    excerpt_range.start <= range.start
 4702                                        && excerpt_range.end >= range.end
 4703                                })
 4704                        })?;
 4705
 4706                        if all_edits_within_excerpt {
 4707                            return Ok(());
 4708                        }
 4709                    }
 4710                }
 4711            }
 4712        } else {
 4713            return Ok(());
 4714        }
 4715
 4716        let mut ranges_to_highlight = Vec::new();
 4717        let excerpt_buffer = cx.new(|cx| {
 4718            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4719            for (buffer_handle, transaction) in &entries {
 4720                let buffer = buffer_handle.read(cx);
 4721                ranges_to_highlight.extend(
 4722                    multibuffer.push_excerpts_with_context_lines(
 4723                        buffer_handle.clone(),
 4724                        buffer
 4725                            .edited_ranges_for_transaction::<usize>(transaction)
 4726                            .collect(),
 4727                        DEFAULT_MULTIBUFFER_CONTEXT,
 4728                        cx,
 4729                    ),
 4730                );
 4731            }
 4732            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4733            multibuffer
 4734        })?;
 4735
 4736        workspace.update_in(&mut cx, |workspace, window, cx| {
 4737            let project = workspace.project().clone();
 4738            let editor =
 4739                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 4740            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4741            editor.update(cx, |editor, cx| {
 4742                editor.highlight_background::<Self>(
 4743                    &ranges_to_highlight,
 4744                    |theme| theme.editor_highlighted_line_background,
 4745                    cx,
 4746                );
 4747            });
 4748        })?;
 4749
 4750        Ok(())
 4751    }
 4752
 4753    pub fn clear_code_action_providers(&mut self) {
 4754        self.code_action_providers.clear();
 4755        self.available_code_actions.take();
 4756    }
 4757
 4758    pub fn add_code_action_provider(
 4759        &mut self,
 4760        provider: Rc<dyn CodeActionProvider>,
 4761        window: &mut Window,
 4762        cx: &mut Context<Self>,
 4763    ) {
 4764        if self
 4765            .code_action_providers
 4766            .iter()
 4767            .any(|existing_provider| existing_provider.id() == provider.id())
 4768        {
 4769            return;
 4770        }
 4771
 4772        self.code_action_providers.push(provider);
 4773        self.refresh_code_actions(window, cx);
 4774    }
 4775
 4776    pub fn remove_code_action_provider(
 4777        &mut self,
 4778        id: Arc<str>,
 4779        window: &mut Window,
 4780        cx: &mut Context<Self>,
 4781    ) {
 4782        self.code_action_providers
 4783            .retain(|provider| provider.id() != id);
 4784        self.refresh_code_actions(window, cx);
 4785    }
 4786
 4787    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4788        let buffer = self.buffer.read(cx);
 4789        let newest_selection = self.selections.newest_anchor().clone();
 4790        if newest_selection.head().diff_base_anchor.is_some() {
 4791            return None;
 4792        }
 4793        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4794        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4795        if start_buffer != end_buffer {
 4796            return None;
 4797        }
 4798
 4799        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4800            cx.background_executor()
 4801                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4802                .await;
 4803
 4804            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4805                let providers = this.code_action_providers.clone();
 4806                let tasks = this
 4807                    .code_action_providers
 4808                    .iter()
 4809                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4810                    .collect::<Vec<_>>();
 4811                (providers, tasks)
 4812            })?;
 4813
 4814            let mut actions = Vec::new();
 4815            for (provider, provider_actions) in
 4816                providers.into_iter().zip(future::join_all(tasks).await)
 4817            {
 4818                if let Some(provider_actions) = provider_actions.log_err() {
 4819                    actions.extend(provider_actions.into_iter().map(|action| {
 4820                        AvailableCodeAction {
 4821                            excerpt_id: newest_selection.start.excerpt_id,
 4822                            action,
 4823                            provider: provider.clone(),
 4824                        }
 4825                    }));
 4826                }
 4827            }
 4828
 4829            this.update(&mut cx, |this, cx| {
 4830                this.available_code_actions = if actions.is_empty() {
 4831                    None
 4832                } else {
 4833                    Some((
 4834                        Location {
 4835                            buffer: start_buffer,
 4836                            range: start..end,
 4837                        },
 4838                        actions.into(),
 4839                    ))
 4840                };
 4841                cx.notify();
 4842            })
 4843        }));
 4844        None
 4845    }
 4846
 4847    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4848        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4849            self.show_git_blame_inline = false;
 4850
 4851            self.show_git_blame_inline_delay_task =
 4852                Some(cx.spawn_in(window, |this, mut cx| async move {
 4853                    cx.background_executor().timer(delay).await;
 4854
 4855                    this.update(&mut cx, |this, cx| {
 4856                        this.show_git_blame_inline = true;
 4857                        cx.notify();
 4858                    })
 4859                    .log_err();
 4860                }));
 4861        }
 4862    }
 4863
 4864    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4865        if self.pending_rename.is_some() {
 4866            return None;
 4867        }
 4868
 4869        let provider = self.semantics_provider.clone()?;
 4870        let buffer = self.buffer.read(cx);
 4871        let newest_selection = self.selections.newest_anchor().clone();
 4872        let cursor_position = newest_selection.head();
 4873        let (cursor_buffer, cursor_buffer_position) =
 4874            buffer.text_anchor_for_position(cursor_position, cx)?;
 4875        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4876        if cursor_buffer != tail_buffer {
 4877            return None;
 4878        }
 4879        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4880        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4881            cx.background_executor()
 4882                .timer(Duration::from_millis(debounce))
 4883                .await;
 4884
 4885            let highlights = if let Some(highlights) = cx
 4886                .update(|cx| {
 4887                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4888                })
 4889                .ok()
 4890                .flatten()
 4891            {
 4892                highlights.await.log_err()
 4893            } else {
 4894                None
 4895            };
 4896
 4897            if let Some(highlights) = highlights {
 4898                this.update(&mut cx, |this, cx| {
 4899                    if this.pending_rename.is_some() {
 4900                        return;
 4901                    }
 4902
 4903                    let buffer_id = cursor_position.buffer_id;
 4904                    let buffer = this.buffer.read(cx);
 4905                    if !buffer
 4906                        .text_anchor_for_position(cursor_position, cx)
 4907                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4908                    {
 4909                        return;
 4910                    }
 4911
 4912                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4913                    let mut write_ranges = Vec::new();
 4914                    let mut read_ranges = Vec::new();
 4915                    for highlight in highlights {
 4916                        for (excerpt_id, excerpt_range) in
 4917                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4918                        {
 4919                            let start = highlight
 4920                                .range
 4921                                .start
 4922                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4923                            let end = highlight
 4924                                .range
 4925                                .end
 4926                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4927                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4928                                continue;
 4929                            }
 4930
 4931                            let range = Anchor {
 4932                                buffer_id,
 4933                                excerpt_id,
 4934                                text_anchor: start,
 4935                                diff_base_anchor: None,
 4936                            }..Anchor {
 4937                                buffer_id,
 4938                                excerpt_id,
 4939                                text_anchor: end,
 4940                                diff_base_anchor: None,
 4941                            };
 4942                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4943                                write_ranges.push(range);
 4944                            } else {
 4945                                read_ranges.push(range);
 4946                            }
 4947                        }
 4948                    }
 4949
 4950                    this.highlight_background::<DocumentHighlightRead>(
 4951                        &read_ranges,
 4952                        |theme| theme.editor_document_highlight_read_background,
 4953                        cx,
 4954                    );
 4955                    this.highlight_background::<DocumentHighlightWrite>(
 4956                        &write_ranges,
 4957                        |theme| theme.editor_document_highlight_write_background,
 4958                        cx,
 4959                    );
 4960                    cx.notify();
 4961                })
 4962                .log_err();
 4963            }
 4964        }));
 4965        None
 4966    }
 4967
 4968    pub fn refresh_selected_text_highlights(
 4969        &mut self,
 4970        window: &mut Window,
 4971        cx: &mut Context<Editor>,
 4972    ) {
 4973        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 4974            return;
 4975        }
 4976        self.selection_highlight_task.take();
 4977        if !EditorSettings::get_global(cx).selection_highlight {
 4978            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4979            return;
 4980        }
 4981        if self.selections.count() != 1 || self.selections.line_mode {
 4982            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4983            return;
 4984        }
 4985        let selection = self.selections.newest::<Point>(cx);
 4986        if selection.is_empty() || selection.start.row != selection.end.row {
 4987            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4988            return;
 4989        }
 4990        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4991        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4992            cx.background_executor()
 4993                .timer(Duration::from_millis(debounce))
 4994                .await;
 4995            let Some(Some(matches_task)) = editor
 4996                .update_in(&mut cx, |editor, _, cx| {
 4997                    if editor.selections.count() != 1 || editor.selections.line_mode {
 4998                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4999                        return None;
 5000                    }
 5001                    let selection = editor.selections.newest::<Point>(cx);
 5002                    if selection.is_empty() || selection.start.row != selection.end.row {
 5003                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5004                        return None;
 5005                    }
 5006                    let buffer = editor.buffer().read(cx).snapshot(cx);
 5007                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 5008                    if query.trim().is_empty() {
 5009                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5010                        return None;
 5011                    }
 5012                    Some(cx.background_spawn(async move {
 5013                        let mut ranges = Vec::new();
 5014                        let selection_anchors = selection.range().to_anchors(&buffer);
 5015                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 5016                            for (search_buffer, search_range, excerpt_id) in
 5017                                buffer.range_to_buffer_ranges(range)
 5018                            {
 5019                                ranges.extend(
 5020                                    project::search::SearchQuery::text(
 5021                                        query.clone(),
 5022                                        false,
 5023                                        false,
 5024                                        false,
 5025                                        Default::default(),
 5026                                        Default::default(),
 5027                                        None,
 5028                                    )
 5029                                    .unwrap()
 5030                                    .search(search_buffer, Some(search_range.clone()))
 5031                                    .await
 5032                                    .into_iter()
 5033                                    .filter_map(
 5034                                        |match_range| {
 5035                                            let start = search_buffer.anchor_after(
 5036                                                search_range.start + match_range.start,
 5037                                            );
 5038                                            let end = search_buffer.anchor_before(
 5039                                                search_range.start + match_range.end,
 5040                                            );
 5041                                            let range = Anchor::range_in_buffer(
 5042                                                excerpt_id,
 5043                                                search_buffer.remote_id(),
 5044                                                start..end,
 5045                                            );
 5046                                            (range != selection_anchors).then_some(range)
 5047                                        },
 5048                                    ),
 5049                                );
 5050                            }
 5051                        }
 5052                        ranges
 5053                    }))
 5054                })
 5055                .log_err()
 5056            else {
 5057                return;
 5058            };
 5059            let matches = matches_task.await;
 5060            editor
 5061                .update_in(&mut cx, |editor, _, cx| {
 5062                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5063                    if !matches.is_empty() {
 5064                        editor.highlight_background::<SelectedTextHighlight>(
 5065                            &matches,
 5066                            |theme| theme.editor_document_highlight_bracket_background,
 5067                            cx,
 5068                        )
 5069                    }
 5070                })
 5071                .log_err();
 5072        }));
 5073    }
 5074
 5075    pub fn refresh_inline_completion(
 5076        &mut self,
 5077        debounce: bool,
 5078        user_requested: bool,
 5079        window: &mut Window,
 5080        cx: &mut Context<Self>,
 5081    ) -> Option<()> {
 5082        let provider = self.edit_prediction_provider()?;
 5083        let cursor = self.selections.newest_anchor().head();
 5084        let (buffer, cursor_buffer_position) =
 5085            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5086
 5087        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5088            self.discard_inline_completion(false, cx);
 5089            return None;
 5090        }
 5091
 5092        if !user_requested
 5093            && (!self.should_show_edit_predictions()
 5094                || !self.is_focused(window)
 5095                || buffer.read(cx).is_empty())
 5096        {
 5097            self.discard_inline_completion(false, cx);
 5098            return None;
 5099        }
 5100
 5101        self.update_visible_inline_completion(window, cx);
 5102        provider.refresh(
 5103            self.project.clone(),
 5104            buffer,
 5105            cursor_buffer_position,
 5106            debounce,
 5107            cx,
 5108        );
 5109        Some(())
 5110    }
 5111
 5112    fn show_edit_predictions_in_menu(&self) -> bool {
 5113        match self.edit_prediction_settings {
 5114            EditPredictionSettings::Disabled => false,
 5115            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5116        }
 5117    }
 5118
 5119    pub fn edit_predictions_enabled(&self) -> bool {
 5120        match self.edit_prediction_settings {
 5121            EditPredictionSettings::Disabled => false,
 5122            EditPredictionSettings::Enabled { .. } => true,
 5123        }
 5124    }
 5125
 5126    fn edit_prediction_requires_modifier(&self) -> bool {
 5127        match self.edit_prediction_settings {
 5128            EditPredictionSettings::Disabled => false,
 5129            EditPredictionSettings::Enabled {
 5130                preview_requires_modifier,
 5131                ..
 5132            } => preview_requires_modifier,
 5133        }
 5134    }
 5135
 5136    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5137        if self.edit_prediction_provider.is_none() {
 5138            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5139        } else {
 5140            let selection = self.selections.newest_anchor();
 5141            let cursor = selection.head();
 5142
 5143            if let Some((buffer, cursor_buffer_position)) =
 5144                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5145            {
 5146                self.edit_prediction_settings =
 5147                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5148            }
 5149        }
 5150    }
 5151
 5152    fn edit_prediction_settings_at_position(
 5153        &self,
 5154        buffer: &Entity<Buffer>,
 5155        buffer_position: language::Anchor,
 5156        cx: &App,
 5157    ) -> EditPredictionSettings {
 5158        if self.mode != EditorMode::Full
 5159            || !self.show_inline_completions_override.unwrap_or(true)
 5160            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5161        {
 5162            return EditPredictionSettings::Disabled;
 5163        }
 5164
 5165        let buffer = buffer.read(cx);
 5166
 5167        let file = buffer.file();
 5168
 5169        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5170            return EditPredictionSettings::Disabled;
 5171        };
 5172
 5173        let by_provider = matches!(
 5174            self.menu_inline_completions_policy,
 5175            MenuInlineCompletionsPolicy::ByProvider
 5176        );
 5177
 5178        let show_in_menu = by_provider
 5179            && self
 5180                .edit_prediction_provider
 5181                .as_ref()
 5182                .map_or(false, |provider| {
 5183                    provider.provider.show_completions_in_menu()
 5184                });
 5185
 5186        let preview_requires_modifier =
 5187            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5188
 5189        EditPredictionSettings::Enabled {
 5190            show_in_menu,
 5191            preview_requires_modifier,
 5192        }
 5193    }
 5194
 5195    fn should_show_edit_predictions(&self) -> bool {
 5196        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5197    }
 5198
 5199    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5200        matches!(
 5201            self.edit_prediction_preview,
 5202            EditPredictionPreview::Active { .. }
 5203        )
 5204    }
 5205
 5206    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5207        let cursor = self.selections.newest_anchor().head();
 5208        if let Some((buffer, cursor_position)) =
 5209            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5210        {
 5211            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5212        } else {
 5213            false
 5214        }
 5215    }
 5216
 5217    fn edit_predictions_enabled_in_buffer(
 5218        &self,
 5219        buffer: &Entity<Buffer>,
 5220        buffer_position: language::Anchor,
 5221        cx: &App,
 5222    ) -> bool {
 5223        maybe!({
 5224            if self.read_only(cx) {
 5225                return Some(false);
 5226            }
 5227            let provider = self.edit_prediction_provider()?;
 5228            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5229                return Some(false);
 5230            }
 5231            let buffer = buffer.read(cx);
 5232            let Some(file) = buffer.file() else {
 5233                return Some(true);
 5234            };
 5235            let settings = all_language_settings(Some(file), cx);
 5236            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5237        })
 5238        .unwrap_or(false)
 5239    }
 5240
 5241    fn cycle_inline_completion(
 5242        &mut self,
 5243        direction: Direction,
 5244        window: &mut Window,
 5245        cx: &mut Context<Self>,
 5246    ) -> Option<()> {
 5247        let provider = self.edit_prediction_provider()?;
 5248        let cursor = self.selections.newest_anchor().head();
 5249        let (buffer, cursor_buffer_position) =
 5250            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5251        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5252            return None;
 5253        }
 5254
 5255        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5256        self.update_visible_inline_completion(window, cx);
 5257
 5258        Some(())
 5259    }
 5260
 5261    pub fn show_inline_completion(
 5262        &mut self,
 5263        _: &ShowEditPrediction,
 5264        window: &mut Window,
 5265        cx: &mut Context<Self>,
 5266    ) {
 5267        if !self.has_active_inline_completion() {
 5268            self.refresh_inline_completion(false, true, window, cx);
 5269            return;
 5270        }
 5271
 5272        self.update_visible_inline_completion(window, cx);
 5273    }
 5274
 5275    pub fn display_cursor_names(
 5276        &mut self,
 5277        _: &DisplayCursorNames,
 5278        window: &mut Window,
 5279        cx: &mut Context<Self>,
 5280    ) {
 5281        self.show_cursor_names(window, cx);
 5282    }
 5283
 5284    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5285        self.show_cursor_names = true;
 5286        cx.notify();
 5287        cx.spawn_in(window, |this, mut cx| async move {
 5288            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5289            this.update(&mut cx, |this, cx| {
 5290                this.show_cursor_names = false;
 5291                cx.notify()
 5292            })
 5293            .ok()
 5294        })
 5295        .detach();
 5296    }
 5297
 5298    pub fn next_edit_prediction(
 5299        &mut self,
 5300        _: &NextEditPrediction,
 5301        window: &mut Window,
 5302        cx: &mut Context<Self>,
 5303    ) {
 5304        if self.has_active_inline_completion() {
 5305            self.cycle_inline_completion(Direction::Next, window, cx);
 5306        } else {
 5307            let is_copilot_disabled = self
 5308                .refresh_inline_completion(false, true, window, cx)
 5309                .is_none();
 5310            if is_copilot_disabled {
 5311                cx.propagate();
 5312            }
 5313        }
 5314    }
 5315
 5316    pub fn previous_edit_prediction(
 5317        &mut self,
 5318        _: &PreviousEditPrediction,
 5319        window: &mut Window,
 5320        cx: &mut Context<Self>,
 5321    ) {
 5322        if self.has_active_inline_completion() {
 5323            self.cycle_inline_completion(Direction::Prev, window, cx);
 5324        } else {
 5325            let is_copilot_disabled = self
 5326                .refresh_inline_completion(false, true, window, cx)
 5327                .is_none();
 5328            if is_copilot_disabled {
 5329                cx.propagate();
 5330            }
 5331        }
 5332    }
 5333
 5334    pub fn accept_edit_prediction(
 5335        &mut self,
 5336        _: &AcceptEditPrediction,
 5337        window: &mut Window,
 5338        cx: &mut Context<Self>,
 5339    ) {
 5340        if self.show_edit_predictions_in_menu() {
 5341            self.hide_context_menu(window, cx);
 5342        }
 5343
 5344        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5345            return;
 5346        };
 5347
 5348        self.report_inline_completion_event(
 5349            active_inline_completion.completion_id.clone(),
 5350            true,
 5351            cx,
 5352        );
 5353
 5354        match &active_inline_completion.completion {
 5355            InlineCompletion::Move { target, .. } => {
 5356                let target = *target;
 5357
 5358                if let Some(position_map) = &self.last_position_map {
 5359                    if position_map
 5360                        .visible_row_range
 5361                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5362                        || !self.edit_prediction_requires_modifier()
 5363                    {
 5364                        self.unfold_ranges(&[target..target], true, false, cx);
 5365                        // Note that this is also done in vim's handler of the Tab action.
 5366                        self.change_selections(
 5367                            Some(Autoscroll::newest()),
 5368                            window,
 5369                            cx,
 5370                            |selections| {
 5371                                selections.select_anchor_ranges([target..target]);
 5372                            },
 5373                        );
 5374                        self.clear_row_highlights::<EditPredictionPreview>();
 5375
 5376                        self.edit_prediction_preview
 5377                            .set_previous_scroll_position(None);
 5378                    } else {
 5379                        self.edit_prediction_preview
 5380                            .set_previous_scroll_position(Some(
 5381                                position_map.snapshot.scroll_anchor,
 5382                            ));
 5383
 5384                        self.highlight_rows::<EditPredictionPreview>(
 5385                            target..target,
 5386                            cx.theme().colors().editor_highlighted_line_background,
 5387                            true,
 5388                            cx,
 5389                        );
 5390                        self.request_autoscroll(Autoscroll::fit(), cx);
 5391                    }
 5392                }
 5393            }
 5394            InlineCompletion::Edit { edits, .. } => {
 5395                if let Some(provider) = self.edit_prediction_provider() {
 5396                    provider.accept(cx);
 5397                }
 5398
 5399                let snapshot = self.buffer.read(cx).snapshot(cx);
 5400                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5401
 5402                self.buffer.update(cx, |buffer, cx| {
 5403                    buffer.edit(edits.iter().cloned(), None, cx)
 5404                });
 5405
 5406                self.change_selections(None, window, cx, |s| {
 5407                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5408                });
 5409
 5410                self.update_visible_inline_completion(window, cx);
 5411                if self.active_inline_completion.is_none() {
 5412                    self.refresh_inline_completion(true, true, window, cx);
 5413                }
 5414
 5415                cx.notify();
 5416            }
 5417        }
 5418
 5419        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5420    }
 5421
 5422    pub fn accept_partial_inline_completion(
 5423        &mut self,
 5424        _: &AcceptPartialEditPrediction,
 5425        window: &mut Window,
 5426        cx: &mut Context<Self>,
 5427    ) {
 5428        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5429            return;
 5430        };
 5431        if self.selections.count() != 1 {
 5432            return;
 5433        }
 5434
 5435        self.report_inline_completion_event(
 5436            active_inline_completion.completion_id.clone(),
 5437            true,
 5438            cx,
 5439        );
 5440
 5441        match &active_inline_completion.completion {
 5442            InlineCompletion::Move { target, .. } => {
 5443                let target = *target;
 5444                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5445                    selections.select_anchor_ranges([target..target]);
 5446                });
 5447            }
 5448            InlineCompletion::Edit { edits, .. } => {
 5449                // Find an insertion that starts at the cursor position.
 5450                let snapshot = self.buffer.read(cx).snapshot(cx);
 5451                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5452                let insertion = edits.iter().find_map(|(range, text)| {
 5453                    let range = range.to_offset(&snapshot);
 5454                    if range.is_empty() && range.start == cursor_offset {
 5455                        Some(text)
 5456                    } else {
 5457                        None
 5458                    }
 5459                });
 5460
 5461                if let Some(text) = insertion {
 5462                    let mut partial_completion = text
 5463                        .chars()
 5464                        .by_ref()
 5465                        .take_while(|c| c.is_alphabetic())
 5466                        .collect::<String>();
 5467                    if partial_completion.is_empty() {
 5468                        partial_completion = text
 5469                            .chars()
 5470                            .by_ref()
 5471                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5472                            .collect::<String>();
 5473                    }
 5474
 5475                    cx.emit(EditorEvent::InputHandled {
 5476                        utf16_range_to_replace: None,
 5477                        text: partial_completion.clone().into(),
 5478                    });
 5479
 5480                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5481
 5482                    self.refresh_inline_completion(true, true, window, cx);
 5483                    cx.notify();
 5484                } else {
 5485                    self.accept_edit_prediction(&Default::default(), window, cx);
 5486                }
 5487            }
 5488        }
 5489    }
 5490
 5491    fn discard_inline_completion(
 5492        &mut self,
 5493        should_report_inline_completion_event: bool,
 5494        cx: &mut Context<Self>,
 5495    ) -> bool {
 5496        if should_report_inline_completion_event {
 5497            let completion_id = self
 5498                .active_inline_completion
 5499                .as_ref()
 5500                .and_then(|active_completion| active_completion.completion_id.clone());
 5501
 5502            self.report_inline_completion_event(completion_id, false, cx);
 5503        }
 5504
 5505        if let Some(provider) = self.edit_prediction_provider() {
 5506            provider.discard(cx);
 5507        }
 5508
 5509        self.take_active_inline_completion(cx)
 5510    }
 5511
 5512    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5513        let Some(provider) = self.edit_prediction_provider() else {
 5514            return;
 5515        };
 5516
 5517        let Some((_, buffer, _)) = self
 5518            .buffer
 5519            .read(cx)
 5520            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5521        else {
 5522            return;
 5523        };
 5524
 5525        let extension = buffer
 5526            .read(cx)
 5527            .file()
 5528            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5529
 5530        let event_type = match accepted {
 5531            true => "Edit Prediction Accepted",
 5532            false => "Edit Prediction Discarded",
 5533        };
 5534        telemetry::event!(
 5535            event_type,
 5536            provider = provider.name(),
 5537            prediction_id = id,
 5538            suggestion_accepted = accepted,
 5539            file_extension = extension,
 5540        );
 5541    }
 5542
 5543    pub fn has_active_inline_completion(&self) -> bool {
 5544        self.active_inline_completion.is_some()
 5545    }
 5546
 5547    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5548        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5549            return false;
 5550        };
 5551
 5552        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5553        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5554        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5555        true
 5556    }
 5557
 5558    /// Returns true when we're displaying the edit prediction popover below the cursor
 5559    /// like we are not previewing and the LSP autocomplete menu is visible
 5560    /// or we are in `when_holding_modifier` mode.
 5561    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5562        if self.edit_prediction_preview_is_active()
 5563            || !self.show_edit_predictions_in_menu()
 5564            || !self.edit_predictions_enabled()
 5565        {
 5566            return false;
 5567        }
 5568
 5569        if self.has_visible_completions_menu() {
 5570            return true;
 5571        }
 5572
 5573        has_completion && self.edit_prediction_requires_modifier()
 5574    }
 5575
 5576    fn handle_modifiers_changed(
 5577        &mut self,
 5578        modifiers: Modifiers,
 5579        position_map: &PositionMap,
 5580        window: &mut Window,
 5581        cx: &mut Context<Self>,
 5582    ) {
 5583        if self.show_edit_predictions_in_menu() {
 5584            self.update_edit_prediction_preview(&modifiers, window, cx);
 5585        }
 5586
 5587        self.update_selection_mode(&modifiers, position_map, window, cx);
 5588
 5589        let mouse_position = window.mouse_position();
 5590        if !position_map.text_hitbox.is_hovered(window) {
 5591            return;
 5592        }
 5593
 5594        self.update_hovered_link(
 5595            position_map.point_for_position(mouse_position),
 5596            &position_map.snapshot,
 5597            modifiers,
 5598            window,
 5599            cx,
 5600        )
 5601    }
 5602
 5603    fn update_selection_mode(
 5604        &mut self,
 5605        modifiers: &Modifiers,
 5606        position_map: &PositionMap,
 5607        window: &mut Window,
 5608        cx: &mut Context<Self>,
 5609    ) {
 5610        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5611            return;
 5612        }
 5613
 5614        let mouse_position = window.mouse_position();
 5615        let point_for_position = position_map.point_for_position(mouse_position);
 5616        let position = point_for_position.previous_valid;
 5617
 5618        self.select(
 5619            SelectPhase::BeginColumnar {
 5620                position,
 5621                reset: false,
 5622                goal_column: point_for_position.exact_unclipped.column(),
 5623            },
 5624            window,
 5625            cx,
 5626        );
 5627    }
 5628
 5629    fn update_edit_prediction_preview(
 5630        &mut self,
 5631        modifiers: &Modifiers,
 5632        window: &mut Window,
 5633        cx: &mut Context<Self>,
 5634    ) {
 5635        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5636        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5637            return;
 5638        };
 5639
 5640        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5641            if matches!(
 5642                self.edit_prediction_preview,
 5643                EditPredictionPreview::Inactive { .. }
 5644            ) {
 5645                self.edit_prediction_preview = EditPredictionPreview::Active {
 5646                    previous_scroll_position: None,
 5647                    since: Instant::now(),
 5648                };
 5649
 5650                self.update_visible_inline_completion(window, cx);
 5651                cx.notify();
 5652            }
 5653        } else if let EditPredictionPreview::Active {
 5654            previous_scroll_position,
 5655            since,
 5656        } = self.edit_prediction_preview
 5657        {
 5658            if let (Some(previous_scroll_position), Some(position_map)) =
 5659                (previous_scroll_position, self.last_position_map.as_ref())
 5660            {
 5661                self.set_scroll_position(
 5662                    previous_scroll_position
 5663                        .scroll_position(&position_map.snapshot.display_snapshot),
 5664                    window,
 5665                    cx,
 5666                );
 5667            }
 5668
 5669            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 5670                released_too_fast: since.elapsed() < Duration::from_millis(200),
 5671            };
 5672            self.clear_row_highlights::<EditPredictionPreview>();
 5673            self.update_visible_inline_completion(window, cx);
 5674            cx.notify();
 5675        }
 5676    }
 5677
 5678    fn update_visible_inline_completion(
 5679        &mut self,
 5680        _window: &mut Window,
 5681        cx: &mut Context<Self>,
 5682    ) -> Option<()> {
 5683        let selection = self.selections.newest_anchor();
 5684        let cursor = selection.head();
 5685        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5686        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5687        let excerpt_id = cursor.excerpt_id;
 5688
 5689        let show_in_menu = self.show_edit_predictions_in_menu();
 5690        let completions_menu_has_precedence = !show_in_menu
 5691            && (self.context_menu.borrow().is_some()
 5692                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5693
 5694        if completions_menu_has_precedence
 5695            || !offset_selection.is_empty()
 5696            || self
 5697                .active_inline_completion
 5698                .as_ref()
 5699                .map_or(false, |completion| {
 5700                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5701                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5702                    !invalidation_range.contains(&offset_selection.head())
 5703                })
 5704        {
 5705            self.discard_inline_completion(false, cx);
 5706            return None;
 5707        }
 5708
 5709        self.take_active_inline_completion(cx);
 5710        let Some(provider) = self.edit_prediction_provider() else {
 5711            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5712            return None;
 5713        };
 5714
 5715        let (buffer, cursor_buffer_position) =
 5716            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5717
 5718        self.edit_prediction_settings =
 5719            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5720
 5721        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 5722
 5723        if self.edit_prediction_indent_conflict {
 5724            let cursor_point = cursor.to_point(&multibuffer);
 5725
 5726            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 5727
 5728            if let Some((_, indent)) = indents.iter().next() {
 5729                if indent.len == cursor_point.column {
 5730                    self.edit_prediction_indent_conflict = false;
 5731                }
 5732            }
 5733        }
 5734
 5735        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5736        let edits = inline_completion
 5737            .edits
 5738            .into_iter()
 5739            .flat_map(|(range, new_text)| {
 5740                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5741                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5742                Some((start..end, new_text))
 5743            })
 5744            .collect::<Vec<_>>();
 5745        if edits.is_empty() {
 5746            return None;
 5747        }
 5748
 5749        let first_edit_start = edits.first().unwrap().0.start;
 5750        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5751        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5752
 5753        let last_edit_end = edits.last().unwrap().0.end;
 5754        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5755        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5756
 5757        let cursor_row = cursor.to_point(&multibuffer).row;
 5758
 5759        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5760
 5761        let mut inlay_ids = Vec::new();
 5762        let invalidation_row_range;
 5763        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5764            Some(cursor_row..edit_end_row)
 5765        } else if cursor_row > edit_end_row {
 5766            Some(edit_start_row..cursor_row)
 5767        } else {
 5768            None
 5769        };
 5770        let is_move =
 5771            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5772        let completion = if is_move {
 5773            invalidation_row_range =
 5774                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5775            let target = first_edit_start;
 5776            InlineCompletion::Move { target, snapshot }
 5777        } else {
 5778            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5779                && !self.inline_completions_hidden_for_vim_mode;
 5780
 5781            if show_completions_in_buffer {
 5782                if edits
 5783                    .iter()
 5784                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5785                {
 5786                    let mut inlays = Vec::new();
 5787                    for (range, new_text) in &edits {
 5788                        let inlay = Inlay::inline_completion(
 5789                            post_inc(&mut self.next_inlay_id),
 5790                            range.start,
 5791                            new_text.as_str(),
 5792                        );
 5793                        inlay_ids.push(inlay.id);
 5794                        inlays.push(inlay);
 5795                    }
 5796
 5797                    self.splice_inlays(&[], inlays, cx);
 5798                } else {
 5799                    let background_color = cx.theme().status().deleted_background;
 5800                    self.highlight_text::<InlineCompletionHighlight>(
 5801                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5802                        HighlightStyle {
 5803                            background_color: Some(background_color),
 5804                            ..Default::default()
 5805                        },
 5806                        cx,
 5807                    );
 5808                }
 5809            }
 5810
 5811            invalidation_row_range = edit_start_row..edit_end_row;
 5812
 5813            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5814                if provider.show_tab_accept_marker() {
 5815                    EditDisplayMode::TabAccept
 5816                } else {
 5817                    EditDisplayMode::Inline
 5818                }
 5819            } else {
 5820                EditDisplayMode::DiffPopover
 5821            };
 5822
 5823            InlineCompletion::Edit {
 5824                edits,
 5825                edit_preview: inline_completion.edit_preview,
 5826                display_mode,
 5827                snapshot,
 5828            }
 5829        };
 5830
 5831        let invalidation_range = multibuffer
 5832            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5833            ..multibuffer.anchor_after(Point::new(
 5834                invalidation_row_range.end,
 5835                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5836            ));
 5837
 5838        self.stale_inline_completion_in_menu = None;
 5839        self.active_inline_completion = Some(InlineCompletionState {
 5840            inlay_ids,
 5841            completion,
 5842            completion_id: inline_completion.id,
 5843            invalidation_range,
 5844        });
 5845
 5846        cx.notify();
 5847
 5848        Some(())
 5849    }
 5850
 5851    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5852        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5853    }
 5854
 5855    fn render_code_actions_indicator(
 5856        &self,
 5857        _style: &EditorStyle,
 5858        row: DisplayRow,
 5859        is_active: bool,
 5860        cx: &mut Context<Self>,
 5861    ) -> Option<IconButton> {
 5862        if self.available_code_actions.is_some() {
 5863            Some(
 5864                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5865                    .shape(ui::IconButtonShape::Square)
 5866                    .icon_size(IconSize::XSmall)
 5867                    .icon_color(Color::Muted)
 5868                    .toggle_state(is_active)
 5869                    .tooltip({
 5870                        let focus_handle = self.focus_handle.clone();
 5871                        move |window, cx| {
 5872                            Tooltip::for_action_in(
 5873                                "Toggle Code Actions",
 5874                                &ToggleCodeActions {
 5875                                    deployed_from_indicator: None,
 5876                                },
 5877                                &focus_handle,
 5878                                window,
 5879                                cx,
 5880                            )
 5881                        }
 5882                    })
 5883                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5884                        window.focus(&editor.focus_handle(cx));
 5885                        editor.toggle_code_actions(
 5886                            &ToggleCodeActions {
 5887                                deployed_from_indicator: Some(row),
 5888                            },
 5889                            window,
 5890                            cx,
 5891                        );
 5892                    })),
 5893            )
 5894        } else {
 5895            None
 5896        }
 5897    }
 5898
 5899    fn clear_tasks(&mut self) {
 5900        self.tasks.clear()
 5901    }
 5902
 5903    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5904        if self.tasks.insert(key, value).is_some() {
 5905            // This case should hopefully be rare, but just in case...
 5906            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5907        }
 5908    }
 5909
 5910    fn build_tasks_context(
 5911        project: &Entity<Project>,
 5912        buffer: &Entity<Buffer>,
 5913        buffer_row: u32,
 5914        tasks: &Arc<RunnableTasks>,
 5915        cx: &mut Context<Self>,
 5916    ) -> Task<Option<task::TaskContext>> {
 5917        let position = Point::new(buffer_row, tasks.column);
 5918        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5919        let location = Location {
 5920            buffer: buffer.clone(),
 5921            range: range_start..range_start,
 5922        };
 5923        // Fill in the environmental variables from the tree-sitter captures
 5924        let mut captured_task_variables = TaskVariables::default();
 5925        for (capture_name, value) in tasks.extra_variables.clone() {
 5926            captured_task_variables.insert(
 5927                task::VariableName::Custom(capture_name.into()),
 5928                value.clone(),
 5929            );
 5930        }
 5931        project.update(cx, |project, cx| {
 5932            project.task_store().update(cx, |task_store, cx| {
 5933                task_store.task_context_for_location(captured_task_variables, location, cx)
 5934            })
 5935        })
 5936    }
 5937
 5938    pub fn spawn_nearest_task(
 5939        &mut self,
 5940        action: &SpawnNearestTask,
 5941        window: &mut Window,
 5942        cx: &mut Context<Self>,
 5943    ) {
 5944        let Some((workspace, _)) = self.workspace.clone() else {
 5945            return;
 5946        };
 5947        let Some(project) = self.project.clone() else {
 5948            return;
 5949        };
 5950
 5951        // Try to find a closest, enclosing node using tree-sitter that has a
 5952        // task
 5953        let Some((buffer, buffer_row, tasks)) = self
 5954            .find_enclosing_node_task(cx)
 5955            // Or find the task that's closest in row-distance.
 5956            .or_else(|| self.find_closest_task(cx))
 5957        else {
 5958            return;
 5959        };
 5960
 5961        let reveal_strategy = action.reveal;
 5962        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5963        cx.spawn_in(window, |_, mut cx| async move {
 5964            let context = task_context.await?;
 5965            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5966
 5967            let resolved = resolved_task.resolved.as_mut()?;
 5968            resolved.reveal = reveal_strategy;
 5969
 5970            workspace
 5971                .update(&mut cx, |workspace, cx| {
 5972                    workspace::tasks::schedule_resolved_task(
 5973                        workspace,
 5974                        task_source_kind,
 5975                        resolved_task,
 5976                        false,
 5977                        cx,
 5978                    );
 5979                })
 5980                .ok()
 5981        })
 5982        .detach();
 5983    }
 5984
 5985    fn find_closest_task(
 5986        &mut self,
 5987        cx: &mut Context<Self>,
 5988    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5989        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5990
 5991        let ((buffer_id, row), tasks) = self
 5992            .tasks
 5993            .iter()
 5994            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5995
 5996        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5997        let tasks = Arc::new(tasks.to_owned());
 5998        Some((buffer, *row, tasks))
 5999    }
 6000
 6001    fn find_enclosing_node_task(
 6002        &mut self,
 6003        cx: &mut Context<Self>,
 6004    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6005        let snapshot = self.buffer.read(cx).snapshot(cx);
 6006        let offset = self.selections.newest::<usize>(cx).head();
 6007        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 6008        let buffer_id = excerpt.buffer().remote_id();
 6009
 6010        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 6011        let mut cursor = layer.node().walk();
 6012
 6013        while cursor.goto_first_child_for_byte(offset).is_some() {
 6014            if cursor.node().end_byte() == offset {
 6015                cursor.goto_next_sibling();
 6016            }
 6017        }
 6018
 6019        // Ascend to the smallest ancestor that contains the range and has a task.
 6020        loop {
 6021            let node = cursor.node();
 6022            let node_range = node.byte_range();
 6023            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 6024
 6025            // Check if this node contains our offset
 6026            if node_range.start <= offset && node_range.end >= offset {
 6027                // If it contains offset, check for task
 6028                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 6029                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 6030                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 6031                }
 6032            }
 6033
 6034            if !cursor.goto_parent() {
 6035                break;
 6036            }
 6037        }
 6038        None
 6039    }
 6040
 6041    fn render_run_indicator(
 6042        &self,
 6043        _style: &EditorStyle,
 6044        is_active: bool,
 6045        row: DisplayRow,
 6046        cx: &mut Context<Self>,
 6047    ) -> IconButton {
 6048        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 6049            .shape(ui::IconButtonShape::Square)
 6050            .icon_size(IconSize::XSmall)
 6051            .icon_color(Color::Muted)
 6052            .toggle_state(is_active)
 6053            .on_click(cx.listener(move |editor, _e, window, cx| {
 6054                window.focus(&editor.focus_handle(cx));
 6055                editor.toggle_code_actions(
 6056                    &ToggleCodeActions {
 6057                        deployed_from_indicator: Some(row),
 6058                    },
 6059                    window,
 6060                    cx,
 6061                );
 6062            }))
 6063    }
 6064
 6065    pub fn context_menu_visible(&self) -> bool {
 6066        !self.edit_prediction_preview_is_active()
 6067            && self
 6068                .context_menu
 6069                .borrow()
 6070                .as_ref()
 6071                .map_or(false, |menu| menu.visible())
 6072    }
 6073
 6074    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 6075        self.context_menu
 6076            .borrow()
 6077            .as_ref()
 6078            .map(|menu| menu.origin())
 6079    }
 6080
 6081    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 6082    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 6083
 6084    fn render_edit_prediction_popover(
 6085        &mut self,
 6086        text_bounds: &Bounds<Pixels>,
 6087        content_origin: gpui::Point<Pixels>,
 6088        editor_snapshot: &EditorSnapshot,
 6089        visible_row_range: Range<DisplayRow>,
 6090        scroll_top: f32,
 6091        scroll_bottom: f32,
 6092        line_layouts: &[LineWithInvisibles],
 6093        line_height: Pixels,
 6094        scroll_pixel_position: gpui::Point<Pixels>,
 6095        newest_selection_head: Option<DisplayPoint>,
 6096        editor_width: Pixels,
 6097        style: &EditorStyle,
 6098        window: &mut Window,
 6099        cx: &mut App,
 6100    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6101        let active_inline_completion = self.active_inline_completion.as_ref()?;
 6102
 6103        if self.edit_prediction_visible_in_cursor_popover(true) {
 6104            return None;
 6105        }
 6106
 6107        match &active_inline_completion.completion {
 6108            InlineCompletion::Move { target, .. } => {
 6109                let target_display_point = target.to_display_point(editor_snapshot);
 6110
 6111                if self.edit_prediction_requires_modifier() {
 6112                    if !self.edit_prediction_preview_is_active() {
 6113                        return None;
 6114                    }
 6115
 6116                    self.render_edit_prediction_modifier_jump_popover(
 6117                        text_bounds,
 6118                        content_origin,
 6119                        visible_row_range,
 6120                        line_layouts,
 6121                        line_height,
 6122                        scroll_pixel_position,
 6123                        newest_selection_head,
 6124                        target_display_point,
 6125                        window,
 6126                        cx,
 6127                    )
 6128                } else {
 6129                    self.render_edit_prediction_eager_jump_popover(
 6130                        text_bounds,
 6131                        content_origin,
 6132                        editor_snapshot,
 6133                        visible_row_range,
 6134                        scroll_top,
 6135                        scroll_bottom,
 6136                        line_height,
 6137                        scroll_pixel_position,
 6138                        target_display_point,
 6139                        editor_width,
 6140                        window,
 6141                        cx,
 6142                    )
 6143                }
 6144            }
 6145            InlineCompletion::Edit {
 6146                display_mode: EditDisplayMode::Inline,
 6147                ..
 6148            } => None,
 6149            InlineCompletion::Edit {
 6150                display_mode: EditDisplayMode::TabAccept,
 6151                edits,
 6152                ..
 6153            } => {
 6154                let range = &edits.first()?.0;
 6155                let target_display_point = range.end.to_display_point(editor_snapshot);
 6156
 6157                self.render_edit_prediction_end_of_line_popover(
 6158                    "Accept",
 6159                    editor_snapshot,
 6160                    visible_row_range,
 6161                    target_display_point,
 6162                    line_height,
 6163                    scroll_pixel_position,
 6164                    content_origin,
 6165                    editor_width,
 6166                    window,
 6167                    cx,
 6168                )
 6169            }
 6170            InlineCompletion::Edit {
 6171                edits,
 6172                edit_preview,
 6173                display_mode: EditDisplayMode::DiffPopover,
 6174                snapshot,
 6175            } => self.render_edit_prediction_diff_popover(
 6176                text_bounds,
 6177                content_origin,
 6178                editor_snapshot,
 6179                visible_row_range,
 6180                line_layouts,
 6181                line_height,
 6182                scroll_pixel_position,
 6183                newest_selection_head,
 6184                editor_width,
 6185                style,
 6186                edits,
 6187                edit_preview,
 6188                snapshot,
 6189                window,
 6190                cx,
 6191            ),
 6192        }
 6193    }
 6194
 6195    fn render_edit_prediction_modifier_jump_popover(
 6196        &mut self,
 6197        text_bounds: &Bounds<Pixels>,
 6198        content_origin: gpui::Point<Pixels>,
 6199        visible_row_range: Range<DisplayRow>,
 6200        line_layouts: &[LineWithInvisibles],
 6201        line_height: Pixels,
 6202        scroll_pixel_position: gpui::Point<Pixels>,
 6203        newest_selection_head: Option<DisplayPoint>,
 6204        target_display_point: DisplayPoint,
 6205        window: &mut Window,
 6206        cx: &mut App,
 6207    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6208        let scrolled_content_origin =
 6209            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 6210
 6211        const SCROLL_PADDING_Y: Pixels = px(12.);
 6212
 6213        if target_display_point.row() < visible_row_range.start {
 6214            return self.render_edit_prediction_scroll_popover(
 6215                |_| SCROLL_PADDING_Y,
 6216                IconName::ArrowUp,
 6217                visible_row_range,
 6218                line_layouts,
 6219                newest_selection_head,
 6220                scrolled_content_origin,
 6221                window,
 6222                cx,
 6223            );
 6224        } else if target_display_point.row() >= visible_row_range.end {
 6225            return self.render_edit_prediction_scroll_popover(
 6226                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 6227                IconName::ArrowDown,
 6228                visible_row_range,
 6229                line_layouts,
 6230                newest_selection_head,
 6231                scrolled_content_origin,
 6232                window,
 6233                cx,
 6234            );
 6235        }
 6236
 6237        const POLE_WIDTH: Pixels = px(2.);
 6238
 6239        let line_layout =
 6240            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 6241        let target_column = target_display_point.column() as usize;
 6242
 6243        let target_x = line_layout.x_for_index(target_column);
 6244        let target_y =
 6245            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 6246
 6247        let flag_on_right = target_x < text_bounds.size.width / 2.;
 6248
 6249        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 6250        border_color.l += 0.001;
 6251
 6252        let mut element = v_flex()
 6253            .items_end()
 6254            .when(flag_on_right, |el| el.items_start())
 6255            .child(if flag_on_right {
 6256                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6257                    .rounded_bl(px(0.))
 6258                    .rounded_tl(px(0.))
 6259                    .border_l_2()
 6260                    .border_color(border_color)
 6261            } else {
 6262                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6263                    .rounded_br(px(0.))
 6264                    .rounded_tr(px(0.))
 6265                    .border_r_2()
 6266                    .border_color(border_color)
 6267            })
 6268            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 6269            .into_any();
 6270
 6271        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6272
 6273        let mut origin = scrolled_content_origin + point(target_x, target_y)
 6274            - point(
 6275                if flag_on_right {
 6276                    POLE_WIDTH
 6277                } else {
 6278                    size.width - POLE_WIDTH
 6279                },
 6280                size.height - line_height,
 6281            );
 6282
 6283        origin.x = origin.x.max(content_origin.x);
 6284
 6285        element.prepaint_at(origin, window, cx);
 6286
 6287        Some((element, origin))
 6288    }
 6289
 6290    fn render_edit_prediction_scroll_popover(
 6291        &mut self,
 6292        to_y: impl Fn(Size<Pixels>) -> Pixels,
 6293        scroll_icon: IconName,
 6294        visible_row_range: Range<DisplayRow>,
 6295        line_layouts: &[LineWithInvisibles],
 6296        newest_selection_head: Option<DisplayPoint>,
 6297        scrolled_content_origin: gpui::Point<Pixels>,
 6298        window: &mut Window,
 6299        cx: &mut App,
 6300    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6301        let mut element = self
 6302            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 6303            .into_any();
 6304
 6305        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6306
 6307        let cursor = newest_selection_head?;
 6308        let cursor_row_layout =
 6309            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6310        let cursor_column = cursor.column() as usize;
 6311
 6312        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6313
 6314        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6315
 6316        element.prepaint_at(origin, window, cx);
 6317        Some((element, origin))
 6318    }
 6319
 6320    fn render_edit_prediction_eager_jump_popover(
 6321        &mut self,
 6322        text_bounds: &Bounds<Pixels>,
 6323        content_origin: gpui::Point<Pixels>,
 6324        editor_snapshot: &EditorSnapshot,
 6325        visible_row_range: Range<DisplayRow>,
 6326        scroll_top: f32,
 6327        scroll_bottom: f32,
 6328        line_height: Pixels,
 6329        scroll_pixel_position: gpui::Point<Pixels>,
 6330        target_display_point: DisplayPoint,
 6331        editor_width: Pixels,
 6332        window: &mut Window,
 6333        cx: &mut App,
 6334    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6335        if target_display_point.row().as_f32() < scroll_top {
 6336            let mut element = self
 6337                .render_edit_prediction_line_popover(
 6338                    "Jump to Edit",
 6339                    Some(IconName::ArrowUp),
 6340                    window,
 6341                    cx,
 6342                )?
 6343                .into_any();
 6344
 6345            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6346            let offset = point(
 6347                (text_bounds.size.width - size.width) / 2.,
 6348                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6349            );
 6350
 6351            let origin = text_bounds.origin + offset;
 6352            element.prepaint_at(origin, window, cx);
 6353            Some((element, origin))
 6354        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6355            let mut element = self
 6356                .render_edit_prediction_line_popover(
 6357                    "Jump to Edit",
 6358                    Some(IconName::ArrowDown),
 6359                    window,
 6360                    cx,
 6361                )?
 6362                .into_any();
 6363
 6364            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6365            let offset = point(
 6366                (text_bounds.size.width - size.width) / 2.,
 6367                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6368            );
 6369
 6370            let origin = text_bounds.origin + offset;
 6371            element.prepaint_at(origin, window, cx);
 6372            Some((element, origin))
 6373        } else {
 6374            self.render_edit_prediction_end_of_line_popover(
 6375                "Jump to Edit",
 6376                editor_snapshot,
 6377                visible_row_range,
 6378                target_display_point,
 6379                line_height,
 6380                scroll_pixel_position,
 6381                content_origin,
 6382                editor_width,
 6383                window,
 6384                cx,
 6385            )
 6386        }
 6387    }
 6388
 6389    fn render_edit_prediction_end_of_line_popover(
 6390        self: &mut Editor,
 6391        label: &'static str,
 6392        editor_snapshot: &EditorSnapshot,
 6393        visible_row_range: Range<DisplayRow>,
 6394        target_display_point: DisplayPoint,
 6395        line_height: Pixels,
 6396        scroll_pixel_position: gpui::Point<Pixels>,
 6397        content_origin: gpui::Point<Pixels>,
 6398        editor_width: Pixels,
 6399        window: &mut Window,
 6400        cx: &mut App,
 6401    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6402        let target_line_end = DisplayPoint::new(
 6403            target_display_point.row(),
 6404            editor_snapshot.line_len(target_display_point.row()),
 6405        );
 6406
 6407        let mut element = self
 6408            .render_edit_prediction_line_popover(label, None, window, cx)?
 6409            .into_any();
 6410
 6411        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6412
 6413        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 6414
 6415        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 6416        let mut origin = start_point
 6417            + line_origin
 6418            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 6419        origin.x = origin.x.max(content_origin.x);
 6420
 6421        let max_x = content_origin.x + editor_width - size.width;
 6422
 6423        if origin.x > max_x {
 6424            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 6425
 6426            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 6427                origin.y += offset;
 6428                IconName::ArrowUp
 6429            } else {
 6430                origin.y -= offset;
 6431                IconName::ArrowDown
 6432            };
 6433
 6434            element = self
 6435                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 6436                .into_any();
 6437
 6438            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6439
 6440            origin.x = content_origin.x + editor_width - size.width - px(2.);
 6441        }
 6442
 6443        element.prepaint_at(origin, window, cx);
 6444        Some((element, origin))
 6445    }
 6446
 6447    fn render_edit_prediction_diff_popover(
 6448        self: &Editor,
 6449        text_bounds: &Bounds<Pixels>,
 6450        content_origin: gpui::Point<Pixels>,
 6451        editor_snapshot: &EditorSnapshot,
 6452        visible_row_range: Range<DisplayRow>,
 6453        line_layouts: &[LineWithInvisibles],
 6454        line_height: Pixels,
 6455        scroll_pixel_position: gpui::Point<Pixels>,
 6456        newest_selection_head: Option<DisplayPoint>,
 6457        editor_width: Pixels,
 6458        style: &EditorStyle,
 6459        edits: &Vec<(Range<Anchor>, String)>,
 6460        edit_preview: &Option<language::EditPreview>,
 6461        snapshot: &language::BufferSnapshot,
 6462        window: &mut Window,
 6463        cx: &mut App,
 6464    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6465        let edit_start = edits
 6466            .first()
 6467            .unwrap()
 6468            .0
 6469            .start
 6470            .to_display_point(editor_snapshot);
 6471        let edit_end = edits
 6472            .last()
 6473            .unwrap()
 6474            .0
 6475            .end
 6476            .to_display_point(editor_snapshot);
 6477
 6478        let is_visible = visible_row_range.contains(&edit_start.row())
 6479            || visible_row_range.contains(&edit_end.row());
 6480        if !is_visible {
 6481            return None;
 6482        }
 6483
 6484        let highlighted_edits =
 6485            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 6486
 6487        let styled_text = highlighted_edits.to_styled_text(&style.text);
 6488        let line_count = highlighted_edits.text.lines().count();
 6489
 6490        const BORDER_WIDTH: Pixels = px(1.);
 6491
 6492        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 6493        let has_keybind = keybind.is_some();
 6494
 6495        let mut element = h_flex()
 6496            .items_start()
 6497            .child(
 6498                h_flex()
 6499                    .bg(cx.theme().colors().editor_background)
 6500                    .border(BORDER_WIDTH)
 6501                    .shadow_sm()
 6502                    .border_color(cx.theme().colors().border)
 6503                    .rounded_l_lg()
 6504                    .when(line_count > 1, |el| el.rounded_br_lg())
 6505                    .pr_1()
 6506                    .child(styled_text),
 6507            )
 6508            .child(
 6509                h_flex()
 6510                    .h(line_height + BORDER_WIDTH * px(2.))
 6511                    .px_1p5()
 6512                    .gap_1()
 6513                    // Workaround: For some reason, there's a gap if we don't do this
 6514                    .ml(-BORDER_WIDTH)
 6515                    .shadow(smallvec![gpui::BoxShadow {
 6516                        color: gpui::black().opacity(0.05),
 6517                        offset: point(px(1.), px(1.)),
 6518                        blur_radius: px(2.),
 6519                        spread_radius: px(0.),
 6520                    }])
 6521                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 6522                    .border(BORDER_WIDTH)
 6523                    .border_color(cx.theme().colors().border)
 6524                    .rounded_r_lg()
 6525                    .id("edit_prediction_diff_popover_keybind")
 6526                    .when(!has_keybind, |el| {
 6527                        let status_colors = cx.theme().status();
 6528
 6529                        el.bg(status_colors.error_background)
 6530                            .border_color(status_colors.error.opacity(0.6))
 6531                            .child(Icon::new(IconName::Info).color(Color::Error))
 6532                            .cursor_default()
 6533                            .hoverable_tooltip(move |_window, cx| {
 6534                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 6535                            })
 6536                    })
 6537                    .children(keybind),
 6538            )
 6539            .into_any();
 6540
 6541        let longest_row =
 6542            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 6543        let longest_line_width = if visible_row_range.contains(&longest_row) {
 6544            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 6545        } else {
 6546            layout_line(
 6547                longest_row,
 6548                editor_snapshot,
 6549                style,
 6550                editor_width,
 6551                |_| false,
 6552                window,
 6553                cx,
 6554            )
 6555            .width
 6556        };
 6557
 6558        let viewport_bounds =
 6559            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 6560                right: -EditorElement::SCROLLBAR_WIDTH,
 6561                ..Default::default()
 6562            });
 6563
 6564        let x_after_longest =
 6565            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 6566                - scroll_pixel_position.x;
 6567
 6568        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6569
 6570        // Fully visible if it can be displayed within the window (allow overlapping other
 6571        // panes). However, this is only allowed if the popover starts within text_bounds.
 6572        let can_position_to_the_right = x_after_longest < text_bounds.right()
 6573            && x_after_longest + element_bounds.width < viewport_bounds.right();
 6574
 6575        let mut origin = if can_position_to_the_right {
 6576            point(
 6577                x_after_longest,
 6578                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 6579                    - scroll_pixel_position.y,
 6580            )
 6581        } else {
 6582            let cursor_row = newest_selection_head.map(|head| head.row());
 6583            let above_edit = edit_start
 6584                .row()
 6585                .0
 6586                .checked_sub(line_count as u32)
 6587                .map(DisplayRow);
 6588            let below_edit = Some(edit_end.row() + 1);
 6589            let above_cursor =
 6590                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 6591            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 6592
 6593            // Place the edit popover adjacent to the edit if there is a location
 6594            // available that is onscreen and does not obscure the cursor. Otherwise,
 6595            // place it adjacent to the cursor.
 6596            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 6597                .into_iter()
 6598                .flatten()
 6599                .find(|&start_row| {
 6600                    let end_row = start_row + line_count as u32;
 6601                    visible_row_range.contains(&start_row)
 6602                        && visible_row_range.contains(&end_row)
 6603                        && cursor_row.map_or(true, |cursor_row| {
 6604                            !((start_row..end_row).contains(&cursor_row))
 6605                        })
 6606                })?;
 6607
 6608            content_origin
 6609                + point(
 6610                    -scroll_pixel_position.x,
 6611                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 6612                )
 6613        };
 6614
 6615        origin.x -= BORDER_WIDTH;
 6616
 6617        window.defer_draw(element, origin, 1);
 6618
 6619        // Do not return an element, since it will already be drawn due to defer_draw.
 6620        None
 6621    }
 6622
 6623    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 6624        px(30.)
 6625    }
 6626
 6627    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 6628        if self.read_only(cx) {
 6629            cx.theme().players().read_only()
 6630        } else {
 6631            self.style.as_ref().unwrap().local_player
 6632        }
 6633    }
 6634
 6635    fn render_edit_prediction_accept_keybind(
 6636        &self,
 6637        window: &mut Window,
 6638        cx: &App,
 6639    ) -> Option<AnyElement> {
 6640        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 6641        let accept_keystroke = accept_binding.keystroke()?;
 6642
 6643        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6644
 6645        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 6646            Color::Accent
 6647        } else {
 6648            Color::Muted
 6649        };
 6650
 6651        h_flex()
 6652            .px_0p5()
 6653            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 6654            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6655            .text_size(TextSize::XSmall.rems(cx))
 6656            .child(h_flex().children(ui::render_modifiers(
 6657                &accept_keystroke.modifiers,
 6658                PlatformStyle::platform(),
 6659                Some(modifiers_color),
 6660                Some(IconSize::XSmall.rems().into()),
 6661                true,
 6662            )))
 6663            .when(is_platform_style_mac, |parent| {
 6664                parent.child(accept_keystroke.key.clone())
 6665            })
 6666            .when(!is_platform_style_mac, |parent| {
 6667                parent.child(
 6668                    Key::new(
 6669                        util::capitalize(&accept_keystroke.key),
 6670                        Some(Color::Default),
 6671                    )
 6672                    .size(Some(IconSize::XSmall.rems().into())),
 6673                )
 6674            })
 6675            .into_any()
 6676            .into()
 6677    }
 6678
 6679    fn render_edit_prediction_line_popover(
 6680        &self,
 6681        label: impl Into<SharedString>,
 6682        icon: Option<IconName>,
 6683        window: &mut Window,
 6684        cx: &App,
 6685    ) -> Option<Stateful<Div>> {
 6686        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 6687
 6688        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 6689        let has_keybind = keybind.is_some();
 6690
 6691        let result = h_flex()
 6692            .id("ep-line-popover")
 6693            .py_0p5()
 6694            .pl_1()
 6695            .pr(padding_right)
 6696            .gap_1()
 6697            .rounded_md()
 6698            .border_1()
 6699            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6700            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 6701            .shadow_sm()
 6702            .when(!has_keybind, |el| {
 6703                let status_colors = cx.theme().status();
 6704
 6705                el.bg(status_colors.error_background)
 6706                    .border_color(status_colors.error.opacity(0.6))
 6707                    .pl_2()
 6708                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 6709                    .cursor_default()
 6710                    .hoverable_tooltip(move |_window, cx| {
 6711                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 6712                    })
 6713            })
 6714            .children(keybind)
 6715            .child(
 6716                Label::new(label)
 6717                    .size(LabelSize::Small)
 6718                    .when(!has_keybind, |el| {
 6719                        el.color(cx.theme().status().error.into()).strikethrough()
 6720                    }),
 6721            )
 6722            .when(!has_keybind, |el| {
 6723                el.child(
 6724                    h_flex().ml_1().child(
 6725                        Icon::new(IconName::Info)
 6726                            .size(IconSize::Small)
 6727                            .color(cx.theme().status().error.into()),
 6728                    ),
 6729                )
 6730            })
 6731            .when_some(icon, |element, icon| {
 6732                element.child(
 6733                    div()
 6734                        .mt(px(1.5))
 6735                        .child(Icon::new(icon).size(IconSize::Small)),
 6736                )
 6737            });
 6738
 6739        Some(result)
 6740    }
 6741
 6742    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 6743        let accent_color = cx.theme().colors().text_accent;
 6744        let editor_bg_color = cx.theme().colors().editor_background;
 6745        editor_bg_color.blend(accent_color.opacity(0.1))
 6746    }
 6747
 6748    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 6749        let accent_color = cx.theme().colors().text_accent;
 6750        let editor_bg_color = cx.theme().colors().editor_background;
 6751        editor_bg_color.blend(accent_color.opacity(0.6))
 6752    }
 6753
 6754    fn render_edit_prediction_cursor_popover(
 6755        &self,
 6756        min_width: Pixels,
 6757        max_width: Pixels,
 6758        cursor_point: Point,
 6759        style: &EditorStyle,
 6760        accept_keystroke: Option<&gpui::Keystroke>,
 6761        _window: &Window,
 6762        cx: &mut Context<Editor>,
 6763    ) -> Option<AnyElement> {
 6764        let provider = self.edit_prediction_provider.as_ref()?;
 6765
 6766        if provider.provider.needs_terms_acceptance(cx) {
 6767            return Some(
 6768                h_flex()
 6769                    .min_w(min_width)
 6770                    .flex_1()
 6771                    .px_2()
 6772                    .py_1()
 6773                    .gap_3()
 6774                    .elevation_2(cx)
 6775                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 6776                    .id("accept-terms")
 6777                    .cursor_pointer()
 6778                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 6779                    .on_click(cx.listener(|this, _event, window, cx| {
 6780                        cx.stop_propagation();
 6781                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 6782                        window.dispatch_action(
 6783                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 6784                            cx,
 6785                        );
 6786                    }))
 6787                    .child(
 6788                        h_flex()
 6789                            .flex_1()
 6790                            .gap_2()
 6791                            .child(Icon::new(IconName::ZedPredict))
 6792                            .child(Label::new("Accept Terms of Service"))
 6793                            .child(div().w_full())
 6794                            .child(
 6795                                Icon::new(IconName::ArrowUpRight)
 6796                                    .color(Color::Muted)
 6797                                    .size(IconSize::Small),
 6798                            )
 6799                            .into_any_element(),
 6800                    )
 6801                    .into_any(),
 6802            );
 6803        }
 6804
 6805        let is_refreshing = provider.provider.is_refreshing(cx);
 6806
 6807        fn pending_completion_container() -> Div {
 6808            h_flex()
 6809                .h_full()
 6810                .flex_1()
 6811                .gap_2()
 6812                .child(Icon::new(IconName::ZedPredict))
 6813        }
 6814
 6815        let completion = match &self.active_inline_completion {
 6816            Some(prediction) => {
 6817                if !self.has_visible_completions_menu() {
 6818                    const RADIUS: Pixels = px(6.);
 6819                    const BORDER_WIDTH: Pixels = px(1.);
 6820
 6821                    return Some(
 6822                        h_flex()
 6823                            .elevation_2(cx)
 6824                            .border(BORDER_WIDTH)
 6825                            .border_color(cx.theme().colors().border)
 6826                            .when(accept_keystroke.is_none(), |el| {
 6827                                el.border_color(cx.theme().status().error)
 6828                            })
 6829                            .rounded(RADIUS)
 6830                            .rounded_tl(px(0.))
 6831                            .overflow_hidden()
 6832                            .child(div().px_1p5().child(match &prediction.completion {
 6833                                InlineCompletion::Move { target, snapshot } => {
 6834                                    use text::ToPoint as _;
 6835                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 6836                                    {
 6837                                        Icon::new(IconName::ZedPredictDown)
 6838                                    } else {
 6839                                        Icon::new(IconName::ZedPredictUp)
 6840                                    }
 6841                                }
 6842                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 6843                            }))
 6844                            .child(
 6845                                h_flex()
 6846                                    .gap_1()
 6847                                    .py_1()
 6848                                    .px_2()
 6849                                    .rounded_r(RADIUS - BORDER_WIDTH)
 6850                                    .border_l_1()
 6851                                    .border_color(cx.theme().colors().border)
 6852                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6853                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 6854                                        el.child(
 6855                                            Label::new("Hold")
 6856                                                .size(LabelSize::Small)
 6857                                                .when(accept_keystroke.is_none(), |el| {
 6858                                                    el.strikethrough()
 6859                                                })
 6860                                                .line_height_style(LineHeightStyle::UiLabel),
 6861                                        )
 6862                                    })
 6863                                    .id("edit_prediction_cursor_popover_keybind")
 6864                                    .when(accept_keystroke.is_none(), |el| {
 6865                                        let status_colors = cx.theme().status();
 6866
 6867                                        el.bg(status_colors.error_background)
 6868                                            .border_color(status_colors.error.opacity(0.6))
 6869                                            .child(Icon::new(IconName::Info).color(Color::Error))
 6870                                            .cursor_default()
 6871                                            .hoverable_tooltip(move |_window, cx| {
 6872                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 6873                                                    .into()
 6874                                            })
 6875                                    })
 6876                                    .when_some(
 6877                                        accept_keystroke.as_ref(),
 6878                                        |el, accept_keystroke| {
 6879                                            el.child(h_flex().children(ui::render_modifiers(
 6880                                                &accept_keystroke.modifiers,
 6881                                                PlatformStyle::platform(),
 6882                                                Some(Color::Default),
 6883                                                Some(IconSize::XSmall.rems().into()),
 6884                                                false,
 6885                                            )))
 6886                                        },
 6887                                    ),
 6888                            )
 6889                            .into_any(),
 6890                    );
 6891                }
 6892
 6893                self.render_edit_prediction_cursor_popover_preview(
 6894                    prediction,
 6895                    cursor_point,
 6896                    style,
 6897                    cx,
 6898                )?
 6899            }
 6900
 6901            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 6902                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 6903                    stale_completion,
 6904                    cursor_point,
 6905                    style,
 6906                    cx,
 6907                )?,
 6908
 6909                None => {
 6910                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6911                }
 6912            },
 6913
 6914            None => pending_completion_container().child(Label::new("No Prediction")),
 6915        };
 6916
 6917        let completion = if is_refreshing {
 6918            completion
 6919                .with_animation(
 6920                    "loading-completion",
 6921                    Animation::new(Duration::from_secs(2))
 6922                        .repeat()
 6923                        .with_easing(pulsating_between(0.4, 0.8)),
 6924                    |label, delta| label.opacity(delta),
 6925                )
 6926                .into_any_element()
 6927        } else {
 6928            completion.into_any_element()
 6929        };
 6930
 6931        let has_completion = self.active_inline_completion.is_some();
 6932
 6933        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6934        Some(
 6935            h_flex()
 6936                .min_w(min_width)
 6937                .max_w(max_width)
 6938                .flex_1()
 6939                .elevation_2(cx)
 6940                .border_color(cx.theme().colors().border)
 6941                .child(
 6942                    div()
 6943                        .flex_1()
 6944                        .py_1()
 6945                        .px_2()
 6946                        .overflow_hidden()
 6947                        .child(completion),
 6948                )
 6949                .when_some(accept_keystroke, |el, accept_keystroke| {
 6950                    if !accept_keystroke.modifiers.modified() {
 6951                        return el;
 6952                    }
 6953
 6954                    el.child(
 6955                        h_flex()
 6956                            .h_full()
 6957                            .border_l_1()
 6958                            .rounded_r_lg()
 6959                            .border_color(cx.theme().colors().border)
 6960                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6961                            .gap_1()
 6962                            .py_1()
 6963                            .px_2()
 6964                            .child(
 6965                                h_flex()
 6966                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6967                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6968                                    .child(h_flex().children(ui::render_modifiers(
 6969                                        &accept_keystroke.modifiers,
 6970                                        PlatformStyle::platform(),
 6971                                        Some(if !has_completion {
 6972                                            Color::Muted
 6973                                        } else {
 6974                                            Color::Default
 6975                                        }),
 6976                                        None,
 6977                                        false,
 6978                                    ))),
 6979                            )
 6980                            .child(Label::new("Preview").into_any_element())
 6981                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6982                    )
 6983                })
 6984                .into_any(),
 6985        )
 6986    }
 6987
 6988    fn render_edit_prediction_cursor_popover_preview(
 6989        &self,
 6990        completion: &InlineCompletionState,
 6991        cursor_point: Point,
 6992        style: &EditorStyle,
 6993        cx: &mut Context<Editor>,
 6994    ) -> Option<Div> {
 6995        use text::ToPoint as _;
 6996
 6997        fn render_relative_row_jump(
 6998            prefix: impl Into<String>,
 6999            current_row: u32,
 7000            target_row: u32,
 7001        ) -> Div {
 7002            let (row_diff, arrow) = if target_row < current_row {
 7003                (current_row - target_row, IconName::ArrowUp)
 7004            } else {
 7005                (target_row - current_row, IconName::ArrowDown)
 7006            };
 7007
 7008            h_flex()
 7009                .child(
 7010                    Label::new(format!("{}{}", prefix.into(), row_diff))
 7011                        .color(Color::Muted)
 7012                        .size(LabelSize::Small),
 7013                )
 7014                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 7015        }
 7016
 7017        match &completion.completion {
 7018            InlineCompletion::Move {
 7019                target, snapshot, ..
 7020            } => Some(
 7021                h_flex()
 7022                    .px_2()
 7023                    .gap_2()
 7024                    .flex_1()
 7025                    .child(
 7026                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 7027                            Icon::new(IconName::ZedPredictDown)
 7028                        } else {
 7029                            Icon::new(IconName::ZedPredictUp)
 7030                        },
 7031                    )
 7032                    .child(Label::new("Jump to Edit")),
 7033            ),
 7034
 7035            InlineCompletion::Edit {
 7036                edits,
 7037                edit_preview,
 7038                snapshot,
 7039                display_mode: _,
 7040            } => {
 7041                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 7042
 7043                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 7044                    &snapshot,
 7045                    &edits,
 7046                    edit_preview.as_ref()?,
 7047                    true,
 7048                    cx,
 7049                )
 7050                .first_line_preview();
 7051
 7052                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 7053                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 7054
 7055                let preview = h_flex()
 7056                    .gap_1()
 7057                    .min_w_16()
 7058                    .child(styled_text)
 7059                    .when(has_more_lines, |parent| parent.child(""));
 7060
 7061                let left = if first_edit_row != cursor_point.row {
 7062                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 7063                        .into_any_element()
 7064                } else {
 7065                    Icon::new(IconName::ZedPredict).into_any_element()
 7066                };
 7067
 7068                Some(
 7069                    h_flex()
 7070                        .h_full()
 7071                        .flex_1()
 7072                        .gap_2()
 7073                        .pr_1()
 7074                        .overflow_x_hidden()
 7075                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7076                        .child(left)
 7077                        .child(preview),
 7078                )
 7079            }
 7080        }
 7081    }
 7082
 7083    fn render_context_menu(
 7084        &self,
 7085        style: &EditorStyle,
 7086        max_height_in_lines: u32,
 7087        y_flipped: bool,
 7088        window: &mut Window,
 7089        cx: &mut Context<Editor>,
 7090    ) -> Option<AnyElement> {
 7091        let menu = self.context_menu.borrow();
 7092        let menu = menu.as_ref()?;
 7093        if !menu.visible() {
 7094            return None;
 7095        };
 7096        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 7097    }
 7098
 7099    fn render_context_menu_aside(
 7100        &mut self,
 7101        max_size: Size<Pixels>,
 7102        window: &mut Window,
 7103        cx: &mut Context<Editor>,
 7104    ) -> Option<AnyElement> {
 7105        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 7106            if menu.visible() {
 7107                menu.render_aside(self, max_size, window, cx)
 7108            } else {
 7109                None
 7110            }
 7111        })
 7112    }
 7113
 7114    fn hide_context_menu(
 7115        &mut self,
 7116        window: &mut Window,
 7117        cx: &mut Context<Self>,
 7118    ) -> Option<CodeContextMenu> {
 7119        cx.notify();
 7120        self.completion_tasks.clear();
 7121        let context_menu = self.context_menu.borrow_mut().take();
 7122        self.stale_inline_completion_in_menu.take();
 7123        self.update_visible_inline_completion(window, cx);
 7124        context_menu
 7125    }
 7126
 7127    fn show_snippet_choices(
 7128        &mut self,
 7129        choices: &Vec<String>,
 7130        selection: Range<Anchor>,
 7131        cx: &mut Context<Self>,
 7132    ) {
 7133        if selection.start.buffer_id.is_none() {
 7134            return;
 7135        }
 7136        let buffer_id = selection.start.buffer_id.unwrap();
 7137        let buffer = self.buffer().read(cx).buffer(buffer_id);
 7138        let id = post_inc(&mut self.next_completion_id);
 7139
 7140        if let Some(buffer) = buffer {
 7141            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 7142                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 7143            ));
 7144        }
 7145    }
 7146
 7147    pub fn insert_snippet(
 7148        &mut self,
 7149        insertion_ranges: &[Range<usize>],
 7150        snippet: Snippet,
 7151        window: &mut Window,
 7152        cx: &mut Context<Self>,
 7153    ) -> Result<()> {
 7154        struct Tabstop<T> {
 7155            is_end_tabstop: bool,
 7156            ranges: Vec<Range<T>>,
 7157            choices: Option<Vec<String>>,
 7158        }
 7159
 7160        let tabstops = self.buffer.update(cx, |buffer, cx| {
 7161            let snippet_text: Arc<str> = snippet.text.clone().into();
 7162            buffer.edit(
 7163                insertion_ranges
 7164                    .iter()
 7165                    .cloned()
 7166                    .map(|range| (range, snippet_text.clone())),
 7167                Some(AutoindentMode::EachLine),
 7168                cx,
 7169            );
 7170
 7171            let snapshot = &*buffer.read(cx);
 7172            let snippet = &snippet;
 7173            snippet
 7174                .tabstops
 7175                .iter()
 7176                .map(|tabstop| {
 7177                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 7178                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 7179                    });
 7180                    let mut tabstop_ranges = tabstop
 7181                        .ranges
 7182                        .iter()
 7183                        .flat_map(|tabstop_range| {
 7184                            let mut delta = 0_isize;
 7185                            insertion_ranges.iter().map(move |insertion_range| {
 7186                                let insertion_start = insertion_range.start as isize + delta;
 7187                                delta +=
 7188                                    snippet.text.len() as isize - insertion_range.len() as isize;
 7189
 7190                                let start = ((insertion_start + tabstop_range.start) as usize)
 7191                                    .min(snapshot.len());
 7192                                let end = ((insertion_start + tabstop_range.end) as usize)
 7193                                    .min(snapshot.len());
 7194                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 7195                            })
 7196                        })
 7197                        .collect::<Vec<_>>();
 7198                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 7199
 7200                    Tabstop {
 7201                        is_end_tabstop,
 7202                        ranges: tabstop_ranges,
 7203                        choices: tabstop.choices.clone(),
 7204                    }
 7205                })
 7206                .collect::<Vec<_>>()
 7207        });
 7208        if let Some(tabstop) = tabstops.first() {
 7209            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7210                s.select_ranges(tabstop.ranges.iter().cloned());
 7211            });
 7212
 7213            if let Some(choices) = &tabstop.choices {
 7214                if let Some(selection) = tabstop.ranges.first() {
 7215                    self.show_snippet_choices(choices, selection.clone(), cx)
 7216                }
 7217            }
 7218
 7219            // If we're already at the last tabstop and it's at the end of the snippet,
 7220            // we're done, we don't need to keep the state around.
 7221            if !tabstop.is_end_tabstop {
 7222                let choices = tabstops
 7223                    .iter()
 7224                    .map(|tabstop| tabstop.choices.clone())
 7225                    .collect();
 7226
 7227                let ranges = tabstops
 7228                    .into_iter()
 7229                    .map(|tabstop| tabstop.ranges)
 7230                    .collect::<Vec<_>>();
 7231
 7232                self.snippet_stack.push(SnippetState {
 7233                    active_index: 0,
 7234                    ranges,
 7235                    choices,
 7236                });
 7237            }
 7238
 7239            // Check whether the just-entered snippet ends with an auto-closable bracket.
 7240            if self.autoclose_regions.is_empty() {
 7241                let snapshot = self.buffer.read(cx).snapshot(cx);
 7242                for selection in &mut self.selections.all::<Point>(cx) {
 7243                    let selection_head = selection.head();
 7244                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 7245                        continue;
 7246                    };
 7247
 7248                    let mut bracket_pair = None;
 7249                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 7250                    let prev_chars = snapshot
 7251                        .reversed_chars_at(selection_head)
 7252                        .collect::<String>();
 7253                    for (pair, enabled) in scope.brackets() {
 7254                        if enabled
 7255                            && pair.close
 7256                            && prev_chars.starts_with(pair.start.as_str())
 7257                            && next_chars.starts_with(pair.end.as_str())
 7258                        {
 7259                            bracket_pair = Some(pair.clone());
 7260                            break;
 7261                        }
 7262                    }
 7263                    if let Some(pair) = bracket_pair {
 7264                        let start = snapshot.anchor_after(selection_head);
 7265                        let end = snapshot.anchor_after(selection_head);
 7266                        self.autoclose_regions.push(AutocloseRegion {
 7267                            selection_id: selection.id,
 7268                            range: start..end,
 7269                            pair,
 7270                        });
 7271                    }
 7272                }
 7273            }
 7274        }
 7275        Ok(())
 7276    }
 7277
 7278    pub fn move_to_next_snippet_tabstop(
 7279        &mut self,
 7280        window: &mut Window,
 7281        cx: &mut Context<Self>,
 7282    ) -> bool {
 7283        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 7284    }
 7285
 7286    pub fn move_to_prev_snippet_tabstop(
 7287        &mut self,
 7288        window: &mut Window,
 7289        cx: &mut Context<Self>,
 7290    ) -> bool {
 7291        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 7292    }
 7293
 7294    pub fn move_to_snippet_tabstop(
 7295        &mut self,
 7296        bias: Bias,
 7297        window: &mut Window,
 7298        cx: &mut Context<Self>,
 7299    ) -> bool {
 7300        if let Some(mut snippet) = self.snippet_stack.pop() {
 7301            match bias {
 7302                Bias::Left => {
 7303                    if snippet.active_index > 0 {
 7304                        snippet.active_index -= 1;
 7305                    } else {
 7306                        self.snippet_stack.push(snippet);
 7307                        return false;
 7308                    }
 7309                }
 7310                Bias::Right => {
 7311                    if snippet.active_index + 1 < snippet.ranges.len() {
 7312                        snippet.active_index += 1;
 7313                    } else {
 7314                        self.snippet_stack.push(snippet);
 7315                        return false;
 7316                    }
 7317                }
 7318            }
 7319            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 7320                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7321                    s.select_anchor_ranges(current_ranges.iter().cloned())
 7322                });
 7323
 7324                if let Some(choices) = &snippet.choices[snippet.active_index] {
 7325                    if let Some(selection) = current_ranges.first() {
 7326                        self.show_snippet_choices(&choices, selection.clone(), cx);
 7327                    }
 7328                }
 7329
 7330                // If snippet state is not at the last tabstop, push it back on the stack
 7331                if snippet.active_index + 1 < snippet.ranges.len() {
 7332                    self.snippet_stack.push(snippet);
 7333                }
 7334                return true;
 7335            }
 7336        }
 7337
 7338        false
 7339    }
 7340
 7341    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 7342        self.transact(window, cx, |this, window, cx| {
 7343            this.select_all(&SelectAll, window, cx);
 7344            this.insert("", window, cx);
 7345        });
 7346    }
 7347
 7348    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 7349        self.transact(window, cx, |this, window, cx| {
 7350            this.select_autoclose_pair(window, cx);
 7351            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 7352            if !this.linked_edit_ranges.is_empty() {
 7353                let selections = this.selections.all::<MultiBufferPoint>(cx);
 7354                let snapshot = this.buffer.read(cx).snapshot(cx);
 7355
 7356                for selection in selections.iter() {
 7357                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 7358                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 7359                    if selection_start.buffer_id != selection_end.buffer_id {
 7360                        continue;
 7361                    }
 7362                    if let Some(ranges) =
 7363                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 7364                    {
 7365                        for (buffer, entries) in ranges {
 7366                            linked_ranges.entry(buffer).or_default().extend(entries);
 7367                        }
 7368                    }
 7369                }
 7370            }
 7371
 7372            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7373            if !this.selections.line_mode {
 7374                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 7375                for selection in &mut selections {
 7376                    if selection.is_empty() {
 7377                        let old_head = selection.head();
 7378                        let mut new_head =
 7379                            movement::left(&display_map, old_head.to_display_point(&display_map))
 7380                                .to_point(&display_map);
 7381                        if let Some((buffer, line_buffer_range)) = display_map
 7382                            .buffer_snapshot
 7383                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 7384                        {
 7385                            let indent_size =
 7386                                buffer.indent_size_for_line(line_buffer_range.start.row);
 7387                            let indent_len = match indent_size.kind {
 7388                                IndentKind::Space => {
 7389                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 7390                                }
 7391                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 7392                            };
 7393                            if old_head.column <= indent_size.len && old_head.column > 0 {
 7394                                let indent_len = indent_len.get();
 7395                                new_head = cmp::min(
 7396                                    new_head,
 7397                                    MultiBufferPoint::new(
 7398                                        old_head.row,
 7399                                        ((old_head.column - 1) / indent_len) * indent_len,
 7400                                    ),
 7401                                );
 7402                            }
 7403                        }
 7404
 7405                        selection.set_head(new_head, SelectionGoal::None);
 7406                    }
 7407                }
 7408            }
 7409
 7410            this.signature_help_state.set_backspace_pressed(true);
 7411            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7412                s.select(selections)
 7413            });
 7414            this.insert("", window, cx);
 7415            let empty_str: Arc<str> = Arc::from("");
 7416            for (buffer, edits) in linked_ranges {
 7417                let snapshot = buffer.read(cx).snapshot();
 7418                use text::ToPoint as TP;
 7419
 7420                let edits = edits
 7421                    .into_iter()
 7422                    .map(|range| {
 7423                        let end_point = TP::to_point(&range.end, &snapshot);
 7424                        let mut start_point = TP::to_point(&range.start, &snapshot);
 7425
 7426                        if end_point == start_point {
 7427                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 7428                                .saturating_sub(1);
 7429                            start_point =
 7430                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 7431                        };
 7432
 7433                        (start_point..end_point, empty_str.clone())
 7434                    })
 7435                    .sorted_by_key(|(range, _)| range.start)
 7436                    .collect::<Vec<_>>();
 7437                buffer.update(cx, |this, cx| {
 7438                    this.edit(edits, None, cx);
 7439                })
 7440            }
 7441            this.refresh_inline_completion(true, false, window, cx);
 7442            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 7443        });
 7444    }
 7445
 7446    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 7447        self.transact(window, cx, |this, window, cx| {
 7448            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7449                let line_mode = s.line_mode;
 7450                s.move_with(|map, selection| {
 7451                    if selection.is_empty() && !line_mode {
 7452                        let cursor = movement::right(map, selection.head());
 7453                        selection.end = cursor;
 7454                        selection.reversed = true;
 7455                        selection.goal = SelectionGoal::None;
 7456                    }
 7457                })
 7458            });
 7459            this.insert("", window, cx);
 7460            this.refresh_inline_completion(true, false, window, cx);
 7461        });
 7462    }
 7463
 7464    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 7465        if self.move_to_prev_snippet_tabstop(window, cx) {
 7466            return;
 7467        }
 7468
 7469        self.outdent(&Outdent, window, cx);
 7470    }
 7471
 7472    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 7473        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 7474            return;
 7475        }
 7476
 7477        let mut selections = self.selections.all_adjusted(cx);
 7478        let buffer = self.buffer.read(cx);
 7479        let snapshot = buffer.snapshot(cx);
 7480        let rows_iter = selections.iter().map(|s| s.head().row);
 7481        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 7482
 7483        let mut edits = Vec::new();
 7484        let mut prev_edited_row = 0;
 7485        let mut row_delta = 0;
 7486        for selection in &mut selections {
 7487            if selection.start.row != prev_edited_row {
 7488                row_delta = 0;
 7489            }
 7490            prev_edited_row = selection.end.row;
 7491
 7492            // If the selection is non-empty, then increase the indentation of the selected lines.
 7493            if !selection.is_empty() {
 7494                row_delta =
 7495                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7496                continue;
 7497            }
 7498
 7499            // If the selection is empty and the cursor is in the leading whitespace before the
 7500            // suggested indentation, then auto-indent the line.
 7501            let cursor = selection.head();
 7502            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 7503            if let Some(suggested_indent) =
 7504                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 7505            {
 7506                if cursor.column < suggested_indent.len
 7507                    && cursor.column <= current_indent.len
 7508                    && current_indent.len <= suggested_indent.len
 7509                {
 7510                    selection.start = Point::new(cursor.row, suggested_indent.len);
 7511                    selection.end = selection.start;
 7512                    if row_delta == 0 {
 7513                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 7514                            cursor.row,
 7515                            current_indent,
 7516                            suggested_indent,
 7517                        ));
 7518                        row_delta = suggested_indent.len - current_indent.len;
 7519                    }
 7520                    continue;
 7521                }
 7522            }
 7523
 7524            // Otherwise, insert a hard or soft tab.
 7525            let settings = buffer.language_settings_at(cursor, cx);
 7526            let tab_size = if settings.hard_tabs {
 7527                IndentSize::tab()
 7528            } else {
 7529                let tab_size = settings.tab_size.get();
 7530                let char_column = snapshot
 7531                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 7532                    .flat_map(str::chars)
 7533                    .count()
 7534                    + row_delta as usize;
 7535                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 7536                IndentSize::spaces(chars_to_next_tab_stop)
 7537            };
 7538            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 7539            selection.end = selection.start;
 7540            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 7541            row_delta += tab_size.len;
 7542        }
 7543
 7544        self.transact(window, cx, |this, window, cx| {
 7545            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7546            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7547                s.select(selections)
 7548            });
 7549            this.refresh_inline_completion(true, false, window, cx);
 7550        });
 7551    }
 7552
 7553    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 7554        if self.read_only(cx) {
 7555            return;
 7556        }
 7557        let mut selections = self.selections.all::<Point>(cx);
 7558        let mut prev_edited_row = 0;
 7559        let mut row_delta = 0;
 7560        let mut edits = Vec::new();
 7561        let buffer = self.buffer.read(cx);
 7562        let snapshot = buffer.snapshot(cx);
 7563        for selection in &mut selections {
 7564            if selection.start.row != prev_edited_row {
 7565                row_delta = 0;
 7566            }
 7567            prev_edited_row = selection.end.row;
 7568
 7569            row_delta =
 7570                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7571        }
 7572
 7573        self.transact(window, cx, |this, window, cx| {
 7574            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7575            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7576                s.select(selections)
 7577            });
 7578        });
 7579    }
 7580
 7581    fn indent_selection(
 7582        buffer: &MultiBuffer,
 7583        snapshot: &MultiBufferSnapshot,
 7584        selection: &mut Selection<Point>,
 7585        edits: &mut Vec<(Range<Point>, String)>,
 7586        delta_for_start_row: u32,
 7587        cx: &App,
 7588    ) -> u32 {
 7589        let settings = buffer.language_settings_at(selection.start, cx);
 7590        let tab_size = settings.tab_size.get();
 7591        let indent_kind = if settings.hard_tabs {
 7592            IndentKind::Tab
 7593        } else {
 7594            IndentKind::Space
 7595        };
 7596        let mut start_row = selection.start.row;
 7597        let mut end_row = selection.end.row + 1;
 7598
 7599        // If a selection ends at the beginning of a line, don't indent
 7600        // that last line.
 7601        if selection.end.column == 0 && selection.end.row > selection.start.row {
 7602            end_row -= 1;
 7603        }
 7604
 7605        // Avoid re-indenting a row that has already been indented by a
 7606        // previous selection, but still update this selection's column
 7607        // to reflect that indentation.
 7608        if delta_for_start_row > 0 {
 7609            start_row += 1;
 7610            selection.start.column += delta_for_start_row;
 7611            if selection.end.row == selection.start.row {
 7612                selection.end.column += delta_for_start_row;
 7613            }
 7614        }
 7615
 7616        let mut delta_for_end_row = 0;
 7617        let has_multiple_rows = start_row + 1 != end_row;
 7618        for row in start_row..end_row {
 7619            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 7620            let indent_delta = match (current_indent.kind, indent_kind) {
 7621                (IndentKind::Space, IndentKind::Space) => {
 7622                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 7623                    IndentSize::spaces(columns_to_next_tab_stop)
 7624                }
 7625                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 7626                (_, IndentKind::Tab) => IndentSize::tab(),
 7627            };
 7628
 7629            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 7630                0
 7631            } else {
 7632                selection.start.column
 7633            };
 7634            let row_start = Point::new(row, start);
 7635            edits.push((
 7636                row_start..row_start,
 7637                indent_delta.chars().collect::<String>(),
 7638            ));
 7639
 7640            // Update this selection's endpoints to reflect the indentation.
 7641            if row == selection.start.row {
 7642                selection.start.column += indent_delta.len;
 7643            }
 7644            if row == selection.end.row {
 7645                selection.end.column += indent_delta.len;
 7646                delta_for_end_row = indent_delta.len;
 7647            }
 7648        }
 7649
 7650        if selection.start.row == selection.end.row {
 7651            delta_for_start_row + delta_for_end_row
 7652        } else {
 7653            delta_for_end_row
 7654        }
 7655    }
 7656
 7657    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 7658        if self.read_only(cx) {
 7659            return;
 7660        }
 7661        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7662        let selections = self.selections.all::<Point>(cx);
 7663        let mut deletion_ranges = Vec::new();
 7664        let mut last_outdent = None;
 7665        {
 7666            let buffer = self.buffer.read(cx);
 7667            let snapshot = buffer.snapshot(cx);
 7668            for selection in &selections {
 7669                let settings = buffer.language_settings_at(selection.start, cx);
 7670                let tab_size = settings.tab_size.get();
 7671                let mut rows = selection.spanned_rows(false, &display_map);
 7672
 7673                // Avoid re-outdenting a row that has already been outdented by a
 7674                // previous selection.
 7675                if let Some(last_row) = last_outdent {
 7676                    if last_row == rows.start {
 7677                        rows.start = rows.start.next_row();
 7678                    }
 7679                }
 7680                let has_multiple_rows = rows.len() > 1;
 7681                for row in rows.iter_rows() {
 7682                    let indent_size = snapshot.indent_size_for_line(row);
 7683                    if indent_size.len > 0 {
 7684                        let deletion_len = match indent_size.kind {
 7685                            IndentKind::Space => {
 7686                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 7687                                if columns_to_prev_tab_stop == 0 {
 7688                                    tab_size
 7689                                } else {
 7690                                    columns_to_prev_tab_stop
 7691                                }
 7692                            }
 7693                            IndentKind::Tab => 1,
 7694                        };
 7695                        let start = if has_multiple_rows
 7696                            || deletion_len > selection.start.column
 7697                            || indent_size.len < selection.start.column
 7698                        {
 7699                            0
 7700                        } else {
 7701                            selection.start.column - deletion_len
 7702                        };
 7703                        deletion_ranges.push(
 7704                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 7705                        );
 7706                        last_outdent = Some(row);
 7707                    }
 7708                }
 7709            }
 7710        }
 7711
 7712        self.transact(window, cx, |this, window, cx| {
 7713            this.buffer.update(cx, |buffer, cx| {
 7714                let empty_str: Arc<str> = Arc::default();
 7715                buffer.edit(
 7716                    deletion_ranges
 7717                        .into_iter()
 7718                        .map(|range| (range, empty_str.clone())),
 7719                    None,
 7720                    cx,
 7721                );
 7722            });
 7723            let selections = this.selections.all::<usize>(cx);
 7724            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7725                s.select(selections)
 7726            });
 7727        });
 7728    }
 7729
 7730    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 7731        if self.read_only(cx) {
 7732            return;
 7733        }
 7734        let selections = self
 7735            .selections
 7736            .all::<usize>(cx)
 7737            .into_iter()
 7738            .map(|s| s.range());
 7739
 7740        self.transact(window, cx, |this, window, cx| {
 7741            this.buffer.update(cx, |buffer, cx| {
 7742                buffer.autoindent_ranges(selections, cx);
 7743            });
 7744            let selections = this.selections.all::<usize>(cx);
 7745            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7746                s.select(selections)
 7747            });
 7748        });
 7749    }
 7750
 7751    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 7752        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7753        let selections = self.selections.all::<Point>(cx);
 7754
 7755        let mut new_cursors = Vec::new();
 7756        let mut edit_ranges = Vec::new();
 7757        let mut selections = selections.iter().peekable();
 7758        while let Some(selection) = selections.next() {
 7759            let mut rows = selection.spanned_rows(false, &display_map);
 7760            let goal_display_column = selection.head().to_display_point(&display_map).column();
 7761
 7762            // Accumulate contiguous regions of rows that we want to delete.
 7763            while let Some(next_selection) = selections.peek() {
 7764                let next_rows = next_selection.spanned_rows(false, &display_map);
 7765                if next_rows.start <= rows.end {
 7766                    rows.end = next_rows.end;
 7767                    selections.next().unwrap();
 7768                } else {
 7769                    break;
 7770                }
 7771            }
 7772
 7773            let buffer = &display_map.buffer_snapshot;
 7774            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 7775            let edit_end;
 7776            let cursor_buffer_row;
 7777            if buffer.max_point().row >= rows.end.0 {
 7778                // If there's a line after the range, delete the \n from the end of the row range
 7779                // and position the cursor on the next line.
 7780                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 7781                cursor_buffer_row = rows.end;
 7782            } else {
 7783                // If there isn't a line after the range, delete the \n from the line before the
 7784                // start of the row range and position the cursor there.
 7785                edit_start = edit_start.saturating_sub(1);
 7786                edit_end = buffer.len();
 7787                cursor_buffer_row = rows.start.previous_row();
 7788            }
 7789
 7790            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 7791            *cursor.column_mut() =
 7792                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 7793
 7794            new_cursors.push((
 7795                selection.id,
 7796                buffer.anchor_after(cursor.to_point(&display_map)),
 7797            ));
 7798            edit_ranges.push(edit_start..edit_end);
 7799        }
 7800
 7801        self.transact(window, cx, |this, window, cx| {
 7802            let buffer = this.buffer.update(cx, |buffer, cx| {
 7803                let empty_str: Arc<str> = Arc::default();
 7804                buffer.edit(
 7805                    edit_ranges
 7806                        .into_iter()
 7807                        .map(|range| (range, empty_str.clone())),
 7808                    None,
 7809                    cx,
 7810                );
 7811                buffer.snapshot(cx)
 7812            });
 7813            let new_selections = new_cursors
 7814                .into_iter()
 7815                .map(|(id, cursor)| {
 7816                    let cursor = cursor.to_point(&buffer);
 7817                    Selection {
 7818                        id,
 7819                        start: cursor,
 7820                        end: cursor,
 7821                        reversed: false,
 7822                        goal: SelectionGoal::None,
 7823                    }
 7824                })
 7825                .collect();
 7826
 7827            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7828                s.select(new_selections);
 7829            });
 7830        });
 7831    }
 7832
 7833    pub fn join_lines_impl(
 7834        &mut self,
 7835        insert_whitespace: bool,
 7836        window: &mut Window,
 7837        cx: &mut Context<Self>,
 7838    ) {
 7839        if self.read_only(cx) {
 7840            return;
 7841        }
 7842        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 7843        for selection in self.selections.all::<Point>(cx) {
 7844            let start = MultiBufferRow(selection.start.row);
 7845            // Treat single line selections as if they include the next line. Otherwise this action
 7846            // would do nothing for single line selections individual cursors.
 7847            let end = if selection.start.row == selection.end.row {
 7848                MultiBufferRow(selection.start.row + 1)
 7849            } else {
 7850                MultiBufferRow(selection.end.row)
 7851            };
 7852
 7853            if let Some(last_row_range) = row_ranges.last_mut() {
 7854                if start <= last_row_range.end {
 7855                    last_row_range.end = end;
 7856                    continue;
 7857                }
 7858            }
 7859            row_ranges.push(start..end);
 7860        }
 7861
 7862        let snapshot = self.buffer.read(cx).snapshot(cx);
 7863        let mut cursor_positions = Vec::new();
 7864        for row_range in &row_ranges {
 7865            let anchor = snapshot.anchor_before(Point::new(
 7866                row_range.end.previous_row().0,
 7867                snapshot.line_len(row_range.end.previous_row()),
 7868            ));
 7869            cursor_positions.push(anchor..anchor);
 7870        }
 7871
 7872        self.transact(window, cx, |this, window, cx| {
 7873            for row_range in row_ranges.into_iter().rev() {
 7874                for row in row_range.iter_rows().rev() {
 7875                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 7876                    let next_line_row = row.next_row();
 7877                    let indent = snapshot.indent_size_for_line(next_line_row);
 7878                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7879
 7880                    let replace =
 7881                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7882                            " "
 7883                        } else {
 7884                            ""
 7885                        };
 7886
 7887                    this.buffer.update(cx, |buffer, cx| {
 7888                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7889                    });
 7890                }
 7891            }
 7892
 7893            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7894                s.select_anchor_ranges(cursor_positions)
 7895            });
 7896        });
 7897    }
 7898
 7899    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7900        self.join_lines_impl(true, window, cx);
 7901    }
 7902
 7903    pub fn sort_lines_case_sensitive(
 7904        &mut self,
 7905        _: &SortLinesCaseSensitive,
 7906        window: &mut Window,
 7907        cx: &mut Context<Self>,
 7908    ) {
 7909        self.manipulate_lines(window, cx, |lines| lines.sort())
 7910    }
 7911
 7912    pub fn sort_lines_case_insensitive(
 7913        &mut self,
 7914        _: &SortLinesCaseInsensitive,
 7915        window: &mut Window,
 7916        cx: &mut Context<Self>,
 7917    ) {
 7918        self.manipulate_lines(window, cx, |lines| {
 7919            lines.sort_by_key(|line| line.to_lowercase())
 7920        })
 7921    }
 7922
 7923    pub fn unique_lines_case_insensitive(
 7924        &mut self,
 7925        _: &UniqueLinesCaseInsensitive,
 7926        window: &mut Window,
 7927        cx: &mut Context<Self>,
 7928    ) {
 7929        self.manipulate_lines(window, cx, |lines| {
 7930            let mut seen = HashSet::default();
 7931            lines.retain(|line| seen.insert(line.to_lowercase()));
 7932        })
 7933    }
 7934
 7935    pub fn unique_lines_case_sensitive(
 7936        &mut self,
 7937        _: &UniqueLinesCaseSensitive,
 7938        window: &mut Window,
 7939        cx: &mut Context<Self>,
 7940    ) {
 7941        self.manipulate_lines(window, cx, |lines| {
 7942            let mut seen = HashSet::default();
 7943            lines.retain(|line| seen.insert(*line));
 7944        })
 7945    }
 7946
 7947    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7948        let Some(project) = self.project.clone() else {
 7949            return;
 7950        };
 7951        self.reload(project, window, cx)
 7952            .detach_and_notify_err(window, cx);
 7953    }
 7954
 7955    pub fn restore_file(
 7956        &mut self,
 7957        _: &::git::RestoreFile,
 7958        window: &mut Window,
 7959        cx: &mut Context<Self>,
 7960    ) {
 7961        let mut buffer_ids = HashSet::default();
 7962        let snapshot = self.buffer().read(cx).snapshot(cx);
 7963        for selection in self.selections.all::<usize>(cx) {
 7964            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 7965        }
 7966
 7967        let buffer = self.buffer().read(cx);
 7968        let ranges = buffer_ids
 7969            .into_iter()
 7970            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 7971            .collect::<Vec<_>>();
 7972
 7973        self.restore_hunks_in_ranges(ranges, window, cx);
 7974    }
 7975
 7976    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 7977        let selections = self
 7978            .selections
 7979            .all(cx)
 7980            .into_iter()
 7981            .map(|s| s.range())
 7982            .collect();
 7983        self.restore_hunks_in_ranges(selections, window, cx);
 7984    }
 7985
 7986    fn restore_hunks_in_ranges(
 7987        &mut self,
 7988        ranges: Vec<Range<Point>>,
 7989        window: &mut Window,
 7990        cx: &mut Context<Editor>,
 7991    ) {
 7992        let mut revert_changes = HashMap::default();
 7993        let chunk_by = self
 7994            .snapshot(window, cx)
 7995            .hunks_for_ranges(ranges)
 7996            .into_iter()
 7997            .chunk_by(|hunk| hunk.buffer_id);
 7998        for (buffer_id, hunks) in &chunk_by {
 7999            let hunks = hunks.collect::<Vec<_>>();
 8000            for hunk in &hunks {
 8001                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 8002            }
 8003            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 8004        }
 8005        drop(chunk_by);
 8006        if !revert_changes.is_empty() {
 8007            self.transact(window, cx, |editor, window, cx| {
 8008                editor.restore(revert_changes, window, cx);
 8009            });
 8010        }
 8011    }
 8012
 8013    pub fn open_active_item_in_terminal(
 8014        &mut self,
 8015        _: &OpenInTerminal,
 8016        window: &mut Window,
 8017        cx: &mut Context<Self>,
 8018    ) {
 8019        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 8020            let project_path = buffer.read(cx).project_path(cx)?;
 8021            let project = self.project.as_ref()?.read(cx);
 8022            let entry = project.entry_for_path(&project_path, cx)?;
 8023            let parent = match &entry.canonical_path {
 8024                Some(canonical_path) => canonical_path.to_path_buf(),
 8025                None => project.absolute_path(&project_path, cx)?,
 8026            }
 8027            .parent()?
 8028            .to_path_buf();
 8029            Some(parent)
 8030        }) {
 8031            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 8032        }
 8033    }
 8034
 8035    pub fn prepare_restore_change(
 8036        &self,
 8037        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 8038        hunk: &MultiBufferDiffHunk,
 8039        cx: &mut App,
 8040    ) -> Option<()> {
 8041        if hunk.is_created_file() {
 8042            return None;
 8043        }
 8044        let buffer = self.buffer.read(cx);
 8045        let diff = buffer.diff_for(hunk.buffer_id)?;
 8046        let buffer = buffer.buffer(hunk.buffer_id)?;
 8047        let buffer = buffer.read(cx);
 8048        let original_text = diff
 8049            .read(cx)
 8050            .base_text()
 8051            .as_rope()
 8052            .slice(hunk.diff_base_byte_range.clone());
 8053        let buffer_snapshot = buffer.snapshot();
 8054        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 8055        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 8056            probe
 8057                .0
 8058                .start
 8059                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 8060                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 8061        }) {
 8062            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 8063            Some(())
 8064        } else {
 8065            None
 8066        }
 8067    }
 8068
 8069    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 8070        self.manipulate_lines(window, cx, |lines| lines.reverse())
 8071    }
 8072
 8073    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 8074        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 8075    }
 8076
 8077    fn manipulate_lines<Fn>(
 8078        &mut self,
 8079        window: &mut Window,
 8080        cx: &mut Context<Self>,
 8081        mut callback: Fn,
 8082    ) where
 8083        Fn: FnMut(&mut Vec<&str>),
 8084    {
 8085        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8086        let buffer = self.buffer.read(cx).snapshot(cx);
 8087
 8088        let mut edits = Vec::new();
 8089
 8090        let selections = self.selections.all::<Point>(cx);
 8091        let mut selections = selections.iter().peekable();
 8092        let mut contiguous_row_selections = Vec::new();
 8093        let mut new_selections = Vec::new();
 8094        let mut added_lines = 0;
 8095        let mut removed_lines = 0;
 8096
 8097        while let Some(selection) = selections.next() {
 8098            let (start_row, end_row) = consume_contiguous_rows(
 8099                &mut contiguous_row_selections,
 8100                selection,
 8101                &display_map,
 8102                &mut selections,
 8103            );
 8104
 8105            let start_point = Point::new(start_row.0, 0);
 8106            let end_point = Point::new(
 8107                end_row.previous_row().0,
 8108                buffer.line_len(end_row.previous_row()),
 8109            );
 8110            let text = buffer
 8111                .text_for_range(start_point..end_point)
 8112                .collect::<String>();
 8113
 8114            let mut lines = text.split('\n').collect_vec();
 8115
 8116            let lines_before = lines.len();
 8117            callback(&mut lines);
 8118            let lines_after = lines.len();
 8119
 8120            edits.push((start_point..end_point, lines.join("\n")));
 8121
 8122            // Selections must change based on added and removed line count
 8123            let start_row =
 8124                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 8125            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 8126            new_selections.push(Selection {
 8127                id: selection.id,
 8128                start: start_row,
 8129                end: end_row,
 8130                goal: SelectionGoal::None,
 8131                reversed: selection.reversed,
 8132            });
 8133
 8134            if lines_after > lines_before {
 8135                added_lines += lines_after - lines_before;
 8136            } else if lines_before > lines_after {
 8137                removed_lines += lines_before - lines_after;
 8138            }
 8139        }
 8140
 8141        self.transact(window, cx, |this, window, cx| {
 8142            let buffer = this.buffer.update(cx, |buffer, cx| {
 8143                buffer.edit(edits, None, cx);
 8144                buffer.snapshot(cx)
 8145            });
 8146
 8147            // Recalculate offsets on newly edited buffer
 8148            let new_selections = new_selections
 8149                .iter()
 8150                .map(|s| {
 8151                    let start_point = Point::new(s.start.0, 0);
 8152                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 8153                    Selection {
 8154                        id: s.id,
 8155                        start: buffer.point_to_offset(start_point),
 8156                        end: buffer.point_to_offset(end_point),
 8157                        goal: s.goal,
 8158                        reversed: s.reversed,
 8159                    }
 8160                })
 8161                .collect();
 8162
 8163            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8164                s.select(new_selections);
 8165            });
 8166
 8167            this.request_autoscroll(Autoscroll::fit(), cx);
 8168        });
 8169    }
 8170
 8171    pub fn convert_to_upper_case(
 8172        &mut self,
 8173        _: &ConvertToUpperCase,
 8174        window: &mut Window,
 8175        cx: &mut Context<Self>,
 8176    ) {
 8177        self.manipulate_text(window, cx, |text| text.to_uppercase())
 8178    }
 8179
 8180    pub fn convert_to_lower_case(
 8181        &mut self,
 8182        _: &ConvertToLowerCase,
 8183        window: &mut Window,
 8184        cx: &mut Context<Self>,
 8185    ) {
 8186        self.manipulate_text(window, cx, |text| text.to_lowercase())
 8187    }
 8188
 8189    pub fn convert_to_title_case(
 8190        &mut self,
 8191        _: &ConvertToTitleCase,
 8192        window: &mut Window,
 8193        cx: &mut Context<Self>,
 8194    ) {
 8195        self.manipulate_text(window, cx, |text| {
 8196            text.split('\n')
 8197                .map(|line| line.to_case(Case::Title))
 8198                .join("\n")
 8199        })
 8200    }
 8201
 8202    pub fn convert_to_snake_case(
 8203        &mut self,
 8204        _: &ConvertToSnakeCase,
 8205        window: &mut Window,
 8206        cx: &mut Context<Self>,
 8207    ) {
 8208        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 8209    }
 8210
 8211    pub fn convert_to_kebab_case(
 8212        &mut self,
 8213        _: &ConvertToKebabCase,
 8214        window: &mut Window,
 8215        cx: &mut Context<Self>,
 8216    ) {
 8217        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 8218    }
 8219
 8220    pub fn convert_to_upper_camel_case(
 8221        &mut self,
 8222        _: &ConvertToUpperCamelCase,
 8223        window: &mut Window,
 8224        cx: &mut Context<Self>,
 8225    ) {
 8226        self.manipulate_text(window, cx, |text| {
 8227            text.split('\n')
 8228                .map(|line| line.to_case(Case::UpperCamel))
 8229                .join("\n")
 8230        })
 8231    }
 8232
 8233    pub fn convert_to_lower_camel_case(
 8234        &mut self,
 8235        _: &ConvertToLowerCamelCase,
 8236        window: &mut Window,
 8237        cx: &mut Context<Self>,
 8238    ) {
 8239        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 8240    }
 8241
 8242    pub fn convert_to_opposite_case(
 8243        &mut self,
 8244        _: &ConvertToOppositeCase,
 8245        window: &mut Window,
 8246        cx: &mut Context<Self>,
 8247    ) {
 8248        self.manipulate_text(window, cx, |text| {
 8249            text.chars()
 8250                .fold(String::with_capacity(text.len()), |mut t, c| {
 8251                    if c.is_uppercase() {
 8252                        t.extend(c.to_lowercase());
 8253                    } else {
 8254                        t.extend(c.to_uppercase());
 8255                    }
 8256                    t
 8257                })
 8258        })
 8259    }
 8260
 8261    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 8262    where
 8263        Fn: FnMut(&str) -> String,
 8264    {
 8265        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8266        let buffer = self.buffer.read(cx).snapshot(cx);
 8267
 8268        let mut new_selections = Vec::new();
 8269        let mut edits = Vec::new();
 8270        let mut selection_adjustment = 0i32;
 8271
 8272        for selection in self.selections.all::<usize>(cx) {
 8273            let selection_is_empty = selection.is_empty();
 8274
 8275            let (start, end) = if selection_is_empty {
 8276                let word_range = movement::surrounding_word(
 8277                    &display_map,
 8278                    selection.start.to_display_point(&display_map),
 8279                );
 8280                let start = word_range.start.to_offset(&display_map, Bias::Left);
 8281                let end = word_range.end.to_offset(&display_map, Bias::Left);
 8282                (start, end)
 8283            } else {
 8284                (selection.start, selection.end)
 8285            };
 8286
 8287            let text = buffer.text_for_range(start..end).collect::<String>();
 8288            let old_length = text.len() as i32;
 8289            let text = callback(&text);
 8290
 8291            new_selections.push(Selection {
 8292                start: (start as i32 - selection_adjustment) as usize,
 8293                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 8294                goal: SelectionGoal::None,
 8295                ..selection
 8296            });
 8297
 8298            selection_adjustment += old_length - text.len() as i32;
 8299
 8300            edits.push((start..end, text));
 8301        }
 8302
 8303        self.transact(window, cx, |this, window, cx| {
 8304            this.buffer.update(cx, |buffer, cx| {
 8305                buffer.edit(edits, None, cx);
 8306            });
 8307
 8308            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8309                s.select(new_selections);
 8310            });
 8311
 8312            this.request_autoscroll(Autoscroll::fit(), cx);
 8313        });
 8314    }
 8315
 8316    pub fn duplicate(
 8317        &mut self,
 8318        upwards: bool,
 8319        whole_lines: bool,
 8320        window: &mut Window,
 8321        cx: &mut Context<Self>,
 8322    ) {
 8323        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8324        let buffer = &display_map.buffer_snapshot;
 8325        let selections = self.selections.all::<Point>(cx);
 8326
 8327        let mut edits = Vec::new();
 8328        let mut selections_iter = selections.iter().peekable();
 8329        while let Some(selection) = selections_iter.next() {
 8330            let mut rows = selection.spanned_rows(false, &display_map);
 8331            // duplicate line-wise
 8332            if whole_lines || selection.start == selection.end {
 8333                // Avoid duplicating the same lines twice.
 8334                while let Some(next_selection) = selections_iter.peek() {
 8335                    let next_rows = next_selection.spanned_rows(false, &display_map);
 8336                    if next_rows.start < rows.end {
 8337                        rows.end = next_rows.end;
 8338                        selections_iter.next().unwrap();
 8339                    } else {
 8340                        break;
 8341                    }
 8342                }
 8343
 8344                // Copy the text from the selected row region and splice it either at the start
 8345                // or end of the region.
 8346                let start = Point::new(rows.start.0, 0);
 8347                let end = Point::new(
 8348                    rows.end.previous_row().0,
 8349                    buffer.line_len(rows.end.previous_row()),
 8350                );
 8351                let text = buffer
 8352                    .text_for_range(start..end)
 8353                    .chain(Some("\n"))
 8354                    .collect::<String>();
 8355                let insert_location = if upwards {
 8356                    Point::new(rows.end.0, 0)
 8357                } else {
 8358                    start
 8359                };
 8360                edits.push((insert_location..insert_location, text));
 8361            } else {
 8362                // duplicate character-wise
 8363                let start = selection.start;
 8364                let end = selection.end;
 8365                let text = buffer.text_for_range(start..end).collect::<String>();
 8366                edits.push((selection.end..selection.end, text));
 8367            }
 8368        }
 8369
 8370        self.transact(window, cx, |this, _, cx| {
 8371            this.buffer.update(cx, |buffer, cx| {
 8372                buffer.edit(edits, None, cx);
 8373            });
 8374
 8375            this.request_autoscroll(Autoscroll::fit(), cx);
 8376        });
 8377    }
 8378
 8379    pub fn duplicate_line_up(
 8380        &mut self,
 8381        _: &DuplicateLineUp,
 8382        window: &mut Window,
 8383        cx: &mut Context<Self>,
 8384    ) {
 8385        self.duplicate(true, true, window, cx);
 8386    }
 8387
 8388    pub fn duplicate_line_down(
 8389        &mut self,
 8390        _: &DuplicateLineDown,
 8391        window: &mut Window,
 8392        cx: &mut Context<Self>,
 8393    ) {
 8394        self.duplicate(false, true, window, cx);
 8395    }
 8396
 8397    pub fn duplicate_selection(
 8398        &mut self,
 8399        _: &DuplicateSelection,
 8400        window: &mut Window,
 8401        cx: &mut Context<Self>,
 8402    ) {
 8403        self.duplicate(false, false, window, cx);
 8404    }
 8405
 8406    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 8407        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8408        let buffer = self.buffer.read(cx).snapshot(cx);
 8409
 8410        let mut edits = Vec::new();
 8411        let mut unfold_ranges = Vec::new();
 8412        let mut refold_creases = Vec::new();
 8413
 8414        let selections = self.selections.all::<Point>(cx);
 8415        let mut selections = selections.iter().peekable();
 8416        let mut contiguous_row_selections = Vec::new();
 8417        let mut new_selections = Vec::new();
 8418
 8419        while let Some(selection) = selections.next() {
 8420            // Find all the selections that span a contiguous row range
 8421            let (start_row, end_row) = consume_contiguous_rows(
 8422                &mut contiguous_row_selections,
 8423                selection,
 8424                &display_map,
 8425                &mut selections,
 8426            );
 8427
 8428            // Move the text spanned by the row range to be before the line preceding the row range
 8429            if start_row.0 > 0 {
 8430                let range_to_move = Point::new(
 8431                    start_row.previous_row().0,
 8432                    buffer.line_len(start_row.previous_row()),
 8433                )
 8434                    ..Point::new(
 8435                        end_row.previous_row().0,
 8436                        buffer.line_len(end_row.previous_row()),
 8437                    );
 8438                let insertion_point = display_map
 8439                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 8440                    .0;
 8441
 8442                // Don't move lines across excerpts
 8443                if buffer
 8444                    .excerpt_containing(insertion_point..range_to_move.end)
 8445                    .is_some()
 8446                {
 8447                    let text = buffer
 8448                        .text_for_range(range_to_move.clone())
 8449                        .flat_map(|s| s.chars())
 8450                        .skip(1)
 8451                        .chain(['\n'])
 8452                        .collect::<String>();
 8453
 8454                    edits.push((
 8455                        buffer.anchor_after(range_to_move.start)
 8456                            ..buffer.anchor_before(range_to_move.end),
 8457                        String::new(),
 8458                    ));
 8459                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8460                    edits.push((insertion_anchor..insertion_anchor, text));
 8461
 8462                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 8463
 8464                    // Move selections up
 8465                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8466                        |mut selection| {
 8467                            selection.start.row -= row_delta;
 8468                            selection.end.row -= row_delta;
 8469                            selection
 8470                        },
 8471                    ));
 8472
 8473                    // Move folds up
 8474                    unfold_ranges.push(range_to_move.clone());
 8475                    for fold in display_map.folds_in_range(
 8476                        buffer.anchor_before(range_to_move.start)
 8477                            ..buffer.anchor_after(range_to_move.end),
 8478                    ) {
 8479                        let mut start = fold.range.start.to_point(&buffer);
 8480                        let mut end = fold.range.end.to_point(&buffer);
 8481                        start.row -= row_delta;
 8482                        end.row -= row_delta;
 8483                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8484                    }
 8485                }
 8486            }
 8487
 8488            // If we didn't move line(s), preserve the existing selections
 8489            new_selections.append(&mut contiguous_row_selections);
 8490        }
 8491
 8492        self.transact(window, cx, |this, window, cx| {
 8493            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8494            this.buffer.update(cx, |buffer, cx| {
 8495                for (range, text) in edits {
 8496                    buffer.edit([(range, text)], None, cx);
 8497                }
 8498            });
 8499            this.fold_creases(refold_creases, true, window, cx);
 8500            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8501                s.select(new_selections);
 8502            })
 8503        });
 8504    }
 8505
 8506    pub fn move_line_down(
 8507        &mut self,
 8508        _: &MoveLineDown,
 8509        window: &mut Window,
 8510        cx: &mut Context<Self>,
 8511    ) {
 8512        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8513        let buffer = self.buffer.read(cx).snapshot(cx);
 8514
 8515        let mut edits = Vec::new();
 8516        let mut unfold_ranges = Vec::new();
 8517        let mut refold_creases = Vec::new();
 8518
 8519        let selections = self.selections.all::<Point>(cx);
 8520        let mut selections = selections.iter().peekable();
 8521        let mut contiguous_row_selections = Vec::new();
 8522        let mut new_selections = Vec::new();
 8523
 8524        while let Some(selection) = selections.next() {
 8525            // Find all the selections that span a contiguous row range
 8526            let (start_row, end_row) = consume_contiguous_rows(
 8527                &mut contiguous_row_selections,
 8528                selection,
 8529                &display_map,
 8530                &mut selections,
 8531            );
 8532
 8533            // Move the text spanned by the row range to be after the last line of the row range
 8534            if end_row.0 <= buffer.max_point().row {
 8535                let range_to_move =
 8536                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 8537                let insertion_point = display_map
 8538                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 8539                    .0;
 8540
 8541                // Don't move lines across excerpt boundaries
 8542                if buffer
 8543                    .excerpt_containing(range_to_move.start..insertion_point)
 8544                    .is_some()
 8545                {
 8546                    let mut text = String::from("\n");
 8547                    text.extend(buffer.text_for_range(range_to_move.clone()));
 8548                    text.pop(); // Drop trailing newline
 8549                    edits.push((
 8550                        buffer.anchor_after(range_to_move.start)
 8551                            ..buffer.anchor_before(range_to_move.end),
 8552                        String::new(),
 8553                    ));
 8554                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8555                    edits.push((insertion_anchor..insertion_anchor, text));
 8556
 8557                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 8558
 8559                    // Move selections down
 8560                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8561                        |mut selection| {
 8562                            selection.start.row += row_delta;
 8563                            selection.end.row += row_delta;
 8564                            selection
 8565                        },
 8566                    ));
 8567
 8568                    // Move folds down
 8569                    unfold_ranges.push(range_to_move.clone());
 8570                    for fold in display_map.folds_in_range(
 8571                        buffer.anchor_before(range_to_move.start)
 8572                            ..buffer.anchor_after(range_to_move.end),
 8573                    ) {
 8574                        let mut start = fold.range.start.to_point(&buffer);
 8575                        let mut end = fold.range.end.to_point(&buffer);
 8576                        start.row += row_delta;
 8577                        end.row += row_delta;
 8578                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8579                    }
 8580                }
 8581            }
 8582
 8583            // If we didn't move line(s), preserve the existing selections
 8584            new_selections.append(&mut contiguous_row_selections);
 8585        }
 8586
 8587        self.transact(window, cx, |this, window, cx| {
 8588            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8589            this.buffer.update(cx, |buffer, cx| {
 8590                for (range, text) in edits {
 8591                    buffer.edit([(range, text)], None, cx);
 8592                }
 8593            });
 8594            this.fold_creases(refold_creases, true, window, cx);
 8595            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8596                s.select(new_selections)
 8597            });
 8598        });
 8599    }
 8600
 8601    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 8602        let text_layout_details = &self.text_layout_details(window);
 8603        self.transact(window, cx, |this, window, cx| {
 8604            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8605                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 8606                let line_mode = s.line_mode;
 8607                s.move_with(|display_map, selection| {
 8608                    if !selection.is_empty() || line_mode {
 8609                        return;
 8610                    }
 8611
 8612                    let mut head = selection.head();
 8613                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 8614                    if head.column() == display_map.line_len(head.row()) {
 8615                        transpose_offset = display_map
 8616                            .buffer_snapshot
 8617                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8618                    }
 8619
 8620                    if transpose_offset == 0 {
 8621                        return;
 8622                    }
 8623
 8624                    *head.column_mut() += 1;
 8625                    head = display_map.clip_point(head, Bias::Right);
 8626                    let goal = SelectionGoal::HorizontalPosition(
 8627                        display_map
 8628                            .x_for_display_point(head, text_layout_details)
 8629                            .into(),
 8630                    );
 8631                    selection.collapse_to(head, goal);
 8632
 8633                    let transpose_start = display_map
 8634                        .buffer_snapshot
 8635                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8636                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 8637                        let transpose_end = display_map
 8638                            .buffer_snapshot
 8639                            .clip_offset(transpose_offset + 1, Bias::Right);
 8640                        if let Some(ch) =
 8641                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 8642                        {
 8643                            edits.push((transpose_start..transpose_offset, String::new()));
 8644                            edits.push((transpose_end..transpose_end, ch.to_string()));
 8645                        }
 8646                    }
 8647                });
 8648                edits
 8649            });
 8650            this.buffer
 8651                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8652            let selections = this.selections.all::<usize>(cx);
 8653            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8654                s.select(selections);
 8655            });
 8656        });
 8657    }
 8658
 8659    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 8660        self.rewrap_impl(false, cx)
 8661    }
 8662
 8663    pub fn rewrap_impl(&mut self, override_language_settings: bool, cx: &mut Context<Self>) {
 8664        let buffer = self.buffer.read(cx).snapshot(cx);
 8665        let selections = self.selections.all::<Point>(cx);
 8666        let mut selections = selections.iter().peekable();
 8667
 8668        let mut edits = Vec::new();
 8669        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 8670
 8671        while let Some(selection) = selections.next() {
 8672            let mut start_row = selection.start.row;
 8673            let mut end_row = selection.end.row;
 8674
 8675            // Skip selections that overlap with a range that has already been rewrapped.
 8676            let selection_range = start_row..end_row;
 8677            if rewrapped_row_ranges
 8678                .iter()
 8679                .any(|range| range.overlaps(&selection_range))
 8680            {
 8681                continue;
 8682            }
 8683
 8684            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 8685
 8686            // Since not all lines in the selection may be at the same indent
 8687            // level, choose the indent size that is the most common between all
 8688            // of the lines.
 8689            //
 8690            // If there is a tie, we use the deepest indent.
 8691            let (indent_size, indent_end) = {
 8692                let mut indent_size_occurrences = HashMap::default();
 8693                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 8694
 8695                for row in start_row..=end_row {
 8696                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 8697                    rows_by_indent_size.entry(indent).or_default().push(row);
 8698                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 8699                }
 8700
 8701                let indent_size = indent_size_occurrences
 8702                    .into_iter()
 8703                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 8704                    .map(|(indent, _)| indent)
 8705                    .unwrap_or_default();
 8706                let row = rows_by_indent_size[&indent_size][0];
 8707                let indent_end = Point::new(row, indent_size.len);
 8708
 8709                (indent_size, indent_end)
 8710            };
 8711
 8712            let mut line_prefix = indent_size.chars().collect::<String>();
 8713
 8714            let mut inside_comment = false;
 8715            if let Some(comment_prefix) =
 8716                buffer
 8717                    .language_scope_at(selection.head())
 8718                    .and_then(|language| {
 8719                        language
 8720                            .line_comment_prefixes()
 8721                            .iter()
 8722                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 8723                            .cloned()
 8724                    })
 8725            {
 8726                line_prefix.push_str(&comment_prefix);
 8727                inside_comment = true;
 8728            }
 8729
 8730            let language_settings = buffer.language_settings_at(selection.head(), cx);
 8731            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 8732                RewrapBehavior::InComments => inside_comment,
 8733                RewrapBehavior::InSelections => !selection.is_empty(),
 8734                RewrapBehavior::Anywhere => true,
 8735            };
 8736
 8737            let should_rewrap = override_language_settings
 8738                || allow_rewrap_based_on_language
 8739                || self.hard_wrap.is_some();
 8740            if !should_rewrap {
 8741                continue;
 8742            }
 8743
 8744            if selection.is_empty() {
 8745                'expand_upwards: while start_row > 0 {
 8746                    let prev_row = start_row - 1;
 8747                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 8748                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 8749                    {
 8750                        start_row = prev_row;
 8751                    } else {
 8752                        break 'expand_upwards;
 8753                    }
 8754                }
 8755
 8756                'expand_downwards: while end_row < buffer.max_point().row {
 8757                    let next_row = end_row + 1;
 8758                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 8759                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 8760                    {
 8761                        end_row = next_row;
 8762                    } else {
 8763                        break 'expand_downwards;
 8764                    }
 8765                }
 8766            }
 8767
 8768            let start = Point::new(start_row, 0);
 8769            let start_offset = start.to_offset(&buffer);
 8770            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 8771            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 8772            let Some(lines_without_prefixes) = selection_text
 8773                .lines()
 8774                .map(|line| {
 8775                    line.strip_prefix(&line_prefix)
 8776                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 8777                        .ok_or_else(|| {
 8778                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 8779                        })
 8780                })
 8781                .collect::<Result<Vec<_>, _>>()
 8782                .log_err()
 8783            else {
 8784                continue;
 8785            };
 8786
 8787            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
 8788                buffer
 8789                    .language_settings_at(Point::new(start_row, 0), cx)
 8790                    .preferred_line_length as usize
 8791            });
 8792            let wrapped_text = wrap_with_prefix(
 8793                line_prefix,
 8794                lines_without_prefixes.join(" "),
 8795                wrap_column,
 8796                tab_size,
 8797            );
 8798
 8799            // TODO: should always use char-based diff while still supporting cursor behavior that
 8800            // matches vim.
 8801            let mut diff_options = DiffOptions::default();
 8802            if override_language_settings {
 8803                diff_options.max_word_diff_len = 0;
 8804                diff_options.max_word_diff_line_count = 0;
 8805            } else {
 8806                diff_options.max_word_diff_len = usize::MAX;
 8807                diff_options.max_word_diff_line_count = usize::MAX;
 8808            }
 8809
 8810            for (old_range, new_text) in
 8811                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 8812            {
 8813                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 8814                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 8815                edits.push((edit_start..edit_end, new_text));
 8816            }
 8817
 8818            rewrapped_row_ranges.push(start_row..=end_row);
 8819        }
 8820
 8821        self.buffer
 8822            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8823    }
 8824
 8825    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 8826        let mut text = String::new();
 8827        let buffer = self.buffer.read(cx).snapshot(cx);
 8828        let mut selections = self.selections.all::<Point>(cx);
 8829        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8830        {
 8831            let max_point = buffer.max_point();
 8832            let mut is_first = true;
 8833            for selection in &mut selections {
 8834                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8835                if is_entire_line {
 8836                    selection.start = Point::new(selection.start.row, 0);
 8837                    if !selection.is_empty() && selection.end.column == 0 {
 8838                        selection.end = cmp::min(max_point, selection.end);
 8839                    } else {
 8840                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 8841                    }
 8842                    selection.goal = SelectionGoal::None;
 8843                }
 8844                if is_first {
 8845                    is_first = false;
 8846                } else {
 8847                    text += "\n";
 8848                }
 8849                let mut len = 0;
 8850                for chunk in buffer.text_for_range(selection.start..selection.end) {
 8851                    text.push_str(chunk);
 8852                    len += chunk.len();
 8853                }
 8854                clipboard_selections.push(ClipboardSelection {
 8855                    len,
 8856                    is_entire_line,
 8857                    first_line_indent: buffer
 8858                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 8859                        .len,
 8860                });
 8861            }
 8862        }
 8863
 8864        self.transact(window, cx, |this, window, cx| {
 8865            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8866                s.select(selections);
 8867            });
 8868            this.insert("", window, cx);
 8869        });
 8870        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 8871    }
 8872
 8873    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8874        let item = self.cut_common(window, cx);
 8875        cx.write_to_clipboard(item);
 8876    }
 8877
 8878    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8879        self.change_selections(None, window, cx, |s| {
 8880            s.move_with(|snapshot, sel| {
 8881                if sel.is_empty() {
 8882                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8883                }
 8884            });
 8885        });
 8886        let item = self.cut_common(window, cx);
 8887        cx.set_global(KillRing(item))
 8888    }
 8889
 8890    pub fn kill_ring_yank(
 8891        &mut self,
 8892        _: &KillRingYank,
 8893        window: &mut Window,
 8894        cx: &mut Context<Self>,
 8895    ) {
 8896        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8897            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8898                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8899            } else {
 8900                return;
 8901            }
 8902        } else {
 8903            return;
 8904        };
 8905        self.do_paste(&text, metadata, false, window, cx);
 8906    }
 8907
 8908    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8909        let selections = self.selections.all::<Point>(cx);
 8910        let buffer = self.buffer.read(cx).read(cx);
 8911        let mut text = String::new();
 8912
 8913        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8914        {
 8915            let max_point = buffer.max_point();
 8916            let mut is_first = true;
 8917            for selection in selections.iter() {
 8918                let mut start = selection.start;
 8919                let mut end = selection.end;
 8920                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8921                if is_entire_line {
 8922                    start = Point::new(start.row, 0);
 8923                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8924                }
 8925                if is_first {
 8926                    is_first = false;
 8927                } else {
 8928                    text += "\n";
 8929                }
 8930                let mut len = 0;
 8931                for chunk in buffer.text_for_range(start..end) {
 8932                    text.push_str(chunk);
 8933                    len += chunk.len();
 8934                }
 8935                clipboard_selections.push(ClipboardSelection {
 8936                    len,
 8937                    is_entire_line,
 8938                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 8939                });
 8940            }
 8941        }
 8942
 8943        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8944            text,
 8945            clipboard_selections,
 8946        ));
 8947    }
 8948
 8949    pub fn do_paste(
 8950        &mut self,
 8951        text: &String,
 8952        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8953        handle_entire_lines: bool,
 8954        window: &mut Window,
 8955        cx: &mut Context<Self>,
 8956    ) {
 8957        if self.read_only(cx) {
 8958            return;
 8959        }
 8960
 8961        let clipboard_text = Cow::Borrowed(text);
 8962
 8963        self.transact(window, cx, |this, window, cx| {
 8964            if let Some(mut clipboard_selections) = clipboard_selections {
 8965                let old_selections = this.selections.all::<usize>(cx);
 8966                let all_selections_were_entire_line =
 8967                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8968                let first_selection_indent_column =
 8969                    clipboard_selections.first().map(|s| s.first_line_indent);
 8970                if clipboard_selections.len() != old_selections.len() {
 8971                    clipboard_selections.drain(..);
 8972                }
 8973                let cursor_offset = this.selections.last::<usize>(cx).head();
 8974                let mut auto_indent_on_paste = true;
 8975
 8976                this.buffer.update(cx, |buffer, cx| {
 8977                    let snapshot = buffer.read(cx);
 8978                    auto_indent_on_paste = snapshot
 8979                        .language_settings_at(cursor_offset, cx)
 8980                        .auto_indent_on_paste;
 8981
 8982                    let mut start_offset = 0;
 8983                    let mut edits = Vec::new();
 8984                    let mut original_indent_columns = Vec::new();
 8985                    for (ix, selection) in old_selections.iter().enumerate() {
 8986                        let to_insert;
 8987                        let entire_line;
 8988                        let original_indent_column;
 8989                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8990                            let end_offset = start_offset + clipboard_selection.len;
 8991                            to_insert = &clipboard_text[start_offset..end_offset];
 8992                            entire_line = clipboard_selection.is_entire_line;
 8993                            start_offset = end_offset + 1;
 8994                            original_indent_column = Some(clipboard_selection.first_line_indent);
 8995                        } else {
 8996                            to_insert = clipboard_text.as_str();
 8997                            entire_line = all_selections_were_entire_line;
 8998                            original_indent_column = first_selection_indent_column
 8999                        }
 9000
 9001                        // If the corresponding selection was empty when this slice of the
 9002                        // clipboard text was written, then the entire line containing the
 9003                        // selection was copied. If this selection is also currently empty,
 9004                        // then paste the line before the current line of the buffer.
 9005                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 9006                            let column = selection.start.to_point(&snapshot).column as usize;
 9007                            let line_start = selection.start - column;
 9008                            line_start..line_start
 9009                        } else {
 9010                            selection.range()
 9011                        };
 9012
 9013                        edits.push((range, to_insert));
 9014                        original_indent_columns.push(original_indent_column);
 9015                    }
 9016                    drop(snapshot);
 9017
 9018                    buffer.edit(
 9019                        edits,
 9020                        if auto_indent_on_paste {
 9021                            Some(AutoindentMode::Block {
 9022                                original_indent_columns,
 9023                            })
 9024                        } else {
 9025                            None
 9026                        },
 9027                        cx,
 9028                    );
 9029                });
 9030
 9031                let selections = this.selections.all::<usize>(cx);
 9032                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9033                    s.select(selections)
 9034                });
 9035            } else {
 9036                this.insert(&clipboard_text, window, cx);
 9037            }
 9038        });
 9039    }
 9040
 9041    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 9042        if let Some(item) = cx.read_from_clipboard() {
 9043            let entries = item.entries();
 9044
 9045            match entries.first() {
 9046                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 9047                // of all the pasted entries.
 9048                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 9049                    .do_paste(
 9050                        clipboard_string.text(),
 9051                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 9052                        true,
 9053                        window,
 9054                        cx,
 9055                    ),
 9056                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 9057            }
 9058        }
 9059    }
 9060
 9061    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 9062        if self.read_only(cx) {
 9063            return;
 9064        }
 9065
 9066        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 9067            if let Some((selections, _)) =
 9068                self.selection_history.transaction(transaction_id).cloned()
 9069            {
 9070                self.change_selections(None, window, cx, |s| {
 9071                    s.select_anchors(selections.to_vec());
 9072                });
 9073            } else {
 9074                log::error!(
 9075                    "No entry in selection_history found for undo. \
 9076                     This may correspond to a bug where undo does not update the selection. \
 9077                     If this is occurring, please add details to \
 9078                     https://github.com/zed-industries/zed/issues/22692"
 9079                );
 9080            }
 9081            self.request_autoscroll(Autoscroll::fit(), cx);
 9082            self.unmark_text(window, cx);
 9083            self.refresh_inline_completion(true, false, window, cx);
 9084            cx.emit(EditorEvent::Edited { transaction_id });
 9085            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 9086        }
 9087    }
 9088
 9089    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 9090        if self.read_only(cx) {
 9091            return;
 9092        }
 9093
 9094        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 9095            if let Some((_, Some(selections))) =
 9096                self.selection_history.transaction(transaction_id).cloned()
 9097            {
 9098                self.change_selections(None, window, cx, |s| {
 9099                    s.select_anchors(selections.to_vec());
 9100                });
 9101            } else {
 9102                log::error!(
 9103                    "No entry in selection_history found for redo. \
 9104                     This may correspond to a bug where undo does not update the selection. \
 9105                     If this is occurring, please add details to \
 9106                     https://github.com/zed-industries/zed/issues/22692"
 9107                );
 9108            }
 9109            self.request_autoscroll(Autoscroll::fit(), cx);
 9110            self.unmark_text(window, cx);
 9111            self.refresh_inline_completion(true, false, window, cx);
 9112            cx.emit(EditorEvent::Edited { transaction_id });
 9113        }
 9114    }
 9115
 9116    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 9117        self.buffer
 9118            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 9119    }
 9120
 9121    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 9122        self.buffer
 9123            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 9124    }
 9125
 9126    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 9127        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9128            let line_mode = s.line_mode;
 9129            s.move_with(|map, selection| {
 9130                let cursor = if selection.is_empty() && !line_mode {
 9131                    movement::left(map, selection.start)
 9132                } else {
 9133                    selection.start
 9134                };
 9135                selection.collapse_to(cursor, SelectionGoal::None);
 9136            });
 9137        })
 9138    }
 9139
 9140    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 9141        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9142            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 9143        })
 9144    }
 9145
 9146    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 9147        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9148            let line_mode = s.line_mode;
 9149            s.move_with(|map, selection| {
 9150                let cursor = if selection.is_empty() && !line_mode {
 9151                    movement::right(map, selection.end)
 9152                } else {
 9153                    selection.end
 9154                };
 9155                selection.collapse_to(cursor, SelectionGoal::None)
 9156            });
 9157        })
 9158    }
 9159
 9160    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 9161        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9162            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 9163        })
 9164    }
 9165
 9166    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 9167        if self.take_rename(true, window, cx).is_some() {
 9168            return;
 9169        }
 9170
 9171        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9172            cx.propagate();
 9173            return;
 9174        }
 9175
 9176        let text_layout_details = &self.text_layout_details(window);
 9177        let selection_count = self.selections.count();
 9178        let first_selection = self.selections.first_anchor();
 9179
 9180        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9181            let line_mode = s.line_mode;
 9182            s.move_with(|map, selection| {
 9183                if !selection.is_empty() && !line_mode {
 9184                    selection.goal = SelectionGoal::None;
 9185                }
 9186                let (cursor, goal) = movement::up(
 9187                    map,
 9188                    selection.start,
 9189                    selection.goal,
 9190                    false,
 9191                    text_layout_details,
 9192                );
 9193                selection.collapse_to(cursor, goal);
 9194            });
 9195        });
 9196
 9197        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9198        {
 9199            cx.propagate();
 9200        }
 9201    }
 9202
 9203    pub fn move_up_by_lines(
 9204        &mut self,
 9205        action: &MoveUpByLines,
 9206        window: &mut Window,
 9207        cx: &mut Context<Self>,
 9208    ) {
 9209        if self.take_rename(true, window, cx).is_some() {
 9210            return;
 9211        }
 9212
 9213        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9214            cx.propagate();
 9215            return;
 9216        }
 9217
 9218        let text_layout_details = &self.text_layout_details(window);
 9219
 9220        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9221            let line_mode = s.line_mode;
 9222            s.move_with(|map, selection| {
 9223                if !selection.is_empty() && !line_mode {
 9224                    selection.goal = SelectionGoal::None;
 9225                }
 9226                let (cursor, goal) = movement::up_by_rows(
 9227                    map,
 9228                    selection.start,
 9229                    action.lines,
 9230                    selection.goal,
 9231                    false,
 9232                    text_layout_details,
 9233                );
 9234                selection.collapse_to(cursor, goal);
 9235            });
 9236        })
 9237    }
 9238
 9239    pub fn move_down_by_lines(
 9240        &mut self,
 9241        action: &MoveDownByLines,
 9242        window: &mut Window,
 9243        cx: &mut Context<Self>,
 9244    ) {
 9245        if self.take_rename(true, window, cx).is_some() {
 9246            return;
 9247        }
 9248
 9249        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9250            cx.propagate();
 9251            return;
 9252        }
 9253
 9254        let text_layout_details = &self.text_layout_details(window);
 9255
 9256        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9257            let line_mode = s.line_mode;
 9258            s.move_with(|map, selection| {
 9259                if !selection.is_empty() && !line_mode {
 9260                    selection.goal = SelectionGoal::None;
 9261                }
 9262                let (cursor, goal) = movement::down_by_rows(
 9263                    map,
 9264                    selection.start,
 9265                    action.lines,
 9266                    selection.goal,
 9267                    false,
 9268                    text_layout_details,
 9269                );
 9270                selection.collapse_to(cursor, goal);
 9271            });
 9272        })
 9273    }
 9274
 9275    pub fn select_down_by_lines(
 9276        &mut self,
 9277        action: &SelectDownByLines,
 9278        window: &mut Window,
 9279        cx: &mut Context<Self>,
 9280    ) {
 9281        let text_layout_details = &self.text_layout_details(window);
 9282        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9283            s.move_heads_with(|map, head, goal| {
 9284                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9285            })
 9286        })
 9287    }
 9288
 9289    pub fn select_up_by_lines(
 9290        &mut self,
 9291        action: &SelectUpByLines,
 9292        window: &mut Window,
 9293        cx: &mut Context<Self>,
 9294    ) {
 9295        let text_layout_details = &self.text_layout_details(window);
 9296        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9297            s.move_heads_with(|map, head, goal| {
 9298                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9299            })
 9300        })
 9301    }
 9302
 9303    pub fn select_page_up(
 9304        &mut self,
 9305        _: &SelectPageUp,
 9306        window: &mut Window,
 9307        cx: &mut Context<Self>,
 9308    ) {
 9309        let Some(row_count) = self.visible_row_count() else {
 9310            return;
 9311        };
 9312
 9313        let text_layout_details = &self.text_layout_details(window);
 9314
 9315        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9316            s.move_heads_with(|map, head, goal| {
 9317                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 9318            })
 9319        })
 9320    }
 9321
 9322    pub fn move_page_up(
 9323        &mut self,
 9324        action: &MovePageUp,
 9325        window: &mut Window,
 9326        cx: &mut Context<Self>,
 9327    ) {
 9328        if self.take_rename(true, window, cx).is_some() {
 9329            return;
 9330        }
 9331
 9332        if self
 9333            .context_menu
 9334            .borrow_mut()
 9335            .as_mut()
 9336            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 9337            .unwrap_or(false)
 9338        {
 9339            return;
 9340        }
 9341
 9342        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9343            cx.propagate();
 9344            return;
 9345        }
 9346
 9347        let Some(row_count) = self.visible_row_count() else {
 9348            return;
 9349        };
 9350
 9351        let autoscroll = if action.center_cursor {
 9352            Autoscroll::center()
 9353        } else {
 9354            Autoscroll::fit()
 9355        };
 9356
 9357        let text_layout_details = &self.text_layout_details(window);
 9358
 9359        self.change_selections(Some(autoscroll), window, cx, |s| {
 9360            let line_mode = s.line_mode;
 9361            s.move_with(|map, selection| {
 9362                if !selection.is_empty() && !line_mode {
 9363                    selection.goal = SelectionGoal::None;
 9364                }
 9365                let (cursor, goal) = movement::up_by_rows(
 9366                    map,
 9367                    selection.end,
 9368                    row_count,
 9369                    selection.goal,
 9370                    false,
 9371                    text_layout_details,
 9372                );
 9373                selection.collapse_to(cursor, goal);
 9374            });
 9375        });
 9376    }
 9377
 9378    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 9379        let text_layout_details = &self.text_layout_details(window);
 9380        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9381            s.move_heads_with(|map, head, goal| {
 9382                movement::up(map, head, goal, false, text_layout_details)
 9383            })
 9384        })
 9385    }
 9386
 9387    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 9388        self.take_rename(true, window, cx);
 9389
 9390        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9391            cx.propagate();
 9392            return;
 9393        }
 9394
 9395        let text_layout_details = &self.text_layout_details(window);
 9396        let selection_count = self.selections.count();
 9397        let first_selection = self.selections.first_anchor();
 9398
 9399        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9400            let line_mode = s.line_mode;
 9401            s.move_with(|map, selection| {
 9402                if !selection.is_empty() && !line_mode {
 9403                    selection.goal = SelectionGoal::None;
 9404                }
 9405                let (cursor, goal) = movement::down(
 9406                    map,
 9407                    selection.end,
 9408                    selection.goal,
 9409                    false,
 9410                    text_layout_details,
 9411                );
 9412                selection.collapse_to(cursor, goal);
 9413            });
 9414        });
 9415
 9416        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9417        {
 9418            cx.propagate();
 9419        }
 9420    }
 9421
 9422    pub fn select_page_down(
 9423        &mut self,
 9424        _: &SelectPageDown,
 9425        window: &mut Window,
 9426        cx: &mut Context<Self>,
 9427    ) {
 9428        let Some(row_count) = self.visible_row_count() else {
 9429            return;
 9430        };
 9431
 9432        let text_layout_details = &self.text_layout_details(window);
 9433
 9434        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9435            s.move_heads_with(|map, head, goal| {
 9436                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 9437            })
 9438        })
 9439    }
 9440
 9441    pub fn move_page_down(
 9442        &mut self,
 9443        action: &MovePageDown,
 9444        window: &mut Window,
 9445        cx: &mut Context<Self>,
 9446    ) {
 9447        if self.take_rename(true, window, cx).is_some() {
 9448            return;
 9449        }
 9450
 9451        if self
 9452            .context_menu
 9453            .borrow_mut()
 9454            .as_mut()
 9455            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 9456            .unwrap_or(false)
 9457        {
 9458            return;
 9459        }
 9460
 9461        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9462            cx.propagate();
 9463            return;
 9464        }
 9465
 9466        let Some(row_count) = self.visible_row_count() else {
 9467            return;
 9468        };
 9469
 9470        let autoscroll = if action.center_cursor {
 9471            Autoscroll::center()
 9472        } else {
 9473            Autoscroll::fit()
 9474        };
 9475
 9476        let text_layout_details = &self.text_layout_details(window);
 9477        self.change_selections(Some(autoscroll), window, cx, |s| {
 9478            let line_mode = s.line_mode;
 9479            s.move_with(|map, selection| {
 9480                if !selection.is_empty() && !line_mode {
 9481                    selection.goal = SelectionGoal::None;
 9482                }
 9483                let (cursor, goal) = movement::down_by_rows(
 9484                    map,
 9485                    selection.end,
 9486                    row_count,
 9487                    selection.goal,
 9488                    false,
 9489                    text_layout_details,
 9490                );
 9491                selection.collapse_to(cursor, goal);
 9492            });
 9493        });
 9494    }
 9495
 9496    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 9497        let text_layout_details = &self.text_layout_details(window);
 9498        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9499            s.move_heads_with(|map, head, goal| {
 9500                movement::down(map, head, goal, false, text_layout_details)
 9501            })
 9502        });
 9503    }
 9504
 9505    pub fn context_menu_first(
 9506        &mut self,
 9507        _: &ContextMenuFirst,
 9508        _window: &mut Window,
 9509        cx: &mut Context<Self>,
 9510    ) {
 9511        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9512            context_menu.select_first(self.completion_provider.as_deref(), cx);
 9513        }
 9514    }
 9515
 9516    pub fn context_menu_prev(
 9517        &mut self,
 9518        _: &ContextMenuPrevious,
 9519        _window: &mut Window,
 9520        cx: &mut Context<Self>,
 9521    ) {
 9522        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9523            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 9524        }
 9525    }
 9526
 9527    pub fn context_menu_next(
 9528        &mut self,
 9529        _: &ContextMenuNext,
 9530        _window: &mut Window,
 9531        cx: &mut Context<Self>,
 9532    ) {
 9533        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9534            context_menu.select_next(self.completion_provider.as_deref(), cx);
 9535        }
 9536    }
 9537
 9538    pub fn context_menu_last(
 9539        &mut self,
 9540        _: &ContextMenuLast,
 9541        _window: &mut Window,
 9542        cx: &mut Context<Self>,
 9543    ) {
 9544        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9545            context_menu.select_last(self.completion_provider.as_deref(), cx);
 9546        }
 9547    }
 9548
 9549    pub fn move_to_previous_word_start(
 9550        &mut self,
 9551        _: &MoveToPreviousWordStart,
 9552        window: &mut Window,
 9553        cx: &mut Context<Self>,
 9554    ) {
 9555        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9556            s.move_cursors_with(|map, head, _| {
 9557                (
 9558                    movement::previous_word_start(map, head),
 9559                    SelectionGoal::None,
 9560                )
 9561            });
 9562        })
 9563    }
 9564
 9565    pub fn move_to_previous_subword_start(
 9566        &mut self,
 9567        _: &MoveToPreviousSubwordStart,
 9568        window: &mut Window,
 9569        cx: &mut Context<Self>,
 9570    ) {
 9571        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9572            s.move_cursors_with(|map, head, _| {
 9573                (
 9574                    movement::previous_subword_start(map, head),
 9575                    SelectionGoal::None,
 9576                )
 9577            });
 9578        })
 9579    }
 9580
 9581    pub fn select_to_previous_word_start(
 9582        &mut self,
 9583        _: &SelectToPreviousWordStart,
 9584        window: &mut Window,
 9585        cx: &mut Context<Self>,
 9586    ) {
 9587        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9588            s.move_heads_with(|map, head, _| {
 9589                (
 9590                    movement::previous_word_start(map, head),
 9591                    SelectionGoal::None,
 9592                )
 9593            });
 9594        })
 9595    }
 9596
 9597    pub fn select_to_previous_subword_start(
 9598        &mut self,
 9599        _: &SelectToPreviousSubwordStart,
 9600        window: &mut Window,
 9601        cx: &mut Context<Self>,
 9602    ) {
 9603        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9604            s.move_heads_with(|map, head, _| {
 9605                (
 9606                    movement::previous_subword_start(map, head),
 9607                    SelectionGoal::None,
 9608                )
 9609            });
 9610        })
 9611    }
 9612
 9613    pub fn delete_to_previous_word_start(
 9614        &mut self,
 9615        action: &DeleteToPreviousWordStart,
 9616        window: &mut Window,
 9617        cx: &mut Context<Self>,
 9618    ) {
 9619        self.transact(window, cx, |this, window, cx| {
 9620            this.select_autoclose_pair(window, cx);
 9621            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9622                let line_mode = s.line_mode;
 9623                s.move_with(|map, selection| {
 9624                    if selection.is_empty() && !line_mode {
 9625                        let cursor = if action.ignore_newlines {
 9626                            movement::previous_word_start(map, selection.head())
 9627                        } else {
 9628                            movement::previous_word_start_or_newline(map, selection.head())
 9629                        };
 9630                        selection.set_head(cursor, SelectionGoal::None);
 9631                    }
 9632                });
 9633            });
 9634            this.insert("", window, cx);
 9635        });
 9636    }
 9637
 9638    pub fn delete_to_previous_subword_start(
 9639        &mut self,
 9640        _: &DeleteToPreviousSubwordStart,
 9641        window: &mut Window,
 9642        cx: &mut Context<Self>,
 9643    ) {
 9644        self.transact(window, cx, |this, window, cx| {
 9645            this.select_autoclose_pair(window, cx);
 9646            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9647                let line_mode = s.line_mode;
 9648                s.move_with(|map, selection| {
 9649                    if selection.is_empty() && !line_mode {
 9650                        let cursor = movement::previous_subword_start(map, selection.head());
 9651                        selection.set_head(cursor, SelectionGoal::None);
 9652                    }
 9653                });
 9654            });
 9655            this.insert("", window, cx);
 9656        });
 9657    }
 9658
 9659    pub fn move_to_next_word_end(
 9660        &mut self,
 9661        _: &MoveToNextWordEnd,
 9662        window: &mut Window,
 9663        cx: &mut Context<Self>,
 9664    ) {
 9665        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9666            s.move_cursors_with(|map, head, _| {
 9667                (movement::next_word_end(map, head), SelectionGoal::None)
 9668            });
 9669        })
 9670    }
 9671
 9672    pub fn move_to_next_subword_end(
 9673        &mut self,
 9674        _: &MoveToNextSubwordEnd,
 9675        window: &mut Window,
 9676        cx: &mut Context<Self>,
 9677    ) {
 9678        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9679            s.move_cursors_with(|map, head, _| {
 9680                (movement::next_subword_end(map, head), SelectionGoal::None)
 9681            });
 9682        })
 9683    }
 9684
 9685    pub fn select_to_next_word_end(
 9686        &mut self,
 9687        _: &SelectToNextWordEnd,
 9688        window: &mut Window,
 9689        cx: &mut Context<Self>,
 9690    ) {
 9691        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9692            s.move_heads_with(|map, head, _| {
 9693                (movement::next_word_end(map, head), SelectionGoal::None)
 9694            });
 9695        })
 9696    }
 9697
 9698    pub fn select_to_next_subword_end(
 9699        &mut self,
 9700        _: &SelectToNextSubwordEnd,
 9701        window: &mut Window,
 9702        cx: &mut Context<Self>,
 9703    ) {
 9704        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9705            s.move_heads_with(|map, head, _| {
 9706                (movement::next_subword_end(map, head), SelectionGoal::None)
 9707            });
 9708        })
 9709    }
 9710
 9711    pub fn delete_to_next_word_end(
 9712        &mut self,
 9713        action: &DeleteToNextWordEnd,
 9714        window: &mut Window,
 9715        cx: &mut Context<Self>,
 9716    ) {
 9717        self.transact(window, cx, |this, window, cx| {
 9718            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9719                let line_mode = s.line_mode;
 9720                s.move_with(|map, selection| {
 9721                    if selection.is_empty() && !line_mode {
 9722                        let cursor = if action.ignore_newlines {
 9723                            movement::next_word_end(map, selection.head())
 9724                        } else {
 9725                            movement::next_word_end_or_newline(map, selection.head())
 9726                        };
 9727                        selection.set_head(cursor, SelectionGoal::None);
 9728                    }
 9729                });
 9730            });
 9731            this.insert("", window, cx);
 9732        });
 9733    }
 9734
 9735    pub fn delete_to_next_subword_end(
 9736        &mut self,
 9737        _: &DeleteToNextSubwordEnd,
 9738        window: &mut Window,
 9739        cx: &mut Context<Self>,
 9740    ) {
 9741        self.transact(window, cx, |this, window, cx| {
 9742            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9743                s.move_with(|map, selection| {
 9744                    if selection.is_empty() {
 9745                        let cursor = movement::next_subword_end(map, selection.head());
 9746                        selection.set_head(cursor, SelectionGoal::None);
 9747                    }
 9748                });
 9749            });
 9750            this.insert("", window, cx);
 9751        });
 9752    }
 9753
 9754    pub fn move_to_beginning_of_line(
 9755        &mut self,
 9756        action: &MoveToBeginningOfLine,
 9757        window: &mut Window,
 9758        cx: &mut Context<Self>,
 9759    ) {
 9760        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9761            s.move_cursors_with(|map, head, _| {
 9762                (
 9763                    movement::indented_line_beginning(
 9764                        map,
 9765                        head,
 9766                        action.stop_at_soft_wraps,
 9767                        action.stop_at_indent,
 9768                    ),
 9769                    SelectionGoal::None,
 9770                )
 9771            });
 9772        })
 9773    }
 9774
 9775    pub fn select_to_beginning_of_line(
 9776        &mut self,
 9777        action: &SelectToBeginningOfLine,
 9778        window: &mut Window,
 9779        cx: &mut Context<Self>,
 9780    ) {
 9781        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9782            s.move_heads_with(|map, head, _| {
 9783                (
 9784                    movement::indented_line_beginning(
 9785                        map,
 9786                        head,
 9787                        action.stop_at_soft_wraps,
 9788                        action.stop_at_indent,
 9789                    ),
 9790                    SelectionGoal::None,
 9791                )
 9792            });
 9793        });
 9794    }
 9795
 9796    pub fn delete_to_beginning_of_line(
 9797        &mut self,
 9798        action: &DeleteToBeginningOfLine,
 9799        window: &mut Window,
 9800        cx: &mut Context<Self>,
 9801    ) {
 9802        self.transact(window, cx, |this, window, cx| {
 9803            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9804                s.move_with(|_, selection| {
 9805                    selection.reversed = true;
 9806                });
 9807            });
 9808
 9809            this.select_to_beginning_of_line(
 9810                &SelectToBeginningOfLine {
 9811                    stop_at_soft_wraps: false,
 9812                    stop_at_indent: action.stop_at_indent,
 9813                },
 9814                window,
 9815                cx,
 9816            );
 9817            this.backspace(&Backspace, window, cx);
 9818        });
 9819    }
 9820
 9821    pub fn move_to_end_of_line(
 9822        &mut self,
 9823        action: &MoveToEndOfLine,
 9824        window: &mut Window,
 9825        cx: &mut Context<Self>,
 9826    ) {
 9827        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9828            s.move_cursors_with(|map, head, _| {
 9829                (
 9830                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9831                    SelectionGoal::None,
 9832                )
 9833            });
 9834        })
 9835    }
 9836
 9837    pub fn select_to_end_of_line(
 9838        &mut self,
 9839        action: &SelectToEndOfLine,
 9840        window: &mut Window,
 9841        cx: &mut Context<Self>,
 9842    ) {
 9843        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9844            s.move_heads_with(|map, head, _| {
 9845                (
 9846                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9847                    SelectionGoal::None,
 9848                )
 9849            });
 9850        })
 9851    }
 9852
 9853    pub fn delete_to_end_of_line(
 9854        &mut self,
 9855        _: &DeleteToEndOfLine,
 9856        window: &mut Window,
 9857        cx: &mut Context<Self>,
 9858    ) {
 9859        self.transact(window, cx, |this, window, cx| {
 9860            this.select_to_end_of_line(
 9861                &SelectToEndOfLine {
 9862                    stop_at_soft_wraps: false,
 9863                },
 9864                window,
 9865                cx,
 9866            );
 9867            this.delete(&Delete, window, cx);
 9868        });
 9869    }
 9870
 9871    pub fn cut_to_end_of_line(
 9872        &mut self,
 9873        _: &CutToEndOfLine,
 9874        window: &mut Window,
 9875        cx: &mut Context<Self>,
 9876    ) {
 9877        self.transact(window, cx, |this, window, cx| {
 9878            this.select_to_end_of_line(
 9879                &SelectToEndOfLine {
 9880                    stop_at_soft_wraps: false,
 9881                },
 9882                window,
 9883                cx,
 9884            );
 9885            this.cut(&Cut, window, cx);
 9886        });
 9887    }
 9888
 9889    pub fn move_to_start_of_paragraph(
 9890        &mut self,
 9891        _: &MoveToStartOfParagraph,
 9892        window: &mut Window,
 9893        cx: &mut Context<Self>,
 9894    ) {
 9895        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9896            cx.propagate();
 9897            return;
 9898        }
 9899
 9900        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9901            s.move_with(|map, selection| {
 9902                selection.collapse_to(
 9903                    movement::start_of_paragraph(map, selection.head(), 1),
 9904                    SelectionGoal::None,
 9905                )
 9906            });
 9907        })
 9908    }
 9909
 9910    pub fn move_to_end_of_paragraph(
 9911        &mut self,
 9912        _: &MoveToEndOfParagraph,
 9913        window: &mut Window,
 9914        cx: &mut Context<Self>,
 9915    ) {
 9916        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9917            cx.propagate();
 9918            return;
 9919        }
 9920
 9921        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9922            s.move_with(|map, selection| {
 9923                selection.collapse_to(
 9924                    movement::end_of_paragraph(map, selection.head(), 1),
 9925                    SelectionGoal::None,
 9926                )
 9927            });
 9928        })
 9929    }
 9930
 9931    pub fn select_to_start_of_paragraph(
 9932        &mut self,
 9933        _: &SelectToStartOfParagraph,
 9934        window: &mut Window,
 9935        cx: &mut Context<Self>,
 9936    ) {
 9937        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9938            cx.propagate();
 9939            return;
 9940        }
 9941
 9942        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9943            s.move_heads_with(|map, head, _| {
 9944                (
 9945                    movement::start_of_paragraph(map, head, 1),
 9946                    SelectionGoal::None,
 9947                )
 9948            });
 9949        })
 9950    }
 9951
 9952    pub fn select_to_end_of_paragraph(
 9953        &mut self,
 9954        _: &SelectToEndOfParagraph,
 9955        window: &mut Window,
 9956        cx: &mut Context<Self>,
 9957    ) {
 9958        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9959            cx.propagate();
 9960            return;
 9961        }
 9962
 9963        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9964            s.move_heads_with(|map, head, _| {
 9965                (
 9966                    movement::end_of_paragraph(map, head, 1),
 9967                    SelectionGoal::None,
 9968                )
 9969            });
 9970        })
 9971    }
 9972
 9973    pub fn move_to_start_of_excerpt(
 9974        &mut self,
 9975        _: &MoveToStartOfExcerpt,
 9976        window: &mut Window,
 9977        cx: &mut Context<Self>,
 9978    ) {
 9979        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9980            cx.propagate();
 9981            return;
 9982        }
 9983
 9984        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9985            s.move_with(|map, selection| {
 9986                selection.collapse_to(
 9987                    movement::start_of_excerpt(
 9988                        map,
 9989                        selection.head(),
 9990                        workspace::searchable::Direction::Prev,
 9991                    ),
 9992                    SelectionGoal::None,
 9993                )
 9994            });
 9995        })
 9996    }
 9997
 9998    pub fn move_to_start_of_next_excerpt(
 9999        &mut self,
10000        _: &MoveToStartOfNextExcerpt,
10001        window: &mut Window,
10002        cx: &mut Context<Self>,
10003    ) {
10004        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10005            cx.propagate();
10006            return;
10007        }
10008
10009        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10010            s.move_with(|map, selection| {
10011                selection.collapse_to(
10012                    movement::start_of_excerpt(
10013                        map,
10014                        selection.head(),
10015                        workspace::searchable::Direction::Next,
10016                    ),
10017                    SelectionGoal::None,
10018                )
10019            });
10020        })
10021    }
10022
10023    pub fn move_to_end_of_excerpt(
10024        &mut self,
10025        _: &MoveToEndOfExcerpt,
10026        window: &mut Window,
10027        cx: &mut Context<Self>,
10028    ) {
10029        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10030            cx.propagate();
10031            return;
10032        }
10033
10034        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10035            s.move_with(|map, selection| {
10036                selection.collapse_to(
10037                    movement::end_of_excerpt(
10038                        map,
10039                        selection.head(),
10040                        workspace::searchable::Direction::Next,
10041                    ),
10042                    SelectionGoal::None,
10043                )
10044            });
10045        })
10046    }
10047
10048    pub fn move_to_end_of_previous_excerpt(
10049        &mut self,
10050        _: &MoveToEndOfPreviousExcerpt,
10051        window: &mut Window,
10052        cx: &mut Context<Self>,
10053    ) {
10054        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10055            cx.propagate();
10056            return;
10057        }
10058
10059        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10060            s.move_with(|map, selection| {
10061                selection.collapse_to(
10062                    movement::end_of_excerpt(
10063                        map,
10064                        selection.head(),
10065                        workspace::searchable::Direction::Prev,
10066                    ),
10067                    SelectionGoal::None,
10068                )
10069            });
10070        })
10071    }
10072
10073    pub fn select_to_start_of_excerpt(
10074        &mut self,
10075        _: &SelectToStartOfExcerpt,
10076        window: &mut Window,
10077        cx: &mut Context<Self>,
10078    ) {
10079        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10080            cx.propagate();
10081            return;
10082        }
10083
10084        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10085            s.move_heads_with(|map, head, _| {
10086                (
10087                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10088                    SelectionGoal::None,
10089                )
10090            });
10091        })
10092    }
10093
10094    pub fn select_to_start_of_next_excerpt(
10095        &mut self,
10096        _: &SelectToStartOfNextExcerpt,
10097        window: &mut Window,
10098        cx: &mut Context<Self>,
10099    ) {
10100        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10101            cx.propagate();
10102            return;
10103        }
10104
10105        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10106            s.move_heads_with(|map, head, _| {
10107                (
10108                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
10109                    SelectionGoal::None,
10110                )
10111            });
10112        })
10113    }
10114
10115    pub fn select_to_end_of_excerpt(
10116        &mut self,
10117        _: &SelectToEndOfExcerpt,
10118        window: &mut Window,
10119        cx: &mut Context<Self>,
10120    ) {
10121        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10122            cx.propagate();
10123            return;
10124        }
10125
10126        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10127            s.move_heads_with(|map, head, _| {
10128                (
10129                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
10130                    SelectionGoal::None,
10131                )
10132            });
10133        })
10134    }
10135
10136    pub fn select_to_end_of_previous_excerpt(
10137        &mut self,
10138        _: &SelectToEndOfPreviousExcerpt,
10139        window: &mut Window,
10140        cx: &mut Context<Self>,
10141    ) {
10142        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10143            cx.propagate();
10144            return;
10145        }
10146
10147        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10148            s.move_heads_with(|map, head, _| {
10149                (
10150                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10151                    SelectionGoal::None,
10152                )
10153            });
10154        })
10155    }
10156
10157    pub fn move_to_beginning(
10158        &mut self,
10159        _: &MoveToBeginning,
10160        window: &mut Window,
10161        cx: &mut Context<Self>,
10162    ) {
10163        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10164            cx.propagate();
10165            return;
10166        }
10167
10168        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10169            s.select_ranges(vec![0..0]);
10170        });
10171    }
10172
10173    pub fn select_to_beginning(
10174        &mut self,
10175        _: &SelectToBeginning,
10176        window: &mut Window,
10177        cx: &mut Context<Self>,
10178    ) {
10179        let mut selection = self.selections.last::<Point>(cx);
10180        selection.set_head(Point::zero(), SelectionGoal::None);
10181
10182        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10183            s.select(vec![selection]);
10184        });
10185    }
10186
10187    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
10188        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10189            cx.propagate();
10190            return;
10191        }
10192
10193        let cursor = self.buffer.read(cx).read(cx).len();
10194        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10195            s.select_ranges(vec![cursor..cursor])
10196        });
10197    }
10198
10199    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
10200        self.nav_history = nav_history;
10201    }
10202
10203    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
10204        self.nav_history.as_ref()
10205    }
10206
10207    fn push_to_nav_history(
10208        &mut self,
10209        cursor_anchor: Anchor,
10210        new_position: Option<Point>,
10211        cx: &mut Context<Self>,
10212    ) {
10213        if let Some(nav_history) = self.nav_history.as_mut() {
10214            let buffer = self.buffer.read(cx).read(cx);
10215            let cursor_position = cursor_anchor.to_point(&buffer);
10216            let scroll_state = self.scroll_manager.anchor();
10217            let scroll_top_row = scroll_state.top_row(&buffer);
10218            drop(buffer);
10219
10220            if let Some(new_position) = new_position {
10221                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
10222                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
10223                    return;
10224                }
10225            }
10226
10227            nav_history.push(
10228                Some(NavigationData {
10229                    cursor_anchor,
10230                    cursor_position,
10231                    scroll_anchor: scroll_state,
10232                    scroll_top_row,
10233                }),
10234                cx,
10235            );
10236        }
10237    }
10238
10239    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
10240        let buffer = self.buffer.read(cx).snapshot(cx);
10241        let mut selection = self.selections.first::<usize>(cx);
10242        selection.set_head(buffer.len(), SelectionGoal::None);
10243        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10244            s.select(vec![selection]);
10245        });
10246    }
10247
10248    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
10249        let end = self.buffer.read(cx).read(cx).len();
10250        self.change_selections(None, window, cx, |s| {
10251            s.select_ranges(vec![0..end]);
10252        });
10253    }
10254
10255    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
10256        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10257        let mut selections = self.selections.all::<Point>(cx);
10258        let max_point = display_map.buffer_snapshot.max_point();
10259        for selection in &mut selections {
10260            let rows = selection.spanned_rows(true, &display_map);
10261            selection.start = Point::new(rows.start.0, 0);
10262            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
10263            selection.reversed = false;
10264        }
10265        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10266            s.select(selections);
10267        });
10268    }
10269
10270    pub fn split_selection_into_lines(
10271        &mut self,
10272        _: &SplitSelectionIntoLines,
10273        window: &mut Window,
10274        cx: &mut Context<Self>,
10275    ) {
10276        let selections = self
10277            .selections
10278            .all::<Point>(cx)
10279            .into_iter()
10280            .map(|selection| selection.start..selection.end)
10281            .collect::<Vec<_>>();
10282        self.unfold_ranges(&selections, true, true, cx);
10283
10284        let mut new_selection_ranges = Vec::new();
10285        {
10286            let buffer = self.buffer.read(cx).read(cx);
10287            for selection in selections {
10288                for row in selection.start.row..selection.end.row {
10289                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
10290                    new_selection_ranges.push(cursor..cursor);
10291                }
10292
10293                let is_multiline_selection = selection.start.row != selection.end.row;
10294                // Don't insert last one if it's a multi-line selection ending at the start of a line,
10295                // so this action feels more ergonomic when paired with other selection operations
10296                let should_skip_last = is_multiline_selection && selection.end.column == 0;
10297                if !should_skip_last {
10298                    new_selection_ranges.push(selection.end..selection.end);
10299                }
10300            }
10301        }
10302        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10303            s.select_ranges(new_selection_ranges);
10304        });
10305    }
10306
10307    pub fn add_selection_above(
10308        &mut self,
10309        _: &AddSelectionAbove,
10310        window: &mut Window,
10311        cx: &mut Context<Self>,
10312    ) {
10313        self.add_selection(true, window, cx);
10314    }
10315
10316    pub fn add_selection_below(
10317        &mut self,
10318        _: &AddSelectionBelow,
10319        window: &mut Window,
10320        cx: &mut Context<Self>,
10321    ) {
10322        self.add_selection(false, window, cx);
10323    }
10324
10325    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
10326        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10327        let mut selections = self.selections.all::<Point>(cx);
10328        let text_layout_details = self.text_layout_details(window);
10329        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10330            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10331            let range = oldest_selection.display_range(&display_map).sorted();
10332
10333            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10334            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10335            let positions = start_x.min(end_x)..start_x.max(end_x);
10336
10337            selections.clear();
10338            let mut stack = Vec::new();
10339            for row in range.start.row().0..=range.end.row().0 {
10340                if let Some(selection) = self.selections.build_columnar_selection(
10341                    &display_map,
10342                    DisplayRow(row),
10343                    &positions,
10344                    oldest_selection.reversed,
10345                    &text_layout_details,
10346                ) {
10347                    stack.push(selection.id);
10348                    selections.push(selection);
10349                }
10350            }
10351
10352            if above {
10353                stack.reverse();
10354            }
10355
10356            AddSelectionsState { above, stack }
10357        });
10358
10359        let last_added_selection = *state.stack.last().unwrap();
10360        let mut new_selections = Vec::new();
10361        if above == state.above {
10362            let end_row = if above {
10363                DisplayRow(0)
10364            } else {
10365                display_map.max_point().row()
10366            };
10367
10368            'outer: for selection in selections {
10369                if selection.id == last_added_selection {
10370                    let range = selection.display_range(&display_map).sorted();
10371                    debug_assert_eq!(range.start.row(), range.end.row());
10372                    let mut row = range.start.row();
10373                    let positions =
10374                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10375                            px(start)..px(end)
10376                        } else {
10377                            let start_x =
10378                                display_map.x_for_display_point(range.start, &text_layout_details);
10379                            let end_x =
10380                                display_map.x_for_display_point(range.end, &text_layout_details);
10381                            start_x.min(end_x)..start_x.max(end_x)
10382                        };
10383
10384                    while row != end_row {
10385                        if above {
10386                            row.0 -= 1;
10387                        } else {
10388                            row.0 += 1;
10389                        }
10390
10391                        if let Some(new_selection) = self.selections.build_columnar_selection(
10392                            &display_map,
10393                            row,
10394                            &positions,
10395                            selection.reversed,
10396                            &text_layout_details,
10397                        ) {
10398                            state.stack.push(new_selection.id);
10399                            if above {
10400                                new_selections.push(new_selection);
10401                                new_selections.push(selection);
10402                            } else {
10403                                new_selections.push(selection);
10404                                new_selections.push(new_selection);
10405                            }
10406
10407                            continue 'outer;
10408                        }
10409                    }
10410                }
10411
10412                new_selections.push(selection);
10413            }
10414        } else {
10415            new_selections = selections;
10416            new_selections.retain(|s| s.id != last_added_selection);
10417            state.stack.pop();
10418        }
10419
10420        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10421            s.select(new_selections);
10422        });
10423        if state.stack.len() > 1 {
10424            self.add_selections_state = Some(state);
10425        }
10426    }
10427
10428    pub fn select_next_match_internal(
10429        &mut self,
10430        display_map: &DisplaySnapshot,
10431        replace_newest: bool,
10432        autoscroll: Option<Autoscroll>,
10433        window: &mut Window,
10434        cx: &mut Context<Self>,
10435    ) -> Result<()> {
10436        fn select_next_match_ranges(
10437            this: &mut Editor,
10438            range: Range<usize>,
10439            replace_newest: bool,
10440            auto_scroll: Option<Autoscroll>,
10441            window: &mut Window,
10442            cx: &mut Context<Editor>,
10443        ) {
10444            this.unfold_ranges(&[range.clone()], false, true, cx);
10445            this.change_selections(auto_scroll, window, cx, |s| {
10446                if replace_newest {
10447                    s.delete(s.newest_anchor().id);
10448                }
10449                s.insert_range(range.clone());
10450            });
10451        }
10452
10453        let buffer = &display_map.buffer_snapshot;
10454        let mut selections = self.selections.all::<usize>(cx);
10455        if let Some(mut select_next_state) = self.select_next_state.take() {
10456            let query = &select_next_state.query;
10457            if !select_next_state.done {
10458                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10459                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10460                let mut next_selected_range = None;
10461
10462                let bytes_after_last_selection =
10463                    buffer.bytes_in_range(last_selection.end..buffer.len());
10464                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10465                let query_matches = query
10466                    .stream_find_iter(bytes_after_last_selection)
10467                    .map(|result| (last_selection.end, result))
10468                    .chain(
10469                        query
10470                            .stream_find_iter(bytes_before_first_selection)
10471                            .map(|result| (0, result)),
10472                    );
10473
10474                for (start_offset, query_match) in query_matches {
10475                    let query_match = query_match.unwrap(); // can only fail due to I/O
10476                    let offset_range =
10477                        start_offset + query_match.start()..start_offset + query_match.end();
10478                    let display_range = offset_range.start.to_display_point(display_map)
10479                        ..offset_range.end.to_display_point(display_map);
10480
10481                    if !select_next_state.wordwise
10482                        || (!movement::is_inside_word(display_map, display_range.start)
10483                            && !movement::is_inside_word(display_map, display_range.end))
10484                    {
10485                        // TODO: This is n^2, because we might check all the selections
10486                        if !selections
10487                            .iter()
10488                            .any(|selection| selection.range().overlaps(&offset_range))
10489                        {
10490                            next_selected_range = Some(offset_range);
10491                            break;
10492                        }
10493                    }
10494                }
10495
10496                if let Some(next_selected_range) = next_selected_range {
10497                    select_next_match_ranges(
10498                        self,
10499                        next_selected_range,
10500                        replace_newest,
10501                        autoscroll,
10502                        window,
10503                        cx,
10504                    );
10505                } else {
10506                    select_next_state.done = true;
10507                }
10508            }
10509
10510            self.select_next_state = Some(select_next_state);
10511        } else {
10512            let mut only_carets = true;
10513            let mut same_text_selected = true;
10514            let mut selected_text = None;
10515
10516            let mut selections_iter = selections.iter().peekable();
10517            while let Some(selection) = selections_iter.next() {
10518                if selection.start != selection.end {
10519                    only_carets = false;
10520                }
10521
10522                if same_text_selected {
10523                    if selected_text.is_none() {
10524                        selected_text =
10525                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10526                    }
10527
10528                    if let Some(next_selection) = selections_iter.peek() {
10529                        if next_selection.range().len() == selection.range().len() {
10530                            let next_selected_text = buffer
10531                                .text_for_range(next_selection.range())
10532                                .collect::<String>();
10533                            if Some(next_selected_text) != selected_text {
10534                                same_text_selected = false;
10535                                selected_text = None;
10536                            }
10537                        } else {
10538                            same_text_selected = false;
10539                            selected_text = None;
10540                        }
10541                    }
10542                }
10543            }
10544
10545            if only_carets {
10546                for selection in &mut selections {
10547                    let word_range = movement::surrounding_word(
10548                        display_map,
10549                        selection.start.to_display_point(display_map),
10550                    );
10551                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
10552                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
10553                    selection.goal = SelectionGoal::None;
10554                    selection.reversed = false;
10555                    select_next_match_ranges(
10556                        self,
10557                        selection.start..selection.end,
10558                        replace_newest,
10559                        autoscroll,
10560                        window,
10561                        cx,
10562                    );
10563                }
10564
10565                if selections.len() == 1 {
10566                    let selection = selections
10567                        .last()
10568                        .expect("ensured that there's only one selection");
10569                    let query = buffer
10570                        .text_for_range(selection.start..selection.end)
10571                        .collect::<String>();
10572                    let is_empty = query.is_empty();
10573                    let select_state = SelectNextState {
10574                        query: AhoCorasick::new(&[query])?,
10575                        wordwise: true,
10576                        done: is_empty,
10577                    };
10578                    self.select_next_state = Some(select_state);
10579                } else {
10580                    self.select_next_state = None;
10581                }
10582            } else if let Some(selected_text) = selected_text {
10583                self.select_next_state = Some(SelectNextState {
10584                    query: AhoCorasick::new(&[selected_text])?,
10585                    wordwise: false,
10586                    done: false,
10587                });
10588                self.select_next_match_internal(
10589                    display_map,
10590                    replace_newest,
10591                    autoscroll,
10592                    window,
10593                    cx,
10594                )?;
10595            }
10596        }
10597        Ok(())
10598    }
10599
10600    pub fn select_all_matches(
10601        &mut self,
10602        _action: &SelectAllMatches,
10603        window: &mut Window,
10604        cx: &mut Context<Self>,
10605    ) -> Result<()> {
10606        self.push_to_selection_history();
10607        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10608
10609        self.select_next_match_internal(&display_map, false, None, window, cx)?;
10610        let Some(select_next_state) = self.select_next_state.as_mut() else {
10611            return Ok(());
10612        };
10613        if select_next_state.done {
10614            return Ok(());
10615        }
10616
10617        let mut new_selections = self.selections.all::<usize>(cx);
10618
10619        let buffer = &display_map.buffer_snapshot;
10620        let query_matches = select_next_state
10621            .query
10622            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10623
10624        for query_match in query_matches {
10625            let query_match = query_match.unwrap(); // can only fail due to I/O
10626            let offset_range = query_match.start()..query_match.end();
10627            let display_range = offset_range.start.to_display_point(&display_map)
10628                ..offset_range.end.to_display_point(&display_map);
10629
10630            if !select_next_state.wordwise
10631                || (!movement::is_inside_word(&display_map, display_range.start)
10632                    && !movement::is_inside_word(&display_map, display_range.end))
10633            {
10634                self.selections.change_with(cx, |selections| {
10635                    new_selections.push(Selection {
10636                        id: selections.new_selection_id(),
10637                        start: offset_range.start,
10638                        end: offset_range.end,
10639                        reversed: false,
10640                        goal: SelectionGoal::None,
10641                    });
10642                });
10643            }
10644        }
10645
10646        new_selections.sort_by_key(|selection| selection.start);
10647        let mut ix = 0;
10648        while ix + 1 < new_selections.len() {
10649            let current_selection = &new_selections[ix];
10650            let next_selection = &new_selections[ix + 1];
10651            if current_selection.range().overlaps(&next_selection.range()) {
10652                if current_selection.id < next_selection.id {
10653                    new_selections.remove(ix + 1);
10654                } else {
10655                    new_selections.remove(ix);
10656                }
10657            } else {
10658                ix += 1;
10659            }
10660        }
10661
10662        let reversed = self.selections.oldest::<usize>(cx).reversed;
10663
10664        for selection in new_selections.iter_mut() {
10665            selection.reversed = reversed;
10666        }
10667
10668        select_next_state.done = true;
10669        self.unfold_ranges(
10670            &new_selections
10671                .iter()
10672                .map(|selection| selection.range())
10673                .collect::<Vec<_>>(),
10674            false,
10675            false,
10676            cx,
10677        );
10678        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10679            selections.select(new_selections)
10680        });
10681
10682        Ok(())
10683    }
10684
10685    pub fn select_next(
10686        &mut self,
10687        action: &SelectNext,
10688        window: &mut Window,
10689        cx: &mut Context<Self>,
10690    ) -> Result<()> {
10691        self.push_to_selection_history();
10692        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10693        self.select_next_match_internal(
10694            &display_map,
10695            action.replace_newest,
10696            Some(Autoscroll::newest()),
10697            window,
10698            cx,
10699        )?;
10700        Ok(())
10701    }
10702
10703    pub fn select_previous(
10704        &mut self,
10705        action: &SelectPrevious,
10706        window: &mut Window,
10707        cx: &mut Context<Self>,
10708    ) -> Result<()> {
10709        self.push_to_selection_history();
10710        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10711        let buffer = &display_map.buffer_snapshot;
10712        let mut selections = self.selections.all::<usize>(cx);
10713        if let Some(mut select_prev_state) = self.select_prev_state.take() {
10714            let query = &select_prev_state.query;
10715            if !select_prev_state.done {
10716                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10717                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10718                let mut next_selected_range = None;
10719                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10720                let bytes_before_last_selection =
10721                    buffer.reversed_bytes_in_range(0..last_selection.start);
10722                let bytes_after_first_selection =
10723                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10724                let query_matches = query
10725                    .stream_find_iter(bytes_before_last_selection)
10726                    .map(|result| (last_selection.start, result))
10727                    .chain(
10728                        query
10729                            .stream_find_iter(bytes_after_first_selection)
10730                            .map(|result| (buffer.len(), result)),
10731                    );
10732                for (end_offset, query_match) in query_matches {
10733                    let query_match = query_match.unwrap(); // can only fail due to I/O
10734                    let offset_range =
10735                        end_offset - query_match.end()..end_offset - query_match.start();
10736                    let display_range = offset_range.start.to_display_point(&display_map)
10737                        ..offset_range.end.to_display_point(&display_map);
10738
10739                    if !select_prev_state.wordwise
10740                        || (!movement::is_inside_word(&display_map, display_range.start)
10741                            && !movement::is_inside_word(&display_map, display_range.end))
10742                    {
10743                        next_selected_range = Some(offset_range);
10744                        break;
10745                    }
10746                }
10747
10748                if let Some(next_selected_range) = next_selected_range {
10749                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10750                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10751                        if action.replace_newest {
10752                            s.delete(s.newest_anchor().id);
10753                        }
10754                        s.insert_range(next_selected_range);
10755                    });
10756                } else {
10757                    select_prev_state.done = true;
10758                }
10759            }
10760
10761            self.select_prev_state = Some(select_prev_state);
10762        } else {
10763            let mut only_carets = true;
10764            let mut same_text_selected = true;
10765            let mut selected_text = None;
10766
10767            let mut selections_iter = selections.iter().peekable();
10768            while let Some(selection) = selections_iter.next() {
10769                if selection.start != selection.end {
10770                    only_carets = false;
10771                }
10772
10773                if same_text_selected {
10774                    if selected_text.is_none() {
10775                        selected_text =
10776                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10777                    }
10778
10779                    if let Some(next_selection) = selections_iter.peek() {
10780                        if next_selection.range().len() == selection.range().len() {
10781                            let next_selected_text = buffer
10782                                .text_for_range(next_selection.range())
10783                                .collect::<String>();
10784                            if Some(next_selected_text) != selected_text {
10785                                same_text_selected = false;
10786                                selected_text = None;
10787                            }
10788                        } else {
10789                            same_text_selected = false;
10790                            selected_text = None;
10791                        }
10792                    }
10793                }
10794            }
10795
10796            if only_carets {
10797                for selection in &mut selections {
10798                    let word_range = movement::surrounding_word(
10799                        &display_map,
10800                        selection.start.to_display_point(&display_map),
10801                    );
10802                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10803                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10804                    selection.goal = SelectionGoal::None;
10805                    selection.reversed = false;
10806                }
10807                if selections.len() == 1 {
10808                    let selection = selections
10809                        .last()
10810                        .expect("ensured that there's only one selection");
10811                    let query = buffer
10812                        .text_for_range(selection.start..selection.end)
10813                        .collect::<String>();
10814                    let is_empty = query.is_empty();
10815                    let select_state = SelectNextState {
10816                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10817                        wordwise: true,
10818                        done: is_empty,
10819                    };
10820                    self.select_prev_state = Some(select_state);
10821                } else {
10822                    self.select_prev_state = None;
10823                }
10824
10825                self.unfold_ranges(
10826                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10827                    false,
10828                    true,
10829                    cx,
10830                );
10831                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10832                    s.select(selections);
10833                });
10834            } else if let Some(selected_text) = selected_text {
10835                self.select_prev_state = Some(SelectNextState {
10836                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10837                    wordwise: false,
10838                    done: false,
10839                });
10840                self.select_previous(action, window, cx)?;
10841            }
10842        }
10843        Ok(())
10844    }
10845
10846    pub fn toggle_comments(
10847        &mut self,
10848        action: &ToggleComments,
10849        window: &mut Window,
10850        cx: &mut Context<Self>,
10851    ) {
10852        if self.read_only(cx) {
10853            return;
10854        }
10855        let text_layout_details = &self.text_layout_details(window);
10856        self.transact(window, cx, |this, window, cx| {
10857            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10858            let mut edits = Vec::new();
10859            let mut selection_edit_ranges = Vec::new();
10860            let mut last_toggled_row = None;
10861            let snapshot = this.buffer.read(cx).read(cx);
10862            let empty_str: Arc<str> = Arc::default();
10863            let mut suffixes_inserted = Vec::new();
10864            let ignore_indent = action.ignore_indent;
10865
10866            fn comment_prefix_range(
10867                snapshot: &MultiBufferSnapshot,
10868                row: MultiBufferRow,
10869                comment_prefix: &str,
10870                comment_prefix_whitespace: &str,
10871                ignore_indent: bool,
10872            ) -> Range<Point> {
10873                let indent_size = if ignore_indent {
10874                    0
10875                } else {
10876                    snapshot.indent_size_for_line(row).len
10877                };
10878
10879                let start = Point::new(row.0, indent_size);
10880
10881                let mut line_bytes = snapshot
10882                    .bytes_in_range(start..snapshot.max_point())
10883                    .flatten()
10884                    .copied();
10885
10886                // If this line currently begins with the line comment prefix, then record
10887                // the range containing the prefix.
10888                if line_bytes
10889                    .by_ref()
10890                    .take(comment_prefix.len())
10891                    .eq(comment_prefix.bytes())
10892                {
10893                    // Include any whitespace that matches the comment prefix.
10894                    let matching_whitespace_len = line_bytes
10895                        .zip(comment_prefix_whitespace.bytes())
10896                        .take_while(|(a, b)| a == b)
10897                        .count() as u32;
10898                    let end = Point::new(
10899                        start.row,
10900                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10901                    );
10902                    start..end
10903                } else {
10904                    start..start
10905                }
10906            }
10907
10908            fn comment_suffix_range(
10909                snapshot: &MultiBufferSnapshot,
10910                row: MultiBufferRow,
10911                comment_suffix: &str,
10912                comment_suffix_has_leading_space: bool,
10913            ) -> Range<Point> {
10914                let end = Point::new(row.0, snapshot.line_len(row));
10915                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10916
10917                let mut line_end_bytes = snapshot
10918                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10919                    .flatten()
10920                    .copied();
10921
10922                let leading_space_len = if suffix_start_column > 0
10923                    && line_end_bytes.next() == Some(b' ')
10924                    && comment_suffix_has_leading_space
10925                {
10926                    1
10927                } else {
10928                    0
10929                };
10930
10931                // If this line currently begins with the line comment prefix, then record
10932                // the range containing the prefix.
10933                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10934                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
10935                    start..end
10936                } else {
10937                    end..end
10938                }
10939            }
10940
10941            // TODO: Handle selections that cross excerpts
10942            for selection in &mut selections {
10943                let start_column = snapshot
10944                    .indent_size_for_line(MultiBufferRow(selection.start.row))
10945                    .len;
10946                let language = if let Some(language) =
10947                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10948                {
10949                    language
10950                } else {
10951                    continue;
10952                };
10953
10954                selection_edit_ranges.clear();
10955
10956                // If multiple selections contain a given row, avoid processing that
10957                // row more than once.
10958                let mut start_row = MultiBufferRow(selection.start.row);
10959                if last_toggled_row == Some(start_row) {
10960                    start_row = start_row.next_row();
10961                }
10962                let end_row =
10963                    if selection.end.row > selection.start.row && selection.end.column == 0 {
10964                        MultiBufferRow(selection.end.row - 1)
10965                    } else {
10966                        MultiBufferRow(selection.end.row)
10967                    };
10968                last_toggled_row = Some(end_row);
10969
10970                if start_row > end_row {
10971                    continue;
10972                }
10973
10974                // If the language has line comments, toggle those.
10975                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10976
10977                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10978                if ignore_indent {
10979                    full_comment_prefixes = full_comment_prefixes
10980                        .into_iter()
10981                        .map(|s| Arc::from(s.trim_end()))
10982                        .collect();
10983                }
10984
10985                if !full_comment_prefixes.is_empty() {
10986                    let first_prefix = full_comment_prefixes
10987                        .first()
10988                        .expect("prefixes is non-empty");
10989                    let prefix_trimmed_lengths = full_comment_prefixes
10990                        .iter()
10991                        .map(|p| p.trim_end_matches(' ').len())
10992                        .collect::<SmallVec<[usize; 4]>>();
10993
10994                    let mut all_selection_lines_are_comments = true;
10995
10996                    for row in start_row.0..=end_row.0 {
10997                        let row = MultiBufferRow(row);
10998                        if start_row < end_row && snapshot.is_line_blank(row) {
10999                            continue;
11000                        }
11001
11002                        let prefix_range = full_comment_prefixes
11003                            .iter()
11004                            .zip(prefix_trimmed_lengths.iter().copied())
11005                            .map(|(prefix, trimmed_prefix_len)| {
11006                                comment_prefix_range(
11007                                    snapshot.deref(),
11008                                    row,
11009                                    &prefix[..trimmed_prefix_len],
11010                                    &prefix[trimmed_prefix_len..],
11011                                    ignore_indent,
11012                                )
11013                            })
11014                            .max_by_key(|range| range.end.column - range.start.column)
11015                            .expect("prefixes is non-empty");
11016
11017                        if prefix_range.is_empty() {
11018                            all_selection_lines_are_comments = false;
11019                        }
11020
11021                        selection_edit_ranges.push(prefix_range);
11022                    }
11023
11024                    if all_selection_lines_are_comments {
11025                        edits.extend(
11026                            selection_edit_ranges
11027                                .iter()
11028                                .cloned()
11029                                .map(|range| (range, empty_str.clone())),
11030                        );
11031                    } else {
11032                        let min_column = selection_edit_ranges
11033                            .iter()
11034                            .map(|range| range.start.column)
11035                            .min()
11036                            .unwrap_or(0);
11037                        edits.extend(selection_edit_ranges.iter().map(|range| {
11038                            let position = Point::new(range.start.row, min_column);
11039                            (position..position, first_prefix.clone())
11040                        }));
11041                    }
11042                } else if let Some((full_comment_prefix, comment_suffix)) =
11043                    language.block_comment_delimiters()
11044                {
11045                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
11046                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
11047                    let prefix_range = comment_prefix_range(
11048                        snapshot.deref(),
11049                        start_row,
11050                        comment_prefix,
11051                        comment_prefix_whitespace,
11052                        ignore_indent,
11053                    );
11054                    let suffix_range = comment_suffix_range(
11055                        snapshot.deref(),
11056                        end_row,
11057                        comment_suffix.trim_start_matches(' '),
11058                        comment_suffix.starts_with(' '),
11059                    );
11060
11061                    if prefix_range.is_empty() || suffix_range.is_empty() {
11062                        edits.push((
11063                            prefix_range.start..prefix_range.start,
11064                            full_comment_prefix.clone(),
11065                        ));
11066                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
11067                        suffixes_inserted.push((end_row, comment_suffix.len()));
11068                    } else {
11069                        edits.push((prefix_range, empty_str.clone()));
11070                        edits.push((suffix_range, empty_str.clone()));
11071                    }
11072                } else {
11073                    continue;
11074                }
11075            }
11076
11077            drop(snapshot);
11078            this.buffer.update(cx, |buffer, cx| {
11079                buffer.edit(edits, None, cx);
11080            });
11081
11082            // Adjust selections so that they end before any comment suffixes that
11083            // were inserted.
11084            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
11085            let mut selections = this.selections.all::<Point>(cx);
11086            let snapshot = this.buffer.read(cx).read(cx);
11087            for selection in &mut selections {
11088                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
11089                    match row.cmp(&MultiBufferRow(selection.end.row)) {
11090                        Ordering::Less => {
11091                            suffixes_inserted.next();
11092                            continue;
11093                        }
11094                        Ordering::Greater => break,
11095                        Ordering::Equal => {
11096                            if selection.end.column == snapshot.line_len(row) {
11097                                if selection.is_empty() {
11098                                    selection.start.column -= suffix_len as u32;
11099                                }
11100                                selection.end.column -= suffix_len as u32;
11101                            }
11102                            break;
11103                        }
11104                    }
11105                }
11106            }
11107
11108            drop(snapshot);
11109            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11110                s.select(selections)
11111            });
11112
11113            let selections = this.selections.all::<Point>(cx);
11114            let selections_on_single_row = selections.windows(2).all(|selections| {
11115                selections[0].start.row == selections[1].start.row
11116                    && selections[0].end.row == selections[1].end.row
11117                    && selections[0].start.row == selections[0].end.row
11118            });
11119            let selections_selecting = selections
11120                .iter()
11121                .any(|selection| selection.start != selection.end);
11122            let advance_downwards = action.advance_downwards
11123                && selections_on_single_row
11124                && !selections_selecting
11125                && !matches!(this.mode, EditorMode::SingleLine { .. });
11126
11127            if advance_downwards {
11128                let snapshot = this.buffer.read(cx).snapshot(cx);
11129
11130                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11131                    s.move_cursors_with(|display_snapshot, display_point, _| {
11132                        let mut point = display_point.to_point(display_snapshot);
11133                        point.row += 1;
11134                        point = snapshot.clip_point(point, Bias::Left);
11135                        let display_point = point.to_display_point(display_snapshot);
11136                        let goal = SelectionGoal::HorizontalPosition(
11137                            display_snapshot
11138                                .x_for_display_point(display_point, text_layout_details)
11139                                .into(),
11140                        );
11141                        (display_point, goal)
11142                    })
11143                });
11144            }
11145        });
11146    }
11147
11148    pub fn select_enclosing_symbol(
11149        &mut self,
11150        _: &SelectEnclosingSymbol,
11151        window: &mut Window,
11152        cx: &mut Context<Self>,
11153    ) {
11154        let buffer = self.buffer.read(cx).snapshot(cx);
11155        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11156
11157        fn update_selection(
11158            selection: &Selection<usize>,
11159            buffer_snap: &MultiBufferSnapshot,
11160        ) -> Option<Selection<usize>> {
11161            let cursor = selection.head();
11162            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
11163            for symbol in symbols.iter().rev() {
11164                let start = symbol.range.start.to_offset(buffer_snap);
11165                let end = symbol.range.end.to_offset(buffer_snap);
11166                let new_range = start..end;
11167                if start < selection.start || end > selection.end {
11168                    return Some(Selection {
11169                        id: selection.id,
11170                        start: new_range.start,
11171                        end: new_range.end,
11172                        goal: SelectionGoal::None,
11173                        reversed: selection.reversed,
11174                    });
11175                }
11176            }
11177            None
11178        }
11179
11180        let mut selected_larger_symbol = false;
11181        let new_selections = old_selections
11182            .iter()
11183            .map(|selection| match update_selection(selection, &buffer) {
11184                Some(new_selection) => {
11185                    if new_selection.range() != selection.range() {
11186                        selected_larger_symbol = true;
11187                    }
11188                    new_selection
11189                }
11190                None => selection.clone(),
11191            })
11192            .collect::<Vec<_>>();
11193
11194        if selected_larger_symbol {
11195            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11196                s.select(new_selections);
11197            });
11198        }
11199    }
11200
11201    pub fn select_larger_syntax_node(
11202        &mut self,
11203        _: &SelectLargerSyntaxNode,
11204        window: &mut Window,
11205        cx: &mut Context<Self>,
11206    ) {
11207        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11208        let buffer = self.buffer.read(cx).snapshot(cx);
11209        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11210
11211        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11212        let mut selected_larger_node = false;
11213        let new_selections = old_selections
11214            .iter()
11215            .map(|selection| {
11216                let old_range = selection.start..selection.end;
11217                let mut new_range = old_range.clone();
11218                let mut new_node = None;
11219                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
11220                {
11221                    new_node = Some(node);
11222                    new_range = match containing_range {
11223                        MultiOrSingleBufferOffsetRange::Single(_) => break,
11224                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
11225                    };
11226                    if !display_map.intersects_fold(new_range.start)
11227                        && !display_map.intersects_fold(new_range.end)
11228                    {
11229                        break;
11230                    }
11231                }
11232
11233                if let Some(node) = new_node {
11234                    // Log the ancestor, to support using this action as a way to explore TreeSitter
11235                    // nodes. Parent and grandparent are also logged because this operation will not
11236                    // visit nodes that have the same range as their parent.
11237                    log::info!("Node: {node:?}");
11238                    let parent = node.parent();
11239                    log::info!("Parent: {parent:?}");
11240                    let grandparent = parent.and_then(|x| x.parent());
11241                    log::info!("Grandparent: {grandparent:?}");
11242                }
11243
11244                selected_larger_node |= new_range != old_range;
11245                Selection {
11246                    id: selection.id,
11247                    start: new_range.start,
11248                    end: new_range.end,
11249                    goal: SelectionGoal::None,
11250                    reversed: selection.reversed,
11251                }
11252            })
11253            .collect::<Vec<_>>();
11254
11255        if selected_larger_node {
11256            stack.push(old_selections);
11257            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11258                s.select(new_selections);
11259            });
11260        }
11261        self.select_larger_syntax_node_stack = stack;
11262    }
11263
11264    pub fn select_smaller_syntax_node(
11265        &mut self,
11266        _: &SelectSmallerSyntaxNode,
11267        window: &mut Window,
11268        cx: &mut Context<Self>,
11269    ) {
11270        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11271        if let Some(selections) = stack.pop() {
11272            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11273                s.select(selections.to_vec());
11274            });
11275        }
11276        self.select_larger_syntax_node_stack = stack;
11277    }
11278
11279    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
11280        if !EditorSettings::get_global(cx).gutter.runnables {
11281            self.clear_tasks();
11282            return Task::ready(());
11283        }
11284        let project = self.project.as_ref().map(Entity::downgrade);
11285        cx.spawn_in(window, |this, mut cx| async move {
11286            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
11287            let Some(project) = project.and_then(|p| p.upgrade()) else {
11288                return;
11289            };
11290            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
11291                this.display_map.update(cx, |map, cx| map.snapshot(cx))
11292            }) else {
11293                return;
11294            };
11295
11296            let hide_runnables = project
11297                .update(&mut cx, |project, cx| {
11298                    // Do not display any test indicators in non-dev server remote projects.
11299                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
11300                })
11301                .unwrap_or(true);
11302            if hide_runnables {
11303                return;
11304            }
11305            let new_rows =
11306                cx.background_spawn({
11307                    let snapshot = display_snapshot.clone();
11308                    async move {
11309                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
11310                    }
11311                })
11312                    .await;
11313
11314            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
11315            this.update(&mut cx, |this, _| {
11316                this.clear_tasks();
11317                for (key, value) in rows {
11318                    this.insert_tasks(key, value);
11319                }
11320            })
11321            .ok();
11322        })
11323    }
11324    fn fetch_runnable_ranges(
11325        snapshot: &DisplaySnapshot,
11326        range: Range<Anchor>,
11327    ) -> Vec<language::RunnableRange> {
11328        snapshot.buffer_snapshot.runnable_ranges(range).collect()
11329    }
11330
11331    fn runnable_rows(
11332        project: Entity<Project>,
11333        snapshot: DisplaySnapshot,
11334        runnable_ranges: Vec<RunnableRange>,
11335        mut cx: AsyncWindowContext,
11336    ) -> Vec<((BufferId, u32), RunnableTasks)> {
11337        runnable_ranges
11338            .into_iter()
11339            .filter_map(|mut runnable| {
11340                let tasks = cx
11341                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11342                    .ok()?;
11343                if tasks.is_empty() {
11344                    return None;
11345                }
11346
11347                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11348
11349                let row = snapshot
11350                    .buffer_snapshot
11351                    .buffer_line_for_row(MultiBufferRow(point.row))?
11352                    .1
11353                    .start
11354                    .row;
11355
11356                let context_range =
11357                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11358                Some((
11359                    (runnable.buffer_id, row),
11360                    RunnableTasks {
11361                        templates: tasks,
11362                        offset: snapshot
11363                            .buffer_snapshot
11364                            .anchor_before(runnable.run_range.start),
11365                        context_range,
11366                        column: point.column,
11367                        extra_variables: runnable.extra_captures,
11368                    },
11369                ))
11370            })
11371            .collect()
11372    }
11373
11374    fn templates_with_tags(
11375        project: &Entity<Project>,
11376        runnable: &mut Runnable,
11377        cx: &mut App,
11378    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11379        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11380            let (worktree_id, file) = project
11381                .buffer_for_id(runnable.buffer, cx)
11382                .and_then(|buffer| buffer.read(cx).file())
11383                .map(|file| (file.worktree_id(cx), file.clone()))
11384                .unzip();
11385
11386            (
11387                project.task_store().read(cx).task_inventory().cloned(),
11388                worktree_id,
11389                file,
11390            )
11391        });
11392
11393        let tags = mem::take(&mut runnable.tags);
11394        let mut tags: Vec<_> = tags
11395            .into_iter()
11396            .flat_map(|tag| {
11397                let tag = tag.0.clone();
11398                inventory
11399                    .as_ref()
11400                    .into_iter()
11401                    .flat_map(|inventory| {
11402                        inventory.read(cx).list_tasks(
11403                            file.clone(),
11404                            Some(runnable.language.clone()),
11405                            worktree_id,
11406                            cx,
11407                        )
11408                    })
11409                    .filter(move |(_, template)| {
11410                        template.tags.iter().any(|source_tag| source_tag == &tag)
11411                    })
11412            })
11413            .sorted_by_key(|(kind, _)| kind.to_owned())
11414            .collect();
11415        if let Some((leading_tag_source, _)) = tags.first() {
11416            // Strongest source wins; if we have worktree tag binding, prefer that to
11417            // global and language bindings;
11418            // if we have a global binding, prefer that to language binding.
11419            let first_mismatch = tags
11420                .iter()
11421                .position(|(tag_source, _)| tag_source != leading_tag_source);
11422            if let Some(index) = first_mismatch {
11423                tags.truncate(index);
11424            }
11425        }
11426
11427        tags
11428    }
11429
11430    pub fn move_to_enclosing_bracket(
11431        &mut self,
11432        _: &MoveToEnclosingBracket,
11433        window: &mut Window,
11434        cx: &mut Context<Self>,
11435    ) {
11436        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11437            s.move_offsets_with(|snapshot, selection| {
11438                let Some(enclosing_bracket_ranges) =
11439                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11440                else {
11441                    return;
11442                };
11443
11444                let mut best_length = usize::MAX;
11445                let mut best_inside = false;
11446                let mut best_in_bracket_range = false;
11447                let mut best_destination = None;
11448                for (open, close) in enclosing_bracket_ranges {
11449                    let close = close.to_inclusive();
11450                    let length = close.end() - open.start;
11451                    let inside = selection.start >= open.end && selection.end <= *close.start();
11452                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
11453                        || close.contains(&selection.head());
11454
11455                    // If best is next to a bracket and current isn't, skip
11456                    if !in_bracket_range && best_in_bracket_range {
11457                        continue;
11458                    }
11459
11460                    // Prefer smaller lengths unless best is inside and current isn't
11461                    if length > best_length && (best_inside || !inside) {
11462                        continue;
11463                    }
11464
11465                    best_length = length;
11466                    best_inside = inside;
11467                    best_in_bracket_range = in_bracket_range;
11468                    best_destination = Some(
11469                        if close.contains(&selection.start) && close.contains(&selection.end) {
11470                            if inside {
11471                                open.end
11472                            } else {
11473                                open.start
11474                            }
11475                        } else if inside {
11476                            *close.start()
11477                        } else {
11478                            *close.end()
11479                        },
11480                    );
11481                }
11482
11483                if let Some(destination) = best_destination {
11484                    selection.collapse_to(destination, SelectionGoal::None);
11485                }
11486            })
11487        });
11488    }
11489
11490    pub fn undo_selection(
11491        &mut self,
11492        _: &UndoSelection,
11493        window: &mut Window,
11494        cx: &mut Context<Self>,
11495    ) {
11496        self.end_selection(window, cx);
11497        self.selection_history.mode = SelectionHistoryMode::Undoing;
11498        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11499            self.change_selections(None, window, cx, |s| {
11500                s.select_anchors(entry.selections.to_vec())
11501            });
11502            self.select_next_state = entry.select_next_state;
11503            self.select_prev_state = entry.select_prev_state;
11504            self.add_selections_state = entry.add_selections_state;
11505            self.request_autoscroll(Autoscroll::newest(), cx);
11506        }
11507        self.selection_history.mode = SelectionHistoryMode::Normal;
11508    }
11509
11510    pub fn redo_selection(
11511        &mut self,
11512        _: &RedoSelection,
11513        window: &mut Window,
11514        cx: &mut Context<Self>,
11515    ) {
11516        self.end_selection(window, cx);
11517        self.selection_history.mode = SelectionHistoryMode::Redoing;
11518        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11519            self.change_selections(None, window, cx, |s| {
11520                s.select_anchors(entry.selections.to_vec())
11521            });
11522            self.select_next_state = entry.select_next_state;
11523            self.select_prev_state = entry.select_prev_state;
11524            self.add_selections_state = entry.add_selections_state;
11525            self.request_autoscroll(Autoscroll::newest(), cx);
11526        }
11527        self.selection_history.mode = SelectionHistoryMode::Normal;
11528    }
11529
11530    pub fn expand_excerpts(
11531        &mut self,
11532        action: &ExpandExcerpts,
11533        _: &mut Window,
11534        cx: &mut Context<Self>,
11535    ) {
11536        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11537    }
11538
11539    pub fn expand_excerpts_down(
11540        &mut self,
11541        action: &ExpandExcerptsDown,
11542        _: &mut Window,
11543        cx: &mut Context<Self>,
11544    ) {
11545        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11546    }
11547
11548    pub fn expand_excerpts_up(
11549        &mut self,
11550        action: &ExpandExcerptsUp,
11551        _: &mut Window,
11552        cx: &mut Context<Self>,
11553    ) {
11554        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11555    }
11556
11557    pub fn expand_excerpts_for_direction(
11558        &mut self,
11559        lines: u32,
11560        direction: ExpandExcerptDirection,
11561
11562        cx: &mut Context<Self>,
11563    ) {
11564        let selections = self.selections.disjoint_anchors();
11565
11566        let lines = if lines == 0 {
11567            EditorSettings::get_global(cx).expand_excerpt_lines
11568        } else {
11569            lines
11570        };
11571
11572        self.buffer.update(cx, |buffer, cx| {
11573            let snapshot = buffer.snapshot(cx);
11574            let mut excerpt_ids = selections
11575                .iter()
11576                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11577                .collect::<Vec<_>>();
11578            excerpt_ids.sort();
11579            excerpt_ids.dedup();
11580            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11581        })
11582    }
11583
11584    pub fn expand_excerpt(
11585        &mut self,
11586        excerpt: ExcerptId,
11587        direction: ExpandExcerptDirection,
11588        cx: &mut Context<Self>,
11589    ) {
11590        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11591        self.buffer.update(cx, |buffer, cx| {
11592            buffer.expand_excerpts([excerpt], lines, direction, cx)
11593        })
11594    }
11595
11596    pub fn go_to_singleton_buffer_point(
11597        &mut self,
11598        point: Point,
11599        window: &mut Window,
11600        cx: &mut Context<Self>,
11601    ) {
11602        self.go_to_singleton_buffer_range(point..point, window, cx);
11603    }
11604
11605    pub fn go_to_singleton_buffer_range(
11606        &mut self,
11607        range: Range<Point>,
11608        window: &mut Window,
11609        cx: &mut Context<Self>,
11610    ) {
11611        let multibuffer = self.buffer().read(cx);
11612        let Some(buffer) = multibuffer.as_singleton() else {
11613            return;
11614        };
11615        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11616            return;
11617        };
11618        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11619            return;
11620        };
11621        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11622            s.select_anchor_ranges([start..end])
11623        });
11624    }
11625
11626    fn go_to_diagnostic(
11627        &mut self,
11628        _: &GoToDiagnostic,
11629        window: &mut Window,
11630        cx: &mut Context<Self>,
11631    ) {
11632        self.go_to_diagnostic_impl(Direction::Next, window, cx)
11633    }
11634
11635    fn go_to_prev_diagnostic(
11636        &mut self,
11637        _: &GoToPreviousDiagnostic,
11638        window: &mut Window,
11639        cx: &mut Context<Self>,
11640    ) {
11641        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11642    }
11643
11644    pub fn go_to_diagnostic_impl(
11645        &mut self,
11646        direction: Direction,
11647        window: &mut Window,
11648        cx: &mut Context<Self>,
11649    ) {
11650        let buffer = self.buffer.read(cx).snapshot(cx);
11651        let selection = self.selections.newest::<usize>(cx);
11652
11653        // If there is an active Diagnostic Popover jump to its diagnostic instead.
11654        if direction == Direction::Next {
11655            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11656                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11657                    return;
11658                };
11659                self.activate_diagnostics(
11660                    buffer_id,
11661                    popover.local_diagnostic.diagnostic.group_id,
11662                    window,
11663                    cx,
11664                );
11665                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11666                    let primary_range_start = active_diagnostics.primary_range.start;
11667                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11668                        let mut new_selection = s.newest_anchor().clone();
11669                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11670                        s.select_anchors(vec![new_selection.clone()]);
11671                    });
11672                    self.refresh_inline_completion(false, true, window, cx);
11673                }
11674                return;
11675            }
11676        }
11677
11678        let active_group_id = self
11679            .active_diagnostics
11680            .as_ref()
11681            .map(|active_group| active_group.group_id);
11682        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11683            active_diagnostics
11684                .primary_range
11685                .to_offset(&buffer)
11686                .to_inclusive()
11687        });
11688        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11689            if active_primary_range.contains(&selection.head()) {
11690                *active_primary_range.start()
11691            } else {
11692                selection.head()
11693            }
11694        } else {
11695            selection.head()
11696        };
11697
11698        let snapshot = self.snapshot(window, cx);
11699        let primary_diagnostics_before = buffer
11700            .diagnostics_in_range::<usize>(0..search_start)
11701            .filter(|entry| entry.diagnostic.is_primary)
11702            .filter(|entry| entry.range.start != entry.range.end)
11703            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11704            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11705            .collect::<Vec<_>>();
11706        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11707            primary_diagnostics_before
11708                .iter()
11709                .position(|entry| entry.diagnostic.group_id == active_group_id)
11710        });
11711
11712        let primary_diagnostics_after = buffer
11713            .diagnostics_in_range::<usize>(search_start..buffer.len())
11714            .filter(|entry| entry.diagnostic.is_primary)
11715            .filter(|entry| entry.range.start != entry.range.end)
11716            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11717            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11718            .collect::<Vec<_>>();
11719        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11720            primary_diagnostics_after
11721                .iter()
11722                .enumerate()
11723                .rev()
11724                .find_map(|(i, entry)| {
11725                    if entry.diagnostic.group_id == active_group_id {
11726                        Some(i)
11727                    } else {
11728                        None
11729                    }
11730                })
11731        });
11732
11733        let next_primary_diagnostic = match direction {
11734            Direction::Prev => primary_diagnostics_before
11735                .iter()
11736                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11737                .rev()
11738                .next(),
11739            Direction::Next => primary_diagnostics_after
11740                .iter()
11741                .skip(
11742                    last_same_group_diagnostic_after
11743                        .map(|index| index + 1)
11744                        .unwrap_or(0),
11745                )
11746                .next(),
11747        };
11748
11749        // Cycle around to the start of the buffer, potentially moving back to the start of
11750        // the currently active diagnostic.
11751        let cycle_around = || match direction {
11752            Direction::Prev => primary_diagnostics_after
11753                .iter()
11754                .rev()
11755                .chain(primary_diagnostics_before.iter().rev())
11756                .next(),
11757            Direction::Next => primary_diagnostics_before
11758                .iter()
11759                .chain(primary_diagnostics_after.iter())
11760                .next(),
11761        };
11762
11763        if let Some((primary_range, group_id)) = next_primary_diagnostic
11764            .or_else(cycle_around)
11765            .map(|entry| (&entry.range, entry.diagnostic.group_id))
11766        {
11767            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11768                return;
11769            };
11770            self.activate_diagnostics(buffer_id, group_id, window, cx);
11771            if self.active_diagnostics.is_some() {
11772                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11773                    s.select(vec![Selection {
11774                        id: selection.id,
11775                        start: primary_range.start,
11776                        end: primary_range.start,
11777                        reversed: false,
11778                        goal: SelectionGoal::None,
11779                    }]);
11780                });
11781                self.refresh_inline_completion(false, true, window, cx);
11782            }
11783        }
11784    }
11785
11786    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11787        let snapshot = self.snapshot(window, cx);
11788        let selection = self.selections.newest::<Point>(cx);
11789        self.go_to_hunk_before_or_after_position(
11790            &snapshot,
11791            selection.head(),
11792            Direction::Next,
11793            window,
11794            cx,
11795        );
11796    }
11797
11798    fn go_to_hunk_before_or_after_position(
11799        &mut self,
11800        snapshot: &EditorSnapshot,
11801        position: Point,
11802        direction: Direction,
11803        window: &mut Window,
11804        cx: &mut Context<Editor>,
11805    ) {
11806        let row = if direction == Direction::Next {
11807            self.hunk_after_position(snapshot, position)
11808                .map(|hunk| hunk.row_range.start)
11809        } else {
11810            self.hunk_before_position(snapshot, position)
11811        };
11812
11813        if let Some(row) = row {
11814            let destination = Point::new(row.0, 0);
11815            let autoscroll = Autoscroll::center();
11816
11817            self.unfold_ranges(&[destination..destination], false, false, cx);
11818            self.change_selections(Some(autoscroll), window, cx, |s| {
11819                s.select_ranges([destination..destination]);
11820            });
11821        }
11822    }
11823
11824    fn hunk_after_position(
11825        &mut self,
11826        snapshot: &EditorSnapshot,
11827        position: Point,
11828    ) -> Option<MultiBufferDiffHunk> {
11829        snapshot
11830            .buffer_snapshot
11831            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11832            .find(|hunk| hunk.row_range.start.0 > position.row)
11833            .or_else(|| {
11834                snapshot
11835                    .buffer_snapshot
11836                    .diff_hunks_in_range(Point::zero()..position)
11837                    .find(|hunk| hunk.row_range.end.0 < position.row)
11838            })
11839    }
11840
11841    fn go_to_prev_hunk(
11842        &mut self,
11843        _: &GoToPreviousHunk,
11844        window: &mut Window,
11845        cx: &mut Context<Self>,
11846    ) {
11847        let snapshot = self.snapshot(window, cx);
11848        let selection = self.selections.newest::<Point>(cx);
11849        self.go_to_hunk_before_or_after_position(
11850            &snapshot,
11851            selection.head(),
11852            Direction::Prev,
11853            window,
11854            cx,
11855        );
11856    }
11857
11858    fn hunk_before_position(
11859        &mut self,
11860        snapshot: &EditorSnapshot,
11861        position: Point,
11862    ) -> Option<MultiBufferRow> {
11863        snapshot
11864            .buffer_snapshot
11865            .diff_hunk_before(position)
11866            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11867    }
11868
11869    pub fn go_to_definition(
11870        &mut self,
11871        _: &GoToDefinition,
11872        window: &mut Window,
11873        cx: &mut Context<Self>,
11874    ) -> Task<Result<Navigated>> {
11875        let definition =
11876            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11877        cx.spawn_in(window, |editor, mut cx| async move {
11878            if definition.await? == Navigated::Yes {
11879                return Ok(Navigated::Yes);
11880            }
11881            match editor.update_in(&mut cx, |editor, window, cx| {
11882                editor.find_all_references(&FindAllReferences, window, cx)
11883            })? {
11884                Some(references) => references.await,
11885                None => Ok(Navigated::No),
11886            }
11887        })
11888    }
11889
11890    pub fn go_to_declaration(
11891        &mut self,
11892        _: &GoToDeclaration,
11893        window: &mut Window,
11894        cx: &mut Context<Self>,
11895    ) -> Task<Result<Navigated>> {
11896        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11897    }
11898
11899    pub fn go_to_declaration_split(
11900        &mut self,
11901        _: &GoToDeclaration,
11902        window: &mut Window,
11903        cx: &mut Context<Self>,
11904    ) -> Task<Result<Navigated>> {
11905        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11906    }
11907
11908    pub fn go_to_implementation(
11909        &mut self,
11910        _: &GoToImplementation,
11911        window: &mut Window,
11912        cx: &mut Context<Self>,
11913    ) -> Task<Result<Navigated>> {
11914        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11915    }
11916
11917    pub fn go_to_implementation_split(
11918        &mut self,
11919        _: &GoToImplementationSplit,
11920        window: &mut Window,
11921        cx: &mut Context<Self>,
11922    ) -> Task<Result<Navigated>> {
11923        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11924    }
11925
11926    pub fn go_to_type_definition(
11927        &mut self,
11928        _: &GoToTypeDefinition,
11929        window: &mut Window,
11930        cx: &mut Context<Self>,
11931    ) -> Task<Result<Navigated>> {
11932        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11933    }
11934
11935    pub fn go_to_definition_split(
11936        &mut self,
11937        _: &GoToDefinitionSplit,
11938        window: &mut Window,
11939        cx: &mut Context<Self>,
11940    ) -> Task<Result<Navigated>> {
11941        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11942    }
11943
11944    pub fn go_to_type_definition_split(
11945        &mut self,
11946        _: &GoToTypeDefinitionSplit,
11947        window: &mut Window,
11948        cx: &mut Context<Self>,
11949    ) -> Task<Result<Navigated>> {
11950        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11951    }
11952
11953    fn go_to_definition_of_kind(
11954        &mut self,
11955        kind: GotoDefinitionKind,
11956        split: bool,
11957        window: &mut Window,
11958        cx: &mut Context<Self>,
11959    ) -> Task<Result<Navigated>> {
11960        let Some(provider) = self.semantics_provider.clone() else {
11961            return Task::ready(Ok(Navigated::No));
11962        };
11963        let head = self.selections.newest::<usize>(cx).head();
11964        let buffer = self.buffer.read(cx);
11965        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11966            text_anchor
11967        } else {
11968            return Task::ready(Ok(Navigated::No));
11969        };
11970
11971        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11972            return Task::ready(Ok(Navigated::No));
11973        };
11974
11975        cx.spawn_in(window, |editor, mut cx| async move {
11976            let definitions = definitions.await?;
11977            let navigated = editor
11978                .update_in(&mut cx, |editor, window, cx| {
11979                    editor.navigate_to_hover_links(
11980                        Some(kind),
11981                        definitions
11982                            .into_iter()
11983                            .filter(|location| {
11984                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11985                            })
11986                            .map(HoverLink::Text)
11987                            .collect::<Vec<_>>(),
11988                        split,
11989                        window,
11990                        cx,
11991                    )
11992                })?
11993                .await?;
11994            anyhow::Ok(navigated)
11995        })
11996    }
11997
11998    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11999        let selection = self.selections.newest_anchor();
12000        let head = selection.head();
12001        let tail = selection.tail();
12002
12003        let Some((buffer, start_position)) =
12004            self.buffer.read(cx).text_anchor_for_position(head, cx)
12005        else {
12006            return;
12007        };
12008
12009        let end_position = if head != tail {
12010            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
12011                return;
12012            };
12013            Some(pos)
12014        } else {
12015            None
12016        };
12017
12018        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
12019            let url = if let Some(end_pos) = end_position {
12020                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
12021            } else {
12022                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
12023            };
12024
12025            if let Some(url) = url {
12026                editor.update(&mut cx, |_, cx| {
12027                    cx.open_url(&url);
12028                })
12029            } else {
12030                Ok(())
12031            }
12032        });
12033
12034        url_finder.detach();
12035    }
12036
12037    pub fn open_selected_filename(
12038        &mut self,
12039        _: &OpenSelectedFilename,
12040        window: &mut Window,
12041        cx: &mut Context<Self>,
12042    ) {
12043        let Some(workspace) = self.workspace() else {
12044            return;
12045        };
12046
12047        let position = self.selections.newest_anchor().head();
12048
12049        let Some((buffer, buffer_position)) =
12050            self.buffer.read(cx).text_anchor_for_position(position, cx)
12051        else {
12052            return;
12053        };
12054
12055        let project = self.project.clone();
12056
12057        cx.spawn_in(window, |_, mut cx| async move {
12058            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
12059
12060            if let Some((_, path)) = result {
12061                workspace
12062                    .update_in(&mut cx, |workspace, window, cx| {
12063                        workspace.open_resolved_path(path, window, cx)
12064                    })?
12065                    .await?;
12066            }
12067            anyhow::Ok(())
12068        })
12069        .detach();
12070    }
12071
12072    pub(crate) fn navigate_to_hover_links(
12073        &mut self,
12074        kind: Option<GotoDefinitionKind>,
12075        mut definitions: Vec<HoverLink>,
12076        split: bool,
12077        window: &mut Window,
12078        cx: &mut Context<Editor>,
12079    ) -> Task<Result<Navigated>> {
12080        // If there is one definition, just open it directly
12081        if definitions.len() == 1 {
12082            let definition = definitions.pop().unwrap();
12083
12084            enum TargetTaskResult {
12085                Location(Option<Location>),
12086                AlreadyNavigated,
12087            }
12088
12089            let target_task = match definition {
12090                HoverLink::Text(link) => {
12091                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
12092                }
12093                HoverLink::InlayHint(lsp_location, server_id) => {
12094                    let computation =
12095                        self.compute_target_location(lsp_location, server_id, window, cx);
12096                    cx.background_spawn(async move {
12097                        let location = computation.await?;
12098                        Ok(TargetTaskResult::Location(location))
12099                    })
12100                }
12101                HoverLink::Url(url) => {
12102                    cx.open_url(&url);
12103                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
12104                }
12105                HoverLink::File(path) => {
12106                    if let Some(workspace) = self.workspace() {
12107                        cx.spawn_in(window, |_, mut cx| async move {
12108                            workspace
12109                                .update_in(&mut cx, |workspace, window, cx| {
12110                                    workspace.open_resolved_path(path, window, cx)
12111                                })?
12112                                .await
12113                                .map(|_| TargetTaskResult::AlreadyNavigated)
12114                        })
12115                    } else {
12116                        Task::ready(Ok(TargetTaskResult::Location(None)))
12117                    }
12118                }
12119            };
12120            cx.spawn_in(window, |editor, mut cx| async move {
12121                let target = match target_task.await.context("target resolution task")? {
12122                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
12123                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
12124                    TargetTaskResult::Location(Some(target)) => target,
12125                };
12126
12127                editor.update_in(&mut cx, |editor, window, cx| {
12128                    let Some(workspace) = editor.workspace() else {
12129                        return Navigated::No;
12130                    };
12131                    let pane = workspace.read(cx).active_pane().clone();
12132
12133                    let range = target.range.to_point(target.buffer.read(cx));
12134                    let range = editor.range_for_match(&range);
12135                    let range = collapse_multiline_range(range);
12136
12137                    if !split
12138                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
12139                    {
12140                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
12141                    } else {
12142                        window.defer(cx, move |window, cx| {
12143                            let target_editor: Entity<Self> =
12144                                workspace.update(cx, |workspace, cx| {
12145                                    let pane = if split {
12146                                        workspace.adjacent_pane(window, cx)
12147                                    } else {
12148                                        workspace.active_pane().clone()
12149                                    };
12150
12151                                    workspace.open_project_item(
12152                                        pane,
12153                                        target.buffer.clone(),
12154                                        true,
12155                                        true,
12156                                        window,
12157                                        cx,
12158                                    )
12159                                });
12160                            target_editor.update(cx, |target_editor, cx| {
12161                                // When selecting a definition in a different buffer, disable the nav history
12162                                // to avoid creating a history entry at the previous cursor location.
12163                                pane.update(cx, |pane, _| pane.disable_history());
12164                                target_editor.go_to_singleton_buffer_range(range, window, cx);
12165                                pane.update(cx, |pane, _| pane.enable_history());
12166                            });
12167                        });
12168                    }
12169                    Navigated::Yes
12170                })
12171            })
12172        } else if !definitions.is_empty() {
12173            cx.spawn_in(window, |editor, mut cx| async move {
12174                let (title, location_tasks, workspace) = editor
12175                    .update_in(&mut cx, |editor, window, cx| {
12176                        let tab_kind = match kind {
12177                            Some(GotoDefinitionKind::Implementation) => "Implementations",
12178                            _ => "Definitions",
12179                        };
12180                        let title = definitions
12181                            .iter()
12182                            .find_map(|definition| match definition {
12183                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
12184                                    let buffer = origin.buffer.read(cx);
12185                                    format!(
12186                                        "{} for {}",
12187                                        tab_kind,
12188                                        buffer
12189                                            .text_for_range(origin.range.clone())
12190                                            .collect::<String>()
12191                                    )
12192                                }),
12193                                HoverLink::InlayHint(_, _) => None,
12194                                HoverLink::Url(_) => None,
12195                                HoverLink::File(_) => None,
12196                            })
12197                            .unwrap_or(tab_kind.to_string());
12198                        let location_tasks = definitions
12199                            .into_iter()
12200                            .map(|definition| match definition {
12201                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
12202                                HoverLink::InlayHint(lsp_location, server_id) => editor
12203                                    .compute_target_location(lsp_location, server_id, window, cx),
12204                                HoverLink::Url(_) => Task::ready(Ok(None)),
12205                                HoverLink::File(_) => Task::ready(Ok(None)),
12206                            })
12207                            .collect::<Vec<_>>();
12208                        (title, location_tasks, editor.workspace().clone())
12209                    })
12210                    .context("location tasks preparation")?;
12211
12212                let locations = future::join_all(location_tasks)
12213                    .await
12214                    .into_iter()
12215                    .filter_map(|location| location.transpose())
12216                    .collect::<Result<_>>()
12217                    .context("location tasks")?;
12218
12219                let Some(workspace) = workspace else {
12220                    return Ok(Navigated::No);
12221                };
12222                let opened = workspace
12223                    .update_in(&mut cx, |workspace, window, cx| {
12224                        Self::open_locations_in_multibuffer(
12225                            workspace,
12226                            locations,
12227                            title,
12228                            split,
12229                            MultibufferSelectionMode::First,
12230                            window,
12231                            cx,
12232                        )
12233                    })
12234                    .ok();
12235
12236                anyhow::Ok(Navigated::from_bool(opened.is_some()))
12237            })
12238        } else {
12239            Task::ready(Ok(Navigated::No))
12240        }
12241    }
12242
12243    fn compute_target_location(
12244        &self,
12245        lsp_location: lsp::Location,
12246        server_id: LanguageServerId,
12247        window: &mut Window,
12248        cx: &mut Context<Self>,
12249    ) -> Task<anyhow::Result<Option<Location>>> {
12250        let Some(project) = self.project.clone() else {
12251            return Task::ready(Ok(None));
12252        };
12253
12254        cx.spawn_in(window, move |editor, mut cx| async move {
12255            let location_task = editor.update(&mut cx, |_, cx| {
12256                project.update(cx, |project, cx| {
12257                    let language_server_name = project
12258                        .language_server_statuses(cx)
12259                        .find(|(id, _)| server_id == *id)
12260                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
12261                    language_server_name.map(|language_server_name| {
12262                        project.open_local_buffer_via_lsp(
12263                            lsp_location.uri.clone(),
12264                            server_id,
12265                            language_server_name,
12266                            cx,
12267                        )
12268                    })
12269                })
12270            })?;
12271            let location = match location_task {
12272                Some(task) => Some({
12273                    let target_buffer_handle = task.await.context("open local buffer")?;
12274                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
12275                        let target_start = target_buffer
12276                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
12277                        let target_end = target_buffer
12278                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
12279                        target_buffer.anchor_after(target_start)
12280                            ..target_buffer.anchor_before(target_end)
12281                    })?;
12282                    Location {
12283                        buffer: target_buffer_handle,
12284                        range,
12285                    }
12286                }),
12287                None => None,
12288            };
12289            Ok(location)
12290        })
12291    }
12292
12293    pub fn find_all_references(
12294        &mut self,
12295        _: &FindAllReferences,
12296        window: &mut Window,
12297        cx: &mut Context<Self>,
12298    ) -> Option<Task<Result<Navigated>>> {
12299        let selection = self.selections.newest::<usize>(cx);
12300        let multi_buffer = self.buffer.read(cx);
12301        let head = selection.head();
12302
12303        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12304        let head_anchor = multi_buffer_snapshot.anchor_at(
12305            head,
12306            if head < selection.tail() {
12307                Bias::Right
12308            } else {
12309                Bias::Left
12310            },
12311        );
12312
12313        match self
12314            .find_all_references_task_sources
12315            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12316        {
12317            Ok(_) => {
12318                log::info!(
12319                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
12320                );
12321                return None;
12322            }
12323            Err(i) => {
12324                self.find_all_references_task_sources.insert(i, head_anchor);
12325            }
12326        }
12327
12328        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12329        let workspace = self.workspace()?;
12330        let project = workspace.read(cx).project().clone();
12331        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12332        Some(cx.spawn_in(window, |editor, mut cx| async move {
12333            let _cleanup = defer({
12334                let mut cx = cx.clone();
12335                move || {
12336                    let _ = editor.update(&mut cx, |editor, _| {
12337                        if let Ok(i) =
12338                            editor
12339                                .find_all_references_task_sources
12340                                .binary_search_by(|anchor| {
12341                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
12342                                })
12343                        {
12344                            editor.find_all_references_task_sources.remove(i);
12345                        }
12346                    });
12347                }
12348            });
12349
12350            let locations = references.await?;
12351            if locations.is_empty() {
12352                return anyhow::Ok(Navigated::No);
12353            }
12354
12355            workspace.update_in(&mut cx, |workspace, window, cx| {
12356                let title = locations
12357                    .first()
12358                    .as_ref()
12359                    .map(|location| {
12360                        let buffer = location.buffer.read(cx);
12361                        format!(
12362                            "References to `{}`",
12363                            buffer
12364                                .text_for_range(location.range.clone())
12365                                .collect::<String>()
12366                        )
12367                    })
12368                    .unwrap();
12369                Self::open_locations_in_multibuffer(
12370                    workspace,
12371                    locations,
12372                    title,
12373                    false,
12374                    MultibufferSelectionMode::First,
12375                    window,
12376                    cx,
12377                );
12378                Navigated::Yes
12379            })
12380        }))
12381    }
12382
12383    /// Opens a multibuffer with the given project locations in it
12384    pub fn open_locations_in_multibuffer(
12385        workspace: &mut Workspace,
12386        mut locations: Vec<Location>,
12387        title: String,
12388        split: bool,
12389        multibuffer_selection_mode: MultibufferSelectionMode,
12390        window: &mut Window,
12391        cx: &mut Context<Workspace>,
12392    ) {
12393        // If there are multiple definitions, open them in a multibuffer
12394        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12395        let mut locations = locations.into_iter().peekable();
12396        let mut ranges = Vec::new();
12397        let capability = workspace.project().read(cx).capability();
12398
12399        let excerpt_buffer = cx.new(|cx| {
12400            let mut multibuffer = MultiBuffer::new(capability);
12401            while let Some(location) = locations.next() {
12402                let buffer = location.buffer.read(cx);
12403                let mut ranges_for_buffer = Vec::new();
12404                let range = location.range.to_offset(buffer);
12405                ranges_for_buffer.push(range.clone());
12406
12407                while let Some(next_location) = locations.peek() {
12408                    if next_location.buffer == location.buffer {
12409                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
12410                        locations.next();
12411                    } else {
12412                        break;
12413                    }
12414                }
12415
12416                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12417                ranges.extend(multibuffer.push_excerpts_with_context_lines(
12418                    location.buffer.clone(),
12419                    ranges_for_buffer,
12420                    DEFAULT_MULTIBUFFER_CONTEXT,
12421                    cx,
12422                ))
12423            }
12424
12425            multibuffer.with_title(title)
12426        });
12427
12428        let editor = cx.new(|cx| {
12429            Editor::for_multibuffer(
12430                excerpt_buffer,
12431                Some(workspace.project().clone()),
12432                window,
12433                cx,
12434            )
12435        });
12436        editor.update(cx, |editor, cx| {
12437            match multibuffer_selection_mode {
12438                MultibufferSelectionMode::First => {
12439                    if let Some(first_range) = ranges.first() {
12440                        editor.change_selections(None, window, cx, |selections| {
12441                            selections.clear_disjoint();
12442                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12443                        });
12444                    }
12445                    editor.highlight_background::<Self>(
12446                        &ranges,
12447                        |theme| theme.editor_highlighted_line_background,
12448                        cx,
12449                    );
12450                }
12451                MultibufferSelectionMode::All => {
12452                    editor.change_selections(None, window, cx, |selections| {
12453                        selections.clear_disjoint();
12454                        selections.select_anchor_ranges(ranges);
12455                    });
12456                }
12457            }
12458            editor.register_buffers_with_language_servers(cx);
12459        });
12460
12461        let item = Box::new(editor);
12462        let item_id = item.item_id();
12463
12464        if split {
12465            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12466        } else {
12467            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12468                let (preview_item_id, preview_item_idx) =
12469                    workspace.active_pane().update(cx, |pane, _| {
12470                        (pane.preview_item_id(), pane.preview_item_idx())
12471                    });
12472
12473                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
12474
12475                if let Some(preview_item_id) = preview_item_id {
12476                    workspace.active_pane().update(cx, |pane, cx| {
12477                        pane.remove_item(preview_item_id, false, false, window, cx);
12478                    });
12479                }
12480            } else {
12481                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
12482            }
12483        }
12484        workspace.active_pane().update(cx, |pane, cx| {
12485            pane.set_preview_item_id(Some(item_id), cx);
12486        });
12487    }
12488
12489    pub fn rename(
12490        &mut self,
12491        _: &Rename,
12492        window: &mut Window,
12493        cx: &mut Context<Self>,
12494    ) -> Option<Task<Result<()>>> {
12495        use language::ToOffset as _;
12496
12497        let provider = self.semantics_provider.clone()?;
12498        let selection = self.selections.newest_anchor().clone();
12499        let (cursor_buffer, cursor_buffer_position) = self
12500            .buffer
12501            .read(cx)
12502            .text_anchor_for_position(selection.head(), cx)?;
12503        let (tail_buffer, cursor_buffer_position_end) = self
12504            .buffer
12505            .read(cx)
12506            .text_anchor_for_position(selection.tail(), cx)?;
12507        if tail_buffer != cursor_buffer {
12508            return None;
12509        }
12510
12511        let snapshot = cursor_buffer.read(cx).snapshot();
12512        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12513        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12514        let prepare_rename = provider
12515            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12516            .unwrap_or_else(|| Task::ready(Ok(None)));
12517        drop(snapshot);
12518
12519        Some(cx.spawn_in(window, |this, mut cx| async move {
12520            let rename_range = if let Some(range) = prepare_rename.await? {
12521                Some(range)
12522            } else {
12523                this.update(&mut cx, |this, cx| {
12524                    let buffer = this.buffer.read(cx).snapshot(cx);
12525                    let mut buffer_highlights = this
12526                        .document_highlights_for_position(selection.head(), &buffer)
12527                        .filter(|highlight| {
12528                            highlight.start.excerpt_id == selection.head().excerpt_id
12529                                && highlight.end.excerpt_id == selection.head().excerpt_id
12530                        });
12531                    buffer_highlights
12532                        .next()
12533                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12534                })?
12535            };
12536            if let Some(rename_range) = rename_range {
12537                this.update_in(&mut cx, |this, window, cx| {
12538                    let snapshot = cursor_buffer.read(cx).snapshot();
12539                    let rename_buffer_range = rename_range.to_offset(&snapshot);
12540                    let cursor_offset_in_rename_range =
12541                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12542                    let cursor_offset_in_rename_range_end =
12543                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12544
12545                    this.take_rename(false, window, cx);
12546                    let buffer = this.buffer.read(cx).read(cx);
12547                    let cursor_offset = selection.head().to_offset(&buffer);
12548                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12549                    let rename_end = rename_start + rename_buffer_range.len();
12550                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12551                    let mut old_highlight_id = None;
12552                    let old_name: Arc<str> = buffer
12553                        .chunks(rename_start..rename_end, true)
12554                        .map(|chunk| {
12555                            if old_highlight_id.is_none() {
12556                                old_highlight_id = chunk.syntax_highlight_id;
12557                            }
12558                            chunk.text
12559                        })
12560                        .collect::<String>()
12561                        .into();
12562
12563                    drop(buffer);
12564
12565                    // Position the selection in the rename editor so that it matches the current selection.
12566                    this.show_local_selections = false;
12567                    let rename_editor = cx.new(|cx| {
12568                        let mut editor = Editor::single_line(window, cx);
12569                        editor.buffer.update(cx, |buffer, cx| {
12570                            buffer.edit([(0..0, old_name.clone())], None, cx)
12571                        });
12572                        let rename_selection_range = match cursor_offset_in_rename_range
12573                            .cmp(&cursor_offset_in_rename_range_end)
12574                        {
12575                            Ordering::Equal => {
12576                                editor.select_all(&SelectAll, window, cx);
12577                                return editor;
12578                            }
12579                            Ordering::Less => {
12580                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12581                            }
12582                            Ordering::Greater => {
12583                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12584                            }
12585                        };
12586                        if rename_selection_range.end > old_name.len() {
12587                            editor.select_all(&SelectAll, window, cx);
12588                        } else {
12589                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12590                                s.select_ranges([rename_selection_range]);
12591                            });
12592                        }
12593                        editor
12594                    });
12595                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12596                        if e == &EditorEvent::Focused {
12597                            cx.emit(EditorEvent::FocusedIn)
12598                        }
12599                    })
12600                    .detach();
12601
12602                    let write_highlights =
12603                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12604                    let read_highlights =
12605                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
12606                    let ranges = write_highlights
12607                        .iter()
12608                        .flat_map(|(_, ranges)| ranges.iter())
12609                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12610                        .cloned()
12611                        .collect();
12612
12613                    this.highlight_text::<Rename>(
12614                        ranges,
12615                        HighlightStyle {
12616                            fade_out: Some(0.6),
12617                            ..Default::default()
12618                        },
12619                        cx,
12620                    );
12621                    let rename_focus_handle = rename_editor.focus_handle(cx);
12622                    window.focus(&rename_focus_handle);
12623                    let block_id = this.insert_blocks(
12624                        [BlockProperties {
12625                            style: BlockStyle::Flex,
12626                            placement: BlockPlacement::Below(range.start),
12627                            height: 1,
12628                            render: Arc::new({
12629                                let rename_editor = rename_editor.clone();
12630                                move |cx: &mut BlockContext| {
12631                                    let mut text_style = cx.editor_style.text.clone();
12632                                    if let Some(highlight_style) = old_highlight_id
12633                                        .and_then(|h| h.style(&cx.editor_style.syntax))
12634                                    {
12635                                        text_style = text_style.highlight(highlight_style);
12636                                    }
12637                                    div()
12638                                        .block_mouse_down()
12639                                        .pl(cx.anchor_x)
12640                                        .child(EditorElement::new(
12641                                            &rename_editor,
12642                                            EditorStyle {
12643                                                background: cx.theme().system().transparent,
12644                                                local_player: cx.editor_style.local_player,
12645                                                text: text_style,
12646                                                scrollbar_width: cx.editor_style.scrollbar_width,
12647                                                syntax: cx.editor_style.syntax.clone(),
12648                                                status: cx.editor_style.status.clone(),
12649                                                inlay_hints_style: HighlightStyle {
12650                                                    font_weight: Some(FontWeight::BOLD),
12651                                                    ..make_inlay_hints_style(cx.app)
12652                                                },
12653                                                inline_completion_styles: make_suggestion_styles(
12654                                                    cx.app,
12655                                                ),
12656                                                ..EditorStyle::default()
12657                                            },
12658                                        ))
12659                                        .into_any_element()
12660                                }
12661                            }),
12662                            priority: 0,
12663                        }],
12664                        Some(Autoscroll::fit()),
12665                        cx,
12666                    )[0];
12667                    this.pending_rename = Some(RenameState {
12668                        range,
12669                        old_name,
12670                        editor: rename_editor,
12671                        block_id,
12672                    });
12673                })?;
12674            }
12675
12676            Ok(())
12677        }))
12678    }
12679
12680    pub fn confirm_rename(
12681        &mut self,
12682        _: &ConfirmRename,
12683        window: &mut Window,
12684        cx: &mut Context<Self>,
12685    ) -> Option<Task<Result<()>>> {
12686        let rename = self.take_rename(false, window, cx)?;
12687        let workspace = self.workspace()?.downgrade();
12688        let (buffer, start) = self
12689            .buffer
12690            .read(cx)
12691            .text_anchor_for_position(rename.range.start, cx)?;
12692        let (end_buffer, _) = self
12693            .buffer
12694            .read(cx)
12695            .text_anchor_for_position(rename.range.end, cx)?;
12696        if buffer != end_buffer {
12697            return None;
12698        }
12699
12700        let old_name = rename.old_name;
12701        let new_name = rename.editor.read(cx).text(cx);
12702
12703        let rename = self.semantics_provider.as_ref()?.perform_rename(
12704            &buffer,
12705            start,
12706            new_name.clone(),
12707            cx,
12708        )?;
12709
12710        Some(cx.spawn_in(window, |editor, mut cx| async move {
12711            let project_transaction = rename.await?;
12712            Self::open_project_transaction(
12713                &editor,
12714                workspace,
12715                project_transaction,
12716                format!("Rename: {}{}", old_name, new_name),
12717                cx.clone(),
12718            )
12719            .await?;
12720
12721            editor.update(&mut cx, |editor, cx| {
12722                editor.refresh_document_highlights(cx);
12723            })?;
12724            Ok(())
12725        }))
12726    }
12727
12728    fn take_rename(
12729        &mut self,
12730        moving_cursor: bool,
12731        window: &mut Window,
12732        cx: &mut Context<Self>,
12733    ) -> Option<RenameState> {
12734        let rename = self.pending_rename.take()?;
12735        if rename.editor.focus_handle(cx).is_focused(window) {
12736            window.focus(&self.focus_handle);
12737        }
12738
12739        self.remove_blocks(
12740            [rename.block_id].into_iter().collect(),
12741            Some(Autoscroll::fit()),
12742            cx,
12743        );
12744        self.clear_highlights::<Rename>(cx);
12745        self.show_local_selections = true;
12746
12747        if moving_cursor {
12748            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12749                editor.selections.newest::<usize>(cx).head()
12750            });
12751
12752            // Update the selection to match the position of the selection inside
12753            // the rename editor.
12754            let snapshot = self.buffer.read(cx).read(cx);
12755            let rename_range = rename.range.to_offset(&snapshot);
12756            let cursor_in_editor = snapshot
12757                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12758                .min(rename_range.end);
12759            drop(snapshot);
12760
12761            self.change_selections(None, window, cx, |s| {
12762                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12763            });
12764        } else {
12765            self.refresh_document_highlights(cx);
12766        }
12767
12768        Some(rename)
12769    }
12770
12771    pub fn pending_rename(&self) -> Option<&RenameState> {
12772        self.pending_rename.as_ref()
12773    }
12774
12775    fn format(
12776        &mut self,
12777        _: &Format,
12778        window: &mut Window,
12779        cx: &mut Context<Self>,
12780    ) -> Option<Task<Result<()>>> {
12781        let project = match &self.project {
12782            Some(project) => project.clone(),
12783            None => return None,
12784        };
12785
12786        Some(self.perform_format(
12787            project,
12788            FormatTrigger::Manual,
12789            FormatTarget::Buffers,
12790            window,
12791            cx,
12792        ))
12793    }
12794
12795    fn format_selections(
12796        &mut self,
12797        _: &FormatSelections,
12798        window: &mut Window,
12799        cx: &mut Context<Self>,
12800    ) -> Option<Task<Result<()>>> {
12801        let project = match &self.project {
12802            Some(project) => project.clone(),
12803            None => return None,
12804        };
12805
12806        let ranges = self
12807            .selections
12808            .all_adjusted(cx)
12809            .into_iter()
12810            .map(|selection| selection.range())
12811            .collect_vec();
12812
12813        Some(self.perform_format(
12814            project,
12815            FormatTrigger::Manual,
12816            FormatTarget::Ranges(ranges),
12817            window,
12818            cx,
12819        ))
12820    }
12821
12822    fn perform_format(
12823        &mut self,
12824        project: Entity<Project>,
12825        trigger: FormatTrigger,
12826        target: FormatTarget,
12827        window: &mut Window,
12828        cx: &mut Context<Self>,
12829    ) -> Task<Result<()>> {
12830        let buffer = self.buffer.clone();
12831        let (buffers, target) = match target {
12832            FormatTarget::Buffers => {
12833                let mut buffers = buffer.read(cx).all_buffers();
12834                if trigger == FormatTrigger::Save {
12835                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
12836                }
12837                (buffers, LspFormatTarget::Buffers)
12838            }
12839            FormatTarget::Ranges(selection_ranges) => {
12840                let multi_buffer = buffer.read(cx);
12841                let snapshot = multi_buffer.read(cx);
12842                let mut buffers = HashSet::default();
12843                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12844                    BTreeMap::new();
12845                for selection_range in selection_ranges {
12846                    for (buffer, buffer_range, _) in
12847                        snapshot.range_to_buffer_ranges(selection_range)
12848                    {
12849                        let buffer_id = buffer.remote_id();
12850                        let start = buffer.anchor_before(buffer_range.start);
12851                        let end = buffer.anchor_after(buffer_range.end);
12852                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12853                        buffer_id_to_ranges
12854                            .entry(buffer_id)
12855                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12856                            .or_insert_with(|| vec![start..end]);
12857                    }
12858                }
12859                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12860            }
12861        };
12862
12863        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12864        let format = project.update(cx, |project, cx| {
12865            project.format(buffers, target, true, trigger, cx)
12866        });
12867
12868        cx.spawn_in(window, |_, mut cx| async move {
12869            let transaction = futures::select_biased! {
12870                transaction = format.log_err().fuse() => transaction,
12871                () = timeout => {
12872                    log::warn!("timed out waiting for formatting");
12873                    None
12874                }
12875            };
12876
12877            buffer
12878                .update(&mut cx, |buffer, cx| {
12879                    if let Some(transaction) = transaction {
12880                        if !buffer.is_singleton() {
12881                            buffer.push_transaction(&transaction.0, cx);
12882                        }
12883                    }
12884                    cx.notify();
12885                })
12886                .ok();
12887
12888            Ok(())
12889        })
12890    }
12891
12892    fn organize_imports(
12893        &mut self,
12894        _: &OrganizeImports,
12895        window: &mut Window,
12896        cx: &mut Context<Self>,
12897    ) -> Option<Task<Result<()>>> {
12898        let project = match &self.project {
12899            Some(project) => project.clone(),
12900            None => return None,
12901        };
12902        Some(self.perform_code_action_kind(
12903            project,
12904            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12905            window,
12906            cx,
12907        ))
12908    }
12909
12910    fn perform_code_action_kind(
12911        &mut self,
12912        project: Entity<Project>,
12913        kind: CodeActionKind,
12914        window: &mut Window,
12915        cx: &mut Context<Self>,
12916    ) -> Task<Result<()>> {
12917        let buffer = self.buffer.clone();
12918        let buffers = buffer.read(cx).all_buffers();
12919        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12920        let apply_action = project.update(cx, |project, cx| {
12921            project.apply_code_action_kind(buffers, kind, true, cx)
12922        });
12923        cx.spawn_in(window, |_, mut cx| async move {
12924            let transaction = futures::select_biased! {
12925                () = timeout => {
12926                    log::warn!("timed out waiting for executing code action");
12927                    None
12928                }
12929                transaction = apply_action.log_err().fuse() => transaction,
12930            };
12931            buffer
12932                .update(&mut cx, |buffer, cx| {
12933                    // check if we need this
12934                    if let Some(transaction) = transaction {
12935                        if !buffer.is_singleton() {
12936                            buffer.push_transaction(&transaction.0, cx);
12937                        }
12938                    }
12939                    cx.notify();
12940                })
12941                .ok();
12942            Ok(())
12943        })
12944    }
12945
12946    fn restart_language_server(
12947        &mut self,
12948        _: &RestartLanguageServer,
12949        _: &mut Window,
12950        cx: &mut Context<Self>,
12951    ) {
12952        if let Some(project) = self.project.clone() {
12953            self.buffer.update(cx, |multi_buffer, cx| {
12954                project.update(cx, |project, cx| {
12955                    project.restart_language_servers_for_buffers(
12956                        multi_buffer.all_buffers().into_iter().collect(),
12957                        cx,
12958                    );
12959                });
12960            })
12961        }
12962    }
12963
12964    fn cancel_language_server_work(
12965        workspace: &mut Workspace,
12966        _: &actions::CancelLanguageServerWork,
12967        _: &mut Window,
12968        cx: &mut Context<Workspace>,
12969    ) {
12970        let project = workspace.project();
12971        let buffers = workspace
12972            .active_item(cx)
12973            .and_then(|item| item.act_as::<Editor>(cx))
12974            .map_or(HashSet::default(), |editor| {
12975                editor.read(cx).buffer.read(cx).all_buffers()
12976            });
12977        project.update(cx, |project, cx| {
12978            project.cancel_language_server_work_for_buffers(buffers, cx);
12979        });
12980    }
12981
12982    fn show_character_palette(
12983        &mut self,
12984        _: &ShowCharacterPalette,
12985        window: &mut Window,
12986        _: &mut Context<Self>,
12987    ) {
12988        window.show_character_palette();
12989    }
12990
12991    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12992        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12993            let buffer = self.buffer.read(cx).snapshot(cx);
12994            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12995            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12996            let is_valid = buffer
12997                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12998                .any(|entry| {
12999                    entry.diagnostic.is_primary
13000                        && !entry.range.is_empty()
13001                        && entry.range.start == primary_range_start
13002                        && entry.diagnostic.message == active_diagnostics.primary_message
13003                });
13004
13005            if is_valid != active_diagnostics.is_valid {
13006                active_diagnostics.is_valid = is_valid;
13007                if is_valid {
13008                    let mut new_styles = HashMap::default();
13009                    for (block_id, diagnostic) in &active_diagnostics.blocks {
13010                        new_styles.insert(
13011                            *block_id,
13012                            diagnostic_block_renderer(diagnostic.clone(), None, true),
13013                        );
13014                    }
13015                    self.display_map.update(cx, |display_map, _cx| {
13016                        display_map.replace_blocks(new_styles);
13017                    });
13018                } else {
13019                    self.dismiss_diagnostics(cx);
13020                }
13021            }
13022        }
13023    }
13024
13025    fn activate_diagnostics(
13026        &mut self,
13027        buffer_id: BufferId,
13028        group_id: usize,
13029        window: &mut Window,
13030        cx: &mut Context<Self>,
13031    ) {
13032        self.dismiss_diagnostics(cx);
13033        let snapshot = self.snapshot(window, cx);
13034        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
13035            let buffer = self.buffer.read(cx).snapshot(cx);
13036
13037            let mut primary_range = None;
13038            let mut primary_message = None;
13039            let diagnostic_group = buffer
13040                .diagnostic_group(buffer_id, group_id)
13041                .filter_map(|entry| {
13042                    let start = entry.range.start;
13043                    let end = entry.range.end;
13044                    if snapshot.is_line_folded(MultiBufferRow(start.row))
13045                        && (start.row == end.row
13046                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
13047                    {
13048                        return None;
13049                    }
13050                    if entry.diagnostic.is_primary {
13051                        primary_range = Some(entry.range.clone());
13052                        primary_message = Some(entry.diagnostic.message.clone());
13053                    }
13054                    Some(entry)
13055                })
13056                .collect::<Vec<_>>();
13057            let primary_range = primary_range?;
13058            let primary_message = primary_message?;
13059
13060            let blocks = display_map
13061                .insert_blocks(
13062                    diagnostic_group.iter().map(|entry| {
13063                        let diagnostic = entry.diagnostic.clone();
13064                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
13065                        BlockProperties {
13066                            style: BlockStyle::Fixed,
13067                            placement: BlockPlacement::Below(
13068                                buffer.anchor_after(entry.range.start),
13069                            ),
13070                            height: message_height,
13071                            render: diagnostic_block_renderer(diagnostic, None, true),
13072                            priority: 0,
13073                        }
13074                    }),
13075                    cx,
13076                )
13077                .into_iter()
13078                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
13079                .collect();
13080
13081            Some(ActiveDiagnosticGroup {
13082                primary_range: buffer.anchor_before(primary_range.start)
13083                    ..buffer.anchor_after(primary_range.end),
13084                primary_message,
13085                group_id,
13086                blocks,
13087                is_valid: true,
13088            })
13089        });
13090    }
13091
13092    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
13093        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
13094            self.display_map.update(cx, |display_map, cx| {
13095                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
13096            });
13097            cx.notify();
13098        }
13099    }
13100
13101    /// Disable inline diagnostics rendering for this editor.
13102    pub fn disable_inline_diagnostics(&mut self) {
13103        self.inline_diagnostics_enabled = false;
13104        self.inline_diagnostics_update = Task::ready(());
13105        self.inline_diagnostics.clear();
13106    }
13107
13108    pub fn inline_diagnostics_enabled(&self) -> bool {
13109        self.inline_diagnostics_enabled
13110    }
13111
13112    pub fn show_inline_diagnostics(&self) -> bool {
13113        self.show_inline_diagnostics
13114    }
13115
13116    pub fn toggle_inline_diagnostics(
13117        &mut self,
13118        _: &ToggleInlineDiagnostics,
13119        window: &mut Window,
13120        cx: &mut Context<'_, Editor>,
13121    ) {
13122        self.show_inline_diagnostics = !self.show_inline_diagnostics;
13123        self.refresh_inline_diagnostics(false, window, cx);
13124    }
13125
13126    fn refresh_inline_diagnostics(
13127        &mut self,
13128        debounce: bool,
13129        window: &mut Window,
13130        cx: &mut Context<Self>,
13131    ) {
13132        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
13133            self.inline_diagnostics_update = Task::ready(());
13134            self.inline_diagnostics.clear();
13135            return;
13136        }
13137
13138        let debounce_ms = ProjectSettings::get_global(cx)
13139            .diagnostics
13140            .inline
13141            .update_debounce_ms;
13142        let debounce = if debounce && debounce_ms > 0 {
13143            Some(Duration::from_millis(debounce_ms))
13144        } else {
13145            None
13146        };
13147        self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
13148            if let Some(debounce) = debounce {
13149                cx.background_executor().timer(debounce).await;
13150            }
13151            let Some(snapshot) = editor
13152                .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
13153                .ok()
13154            else {
13155                return;
13156            };
13157
13158            let new_inline_diagnostics = cx
13159                .background_spawn(async move {
13160                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
13161                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
13162                        let message = diagnostic_entry
13163                            .diagnostic
13164                            .message
13165                            .split_once('\n')
13166                            .map(|(line, _)| line)
13167                            .map(SharedString::new)
13168                            .unwrap_or_else(|| {
13169                                SharedString::from(diagnostic_entry.diagnostic.message)
13170                            });
13171                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
13172                        let (Ok(i) | Err(i)) = inline_diagnostics
13173                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
13174                        inline_diagnostics.insert(
13175                            i,
13176                            (
13177                                start_anchor,
13178                                InlineDiagnostic {
13179                                    message,
13180                                    group_id: diagnostic_entry.diagnostic.group_id,
13181                                    start: diagnostic_entry.range.start.to_point(&snapshot),
13182                                    is_primary: diagnostic_entry.diagnostic.is_primary,
13183                                    severity: diagnostic_entry.diagnostic.severity,
13184                                },
13185                            ),
13186                        );
13187                    }
13188                    inline_diagnostics
13189                })
13190                .await;
13191
13192            editor
13193                .update(&mut cx, |editor, cx| {
13194                    editor.inline_diagnostics = new_inline_diagnostics;
13195                    cx.notify();
13196                })
13197                .ok();
13198        });
13199    }
13200
13201    pub fn set_selections_from_remote(
13202        &mut self,
13203        selections: Vec<Selection<Anchor>>,
13204        pending_selection: Option<Selection<Anchor>>,
13205        window: &mut Window,
13206        cx: &mut Context<Self>,
13207    ) {
13208        let old_cursor_position = self.selections.newest_anchor().head();
13209        self.selections.change_with(cx, |s| {
13210            s.select_anchors(selections);
13211            if let Some(pending_selection) = pending_selection {
13212                s.set_pending(pending_selection, SelectMode::Character);
13213            } else {
13214                s.clear_pending();
13215            }
13216        });
13217        self.selections_did_change(false, &old_cursor_position, true, window, cx);
13218    }
13219
13220    fn push_to_selection_history(&mut self) {
13221        self.selection_history.push(SelectionHistoryEntry {
13222            selections: self.selections.disjoint_anchors(),
13223            select_next_state: self.select_next_state.clone(),
13224            select_prev_state: self.select_prev_state.clone(),
13225            add_selections_state: self.add_selections_state.clone(),
13226        });
13227    }
13228
13229    pub fn transact(
13230        &mut self,
13231        window: &mut Window,
13232        cx: &mut Context<Self>,
13233        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
13234    ) -> Option<TransactionId> {
13235        self.start_transaction_at(Instant::now(), window, cx);
13236        update(self, window, cx);
13237        self.end_transaction_at(Instant::now(), cx)
13238    }
13239
13240    pub fn start_transaction_at(
13241        &mut self,
13242        now: Instant,
13243        window: &mut Window,
13244        cx: &mut Context<Self>,
13245    ) {
13246        self.end_selection(window, cx);
13247        if let Some(tx_id) = self
13248            .buffer
13249            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
13250        {
13251            self.selection_history
13252                .insert_transaction(tx_id, self.selections.disjoint_anchors());
13253            cx.emit(EditorEvent::TransactionBegun {
13254                transaction_id: tx_id,
13255            })
13256        }
13257    }
13258
13259    pub fn end_transaction_at(
13260        &mut self,
13261        now: Instant,
13262        cx: &mut Context<Self>,
13263    ) -> Option<TransactionId> {
13264        if let Some(transaction_id) = self
13265            .buffer
13266            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
13267        {
13268            if let Some((_, end_selections)) =
13269                self.selection_history.transaction_mut(transaction_id)
13270            {
13271                *end_selections = Some(self.selections.disjoint_anchors());
13272            } else {
13273                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
13274            }
13275
13276            cx.emit(EditorEvent::Edited { transaction_id });
13277            Some(transaction_id)
13278        } else {
13279            None
13280        }
13281    }
13282
13283    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
13284        if self.selection_mark_mode {
13285            self.change_selections(None, window, cx, |s| {
13286                s.move_with(|_, sel| {
13287                    sel.collapse_to(sel.head(), SelectionGoal::None);
13288                });
13289            })
13290        }
13291        self.selection_mark_mode = true;
13292        cx.notify();
13293    }
13294
13295    pub fn swap_selection_ends(
13296        &mut self,
13297        _: &actions::SwapSelectionEnds,
13298        window: &mut Window,
13299        cx: &mut Context<Self>,
13300    ) {
13301        self.change_selections(None, window, cx, |s| {
13302            s.move_with(|_, sel| {
13303                if sel.start != sel.end {
13304                    sel.reversed = !sel.reversed
13305                }
13306            });
13307        });
13308        self.request_autoscroll(Autoscroll::newest(), cx);
13309        cx.notify();
13310    }
13311
13312    pub fn toggle_fold(
13313        &mut self,
13314        _: &actions::ToggleFold,
13315        window: &mut Window,
13316        cx: &mut Context<Self>,
13317    ) {
13318        if self.is_singleton(cx) {
13319            let selection = self.selections.newest::<Point>(cx);
13320
13321            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13322            let range = if selection.is_empty() {
13323                let point = selection.head().to_display_point(&display_map);
13324                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13325                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13326                    .to_point(&display_map);
13327                start..end
13328            } else {
13329                selection.range()
13330            };
13331            if display_map.folds_in_range(range).next().is_some() {
13332                self.unfold_lines(&Default::default(), window, cx)
13333            } else {
13334                self.fold(&Default::default(), window, cx)
13335            }
13336        } else {
13337            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13338            let buffer_ids: HashSet<_> = self
13339                .selections
13340                .disjoint_anchor_ranges()
13341                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13342                .collect();
13343
13344            let should_unfold = buffer_ids
13345                .iter()
13346                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13347
13348            for buffer_id in buffer_ids {
13349                if should_unfold {
13350                    self.unfold_buffer(buffer_id, cx);
13351                } else {
13352                    self.fold_buffer(buffer_id, cx);
13353                }
13354            }
13355        }
13356    }
13357
13358    pub fn toggle_fold_recursive(
13359        &mut self,
13360        _: &actions::ToggleFoldRecursive,
13361        window: &mut Window,
13362        cx: &mut Context<Self>,
13363    ) {
13364        let selection = self.selections.newest::<Point>(cx);
13365
13366        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13367        let range = if selection.is_empty() {
13368            let point = selection.head().to_display_point(&display_map);
13369            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13370            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13371                .to_point(&display_map);
13372            start..end
13373        } else {
13374            selection.range()
13375        };
13376        if display_map.folds_in_range(range).next().is_some() {
13377            self.unfold_recursive(&Default::default(), window, cx)
13378        } else {
13379            self.fold_recursive(&Default::default(), window, cx)
13380        }
13381    }
13382
13383    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13384        if self.is_singleton(cx) {
13385            let mut to_fold = Vec::new();
13386            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13387            let selections = self.selections.all_adjusted(cx);
13388
13389            for selection in selections {
13390                let range = selection.range().sorted();
13391                let buffer_start_row = range.start.row;
13392
13393                if range.start.row != range.end.row {
13394                    let mut found = false;
13395                    let mut row = range.start.row;
13396                    while row <= range.end.row {
13397                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13398                        {
13399                            found = true;
13400                            row = crease.range().end.row + 1;
13401                            to_fold.push(crease);
13402                        } else {
13403                            row += 1
13404                        }
13405                    }
13406                    if found {
13407                        continue;
13408                    }
13409                }
13410
13411                for row in (0..=range.start.row).rev() {
13412                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13413                        if crease.range().end.row >= buffer_start_row {
13414                            to_fold.push(crease);
13415                            if row <= range.start.row {
13416                                break;
13417                            }
13418                        }
13419                    }
13420                }
13421            }
13422
13423            self.fold_creases(to_fold, true, window, cx);
13424        } else {
13425            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13426            let buffer_ids = self
13427                .selections
13428                .disjoint_anchor_ranges()
13429                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13430                .collect::<HashSet<_>>();
13431            for buffer_id in buffer_ids {
13432                self.fold_buffer(buffer_id, cx);
13433            }
13434        }
13435    }
13436
13437    fn fold_at_level(
13438        &mut self,
13439        fold_at: &FoldAtLevel,
13440        window: &mut Window,
13441        cx: &mut Context<Self>,
13442    ) {
13443        if !self.buffer.read(cx).is_singleton() {
13444            return;
13445        }
13446
13447        let fold_at_level = fold_at.0;
13448        let snapshot = self.buffer.read(cx).snapshot(cx);
13449        let mut to_fold = Vec::new();
13450        let mut stack = vec![(0, snapshot.max_row().0, 1)];
13451
13452        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13453            while start_row < end_row {
13454                match self
13455                    .snapshot(window, cx)
13456                    .crease_for_buffer_row(MultiBufferRow(start_row))
13457                {
13458                    Some(crease) => {
13459                        let nested_start_row = crease.range().start.row + 1;
13460                        let nested_end_row = crease.range().end.row;
13461
13462                        if current_level < fold_at_level {
13463                            stack.push((nested_start_row, nested_end_row, current_level + 1));
13464                        } else if current_level == fold_at_level {
13465                            to_fold.push(crease);
13466                        }
13467
13468                        start_row = nested_end_row + 1;
13469                    }
13470                    None => start_row += 1,
13471                }
13472            }
13473        }
13474
13475        self.fold_creases(to_fold, true, window, cx);
13476    }
13477
13478    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13479        if self.buffer.read(cx).is_singleton() {
13480            let mut fold_ranges = Vec::new();
13481            let snapshot = self.buffer.read(cx).snapshot(cx);
13482
13483            for row in 0..snapshot.max_row().0 {
13484                if let Some(foldable_range) = self
13485                    .snapshot(window, cx)
13486                    .crease_for_buffer_row(MultiBufferRow(row))
13487                {
13488                    fold_ranges.push(foldable_range);
13489                }
13490            }
13491
13492            self.fold_creases(fold_ranges, true, window, cx);
13493        } else {
13494            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13495                editor
13496                    .update_in(&mut cx, |editor, _, cx| {
13497                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13498                            editor.fold_buffer(buffer_id, cx);
13499                        }
13500                    })
13501                    .ok();
13502            });
13503        }
13504    }
13505
13506    pub fn fold_function_bodies(
13507        &mut self,
13508        _: &actions::FoldFunctionBodies,
13509        window: &mut Window,
13510        cx: &mut Context<Self>,
13511    ) {
13512        let snapshot = self.buffer.read(cx).snapshot(cx);
13513
13514        let ranges = snapshot
13515            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13516            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13517            .collect::<Vec<_>>();
13518
13519        let creases = ranges
13520            .into_iter()
13521            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13522            .collect();
13523
13524        self.fold_creases(creases, true, window, cx);
13525    }
13526
13527    pub fn fold_recursive(
13528        &mut self,
13529        _: &actions::FoldRecursive,
13530        window: &mut Window,
13531        cx: &mut Context<Self>,
13532    ) {
13533        let mut to_fold = Vec::new();
13534        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13535        let selections = self.selections.all_adjusted(cx);
13536
13537        for selection in selections {
13538            let range = selection.range().sorted();
13539            let buffer_start_row = range.start.row;
13540
13541            if range.start.row != range.end.row {
13542                let mut found = false;
13543                for row in range.start.row..=range.end.row {
13544                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13545                        found = true;
13546                        to_fold.push(crease);
13547                    }
13548                }
13549                if found {
13550                    continue;
13551                }
13552            }
13553
13554            for row in (0..=range.start.row).rev() {
13555                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13556                    if crease.range().end.row >= buffer_start_row {
13557                        to_fold.push(crease);
13558                    } else {
13559                        break;
13560                    }
13561                }
13562            }
13563        }
13564
13565        self.fold_creases(to_fold, true, window, cx);
13566    }
13567
13568    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13569        let buffer_row = fold_at.buffer_row;
13570        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13571
13572        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13573            let autoscroll = self
13574                .selections
13575                .all::<Point>(cx)
13576                .iter()
13577                .any(|selection| crease.range().overlaps(&selection.range()));
13578
13579            self.fold_creases(vec![crease], autoscroll, window, cx);
13580        }
13581    }
13582
13583    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13584        if self.is_singleton(cx) {
13585            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13586            let buffer = &display_map.buffer_snapshot;
13587            let selections = self.selections.all::<Point>(cx);
13588            let ranges = selections
13589                .iter()
13590                .map(|s| {
13591                    let range = s.display_range(&display_map).sorted();
13592                    let mut start = range.start.to_point(&display_map);
13593                    let mut end = range.end.to_point(&display_map);
13594                    start.column = 0;
13595                    end.column = buffer.line_len(MultiBufferRow(end.row));
13596                    start..end
13597                })
13598                .collect::<Vec<_>>();
13599
13600            self.unfold_ranges(&ranges, true, true, cx);
13601        } else {
13602            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13603            let buffer_ids = self
13604                .selections
13605                .disjoint_anchor_ranges()
13606                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13607                .collect::<HashSet<_>>();
13608            for buffer_id in buffer_ids {
13609                self.unfold_buffer(buffer_id, cx);
13610            }
13611        }
13612    }
13613
13614    pub fn unfold_recursive(
13615        &mut self,
13616        _: &UnfoldRecursive,
13617        _window: &mut Window,
13618        cx: &mut Context<Self>,
13619    ) {
13620        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13621        let selections = self.selections.all::<Point>(cx);
13622        let ranges = selections
13623            .iter()
13624            .map(|s| {
13625                let mut range = s.display_range(&display_map).sorted();
13626                *range.start.column_mut() = 0;
13627                *range.end.column_mut() = display_map.line_len(range.end.row());
13628                let start = range.start.to_point(&display_map);
13629                let end = range.end.to_point(&display_map);
13630                start..end
13631            })
13632            .collect::<Vec<_>>();
13633
13634        self.unfold_ranges(&ranges, true, true, cx);
13635    }
13636
13637    pub fn unfold_at(
13638        &mut self,
13639        unfold_at: &UnfoldAt,
13640        _window: &mut Window,
13641        cx: &mut Context<Self>,
13642    ) {
13643        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13644
13645        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13646            ..Point::new(
13647                unfold_at.buffer_row.0,
13648                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13649            );
13650
13651        let autoscroll = self
13652            .selections
13653            .all::<Point>(cx)
13654            .iter()
13655            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13656
13657        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13658    }
13659
13660    pub fn unfold_all(
13661        &mut self,
13662        _: &actions::UnfoldAll,
13663        _window: &mut Window,
13664        cx: &mut Context<Self>,
13665    ) {
13666        if self.buffer.read(cx).is_singleton() {
13667            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13668            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13669        } else {
13670            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13671                editor
13672                    .update(&mut cx, |editor, cx| {
13673                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13674                            editor.unfold_buffer(buffer_id, cx);
13675                        }
13676                    })
13677                    .ok();
13678            });
13679        }
13680    }
13681
13682    pub fn fold_selected_ranges(
13683        &mut self,
13684        _: &FoldSelectedRanges,
13685        window: &mut Window,
13686        cx: &mut Context<Self>,
13687    ) {
13688        let selections = self.selections.all::<Point>(cx);
13689        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13690        let line_mode = self.selections.line_mode;
13691        let ranges = selections
13692            .into_iter()
13693            .map(|s| {
13694                if line_mode {
13695                    let start = Point::new(s.start.row, 0);
13696                    let end = Point::new(
13697                        s.end.row,
13698                        display_map
13699                            .buffer_snapshot
13700                            .line_len(MultiBufferRow(s.end.row)),
13701                    );
13702                    Crease::simple(start..end, display_map.fold_placeholder.clone())
13703                } else {
13704                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13705                }
13706            })
13707            .collect::<Vec<_>>();
13708        self.fold_creases(ranges, true, window, cx);
13709    }
13710
13711    pub fn fold_ranges<T: ToOffset + Clone>(
13712        &mut self,
13713        ranges: Vec<Range<T>>,
13714        auto_scroll: bool,
13715        window: &mut Window,
13716        cx: &mut Context<Self>,
13717    ) {
13718        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13719        let ranges = ranges
13720            .into_iter()
13721            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13722            .collect::<Vec<_>>();
13723        self.fold_creases(ranges, auto_scroll, window, cx);
13724    }
13725
13726    pub fn fold_creases<T: ToOffset + Clone>(
13727        &mut self,
13728        creases: Vec<Crease<T>>,
13729        auto_scroll: bool,
13730        window: &mut Window,
13731        cx: &mut Context<Self>,
13732    ) {
13733        if creases.is_empty() {
13734            return;
13735        }
13736
13737        let mut buffers_affected = HashSet::default();
13738        let multi_buffer = self.buffer().read(cx);
13739        for crease in &creases {
13740            if let Some((_, buffer, _)) =
13741                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13742            {
13743                buffers_affected.insert(buffer.read(cx).remote_id());
13744            };
13745        }
13746
13747        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13748
13749        if auto_scroll {
13750            self.request_autoscroll(Autoscroll::fit(), cx);
13751        }
13752
13753        cx.notify();
13754
13755        if let Some(active_diagnostics) = self.active_diagnostics.take() {
13756            // Clear diagnostics block when folding a range that contains it.
13757            let snapshot = self.snapshot(window, cx);
13758            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13759                drop(snapshot);
13760                self.active_diagnostics = Some(active_diagnostics);
13761                self.dismiss_diagnostics(cx);
13762            } else {
13763                self.active_diagnostics = Some(active_diagnostics);
13764            }
13765        }
13766
13767        self.scrollbar_marker_state.dirty = true;
13768    }
13769
13770    /// Removes any folds whose ranges intersect any of the given ranges.
13771    pub fn unfold_ranges<T: ToOffset + Clone>(
13772        &mut self,
13773        ranges: &[Range<T>],
13774        inclusive: bool,
13775        auto_scroll: bool,
13776        cx: &mut Context<Self>,
13777    ) {
13778        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13779            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13780        });
13781    }
13782
13783    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13784        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13785            return;
13786        }
13787        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13788        self.display_map.update(cx, |display_map, cx| {
13789            display_map.fold_buffers([buffer_id], cx)
13790        });
13791        cx.emit(EditorEvent::BufferFoldToggled {
13792            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13793            folded: true,
13794        });
13795        cx.notify();
13796    }
13797
13798    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13799        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13800            return;
13801        }
13802        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13803        self.display_map.update(cx, |display_map, cx| {
13804            display_map.unfold_buffers([buffer_id], cx);
13805        });
13806        cx.emit(EditorEvent::BufferFoldToggled {
13807            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13808            folded: false,
13809        });
13810        cx.notify();
13811    }
13812
13813    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13814        self.display_map.read(cx).is_buffer_folded(buffer)
13815    }
13816
13817    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13818        self.display_map.read(cx).folded_buffers()
13819    }
13820
13821    /// Removes any folds with the given ranges.
13822    pub fn remove_folds_with_type<T: ToOffset + Clone>(
13823        &mut self,
13824        ranges: &[Range<T>],
13825        type_id: TypeId,
13826        auto_scroll: bool,
13827        cx: &mut Context<Self>,
13828    ) {
13829        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13830            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13831        });
13832    }
13833
13834    fn remove_folds_with<T: ToOffset + Clone>(
13835        &mut self,
13836        ranges: &[Range<T>],
13837        auto_scroll: bool,
13838        cx: &mut Context<Self>,
13839        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13840    ) {
13841        if ranges.is_empty() {
13842            return;
13843        }
13844
13845        let mut buffers_affected = HashSet::default();
13846        let multi_buffer = self.buffer().read(cx);
13847        for range in ranges {
13848            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13849                buffers_affected.insert(buffer.read(cx).remote_id());
13850            };
13851        }
13852
13853        self.display_map.update(cx, update);
13854
13855        if auto_scroll {
13856            self.request_autoscroll(Autoscroll::fit(), cx);
13857        }
13858
13859        cx.notify();
13860        self.scrollbar_marker_state.dirty = true;
13861        self.active_indent_guides_state.dirty = true;
13862    }
13863
13864    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13865        self.display_map.read(cx).fold_placeholder.clone()
13866    }
13867
13868    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13869        self.buffer.update(cx, |buffer, cx| {
13870            buffer.set_all_diff_hunks_expanded(cx);
13871        });
13872    }
13873
13874    pub fn expand_all_diff_hunks(
13875        &mut self,
13876        _: &ExpandAllDiffHunks,
13877        _window: &mut Window,
13878        cx: &mut Context<Self>,
13879    ) {
13880        self.buffer.update(cx, |buffer, cx| {
13881            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13882        });
13883    }
13884
13885    pub fn toggle_selected_diff_hunks(
13886        &mut self,
13887        _: &ToggleSelectedDiffHunks,
13888        _window: &mut Window,
13889        cx: &mut Context<Self>,
13890    ) {
13891        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13892        self.toggle_diff_hunks_in_ranges(ranges, cx);
13893    }
13894
13895    pub fn diff_hunks_in_ranges<'a>(
13896        &'a self,
13897        ranges: &'a [Range<Anchor>],
13898        buffer: &'a MultiBufferSnapshot,
13899    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13900        ranges.iter().flat_map(move |range| {
13901            let end_excerpt_id = range.end.excerpt_id;
13902            let range = range.to_point(buffer);
13903            let mut peek_end = range.end;
13904            if range.end.row < buffer.max_row().0 {
13905                peek_end = Point::new(range.end.row + 1, 0);
13906            }
13907            buffer
13908                .diff_hunks_in_range(range.start..peek_end)
13909                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13910        })
13911    }
13912
13913    pub fn has_stageable_diff_hunks_in_ranges(
13914        &self,
13915        ranges: &[Range<Anchor>],
13916        snapshot: &MultiBufferSnapshot,
13917    ) -> bool {
13918        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13919        hunks.any(|hunk| hunk.status().has_secondary_hunk())
13920    }
13921
13922    pub fn toggle_staged_selected_diff_hunks(
13923        &mut self,
13924        _: &::git::ToggleStaged,
13925        _: &mut Window,
13926        cx: &mut Context<Self>,
13927    ) {
13928        let snapshot = self.buffer.read(cx).snapshot(cx);
13929        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13930        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13931        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13932    }
13933
13934    pub fn stage_and_next(
13935        &mut self,
13936        _: &::git::StageAndNext,
13937        window: &mut Window,
13938        cx: &mut Context<Self>,
13939    ) {
13940        self.do_stage_or_unstage_and_next(true, window, cx);
13941    }
13942
13943    pub fn unstage_and_next(
13944        &mut self,
13945        _: &::git::UnstageAndNext,
13946        window: &mut Window,
13947        cx: &mut Context<Self>,
13948    ) {
13949        self.do_stage_or_unstage_and_next(false, window, cx);
13950    }
13951
13952    pub fn stage_or_unstage_diff_hunks(
13953        &mut self,
13954        stage: bool,
13955        ranges: Vec<Range<Anchor>>,
13956        cx: &mut Context<Self>,
13957    ) {
13958        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
13959        cx.spawn(|this, mut cx| async move {
13960            task.await?;
13961            this.update(&mut cx, |this, cx| {
13962                let snapshot = this.buffer.read(cx).snapshot(cx);
13963                let chunk_by = this
13964                    .diff_hunks_in_ranges(&ranges, &snapshot)
13965                    .chunk_by(|hunk| hunk.buffer_id);
13966                for (buffer_id, hunks) in &chunk_by {
13967                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
13968                }
13969            })
13970        })
13971        .detach_and_log_err(cx);
13972    }
13973
13974    fn save_buffers_for_ranges_if_needed(
13975        &mut self,
13976        ranges: &[Range<Anchor>],
13977        cx: &mut Context<'_, Editor>,
13978    ) -> Task<Result<()>> {
13979        let multibuffer = self.buffer.read(cx);
13980        let snapshot = multibuffer.read(cx);
13981        let buffer_ids: HashSet<_> = ranges
13982            .iter()
13983            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
13984            .collect();
13985        drop(snapshot);
13986
13987        let mut buffers = HashSet::default();
13988        for buffer_id in buffer_ids {
13989            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
13990                let buffer = buffer_entity.read(cx);
13991                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
13992                {
13993                    buffers.insert(buffer_entity);
13994                }
13995            }
13996        }
13997
13998        if let Some(project) = &self.project {
13999            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
14000        } else {
14001            Task::ready(Ok(()))
14002        }
14003    }
14004
14005    fn do_stage_or_unstage_and_next(
14006        &mut self,
14007        stage: bool,
14008        window: &mut Window,
14009        cx: &mut Context<Self>,
14010    ) {
14011        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
14012
14013        if ranges.iter().any(|range| range.start != range.end) {
14014            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14015            return;
14016        }
14017
14018        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14019        let snapshot = self.snapshot(window, cx);
14020        let position = self.selections.newest::<Point>(cx).head();
14021        let mut row = snapshot
14022            .buffer_snapshot
14023            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
14024            .find(|hunk| hunk.row_range.start.0 > position.row)
14025            .map(|hunk| hunk.row_range.start);
14026
14027        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
14028        // Outside of the project diff editor, wrap around to the beginning.
14029        if !all_diff_hunks_expanded {
14030            row = row.or_else(|| {
14031                snapshot
14032                    .buffer_snapshot
14033                    .diff_hunks_in_range(Point::zero()..position)
14034                    .find(|hunk| hunk.row_range.end.0 < position.row)
14035                    .map(|hunk| hunk.row_range.start)
14036            });
14037        }
14038
14039        if let Some(row) = row {
14040            let destination = Point::new(row.0, 0);
14041            let autoscroll = Autoscroll::center();
14042
14043            self.unfold_ranges(&[destination..destination], false, false, cx);
14044            self.change_selections(Some(autoscroll), window, cx, |s| {
14045                s.select_ranges([destination..destination]);
14046            });
14047        }
14048    }
14049
14050    fn do_stage_or_unstage(
14051        &self,
14052        stage: bool,
14053        buffer_id: BufferId,
14054        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
14055        cx: &mut App,
14056    ) -> Option<()> {
14057        let project = self.project.as_ref()?;
14058        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
14059        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
14060        let buffer_snapshot = buffer.read(cx).snapshot();
14061        let file_exists = buffer_snapshot
14062            .file()
14063            .is_some_and(|file| file.disk_state().exists());
14064        diff.update(cx, |diff, cx| {
14065            diff.stage_or_unstage_hunks(
14066                stage,
14067                &hunks
14068                    .map(|hunk| buffer_diff::DiffHunk {
14069                        buffer_range: hunk.buffer_range,
14070                        diff_base_byte_range: hunk.diff_base_byte_range,
14071                        secondary_status: hunk.secondary_status,
14072                        range: Point::zero()..Point::zero(), // unused
14073                    })
14074                    .collect::<Vec<_>>(),
14075                &buffer_snapshot,
14076                file_exists,
14077                cx,
14078            )
14079        });
14080        None
14081    }
14082
14083    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
14084        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14085        self.buffer
14086            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
14087    }
14088
14089    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
14090        self.buffer.update(cx, |buffer, cx| {
14091            let ranges = vec![Anchor::min()..Anchor::max()];
14092            if !buffer.all_diff_hunks_expanded()
14093                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
14094            {
14095                buffer.collapse_diff_hunks(ranges, cx);
14096                true
14097            } else {
14098                false
14099            }
14100        })
14101    }
14102
14103    fn toggle_diff_hunks_in_ranges(
14104        &mut self,
14105        ranges: Vec<Range<Anchor>>,
14106        cx: &mut Context<'_, Editor>,
14107    ) {
14108        self.buffer.update(cx, |buffer, cx| {
14109            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
14110            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
14111        })
14112    }
14113
14114    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
14115        self.buffer.update(cx, |buffer, cx| {
14116            let snapshot = buffer.snapshot(cx);
14117            let excerpt_id = range.end.excerpt_id;
14118            let point_range = range.to_point(&snapshot);
14119            let expand = !buffer.single_hunk_is_expanded(range, cx);
14120            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
14121        })
14122    }
14123
14124    pub(crate) fn apply_all_diff_hunks(
14125        &mut self,
14126        _: &ApplyAllDiffHunks,
14127        window: &mut Window,
14128        cx: &mut Context<Self>,
14129    ) {
14130        let buffers = self.buffer.read(cx).all_buffers();
14131        for branch_buffer in buffers {
14132            branch_buffer.update(cx, |branch_buffer, cx| {
14133                branch_buffer.merge_into_base(Vec::new(), cx);
14134            });
14135        }
14136
14137        if let Some(project) = self.project.clone() {
14138            self.save(true, project, window, cx).detach_and_log_err(cx);
14139        }
14140    }
14141
14142    pub(crate) fn apply_selected_diff_hunks(
14143        &mut self,
14144        _: &ApplyDiffHunk,
14145        window: &mut Window,
14146        cx: &mut Context<Self>,
14147    ) {
14148        let snapshot = self.snapshot(window, cx);
14149        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
14150        let mut ranges_by_buffer = HashMap::default();
14151        self.transact(window, cx, |editor, _window, cx| {
14152            for hunk in hunks {
14153                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
14154                    ranges_by_buffer
14155                        .entry(buffer.clone())
14156                        .or_insert_with(Vec::new)
14157                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
14158                }
14159            }
14160
14161            for (buffer, ranges) in ranges_by_buffer {
14162                buffer.update(cx, |buffer, cx| {
14163                    buffer.merge_into_base(ranges, cx);
14164                });
14165            }
14166        });
14167
14168        if let Some(project) = self.project.clone() {
14169            self.save(true, project, window, cx).detach_and_log_err(cx);
14170        }
14171    }
14172
14173    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
14174        if hovered != self.gutter_hovered {
14175            self.gutter_hovered = hovered;
14176            cx.notify();
14177        }
14178    }
14179
14180    pub fn insert_blocks(
14181        &mut self,
14182        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
14183        autoscroll: Option<Autoscroll>,
14184        cx: &mut Context<Self>,
14185    ) -> Vec<CustomBlockId> {
14186        let blocks = self
14187            .display_map
14188            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
14189        if let Some(autoscroll) = autoscroll {
14190            self.request_autoscroll(autoscroll, cx);
14191        }
14192        cx.notify();
14193        blocks
14194    }
14195
14196    pub fn resize_blocks(
14197        &mut self,
14198        heights: HashMap<CustomBlockId, u32>,
14199        autoscroll: Option<Autoscroll>,
14200        cx: &mut Context<Self>,
14201    ) {
14202        self.display_map
14203            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
14204        if let Some(autoscroll) = autoscroll {
14205            self.request_autoscroll(autoscroll, cx);
14206        }
14207        cx.notify();
14208    }
14209
14210    pub fn replace_blocks(
14211        &mut self,
14212        renderers: HashMap<CustomBlockId, RenderBlock>,
14213        autoscroll: Option<Autoscroll>,
14214        cx: &mut Context<Self>,
14215    ) {
14216        self.display_map
14217            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
14218        if let Some(autoscroll) = autoscroll {
14219            self.request_autoscroll(autoscroll, cx);
14220        }
14221        cx.notify();
14222    }
14223
14224    pub fn remove_blocks(
14225        &mut self,
14226        block_ids: HashSet<CustomBlockId>,
14227        autoscroll: Option<Autoscroll>,
14228        cx: &mut Context<Self>,
14229    ) {
14230        self.display_map.update(cx, |display_map, cx| {
14231            display_map.remove_blocks(block_ids, cx)
14232        });
14233        if let Some(autoscroll) = autoscroll {
14234            self.request_autoscroll(autoscroll, cx);
14235        }
14236        cx.notify();
14237    }
14238
14239    pub fn row_for_block(
14240        &self,
14241        block_id: CustomBlockId,
14242        cx: &mut Context<Self>,
14243    ) -> Option<DisplayRow> {
14244        self.display_map
14245            .update(cx, |map, cx| map.row_for_block(block_id, cx))
14246    }
14247
14248    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
14249        self.focused_block = Some(focused_block);
14250    }
14251
14252    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
14253        self.focused_block.take()
14254    }
14255
14256    pub fn insert_creases(
14257        &mut self,
14258        creases: impl IntoIterator<Item = Crease<Anchor>>,
14259        cx: &mut Context<Self>,
14260    ) -> Vec<CreaseId> {
14261        self.display_map
14262            .update(cx, |map, cx| map.insert_creases(creases, cx))
14263    }
14264
14265    pub fn remove_creases(
14266        &mut self,
14267        ids: impl IntoIterator<Item = CreaseId>,
14268        cx: &mut Context<Self>,
14269    ) {
14270        self.display_map
14271            .update(cx, |map, cx| map.remove_creases(ids, cx));
14272    }
14273
14274    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
14275        self.display_map
14276            .update(cx, |map, cx| map.snapshot(cx))
14277            .longest_row()
14278    }
14279
14280    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
14281        self.display_map
14282            .update(cx, |map, cx| map.snapshot(cx))
14283            .max_point()
14284    }
14285
14286    pub fn text(&self, cx: &App) -> String {
14287        self.buffer.read(cx).read(cx).text()
14288    }
14289
14290    pub fn is_empty(&self, cx: &App) -> bool {
14291        self.buffer.read(cx).read(cx).is_empty()
14292    }
14293
14294    pub fn text_option(&self, cx: &App) -> Option<String> {
14295        let text = self.text(cx);
14296        let text = text.trim();
14297
14298        if text.is_empty() {
14299            return None;
14300        }
14301
14302        Some(text.to_string())
14303    }
14304
14305    pub fn set_text(
14306        &mut self,
14307        text: impl Into<Arc<str>>,
14308        window: &mut Window,
14309        cx: &mut Context<Self>,
14310    ) {
14311        self.transact(window, cx, |this, _, cx| {
14312            this.buffer
14313                .read(cx)
14314                .as_singleton()
14315                .expect("you can only call set_text on editors for singleton buffers")
14316                .update(cx, |buffer, cx| buffer.set_text(text, cx));
14317        });
14318    }
14319
14320    pub fn display_text(&self, cx: &mut App) -> String {
14321        self.display_map
14322            .update(cx, |map, cx| map.snapshot(cx))
14323            .text()
14324    }
14325
14326    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
14327        let mut wrap_guides = smallvec::smallvec![];
14328
14329        if self.show_wrap_guides == Some(false) {
14330            return wrap_guides;
14331        }
14332
14333        let settings = self.buffer.read(cx).language_settings(cx);
14334        if settings.show_wrap_guides {
14335            match self.soft_wrap_mode(cx) {
14336                SoftWrap::Column(soft_wrap) => {
14337                    wrap_guides.push((soft_wrap as usize, true));
14338                }
14339                SoftWrap::Bounded(soft_wrap) => {
14340                    wrap_guides.push((soft_wrap as usize, true));
14341                }
14342                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
14343            }
14344            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14345        }
14346
14347        wrap_guides
14348    }
14349
14350    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14351        let settings = self.buffer.read(cx).language_settings(cx);
14352        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14353        match mode {
14354            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14355                SoftWrap::None
14356            }
14357            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14358            language_settings::SoftWrap::PreferredLineLength => {
14359                SoftWrap::Column(settings.preferred_line_length)
14360            }
14361            language_settings::SoftWrap::Bounded => {
14362                SoftWrap::Bounded(settings.preferred_line_length)
14363            }
14364        }
14365    }
14366
14367    pub fn set_soft_wrap_mode(
14368        &mut self,
14369        mode: language_settings::SoftWrap,
14370
14371        cx: &mut Context<Self>,
14372    ) {
14373        self.soft_wrap_mode_override = Some(mode);
14374        cx.notify();
14375    }
14376
14377    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
14378        self.hard_wrap = hard_wrap;
14379        cx.notify();
14380    }
14381
14382    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14383        self.text_style_refinement = Some(style);
14384    }
14385
14386    /// called by the Element so we know what style we were most recently rendered with.
14387    pub(crate) fn set_style(
14388        &mut self,
14389        style: EditorStyle,
14390        window: &mut Window,
14391        cx: &mut Context<Self>,
14392    ) {
14393        let rem_size = window.rem_size();
14394        self.display_map.update(cx, |map, cx| {
14395            map.set_font(
14396                style.text.font(),
14397                style.text.font_size.to_pixels(rem_size),
14398                cx,
14399            )
14400        });
14401        self.style = Some(style);
14402    }
14403
14404    pub fn style(&self) -> Option<&EditorStyle> {
14405        self.style.as_ref()
14406    }
14407
14408    // Called by the element. This method is not designed to be called outside of the editor
14409    // element's layout code because it does not notify when rewrapping is computed synchronously.
14410    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14411        self.display_map
14412            .update(cx, |map, cx| map.set_wrap_width(width, cx))
14413    }
14414
14415    pub fn set_soft_wrap(&mut self) {
14416        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14417    }
14418
14419    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14420        if self.soft_wrap_mode_override.is_some() {
14421            self.soft_wrap_mode_override.take();
14422        } else {
14423            let soft_wrap = match self.soft_wrap_mode(cx) {
14424                SoftWrap::GitDiff => return,
14425                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14426                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14427                    language_settings::SoftWrap::None
14428                }
14429            };
14430            self.soft_wrap_mode_override = Some(soft_wrap);
14431        }
14432        cx.notify();
14433    }
14434
14435    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14436        let Some(workspace) = self.workspace() else {
14437            return;
14438        };
14439        let fs = workspace.read(cx).app_state().fs.clone();
14440        let current_show = TabBarSettings::get_global(cx).show;
14441        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14442            setting.show = Some(!current_show);
14443        });
14444    }
14445
14446    pub fn toggle_indent_guides(
14447        &mut self,
14448        _: &ToggleIndentGuides,
14449        _: &mut Window,
14450        cx: &mut Context<Self>,
14451    ) {
14452        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14453            self.buffer
14454                .read(cx)
14455                .language_settings(cx)
14456                .indent_guides
14457                .enabled
14458        });
14459        self.show_indent_guides = Some(!currently_enabled);
14460        cx.notify();
14461    }
14462
14463    fn should_show_indent_guides(&self) -> Option<bool> {
14464        self.show_indent_guides
14465    }
14466
14467    pub fn toggle_line_numbers(
14468        &mut self,
14469        _: &ToggleLineNumbers,
14470        _: &mut Window,
14471        cx: &mut Context<Self>,
14472    ) {
14473        let mut editor_settings = EditorSettings::get_global(cx).clone();
14474        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14475        EditorSettings::override_global(editor_settings, cx);
14476    }
14477
14478    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
14479        if let Some(show_line_numbers) = self.show_line_numbers {
14480            return show_line_numbers;
14481        }
14482        EditorSettings::get_global(cx).gutter.line_numbers
14483    }
14484
14485    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14486        self.use_relative_line_numbers
14487            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14488    }
14489
14490    pub fn toggle_relative_line_numbers(
14491        &mut self,
14492        _: &ToggleRelativeLineNumbers,
14493        _: &mut Window,
14494        cx: &mut Context<Self>,
14495    ) {
14496        let is_relative = self.should_use_relative_line_numbers(cx);
14497        self.set_relative_line_number(Some(!is_relative), cx)
14498    }
14499
14500    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14501        self.use_relative_line_numbers = is_relative;
14502        cx.notify();
14503    }
14504
14505    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14506        self.show_gutter = show_gutter;
14507        cx.notify();
14508    }
14509
14510    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14511        self.show_scrollbars = show_scrollbars;
14512        cx.notify();
14513    }
14514
14515    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14516        self.show_line_numbers = Some(show_line_numbers);
14517        cx.notify();
14518    }
14519
14520    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14521        self.show_git_diff_gutter = Some(show_git_diff_gutter);
14522        cx.notify();
14523    }
14524
14525    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14526        self.show_code_actions = Some(show_code_actions);
14527        cx.notify();
14528    }
14529
14530    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14531        self.show_runnables = Some(show_runnables);
14532        cx.notify();
14533    }
14534
14535    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14536        if self.display_map.read(cx).masked != masked {
14537            self.display_map.update(cx, |map, _| map.masked = masked);
14538        }
14539        cx.notify()
14540    }
14541
14542    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14543        self.show_wrap_guides = Some(show_wrap_guides);
14544        cx.notify();
14545    }
14546
14547    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14548        self.show_indent_guides = Some(show_indent_guides);
14549        cx.notify();
14550    }
14551
14552    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14553        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14554            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14555                if let Some(dir) = file.abs_path(cx).parent() {
14556                    return Some(dir.to_owned());
14557                }
14558            }
14559
14560            if let Some(project_path) = buffer.read(cx).project_path(cx) {
14561                return Some(project_path.path.to_path_buf());
14562            }
14563        }
14564
14565        None
14566    }
14567
14568    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14569        self.active_excerpt(cx)?
14570            .1
14571            .read(cx)
14572            .file()
14573            .and_then(|f| f.as_local())
14574    }
14575
14576    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14577        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14578            let buffer = buffer.read(cx);
14579            if let Some(project_path) = buffer.project_path(cx) {
14580                let project = self.project.as_ref()?.read(cx);
14581                project.absolute_path(&project_path, cx)
14582            } else {
14583                buffer
14584                    .file()
14585                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14586            }
14587        })
14588    }
14589
14590    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14591        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14592            let project_path = buffer.read(cx).project_path(cx)?;
14593            let project = self.project.as_ref()?.read(cx);
14594            let entry = project.entry_for_path(&project_path, cx)?;
14595            let path = entry.path.to_path_buf();
14596            Some(path)
14597        })
14598    }
14599
14600    pub fn reveal_in_finder(
14601        &mut self,
14602        _: &RevealInFileManager,
14603        _window: &mut Window,
14604        cx: &mut Context<Self>,
14605    ) {
14606        if let Some(target) = self.target_file(cx) {
14607            cx.reveal_path(&target.abs_path(cx));
14608        }
14609    }
14610
14611    pub fn copy_path(
14612        &mut self,
14613        _: &zed_actions::workspace::CopyPath,
14614        _window: &mut Window,
14615        cx: &mut Context<Self>,
14616    ) {
14617        if let Some(path) = self.target_file_abs_path(cx) {
14618            if let Some(path) = path.to_str() {
14619                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14620            }
14621        }
14622    }
14623
14624    pub fn copy_relative_path(
14625        &mut self,
14626        _: &zed_actions::workspace::CopyRelativePath,
14627        _window: &mut Window,
14628        cx: &mut Context<Self>,
14629    ) {
14630        if let Some(path) = self.target_file_path(cx) {
14631            if let Some(path) = path.to_str() {
14632                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14633            }
14634        }
14635    }
14636
14637    pub fn copy_file_name_without_extension(
14638        &mut self,
14639        _: &CopyFileNameWithoutExtension,
14640        _: &mut Window,
14641        cx: &mut Context<Self>,
14642    ) {
14643        if let Some(file) = self.target_file(cx) {
14644            if let Some(file_stem) = file.path().file_stem() {
14645                if let Some(name) = file_stem.to_str() {
14646                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14647                }
14648            }
14649        }
14650    }
14651
14652    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14653        if let Some(file) = self.target_file(cx) {
14654            if let Some(file_name) = file.path().file_name() {
14655                if let Some(name) = file_name.to_str() {
14656                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14657                }
14658            }
14659        }
14660    }
14661
14662    pub fn toggle_git_blame(
14663        &mut self,
14664        _: &::git::Blame,
14665        window: &mut Window,
14666        cx: &mut Context<Self>,
14667    ) {
14668        self.show_git_blame_gutter = !self.show_git_blame_gutter;
14669
14670        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14671            self.start_git_blame(true, window, cx);
14672        }
14673
14674        cx.notify();
14675    }
14676
14677    pub fn toggle_git_blame_inline(
14678        &mut self,
14679        _: &ToggleGitBlameInline,
14680        window: &mut Window,
14681        cx: &mut Context<Self>,
14682    ) {
14683        self.toggle_git_blame_inline_internal(true, window, cx);
14684        cx.notify();
14685    }
14686
14687    pub fn git_blame_inline_enabled(&self) -> bool {
14688        self.git_blame_inline_enabled
14689    }
14690
14691    pub fn toggle_selection_menu(
14692        &mut self,
14693        _: &ToggleSelectionMenu,
14694        _: &mut Window,
14695        cx: &mut Context<Self>,
14696    ) {
14697        self.show_selection_menu = self
14698            .show_selection_menu
14699            .map(|show_selections_menu| !show_selections_menu)
14700            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14701
14702        cx.notify();
14703    }
14704
14705    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14706        self.show_selection_menu
14707            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14708    }
14709
14710    fn start_git_blame(
14711        &mut self,
14712        user_triggered: bool,
14713        window: &mut Window,
14714        cx: &mut Context<Self>,
14715    ) {
14716        if let Some(project) = self.project.as_ref() {
14717            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14718                return;
14719            };
14720
14721            if buffer.read(cx).file().is_none() {
14722                return;
14723            }
14724
14725            let focused = self.focus_handle(cx).contains_focused(window, cx);
14726
14727            let project = project.clone();
14728            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14729            self.blame_subscription =
14730                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14731            self.blame = Some(blame);
14732        }
14733    }
14734
14735    fn toggle_git_blame_inline_internal(
14736        &mut self,
14737        user_triggered: bool,
14738        window: &mut Window,
14739        cx: &mut Context<Self>,
14740    ) {
14741        if self.git_blame_inline_enabled {
14742            self.git_blame_inline_enabled = false;
14743            self.show_git_blame_inline = false;
14744            self.show_git_blame_inline_delay_task.take();
14745        } else {
14746            self.git_blame_inline_enabled = true;
14747            self.start_git_blame_inline(user_triggered, window, cx);
14748        }
14749
14750        cx.notify();
14751    }
14752
14753    fn start_git_blame_inline(
14754        &mut self,
14755        user_triggered: bool,
14756        window: &mut Window,
14757        cx: &mut Context<Self>,
14758    ) {
14759        self.start_git_blame(user_triggered, window, cx);
14760
14761        if ProjectSettings::get_global(cx)
14762            .git
14763            .inline_blame_delay()
14764            .is_some()
14765        {
14766            self.start_inline_blame_timer(window, cx);
14767        } else {
14768            self.show_git_blame_inline = true
14769        }
14770    }
14771
14772    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14773        self.blame.as_ref()
14774    }
14775
14776    pub fn show_git_blame_gutter(&self) -> bool {
14777        self.show_git_blame_gutter
14778    }
14779
14780    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14781        self.show_git_blame_gutter && self.has_blame_entries(cx)
14782    }
14783
14784    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14785        self.show_git_blame_inline
14786            && (self.focus_handle.is_focused(window)
14787                || self
14788                    .git_blame_inline_tooltip
14789                    .as_ref()
14790                    .and_then(|t| t.upgrade())
14791                    .is_some())
14792            && !self.newest_selection_head_on_empty_line(cx)
14793            && self.has_blame_entries(cx)
14794    }
14795
14796    fn has_blame_entries(&self, cx: &App) -> bool {
14797        self.blame()
14798            .map_or(false, |blame| blame.read(cx).has_generated_entries())
14799    }
14800
14801    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14802        let cursor_anchor = self.selections.newest_anchor().head();
14803
14804        let snapshot = self.buffer.read(cx).snapshot(cx);
14805        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14806
14807        snapshot.line_len(buffer_row) == 0
14808    }
14809
14810    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14811        let buffer_and_selection = maybe!({
14812            let selection = self.selections.newest::<Point>(cx);
14813            let selection_range = selection.range();
14814
14815            let multi_buffer = self.buffer().read(cx);
14816            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14817            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14818
14819            let (buffer, range, _) = if selection.reversed {
14820                buffer_ranges.first()
14821            } else {
14822                buffer_ranges.last()
14823            }?;
14824
14825            let selection = text::ToPoint::to_point(&range.start, &buffer).row
14826                ..text::ToPoint::to_point(&range.end, &buffer).row;
14827            Some((
14828                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14829                selection,
14830            ))
14831        });
14832
14833        let Some((buffer, selection)) = buffer_and_selection else {
14834            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14835        };
14836
14837        let Some(project) = self.project.as_ref() else {
14838            return Task::ready(Err(anyhow!("editor does not have project")));
14839        };
14840
14841        project.update(cx, |project, cx| {
14842            project.get_permalink_to_line(&buffer, selection, cx)
14843        })
14844    }
14845
14846    pub fn copy_permalink_to_line(
14847        &mut self,
14848        _: &CopyPermalinkToLine,
14849        window: &mut Window,
14850        cx: &mut Context<Self>,
14851    ) {
14852        let permalink_task = self.get_permalink_to_line(cx);
14853        let workspace = self.workspace();
14854
14855        cx.spawn_in(window, |_, mut cx| async move {
14856            match permalink_task.await {
14857                Ok(permalink) => {
14858                    cx.update(|_, cx| {
14859                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14860                    })
14861                    .ok();
14862                }
14863                Err(err) => {
14864                    let message = format!("Failed to copy permalink: {err}");
14865
14866                    Err::<(), anyhow::Error>(err).log_err();
14867
14868                    if let Some(workspace) = workspace {
14869                        workspace
14870                            .update_in(&mut cx, |workspace, _, cx| {
14871                                struct CopyPermalinkToLine;
14872
14873                                workspace.show_toast(
14874                                    Toast::new(
14875                                        NotificationId::unique::<CopyPermalinkToLine>(),
14876                                        message,
14877                                    ),
14878                                    cx,
14879                                )
14880                            })
14881                            .ok();
14882                    }
14883                }
14884            }
14885        })
14886        .detach();
14887    }
14888
14889    pub fn copy_file_location(
14890        &mut self,
14891        _: &CopyFileLocation,
14892        _: &mut Window,
14893        cx: &mut Context<Self>,
14894    ) {
14895        let selection = self.selections.newest::<Point>(cx).start.row + 1;
14896        if let Some(file) = self.target_file(cx) {
14897            if let Some(path) = file.path().to_str() {
14898                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14899            }
14900        }
14901    }
14902
14903    pub fn open_permalink_to_line(
14904        &mut self,
14905        _: &OpenPermalinkToLine,
14906        window: &mut Window,
14907        cx: &mut Context<Self>,
14908    ) {
14909        let permalink_task = self.get_permalink_to_line(cx);
14910        let workspace = self.workspace();
14911
14912        cx.spawn_in(window, |_, mut cx| async move {
14913            match permalink_task.await {
14914                Ok(permalink) => {
14915                    cx.update(|_, cx| {
14916                        cx.open_url(permalink.as_ref());
14917                    })
14918                    .ok();
14919                }
14920                Err(err) => {
14921                    let message = format!("Failed to open permalink: {err}");
14922
14923                    Err::<(), anyhow::Error>(err).log_err();
14924
14925                    if let Some(workspace) = workspace {
14926                        workspace
14927                            .update(&mut cx, |workspace, cx| {
14928                                struct OpenPermalinkToLine;
14929
14930                                workspace.show_toast(
14931                                    Toast::new(
14932                                        NotificationId::unique::<OpenPermalinkToLine>(),
14933                                        message,
14934                                    ),
14935                                    cx,
14936                                )
14937                            })
14938                            .ok();
14939                    }
14940                }
14941            }
14942        })
14943        .detach();
14944    }
14945
14946    pub fn insert_uuid_v4(
14947        &mut self,
14948        _: &InsertUuidV4,
14949        window: &mut Window,
14950        cx: &mut Context<Self>,
14951    ) {
14952        self.insert_uuid(UuidVersion::V4, window, cx);
14953    }
14954
14955    pub fn insert_uuid_v7(
14956        &mut self,
14957        _: &InsertUuidV7,
14958        window: &mut Window,
14959        cx: &mut Context<Self>,
14960    ) {
14961        self.insert_uuid(UuidVersion::V7, window, cx);
14962    }
14963
14964    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14965        self.transact(window, cx, |this, window, cx| {
14966            let edits = this
14967                .selections
14968                .all::<Point>(cx)
14969                .into_iter()
14970                .map(|selection| {
14971                    let uuid = match version {
14972                        UuidVersion::V4 => uuid::Uuid::new_v4(),
14973                        UuidVersion::V7 => uuid::Uuid::now_v7(),
14974                    };
14975
14976                    (selection.range(), uuid.to_string())
14977                });
14978            this.edit(edits, cx);
14979            this.refresh_inline_completion(true, false, window, cx);
14980        });
14981    }
14982
14983    pub fn open_selections_in_multibuffer(
14984        &mut self,
14985        _: &OpenSelectionsInMultibuffer,
14986        window: &mut Window,
14987        cx: &mut Context<Self>,
14988    ) {
14989        let multibuffer = self.buffer.read(cx);
14990
14991        let Some(buffer) = multibuffer.as_singleton() else {
14992            return;
14993        };
14994
14995        let Some(workspace) = self.workspace() else {
14996            return;
14997        };
14998
14999        let locations = self
15000            .selections
15001            .disjoint_anchors()
15002            .iter()
15003            .map(|range| Location {
15004                buffer: buffer.clone(),
15005                range: range.start.text_anchor..range.end.text_anchor,
15006            })
15007            .collect::<Vec<_>>();
15008
15009        let title = multibuffer.title(cx).to_string();
15010
15011        cx.spawn_in(window, |_, mut cx| async move {
15012            workspace.update_in(&mut cx, |workspace, window, cx| {
15013                Self::open_locations_in_multibuffer(
15014                    workspace,
15015                    locations,
15016                    format!("Selections for '{title}'"),
15017                    false,
15018                    MultibufferSelectionMode::All,
15019                    window,
15020                    cx,
15021                );
15022            })
15023        })
15024        .detach();
15025    }
15026
15027    /// Adds a row highlight for the given range. If a row has multiple highlights, the
15028    /// last highlight added will be used.
15029    ///
15030    /// If the range ends at the beginning of a line, then that line will not be highlighted.
15031    pub fn highlight_rows<T: 'static>(
15032        &mut self,
15033        range: Range<Anchor>,
15034        color: Hsla,
15035        should_autoscroll: bool,
15036        cx: &mut Context<Self>,
15037    ) {
15038        let snapshot = self.buffer().read(cx).snapshot(cx);
15039        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15040        let ix = row_highlights.binary_search_by(|highlight| {
15041            Ordering::Equal
15042                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
15043                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
15044        });
15045
15046        if let Err(mut ix) = ix {
15047            let index = post_inc(&mut self.highlight_order);
15048
15049            // If this range intersects with the preceding highlight, then merge it with
15050            // the preceding highlight. Otherwise insert a new highlight.
15051            let mut merged = false;
15052            if ix > 0 {
15053                let prev_highlight = &mut row_highlights[ix - 1];
15054                if prev_highlight
15055                    .range
15056                    .end
15057                    .cmp(&range.start, &snapshot)
15058                    .is_ge()
15059                {
15060                    ix -= 1;
15061                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
15062                        prev_highlight.range.end = range.end;
15063                    }
15064                    merged = true;
15065                    prev_highlight.index = index;
15066                    prev_highlight.color = color;
15067                    prev_highlight.should_autoscroll = should_autoscroll;
15068                }
15069            }
15070
15071            if !merged {
15072                row_highlights.insert(
15073                    ix,
15074                    RowHighlight {
15075                        range: range.clone(),
15076                        index,
15077                        color,
15078                        should_autoscroll,
15079                    },
15080                );
15081            }
15082
15083            // If any of the following highlights intersect with this one, merge them.
15084            while let Some(next_highlight) = row_highlights.get(ix + 1) {
15085                let highlight = &row_highlights[ix];
15086                if next_highlight
15087                    .range
15088                    .start
15089                    .cmp(&highlight.range.end, &snapshot)
15090                    .is_le()
15091                {
15092                    if next_highlight
15093                        .range
15094                        .end
15095                        .cmp(&highlight.range.end, &snapshot)
15096                        .is_gt()
15097                    {
15098                        row_highlights[ix].range.end = next_highlight.range.end;
15099                    }
15100                    row_highlights.remove(ix + 1);
15101                } else {
15102                    break;
15103                }
15104            }
15105        }
15106    }
15107
15108    /// Remove any highlighted row ranges of the given type that intersect the
15109    /// given ranges.
15110    pub fn remove_highlighted_rows<T: 'static>(
15111        &mut self,
15112        ranges_to_remove: Vec<Range<Anchor>>,
15113        cx: &mut Context<Self>,
15114    ) {
15115        let snapshot = self.buffer().read(cx).snapshot(cx);
15116        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15117        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
15118        row_highlights.retain(|highlight| {
15119            while let Some(range_to_remove) = ranges_to_remove.peek() {
15120                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
15121                    Ordering::Less | Ordering::Equal => {
15122                        ranges_to_remove.next();
15123                    }
15124                    Ordering::Greater => {
15125                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
15126                            Ordering::Less | Ordering::Equal => {
15127                                return false;
15128                            }
15129                            Ordering::Greater => break,
15130                        }
15131                    }
15132                }
15133            }
15134
15135            true
15136        })
15137    }
15138
15139    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
15140    pub fn clear_row_highlights<T: 'static>(&mut self) {
15141        self.highlighted_rows.remove(&TypeId::of::<T>());
15142    }
15143
15144    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
15145    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
15146        self.highlighted_rows
15147            .get(&TypeId::of::<T>())
15148            .map_or(&[] as &[_], |vec| vec.as_slice())
15149            .iter()
15150            .map(|highlight| (highlight.range.clone(), highlight.color))
15151    }
15152
15153    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
15154    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
15155    /// Allows to ignore certain kinds of highlights.
15156    pub fn highlighted_display_rows(
15157        &self,
15158        window: &mut Window,
15159        cx: &mut App,
15160    ) -> BTreeMap<DisplayRow, LineHighlight> {
15161        let snapshot = self.snapshot(window, cx);
15162        let mut used_highlight_orders = HashMap::default();
15163        self.highlighted_rows
15164            .iter()
15165            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
15166            .fold(
15167                BTreeMap::<DisplayRow, LineHighlight>::new(),
15168                |mut unique_rows, highlight| {
15169                    let start = highlight.range.start.to_display_point(&snapshot);
15170                    let end = highlight.range.end.to_display_point(&snapshot);
15171                    let start_row = start.row().0;
15172                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
15173                        && end.column() == 0
15174                    {
15175                        end.row().0.saturating_sub(1)
15176                    } else {
15177                        end.row().0
15178                    };
15179                    for row in start_row..=end_row {
15180                        let used_index =
15181                            used_highlight_orders.entry(row).or_insert(highlight.index);
15182                        if highlight.index >= *used_index {
15183                            *used_index = highlight.index;
15184                            unique_rows.insert(DisplayRow(row), highlight.color.into());
15185                        }
15186                    }
15187                    unique_rows
15188                },
15189            )
15190    }
15191
15192    pub fn highlighted_display_row_for_autoscroll(
15193        &self,
15194        snapshot: &DisplaySnapshot,
15195    ) -> Option<DisplayRow> {
15196        self.highlighted_rows
15197            .values()
15198            .flat_map(|highlighted_rows| highlighted_rows.iter())
15199            .filter_map(|highlight| {
15200                if highlight.should_autoscroll {
15201                    Some(highlight.range.start.to_display_point(snapshot).row())
15202                } else {
15203                    None
15204                }
15205            })
15206            .min()
15207    }
15208
15209    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
15210        self.highlight_background::<SearchWithinRange>(
15211            ranges,
15212            |colors| colors.editor_document_highlight_read_background,
15213            cx,
15214        )
15215    }
15216
15217    pub fn set_breadcrumb_header(&mut self, new_header: String) {
15218        self.breadcrumb_header = Some(new_header);
15219    }
15220
15221    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
15222        self.clear_background_highlights::<SearchWithinRange>(cx);
15223    }
15224
15225    pub fn highlight_background<T: 'static>(
15226        &mut self,
15227        ranges: &[Range<Anchor>],
15228        color_fetcher: fn(&ThemeColors) -> Hsla,
15229        cx: &mut Context<Self>,
15230    ) {
15231        self.background_highlights
15232            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15233        self.scrollbar_marker_state.dirty = true;
15234        cx.notify();
15235    }
15236
15237    pub fn clear_background_highlights<T: 'static>(
15238        &mut self,
15239        cx: &mut Context<Self>,
15240    ) -> Option<BackgroundHighlight> {
15241        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
15242        if !text_highlights.1.is_empty() {
15243            self.scrollbar_marker_state.dirty = true;
15244            cx.notify();
15245        }
15246        Some(text_highlights)
15247    }
15248
15249    pub fn highlight_gutter<T: 'static>(
15250        &mut self,
15251        ranges: &[Range<Anchor>],
15252        color_fetcher: fn(&App) -> Hsla,
15253        cx: &mut Context<Self>,
15254    ) {
15255        self.gutter_highlights
15256            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15257        cx.notify();
15258    }
15259
15260    pub fn clear_gutter_highlights<T: 'static>(
15261        &mut self,
15262        cx: &mut Context<Self>,
15263    ) -> Option<GutterHighlight> {
15264        cx.notify();
15265        self.gutter_highlights.remove(&TypeId::of::<T>())
15266    }
15267
15268    #[cfg(feature = "test-support")]
15269    pub fn all_text_background_highlights(
15270        &self,
15271        window: &mut Window,
15272        cx: &mut Context<Self>,
15273    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15274        let snapshot = self.snapshot(window, cx);
15275        let buffer = &snapshot.buffer_snapshot;
15276        let start = buffer.anchor_before(0);
15277        let end = buffer.anchor_after(buffer.len());
15278        let theme = cx.theme().colors();
15279        self.background_highlights_in_range(start..end, &snapshot, theme)
15280    }
15281
15282    #[cfg(feature = "test-support")]
15283    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
15284        let snapshot = self.buffer().read(cx).snapshot(cx);
15285
15286        let highlights = self
15287            .background_highlights
15288            .get(&TypeId::of::<items::BufferSearchHighlights>());
15289
15290        if let Some((_color, ranges)) = highlights {
15291            ranges
15292                .iter()
15293                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
15294                .collect_vec()
15295        } else {
15296            vec![]
15297        }
15298    }
15299
15300    fn document_highlights_for_position<'a>(
15301        &'a self,
15302        position: Anchor,
15303        buffer: &'a MultiBufferSnapshot,
15304    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
15305        let read_highlights = self
15306            .background_highlights
15307            .get(&TypeId::of::<DocumentHighlightRead>())
15308            .map(|h| &h.1);
15309        let write_highlights = self
15310            .background_highlights
15311            .get(&TypeId::of::<DocumentHighlightWrite>())
15312            .map(|h| &h.1);
15313        let left_position = position.bias_left(buffer);
15314        let right_position = position.bias_right(buffer);
15315        read_highlights
15316            .into_iter()
15317            .chain(write_highlights)
15318            .flat_map(move |ranges| {
15319                let start_ix = match ranges.binary_search_by(|probe| {
15320                    let cmp = probe.end.cmp(&left_position, buffer);
15321                    if cmp.is_ge() {
15322                        Ordering::Greater
15323                    } else {
15324                        Ordering::Less
15325                    }
15326                }) {
15327                    Ok(i) | Err(i) => i,
15328                };
15329
15330                ranges[start_ix..]
15331                    .iter()
15332                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
15333            })
15334    }
15335
15336    pub fn has_background_highlights<T: 'static>(&self) -> bool {
15337        self.background_highlights
15338            .get(&TypeId::of::<T>())
15339            .map_or(false, |(_, highlights)| !highlights.is_empty())
15340    }
15341
15342    pub fn background_highlights_in_range(
15343        &self,
15344        search_range: Range<Anchor>,
15345        display_snapshot: &DisplaySnapshot,
15346        theme: &ThemeColors,
15347    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15348        let mut results = Vec::new();
15349        for (color_fetcher, ranges) in self.background_highlights.values() {
15350            let color = color_fetcher(theme);
15351            let start_ix = match ranges.binary_search_by(|probe| {
15352                let cmp = probe
15353                    .end
15354                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15355                if cmp.is_gt() {
15356                    Ordering::Greater
15357                } else {
15358                    Ordering::Less
15359                }
15360            }) {
15361                Ok(i) | Err(i) => i,
15362            };
15363            for range in &ranges[start_ix..] {
15364                if range
15365                    .start
15366                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15367                    .is_ge()
15368                {
15369                    break;
15370                }
15371
15372                let start = range.start.to_display_point(display_snapshot);
15373                let end = range.end.to_display_point(display_snapshot);
15374                results.push((start..end, color))
15375            }
15376        }
15377        results
15378    }
15379
15380    pub fn background_highlight_row_ranges<T: 'static>(
15381        &self,
15382        search_range: Range<Anchor>,
15383        display_snapshot: &DisplaySnapshot,
15384        count: usize,
15385    ) -> Vec<RangeInclusive<DisplayPoint>> {
15386        let mut results = Vec::new();
15387        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15388            return vec![];
15389        };
15390
15391        let start_ix = match ranges.binary_search_by(|probe| {
15392            let cmp = probe
15393                .end
15394                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15395            if cmp.is_gt() {
15396                Ordering::Greater
15397            } else {
15398                Ordering::Less
15399            }
15400        }) {
15401            Ok(i) | Err(i) => i,
15402        };
15403        let mut push_region = |start: Option<Point>, end: Option<Point>| {
15404            if let (Some(start_display), Some(end_display)) = (start, end) {
15405                results.push(
15406                    start_display.to_display_point(display_snapshot)
15407                        ..=end_display.to_display_point(display_snapshot),
15408                );
15409            }
15410        };
15411        let mut start_row: Option<Point> = None;
15412        let mut end_row: Option<Point> = None;
15413        if ranges.len() > count {
15414            return Vec::new();
15415        }
15416        for range in &ranges[start_ix..] {
15417            if range
15418                .start
15419                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15420                .is_ge()
15421            {
15422                break;
15423            }
15424            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15425            if let Some(current_row) = &end_row {
15426                if end.row == current_row.row {
15427                    continue;
15428                }
15429            }
15430            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15431            if start_row.is_none() {
15432                assert_eq!(end_row, None);
15433                start_row = Some(start);
15434                end_row = Some(end);
15435                continue;
15436            }
15437            if let Some(current_end) = end_row.as_mut() {
15438                if start.row > current_end.row + 1 {
15439                    push_region(start_row, end_row);
15440                    start_row = Some(start);
15441                    end_row = Some(end);
15442                } else {
15443                    // Merge two hunks.
15444                    *current_end = end;
15445                }
15446            } else {
15447                unreachable!();
15448            }
15449        }
15450        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15451        push_region(start_row, end_row);
15452        results
15453    }
15454
15455    pub fn gutter_highlights_in_range(
15456        &self,
15457        search_range: Range<Anchor>,
15458        display_snapshot: &DisplaySnapshot,
15459        cx: &App,
15460    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15461        let mut results = Vec::new();
15462        for (color_fetcher, ranges) in self.gutter_highlights.values() {
15463            let color = color_fetcher(cx);
15464            let start_ix = match ranges.binary_search_by(|probe| {
15465                let cmp = probe
15466                    .end
15467                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15468                if cmp.is_gt() {
15469                    Ordering::Greater
15470                } else {
15471                    Ordering::Less
15472                }
15473            }) {
15474                Ok(i) | Err(i) => i,
15475            };
15476            for range in &ranges[start_ix..] {
15477                if range
15478                    .start
15479                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15480                    .is_ge()
15481                {
15482                    break;
15483                }
15484
15485                let start = range.start.to_display_point(display_snapshot);
15486                let end = range.end.to_display_point(display_snapshot);
15487                results.push((start..end, color))
15488            }
15489        }
15490        results
15491    }
15492
15493    /// Get the text ranges corresponding to the redaction query
15494    pub fn redacted_ranges(
15495        &self,
15496        search_range: Range<Anchor>,
15497        display_snapshot: &DisplaySnapshot,
15498        cx: &App,
15499    ) -> Vec<Range<DisplayPoint>> {
15500        display_snapshot
15501            .buffer_snapshot
15502            .redacted_ranges(search_range, |file| {
15503                if let Some(file) = file {
15504                    file.is_private()
15505                        && EditorSettings::get(
15506                            Some(SettingsLocation {
15507                                worktree_id: file.worktree_id(cx),
15508                                path: file.path().as_ref(),
15509                            }),
15510                            cx,
15511                        )
15512                        .redact_private_values
15513                } else {
15514                    false
15515                }
15516            })
15517            .map(|range| {
15518                range.start.to_display_point(display_snapshot)
15519                    ..range.end.to_display_point(display_snapshot)
15520            })
15521            .collect()
15522    }
15523
15524    pub fn highlight_text<T: 'static>(
15525        &mut self,
15526        ranges: Vec<Range<Anchor>>,
15527        style: HighlightStyle,
15528        cx: &mut Context<Self>,
15529    ) {
15530        self.display_map.update(cx, |map, _| {
15531            map.highlight_text(TypeId::of::<T>(), ranges, style)
15532        });
15533        cx.notify();
15534    }
15535
15536    pub(crate) fn highlight_inlays<T: 'static>(
15537        &mut self,
15538        highlights: Vec<InlayHighlight>,
15539        style: HighlightStyle,
15540        cx: &mut Context<Self>,
15541    ) {
15542        self.display_map.update(cx, |map, _| {
15543            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15544        });
15545        cx.notify();
15546    }
15547
15548    pub fn text_highlights<'a, T: 'static>(
15549        &'a self,
15550        cx: &'a App,
15551    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15552        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15553    }
15554
15555    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15556        let cleared = self
15557            .display_map
15558            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15559        if cleared {
15560            cx.notify();
15561        }
15562    }
15563
15564    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15565        (self.read_only(cx) || self.blink_manager.read(cx).visible())
15566            && self.focus_handle.is_focused(window)
15567    }
15568
15569    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15570        self.show_cursor_when_unfocused = is_enabled;
15571        cx.notify();
15572    }
15573
15574    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15575        cx.notify();
15576    }
15577
15578    fn on_buffer_event(
15579        &mut self,
15580        multibuffer: &Entity<MultiBuffer>,
15581        event: &multi_buffer::Event,
15582        window: &mut Window,
15583        cx: &mut Context<Self>,
15584    ) {
15585        match event {
15586            multi_buffer::Event::Edited {
15587                singleton_buffer_edited,
15588                edited_buffer: buffer_edited,
15589            } => {
15590                self.scrollbar_marker_state.dirty = true;
15591                self.active_indent_guides_state.dirty = true;
15592                self.refresh_active_diagnostics(cx);
15593                self.refresh_code_actions(window, cx);
15594                if self.has_active_inline_completion() {
15595                    self.update_visible_inline_completion(window, cx);
15596                }
15597                if let Some(buffer) = buffer_edited {
15598                    let buffer_id = buffer.read(cx).remote_id();
15599                    if !self.registered_buffers.contains_key(&buffer_id) {
15600                        if let Some(project) = self.project.as_ref() {
15601                            project.update(cx, |project, cx| {
15602                                self.registered_buffers.insert(
15603                                    buffer_id,
15604                                    project.register_buffer_with_language_servers(&buffer, cx),
15605                                );
15606                            })
15607                        }
15608                    }
15609                }
15610                cx.emit(EditorEvent::BufferEdited);
15611                cx.emit(SearchEvent::MatchesInvalidated);
15612                if *singleton_buffer_edited {
15613                    if let Some(project) = &self.project {
15614                        #[allow(clippy::mutable_key_type)]
15615                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15616                            multibuffer
15617                                .all_buffers()
15618                                .into_iter()
15619                                .filter_map(|buffer| {
15620                                    buffer.update(cx, |buffer, cx| {
15621                                        let language = buffer.language()?;
15622                                        let should_discard = project.update(cx, |project, cx| {
15623                                            project.is_local()
15624                                                && !project.has_language_servers_for(buffer, cx)
15625                                        });
15626                                        should_discard.not().then_some(language.clone())
15627                                    })
15628                                })
15629                                .collect::<HashSet<_>>()
15630                        });
15631                        if !languages_affected.is_empty() {
15632                            self.refresh_inlay_hints(
15633                                InlayHintRefreshReason::BufferEdited(languages_affected),
15634                                cx,
15635                            );
15636                        }
15637                    }
15638                }
15639
15640                let Some(project) = &self.project else { return };
15641                let (telemetry, is_via_ssh) = {
15642                    let project = project.read(cx);
15643                    let telemetry = project.client().telemetry().clone();
15644                    let is_via_ssh = project.is_via_ssh();
15645                    (telemetry, is_via_ssh)
15646                };
15647                refresh_linked_ranges(self, window, cx);
15648                telemetry.log_edit_event("editor", is_via_ssh);
15649            }
15650            multi_buffer::Event::ExcerptsAdded {
15651                buffer,
15652                predecessor,
15653                excerpts,
15654            } => {
15655                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15656                let buffer_id = buffer.read(cx).remote_id();
15657                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15658                    if let Some(project) = &self.project {
15659                        get_uncommitted_diff_for_buffer(
15660                            project,
15661                            [buffer.clone()],
15662                            self.buffer.clone(),
15663                            cx,
15664                        )
15665                        .detach();
15666                    }
15667                }
15668                cx.emit(EditorEvent::ExcerptsAdded {
15669                    buffer: buffer.clone(),
15670                    predecessor: *predecessor,
15671                    excerpts: excerpts.clone(),
15672                });
15673                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15674            }
15675            multi_buffer::Event::ExcerptsRemoved { ids } => {
15676                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15677                let buffer = self.buffer.read(cx);
15678                self.registered_buffers
15679                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15680                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15681                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15682            }
15683            multi_buffer::Event::ExcerptsEdited {
15684                excerpt_ids,
15685                buffer_ids,
15686            } => {
15687                self.display_map.update(cx, |map, cx| {
15688                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
15689                });
15690                cx.emit(EditorEvent::ExcerptsEdited {
15691                    ids: excerpt_ids.clone(),
15692                })
15693            }
15694            multi_buffer::Event::ExcerptsExpanded { ids } => {
15695                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15696                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15697            }
15698            multi_buffer::Event::Reparsed(buffer_id) => {
15699                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15700                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15701
15702                cx.emit(EditorEvent::Reparsed(*buffer_id));
15703            }
15704            multi_buffer::Event::DiffHunksToggled => {
15705                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15706            }
15707            multi_buffer::Event::LanguageChanged(buffer_id) => {
15708                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15709                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15710                cx.emit(EditorEvent::Reparsed(*buffer_id));
15711                cx.notify();
15712            }
15713            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15714            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15715            multi_buffer::Event::FileHandleChanged
15716            | multi_buffer::Event::Reloaded
15717            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
15718            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15719            multi_buffer::Event::DiagnosticsUpdated => {
15720                self.refresh_active_diagnostics(cx);
15721                self.refresh_inline_diagnostics(true, window, cx);
15722                self.scrollbar_marker_state.dirty = true;
15723                cx.notify();
15724            }
15725            _ => {}
15726        };
15727    }
15728
15729    fn on_display_map_changed(
15730        &mut self,
15731        _: Entity<DisplayMap>,
15732        _: &mut Window,
15733        cx: &mut Context<Self>,
15734    ) {
15735        cx.notify();
15736    }
15737
15738    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15739        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15740        self.update_edit_prediction_settings(cx);
15741        self.refresh_inline_completion(true, false, window, cx);
15742        self.refresh_inlay_hints(
15743            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15744                self.selections.newest_anchor().head(),
15745                &self.buffer.read(cx).snapshot(cx),
15746                cx,
15747            )),
15748            cx,
15749        );
15750
15751        let old_cursor_shape = self.cursor_shape;
15752
15753        {
15754            let editor_settings = EditorSettings::get_global(cx);
15755            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15756            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15757            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15758        }
15759
15760        if old_cursor_shape != self.cursor_shape {
15761            cx.emit(EditorEvent::CursorShapeChanged);
15762        }
15763
15764        let project_settings = ProjectSettings::get_global(cx);
15765        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15766
15767        if self.mode == EditorMode::Full {
15768            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15769            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15770            if self.show_inline_diagnostics != show_inline_diagnostics {
15771                self.show_inline_diagnostics = show_inline_diagnostics;
15772                self.refresh_inline_diagnostics(false, window, cx);
15773            }
15774
15775            if self.git_blame_inline_enabled != inline_blame_enabled {
15776                self.toggle_git_blame_inline_internal(false, window, cx);
15777            }
15778        }
15779
15780        cx.notify();
15781    }
15782
15783    pub fn set_searchable(&mut self, searchable: bool) {
15784        self.searchable = searchable;
15785    }
15786
15787    pub fn searchable(&self) -> bool {
15788        self.searchable
15789    }
15790
15791    fn open_proposed_changes_editor(
15792        &mut self,
15793        _: &OpenProposedChangesEditor,
15794        window: &mut Window,
15795        cx: &mut Context<Self>,
15796    ) {
15797        let Some(workspace) = self.workspace() else {
15798            cx.propagate();
15799            return;
15800        };
15801
15802        let selections = self.selections.all::<usize>(cx);
15803        let multi_buffer = self.buffer.read(cx);
15804        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15805        let mut new_selections_by_buffer = HashMap::default();
15806        for selection in selections {
15807            for (buffer, range, _) in
15808                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15809            {
15810                let mut range = range.to_point(buffer);
15811                range.start.column = 0;
15812                range.end.column = buffer.line_len(range.end.row);
15813                new_selections_by_buffer
15814                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15815                    .or_insert(Vec::new())
15816                    .push(range)
15817            }
15818        }
15819
15820        let proposed_changes_buffers = new_selections_by_buffer
15821            .into_iter()
15822            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15823            .collect::<Vec<_>>();
15824        let proposed_changes_editor = cx.new(|cx| {
15825            ProposedChangesEditor::new(
15826                "Proposed changes",
15827                proposed_changes_buffers,
15828                self.project.clone(),
15829                window,
15830                cx,
15831            )
15832        });
15833
15834        window.defer(cx, move |window, cx| {
15835            workspace.update(cx, |workspace, cx| {
15836                workspace.active_pane().update(cx, |pane, cx| {
15837                    pane.add_item(
15838                        Box::new(proposed_changes_editor),
15839                        true,
15840                        true,
15841                        None,
15842                        window,
15843                        cx,
15844                    );
15845                });
15846            });
15847        });
15848    }
15849
15850    pub fn open_excerpts_in_split(
15851        &mut self,
15852        _: &OpenExcerptsSplit,
15853        window: &mut Window,
15854        cx: &mut Context<Self>,
15855    ) {
15856        self.open_excerpts_common(None, true, window, cx)
15857    }
15858
15859    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15860        self.open_excerpts_common(None, false, window, cx)
15861    }
15862
15863    fn open_excerpts_common(
15864        &mut self,
15865        jump_data: Option<JumpData>,
15866        split: bool,
15867        window: &mut Window,
15868        cx: &mut Context<Self>,
15869    ) {
15870        let Some(workspace) = self.workspace() else {
15871            cx.propagate();
15872            return;
15873        };
15874
15875        if self.buffer.read(cx).is_singleton() {
15876            cx.propagate();
15877            return;
15878        }
15879
15880        let mut new_selections_by_buffer = HashMap::default();
15881        match &jump_data {
15882            Some(JumpData::MultiBufferPoint {
15883                excerpt_id,
15884                position,
15885                anchor,
15886                line_offset_from_top,
15887            }) => {
15888                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15889                if let Some(buffer) = multi_buffer_snapshot
15890                    .buffer_id_for_excerpt(*excerpt_id)
15891                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15892                {
15893                    let buffer_snapshot = buffer.read(cx).snapshot();
15894                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15895                        language::ToPoint::to_point(anchor, &buffer_snapshot)
15896                    } else {
15897                        buffer_snapshot.clip_point(*position, Bias::Left)
15898                    };
15899                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15900                    new_selections_by_buffer.insert(
15901                        buffer,
15902                        (
15903                            vec![jump_to_offset..jump_to_offset],
15904                            Some(*line_offset_from_top),
15905                        ),
15906                    );
15907                }
15908            }
15909            Some(JumpData::MultiBufferRow {
15910                row,
15911                line_offset_from_top,
15912            }) => {
15913                let point = MultiBufferPoint::new(row.0, 0);
15914                if let Some((buffer, buffer_point, _)) =
15915                    self.buffer.read(cx).point_to_buffer_point(point, cx)
15916                {
15917                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15918                    new_selections_by_buffer
15919                        .entry(buffer)
15920                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
15921                        .0
15922                        .push(buffer_offset..buffer_offset)
15923                }
15924            }
15925            None => {
15926                let selections = self.selections.all::<usize>(cx);
15927                let multi_buffer = self.buffer.read(cx);
15928                for selection in selections {
15929                    for (snapshot, range, _, anchor) in multi_buffer
15930                        .snapshot(cx)
15931                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15932                    {
15933                        if let Some(anchor) = anchor {
15934                            // selection is in a deleted hunk
15935                            let Some(buffer_id) = anchor.buffer_id else {
15936                                continue;
15937                            };
15938                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15939                                continue;
15940                            };
15941                            let offset = text::ToOffset::to_offset(
15942                                &anchor.text_anchor,
15943                                &buffer_handle.read(cx).snapshot(),
15944                            );
15945                            let range = offset..offset;
15946                            new_selections_by_buffer
15947                                .entry(buffer_handle)
15948                                .or_insert((Vec::new(), None))
15949                                .0
15950                                .push(range)
15951                        } else {
15952                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15953                            else {
15954                                continue;
15955                            };
15956                            new_selections_by_buffer
15957                                .entry(buffer_handle)
15958                                .or_insert((Vec::new(), None))
15959                                .0
15960                                .push(range)
15961                        }
15962                    }
15963                }
15964            }
15965        }
15966
15967        if new_selections_by_buffer.is_empty() {
15968            return;
15969        }
15970
15971        // We defer the pane interaction because we ourselves are a workspace item
15972        // and activating a new item causes the pane to call a method on us reentrantly,
15973        // which panics if we're on the stack.
15974        window.defer(cx, move |window, cx| {
15975            workspace.update(cx, |workspace, cx| {
15976                let pane = if split {
15977                    workspace.adjacent_pane(window, cx)
15978                } else {
15979                    workspace.active_pane().clone()
15980                };
15981
15982                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15983                    let editor = buffer
15984                        .read(cx)
15985                        .file()
15986                        .is_none()
15987                        .then(|| {
15988                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15989                            // so `workspace.open_project_item` will never find them, always opening a new editor.
15990                            // Instead, we try to activate the existing editor in the pane first.
15991                            let (editor, pane_item_index) =
15992                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
15993                                    let editor = item.downcast::<Editor>()?;
15994                                    let singleton_buffer =
15995                                        editor.read(cx).buffer().read(cx).as_singleton()?;
15996                                    if singleton_buffer == buffer {
15997                                        Some((editor, i))
15998                                    } else {
15999                                        None
16000                                    }
16001                                })?;
16002                            pane.update(cx, |pane, cx| {
16003                                pane.activate_item(pane_item_index, true, true, window, cx)
16004                            });
16005                            Some(editor)
16006                        })
16007                        .flatten()
16008                        .unwrap_or_else(|| {
16009                            workspace.open_project_item::<Self>(
16010                                pane.clone(),
16011                                buffer,
16012                                true,
16013                                true,
16014                                window,
16015                                cx,
16016                            )
16017                        });
16018
16019                    editor.update(cx, |editor, cx| {
16020                        let autoscroll = match scroll_offset {
16021                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
16022                            None => Autoscroll::newest(),
16023                        };
16024                        let nav_history = editor.nav_history.take();
16025                        editor.change_selections(Some(autoscroll), window, cx, |s| {
16026                            s.select_ranges(ranges);
16027                        });
16028                        editor.nav_history = nav_history;
16029                    });
16030                }
16031            })
16032        });
16033    }
16034
16035    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
16036        let snapshot = self.buffer.read(cx).read(cx);
16037        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
16038        Some(
16039            ranges
16040                .iter()
16041                .map(move |range| {
16042                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
16043                })
16044                .collect(),
16045        )
16046    }
16047
16048    fn selection_replacement_ranges(
16049        &self,
16050        range: Range<OffsetUtf16>,
16051        cx: &mut App,
16052    ) -> Vec<Range<OffsetUtf16>> {
16053        let selections = self.selections.all::<OffsetUtf16>(cx);
16054        let newest_selection = selections
16055            .iter()
16056            .max_by_key(|selection| selection.id)
16057            .unwrap();
16058        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
16059        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
16060        let snapshot = self.buffer.read(cx).read(cx);
16061        selections
16062            .into_iter()
16063            .map(|mut selection| {
16064                selection.start.0 =
16065                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
16066                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
16067                snapshot.clip_offset_utf16(selection.start, Bias::Left)
16068                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
16069            })
16070            .collect()
16071    }
16072
16073    fn report_editor_event(
16074        &self,
16075        event_type: &'static str,
16076        file_extension: Option<String>,
16077        cx: &App,
16078    ) {
16079        if cfg!(any(test, feature = "test-support")) {
16080            return;
16081        }
16082
16083        let Some(project) = &self.project else { return };
16084
16085        // If None, we are in a file without an extension
16086        let file = self
16087            .buffer
16088            .read(cx)
16089            .as_singleton()
16090            .and_then(|b| b.read(cx).file());
16091        let file_extension = file_extension.or(file
16092            .as_ref()
16093            .and_then(|file| Path::new(file.file_name(cx)).extension())
16094            .and_then(|e| e.to_str())
16095            .map(|a| a.to_string()));
16096
16097        let vim_mode = cx
16098            .global::<SettingsStore>()
16099            .raw_user_settings()
16100            .get("vim_mode")
16101            == Some(&serde_json::Value::Bool(true));
16102
16103        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
16104        let copilot_enabled = edit_predictions_provider
16105            == language::language_settings::EditPredictionProvider::Copilot;
16106        let copilot_enabled_for_language = self
16107            .buffer
16108            .read(cx)
16109            .language_settings(cx)
16110            .show_edit_predictions;
16111
16112        let project = project.read(cx);
16113        telemetry::event!(
16114            event_type,
16115            file_extension,
16116            vim_mode,
16117            copilot_enabled,
16118            copilot_enabled_for_language,
16119            edit_predictions_provider,
16120            is_via_ssh = project.is_via_ssh(),
16121        );
16122    }
16123
16124    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
16125    /// with each line being an array of {text, highlight} objects.
16126    fn copy_highlight_json(
16127        &mut self,
16128        _: &CopyHighlightJson,
16129        window: &mut Window,
16130        cx: &mut Context<Self>,
16131    ) {
16132        #[derive(Serialize)]
16133        struct Chunk<'a> {
16134            text: String,
16135            highlight: Option<&'a str>,
16136        }
16137
16138        let snapshot = self.buffer.read(cx).snapshot(cx);
16139        let range = self
16140            .selected_text_range(false, window, cx)
16141            .and_then(|selection| {
16142                if selection.range.is_empty() {
16143                    None
16144                } else {
16145                    Some(selection.range)
16146                }
16147            })
16148            .unwrap_or_else(|| 0..snapshot.len());
16149
16150        let chunks = snapshot.chunks(range, true);
16151        let mut lines = Vec::new();
16152        let mut line: VecDeque<Chunk> = VecDeque::new();
16153
16154        let Some(style) = self.style.as_ref() else {
16155            return;
16156        };
16157
16158        for chunk in chunks {
16159            let highlight = chunk
16160                .syntax_highlight_id
16161                .and_then(|id| id.name(&style.syntax));
16162            let mut chunk_lines = chunk.text.split('\n').peekable();
16163            while let Some(text) = chunk_lines.next() {
16164                let mut merged_with_last_token = false;
16165                if let Some(last_token) = line.back_mut() {
16166                    if last_token.highlight == highlight {
16167                        last_token.text.push_str(text);
16168                        merged_with_last_token = true;
16169                    }
16170                }
16171
16172                if !merged_with_last_token {
16173                    line.push_back(Chunk {
16174                        text: text.into(),
16175                        highlight,
16176                    });
16177                }
16178
16179                if chunk_lines.peek().is_some() {
16180                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
16181                        line.pop_front();
16182                    }
16183                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
16184                        line.pop_back();
16185                    }
16186
16187                    lines.push(mem::take(&mut line));
16188                }
16189            }
16190        }
16191
16192        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
16193            return;
16194        };
16195        cx.write_to_clipboard(ClipboardItem::new_string(lines));
16196    }
16197
16198    pub fn open_context_menu(
16199        &mut self,
16200        _: &OpenContextMenu,
16201        window: &mut Window,
16202        cx: &mut Context<Self>,
16203    ) {
16204        self.request_autoscroll(Autoscroll::newest(), cx);
16205        let position = self.selections.newest_display(cx).start;
16206        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
16207    }
16208
16209    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
16210        &self.inlay_hint_cache
16211    }
16212
16213    pub fn replay_insert_event(
16214        &mut self,
16215        text: &str,
16216        relative_utf16_range: Option<Range<isize>>,
16217        window: &mut Window,
16218        cx: &mut Context<Self>,
16219    ) {
16220        if !self.input_enabled {
16221            cx.emit(EditorEvent::InputIgnored { text: text.into() });
16222            return;
16223        }
16224        if let Some(relative_utf16_range) = relative_utf16_range {
16225            let selections = self.selections.all::<OffsetUtf16>(cx);
16226            self.change_selections(None, window, cx, |s| {
16227                let new_ranges = selections.into_iter().map(|range| {
16228                    let start = OffsetUtf16(
16229                        range
16230                            .head()
16231                            .0
16232                            .saturating_add_signed(relative_utf16_range.start),
16233                    );
16234                    let end = OffsetUtf16(
16235                        range
16236                            .head()
16237                            .0
16238                            .saturating_add_signed(relative_utf16_range.end),
16239                    );
16240                    start..end
16241                });
16242                s.select_ranges(new_ranges);
16243            });
16244        }
16245
16246        self.handle_input(text, window, cx);
16247    }
16248
16249    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
16250        let Some(provider) = self.semantics_provider.as_ref() else {
16251            return false;
16252        };
16253
16254        let mut supports = false;
16255        self.buffer().update(cx, |this, cx| {
16256            this.for_each_buffer(|buffer| {
16257                supports |= provider.supports_inlay_hints(buffer, cx);
16258            });
16259        });
16260
16261        supports
16262    }
16263
16264    pub fn is_focused(&self, window: &Window) -> bool {
16265        self.focus_handle.is_focused(window)
16266    }
16267
16268    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16269        cx.emit(EditorEvent::Focused);
16270
16271        if let Some(descendant) = self
16272            .last_focused_descendant
16273            .take()
16274            .and_then(|descendant| descendant.upgrade())
16275        {
16276            window.focus(&descendant);
16277        } else {
16278            if let Some(blame) = self.blame.as_ref() {
16279                blame.update(cx, GitBlame::focus)
16280            }
16281
16282            self.blink_manager.update(cx, BlinkManager::enable);
16283            self.show_cursor_names(window, cx);
16284            self.buffer.update(cx, |buffer, cx| {
16285                buffer.finalize_last_transaction(cx);
16286                if self.leader_peer_id.is_none() {
16287                    buffer.set_active_selections(
16288                        &self.selections.disjoint_anchors(),
16289                        self.selections.line_mode,
16290                        self.cursor_shape,
16291                        cx,
16292                    );
16293                }
16294            });
16295        }
16296    }
16297
16298    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16299        cx.emit(EditorEvent::FocusedIn)
16300    }
16301
16302    fn handle_focus_out(
16303        &mut self,
16304        event: FocusOutEvent,
16305        _window: &mut Window,
16306        cx: &mut Context<Self>,
16307    ) {
16308        if event.blurred != self.focus_handle {
16309            self.last_focused_descendant = Some(event.blurred);
16310        }
16311        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
16312    }
16313
16314    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16315        self.blink_manager.update(cx, BlinkManager::disable);
16316        self.buffer
16317            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
16318
16319        if let Some(blame) = self.blame.as_ref() {
16320            blame.update(cx, GitBlame::blur)
16321        }
16322        if !self.hover_state.focused(window, cx) {
16323            hide_hover(self, cx);
16324        }
16325        if !self
16326            .context_menu
16327            .borrow()
16328            .as_ref()
16329            .is_some_and(|context_menu| context_menu.focused(window, cx))
16330        {
16331            self.hide_context_menu(window, cx);
16332        }
16333        self.discard_inline_completion(false, cx);
16334        cx.emit(EditorEvent::Blurred);
16335        cx.notify();
16336    }
16337
16338    pub fn register_action<A: Action>(
16339        &mut self,
16340        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
16341    ) -> Subscription {
16342        let id = self.next_editor_action_id.post_inc();
16343        let listener = Arc::new(listener);
16344        self.editor_actions.borrow_mut().insert(
16345            id,
16346            Box::new(move |window, _| {
16347                let listener = listener.clone();
16348                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
16349                    let action = action.downcast_ref().unwrap();
16350                    if phase == DispatchPhase::Bubble {
16351                        listener(action, window, cx)
16352                    }
16353                })
16354            }),
16355        );
16356
16357        let editor_actions = self.editor_actions.clone();
16358        Subscription::new(move || {
16359            editor_actions.borrow_mut().remove(&id);
16360        })
16361    }
16362
16363    pub fn file_header_size(&self) -> u32 {
16364        FILE_HEADER_HEIGHT
16365    }
16366
16367    pub fn restore(
16368        &mut self,
16369        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16370        window: &mut Window,
16371        cx: &mut Context<Self>,
16372    ) {
16373        let workspace = self.workspace();
16374        let project = self.project.as_ref();
16375        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16376            let mut tasks = Vec::new();
16377            for (buffer_id, changes) in revert_changes {
16378                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16379                    buffer.update(cx, |buffer, cx| {
16380                        buffer.edit(
16381                            changes
16382                                .into_iter()
16383                                .map(|(range, text)| (range, text.to_string())),
16384                            None,
16385                            cx,
16386                        );
16387                    });
16388
16389                    if let Some(project) =
16390                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16391                    {
16392                        project.update(cx, |project, cx| {
16393                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16394                        })
16395                    }
16396                }
16397            }
16398            tasks
16399        });
16400        cx.spawn_in(window, |_, mut cx| async move {
16401            for (buffer, task) in save_tasks {
16402                let result = task.await;
16403                if result.is_err() {
16404                    let Some(path) = buffer
16405                        .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16406                        .ok()
16407                    else {
16408                        continue;
16409                    };
16410                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16411                        let Some(task) = cx
16412                            .update_window_entity(&workspace, |workspace, window, cx| {
16413                                workspace
16414                                    .open_path_preview(path, None, false, false, false, window, cx)
16415                            })
16416                            .ok()
16417                        else {
16418                            continue;
16419                        };
16420                        task.await.log_err();
16421                    }
16422                }
16423            }
16424        })
16425        .detach();
16426        self.change_selections(None, window, cx, |selections| selections.refresh());
16427    }
16428
16429    pub fn to_pixel_point(
16430        &self,
16431        source: multi_buffer::Anchor,
16432        editor_snapshot: &EditorSnapshot,
16433        window: &mut Window,
16434    ) -> Option<gpui::Point<Pixels>> {
16435        let source_point = source.to_display_point(editor_snapshot);
16436        self.display_to_pixel_point(source_point, editor_snapshot, window)
16437    }
16438
16439    pub fn display_to_pixel_point(
16440        &self,
16441        source: DisplayPoint,
16442        editor_snapshot: &EditorSnapshot,
16443        window: &mut Window,
16444    ) -> Option<gpui::Point<Pixels>> {
16445        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16446        let text_layout_details = self.text_layout_details(window);
16447        let scroll_top = text_layout_details
16448            .scroll_anchor
16449            .scroll_position(editor_snapshot)
16450            .y;
16451
16452        if source.row().as_f32() < scroll_top.floor() {
16453            return None;
16454        }
16455        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16456        let source_y = line_height * (source.row().as_f32() - scroll_top);
16457        Some(gpui::Point::new(source_x, source_y))
16458    }
16459
16460    pub fn has_visible_completions_menu(&self) -> bool {
16461        !self.edit_prediction_preview_is_active()
16462            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16463                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16464            })
16465    }
16466
16467    pub fn register_addon<T: Addon>(&mut self, instance: T) {
16468        self.addons
16469            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16470    }
16471
16472    pub fn unregister_addon<T: Addon>(&mut self) {
16473        self.addons.remove(&std::any::TypeId::of::<T>());
16474    }
16475
16476    pub fn addon<T: Addon>(&self) -> Option<&T> {
16477        let type_id = std::any::TypeId::of::<T>();
16478        self.addons
16479            .get(&type_id)
16480            .and_then(|item| item.to_any().downcast_ref::<T>())
16481    }
16482
16483    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16484        let text_layout_details = self.text_layout_details(window);
16485        let style = &text_layout_details.editor_style;
16486        let font_id = window.text_system().resolve_font(&style.text.font());
16487        let font_size = style.text.font_size.to_pixels(window.rem_size());
16488        let line_height = style.text.line_height_in_pixels(window.rem_size());
16489        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16490
16491        gpui::Size::new(em_width, line_height)
16492    }
16493
16494    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16495        self.load_diff_task.clone()
16496    }
16497
16498    fn read_selections_from_db(
16499        &mut self,
16500        item_id: u64,
16501        workspace_id: WorkspaceId,
16502        window: &mut Window,
16503        cx: &mut Context<Editor>,
16504    ) {
16505        if !self.is_singleton(cx)
16506            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16507        {
16508            return;
16509        }
16510        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16511            return;
16512        };
16513        if selections.is_empty() {
16514            return;
16515        }
16516
16517        let snapshot = self.buffer.read(cx).snapshot(cx);
16518        self.change_selections(None, window, cx, |s| {
16519            s.select_ranges(selections.into_iter().map(|(start, end)| {
16520                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16521            }));
16522        });
16523    }
16524}
16525
16526fn insert_extra_newline_brackets(
16527    buffer: &MultiBufferSnapshot,
16528    range: Range<usize>,
16529    language: &language::LanguageScope,
16530) -> bool {
16531    let leading_whitespace_len = buffer
16532        .reversed_chars_at(range.start)
16533        .take_while(|c| c.is_whitespace() && *c != '\n')
16534        .map(|c| c.len_utf8())
16535        .sum::<usize>();
16536    let trailing_whitespace_len = buffer
16537        .chars_at(range.end)
16538        .take_while(|c| c.is_whitespace() && *c != '\n')
16539        .map(|c| c.len_utf8())
16540        .sum::<usize>();
16541    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16542
16543    language.brackets().any(|(pair, enabled)| {
16544        let pair_start = pair.start.trim_end();
16545        let pair_end = pair.end.trim_start();
16546
16547        enabled
16548            && pair.newline
16549            && buffer.contains_str_at(range.end, pair_end)
16550            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16551    })
16552}
16553
16554fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16555    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16556        [(buffer, range, _)] => (*buffer, range.clone()),
16557        _ => return false,
16558    };
16559    let pair = {
16560        let mut result: Option<BracketMatch> = None;
16561
16562        for pair in buffer
16563            .all_bracket_ranges(range.clone())
16564            .filter(move |pair| {
16565                pair.open_range.start <= range.start && pair.close_range.end >= range.end
16566            })
16567        {
16568            let len = pair.close_range.end - pair.open_range.start;
16569
16570            if let Some(existing) = &result {
16571                let existing_len = existing.close_range.end - existing.open_range.start;
16572                if len > existing_len {
16573                    continue;
16574                }
16575            }
16576
16577            result = Some(pair);
16578        }
16579
16580        result
16581    };
16582    let Some(pair) = pair else {
16583        return false;
16584    };
16585    pair.newline_only
16586        && buffer
16587            .chars_for_range(pair.open_range.end..range.start)
16588            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16589            .all(|c| c.is_whitespace() && c != '\n')
16590}
16591
16592fn get_uncommitted_diff_for_buffer(
16593    project: &Entity<Project>,
16594    buffers: impl IntoIterator<Item = Entity<Buffer>>,
16595    buffer: Entity<MultiBuffer>,
16596    cx: &mut App,
16597) -> Task<()> {
16598    let mut tasks = Vec::new();
16599    project.update(cx, |project, cx| {
16600        for buffer in buffers {
16601            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16602        }
16603    });
16604    cx.spawn(|mut cx| async move {
16605        let diffs = future::join_all(tasks).await;
16606        buffer
16607            .update(&mut cx, |buffer, cx| {
16608                for diff in diffs.into_iter().flatten() {
16609                    buffer.add_diff(diff, cx);
16610                }
16611            })
16612            .ok();
16613    })
16614}
16615
16616fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16617    let tab_size = tab_size.get() as usize;
16618    let mut width = offset;
16619
16620    for ch in text.chars() {
16621        width += if ch == '\t' {
16622            tab_size - (width % tab_size)
16623        } else {
16624            1
16625        };
16626    }
16627
16628    width - offset
16629}
16630
16631#[cfg(test)]
16632mod tests {
16633    use super::*;
16634
16635    #[test]
16636    fn test_string_size_with_expanded_tabs() {
16637        let nz = |val| NonZeroU32::new(val).unwrap();
16638        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16639        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16640        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16641        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16642        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16643        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16644        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16645        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16646    }
16647}
16648
16649/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16650struct WordBreakingTokenizer<'a> {
16651    input: &'a str,
16652}
16653
16654impl<'a> WordBreakingTokenizer<'a> {
16655    fn new(input: &'a str) -> Self {
16656        Self { input }
16657    }
16658}
16659
16660fn is_char_ideographic(ch: char) -> bool {
16661    use unicode_script::Script::*;
16662    use unicode_script::UnicodeScript;
16663    matches!(ch.script(), Han | Tangut | Yi)
16664}
16665
16666fn is_grapheme_ideographic(text: &str) -> bool {
16667    text.chars().any(is_char_ideographic)
16668}
16669
16670fn is_grapheme_whitespace(text: &str) -> bool {
16671    text.chars().any(|x| x.is_whitespace())
16672}
16673
16674fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16675    text.chars().next().map_or(false, |ch| {
16676        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16677    })
16678}
16679
16680#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16681struct WordBreakToken<'a> {
16682    token: &'a str,
16683    grapheme_len: usize,
16684    is_whitespace: bool,
16685}
16686
16687impl<'a> Iterator for WordBreakingTokenizer<'a> {
16688    /// Yields a span, the count of graphemes in the token, and whether it was
16689    /// whitespace. Note that it also breaks at word boundaries.
16690    type Item = WordBreakToken<'a>;
16691
16692    fn next(&mut self) -> Option<Self::Item> {
16693        use unicode_segmentation::UnicodeSegmentation;
16694        if self.input.is_empty() {
16695            return None;
16696        }
16697
16698        let mut iter = self.input.graphemes(true).peekable();
16699        let mut offset = 0;
16700        let mut graphemes = 0;
16701        if let Some(first_grapheme) = iter.next() {
16702            let is_whitespace = is_grapheme_whitespace(first_grapheme);
16703            offset += first_grapheme.len();
16704            graphemes += 1;
16705            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16706                if let Some(grapheme) = iter.peek().copied() {
16707                    if should_stay_with_preceding_ideograph(grapheme) {
16708                        offset += grapheme.len();
16709                        graphemes += 1;
16710                    }
16711                }
16712            } else {
16713                let mut words = self.input[offset..].split_word_bound_indices().peekable();
16714                let mut next_word_bound = words.peek().copied();
16715                if next_word_bound.map_or(false, |(i, _)| i == 0) {
16716                    next_word_bound = words.next();
16717                }
16718                while let Some(grapheme) = iter.peek().copied() {
16719                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
16720                        break;
16721                    };
16722                    if is_grapheme_whitespace(grapheme) != is_whitespace {
16723                        break;
16724                    };
16725                    offset += grapheme.len();
16726                    graphemes += 1;
16727                    iter.next();
16728                }
16729            }
16730            let token = &self.input[..offset];
16731            self.input = &self.input[offset..];
16732            if is_whitespace {
16733                Some(WordBreakToken {
16734                    token: " ",
16735                    grapheme_len: 1,
16736                    is_whitespace: true,
16737                })
16738            } else {
16739                Some(WordBreakToken {
16740                    token,
16741                    grapheme_len: graphemes,
16742                    is_whitespace: false,
16743                })
16744            }
16745        } else {
16746            None
16747        }
16748    }
16749}
16750
16751#[test]
16752fn test_word_breaking_tokenizer() {
16753    let tests: &[(&str, &[(&str, usize, bool)])] = &[
16754        ("", &[]),
16755        ("  ", &[(" ", 1, true)]),
16756        ("Ʒ", &[("Ʒ", 1, false)]),
16757        ("Ǽ", &[("Ǽ", 1, false)]),
16758        ("", &[("", 1, false)]),
16759        ("⋑⋑", &[("⋑⋑", 2, false)]),
16760        (
16761            "原理,进而",
16762            &[
16763                ("", 1, false),
16764                ("理,", 2, false),
16765                ("", 1, false),
16766                ("", 1, false),
16767            ],
16768        ),
16769        (
16770            "hello world",
16771            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16772        ),
16773        (
16774            "hello, world",
16775            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16776        ),
16777        (
16778            "  hello world",
16779            &[
16780                (" ", 1, true),
16781                ("hello", 5, false),
16782                (" ", 1, true),
16783                ("world", 5, false),
16784            ],
16785        ),
16786        (
16787            "这是什么 \n 钢笔",
16788            &[
16789                ("", 1, false),
16790                ("", 1, false),
16791                ("", 1, false),
16792                ("", 1, false),
16793                (" ", 1, true),
16794                ("", 1, false),
16795                ("", 1, false),
16796            ],
16797        ),
16798        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16799    ];
16800
16801    for (input, result) in tests {
16802        assert_eq!(
16803            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16804            result
16805                .iter()
16806                .copied()
16807                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16808                    token,
16809                    grapheme_len,
16810                    is_whitespace,
16811                })
16812                .collect::<Vec<_>>()
16813        );
16814    }
16815}
16816
16817fn wrap_with_prefix(
16818    line_prefix: String,
16819    unwrapped_text: String,
16820    wrap_column: usize,
16821    tab_size: NonZeroU32,
16822) -> String {
16823    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16824    let mut wrapped_text = String::new();
16825    let mut current_line = line_prefix.clone();
16826
16827    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16828    let mut current_line_len = line_prefix_len;
16829    for WordBreakToken {
16830        token,
16831        grapheme_len,
16832        is_whitespace,
16833    } in tokenizer
16834    {
16835        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16836            wrapped_text.push_str(current_line.trim_end());
16837            wrapped_text.push('\n');
16838            current_line.truncate(line_prefix.len());
16839            current_line_len = line_prefix_len;
16840            if !is_whitespace {
16841                current_line.push_str(token);
16842                current_line_len += grapheme_len;
16843            }
16844        } else if !is_whitespace {
16845            current_line.push_str(token);
16846            current_line_len += grapheme_len;
16847        } else if current_line_len != line_prefix_len {
16848            current_line.push(' ');
16849            current_line_len += 1;
16850        }
16851    }
16852
16853    if !current_line.is_empty() {
16854        wrapped_text.push_str(&current_line);
16855    }
16856    wrapped_text
16857}
16858
16859#[test]
16860fn test_wrap_with_prefix() {
16861    assert_eq!(
16862        wrap_with_prefix(
16863            "# ".to_string(),
16864            "abcdefg".to_string(),
16865            4,
16866            NonZeroU32::new(4).unwrap()
16867        ),
16868        "# abcdefg"
16869    );
16870    assert_eq!(
16871        wrap_with_prefix(
16872            "".to_string(),
16873            "\thello world".to_string(),
16874            8,
16875            NonZeroU32::new(4).unwrap()
16876        ),
16877        "hello\nworld"
16878    );
16879    assert_eq!(
16880        wrap_with_prefix(
16881            "// ".to_string(),
16882            "xx \nyy zz aa bb cc".to_string(),
16883            12,
16884            NonZeroU32::new(4).unwrap()
16885        ),
16886        "// xx yy zz\n// aa bb cc"
16887    );
16888    assert_eq!(
16889        wrap_with_prefix(
16890            String::new(),
16891            "这是什么 \n 钢笔".to_string(),
16892            3,
16893            NonZeroU32::new(4).unwrap()
16894        ),
16895        "这是什\n么 钢\n"
16896    );
16897}
16898
16899pub trait CollaborationHub {
16900    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16901    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16902    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16903}
16904
16905impl CollaborationHub for Entity<Project> {
16906    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16907        self.read(cx).collaborators()
16908    }
16909
16910    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16911        self.read(cx).user_store().read(cx).participant_indices()
16912    }
16913
16914    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16915        let this = self.read(cx);
16916        let user_ids = this.collaborators().values().map(|c| c.user_id);
16917        this.user_store().read_with(cx, |user_store, cx| {
16918            user_store.participant_names(user_ids, cx)
16919        })
16920    }
16921}
16922
16923pub trait SemanticsProvider {
16924    fn hover(
16925        &self,
16926        buffer: &Entity<Buffer>,
16927        position: text::Anchor,
16928        cx: &mut App,
16929    ) -> Option<Task<Vec<project::Hover>>>;
16930
16931    fn inlay_hints(
16932        &self,
16933        buffer_handle: Entity<Buffer>,
16934        range: Range<text::Anchor>,
16935        cx: &mut App,
16936    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16937
16938    fn resolve_inlay_hint(
16939        &self,
16940        hint: InlayHint,
16941        buffer_handle: Entity<Buffer>,
16942        server_id: LanguageServerId,
16943        cx: &mut App,
16944    ) -> Option<Task<anyhow::Result<InlayHint>>>;
16945
16946    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16947
16948    fn document_highlights(
16949        &self,
16950        buffer: &Entity<Buffer>,
16951        position: text::Anchor,
16952        cx: &mut App,
16953    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16954
16955    fn definitions(
16956        &self,
16957        buffer: &Entity<Buffer>,
16958        position: text::Anchor,
16959        kind: GotoDefinitionKind,
16960        cx: &mut App,
16961    ) -> Option<Task<Result<Vec<LocationLink>>>>;
16962
16963    fn range_for_rename(
16964        &self,
16965        buffer: &Entity<Buffer>,
16966        position: text::Anchor,
16967        cx: &mut App,
16968    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16969
16970    fn perform_rename(
16971        &self,
16972        buffer: &Entity<Buffer>,
16973        position: text::Anchor,
16974        new_name: String,
16975        cx: &mut App,
16976    ) -> Option<Task<Result<ProjectTransaction>>>;
16977}
16978
16979pub trait CompletionProvider {
16980    fn completions(
16981        &self,
16982        buffer: &Entity<Buffer>,
16983        buffer_position: text::Anchor,
16984        trigger: CompletionContext,
16985        window: &mut Window,
16986        cx: &mut Context<Editor>,
16987    ) -> Task<Result<Option<Vec<Completion>>>>;
16988
16989    fn resolve_completions(
16990        &self,
16991        buffer: Entity<Buffer>,
16992        completion_indices: Vec<usize>,
16993        completions: Rc<RefCell<Box<[Completion]>>>,
16994        cx: &mut Context<Editor>,
16995    ) -> Task<Result<bool>>;
16996
16997    fn apply_additional_edits_for_completion(
16998        &self,
16999        _buffer: Entity<Buffer>,
17000        _completions: Rc<RefCell<Box<[Completion]>>>,
17001        _completion_index: usize,
17002        _push_to_history: bool,
17003        _cx: &mut Context<Editor>,
17004    ) -> Task<Result<Option<language::Transaction>>> {
17005        Task::ready(Ok(None))
17006    }
17007
17008    fn is_completion_trigger(
17009        &self,
17010        buffer: &Entity<Buffer>,
17011        position: language::Anchor,
17012        text: &str,
17013        trigger_in_words: bool,
17014        cx: &mut Context<Editor>,
17015    ) -> bool;
17016
17017    fn sort_completions(&self) -> bool {
17018        true
17019    }
17020}
17021
17022pub trait CodeActionProvider {
17023    fn id(&self) -> Arc<str>;
17024
17025    fn code_actions(
17026        &self,
17027        buffer: &Entity<Buffer>,
17028        range: Range<text::Anchor>,
17029        window: &mut Window,
17030        cx: &mut App,
17031    ) -> Task<Result<Vec<CodeAction>>>;
17032
17033    fn apply_code_action(
17034        &self,
17035        buffer_handle: Entity<Buffer>,
17036        action: CodeAction,
17037        excerpt_id: ExcerptId,
17038        push_to_history: bool,
17039        window: &mut Window,
17040        cx: &mut App,
17041    ) -> Task<Result<ProjectTransaction>>;
17042}
17043
17044impl CodeActionProvider for Entity<Project> {
17045    fn id(&self) -> Arc<str> {
17046        "project".into()
17047    }
17048
17049    fn code_actions(
17050        &self,
17051        buffer: &Entity<Buffer>,
17052        range: Range<text::Anchor>,
17053        _window: &mut Window,
17054        cx: &mut App,
17055    ) -> Task<Result<Vec<CodeAction>>> {
17056        self.update(cx, |project, cx| {
17057            let code_lens = project.code_lens(buffer, range.clone(), cx);
17058            let code_actions = project.code_actions(buffer, range, None, cx);
17059            cx.background_spawn(async move {
17060                let (code_lens, code_actions) = join(code_lens, code_actions).await;
17061                Ok(code_lens
17062                    .context("code lens fetch")?
17063                    .into_iter()
17064                    .chain(code_actions.context("code action fetch")?)
17065                    .collect())
17066            })
17067        })
17068    }
17069
17070    fn apply_code_action(
17071        &self,
17072        buffer_handle: Entity<Buffer>,
17073        action: CodeAction,
17074        _excerpt_id: ExcerptId,
17075        push_to_history: bool,
17076        _window: &mut Window,
17077        cx: &mut App,
17078    ) -> Task<Result<ProjectTransaction>> {
17079        self.update(cx, |project, cx| {
17080            project.apply_code_action(buffer_handle, action, push_to_history, cx)
17081        })
17082    }
17083}
17084
17085fn snippet_completions(
17086    project: &Project,
17087    buffer: &Entity<Buffer>,
17088    buffer_position: text::Anchor,
17089    cx: &mut App,
17090) -> Task<Result<Vec<Completion>>> {
17091    let language = buffer.read(cx).language_at(buffer_position);
17092    let language_name = language.as_ref().map(|language| language.lsp_id());
17093    let snippet_store = project.snippets().read(cx);
17094    let snippets = snippet_store.snippets_for(language_name, cx);
17095
17096    if snippets.is_empty() {
17097        return Task::ready(Ok(vec![]));
17098    }
17099    let snapshot = buffer.read(cx).text_snapshot();
17100    let chars: String = snapshot
17101        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
17102        .collect();
17103
17104    let scope = language.map(|language| language.default_scope());
17105    let executor = cx.background_executor().clone();
17106
17107    cx.background_spawn(async move {
17108        let classifier = CharClassifier::new(scope).for_completion(true);
17109        let mut last_word = chars
17110            .chars()
17111            .take_while(|c| classifier.is_word(*c))
17112            .collect::<String>();
17113        last_word = last_word.chars().rev().collect();
17114
17115        if last_word.is_empty() {
17116            return Ok(vec![]);
17117        }
17118
17119        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
17120        let to_lsp = |point: &text::Anchor| {
17121            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
17122            point_to_lsp(end)
17123        };
17124        let lsp_end = to_lsp(&buffer_position);
17125
17126        let candidates = snippets
17127            .iter()
17128            .enumerate()
17129            .flat_map(|(ix, snippet)| {
17130                snippet
17131                    .prefix
17132                    .iter()
17133                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
17134            })
17135            .collect::<Vec<StringMatchCandidate>>();
17136
17137        let mut matches = fuzzy::match_strings(
17138            &candidates,
17139            &last_word,
17140            last_word.chars().any(|c| c.is_uppercase()),
17141            100,
17142            &Default::default(),
17143            executor,
17144        )
17145        .await;
17146
17147        // Remove all candidates where the query's start does not match the start of any word in the candidate
17148        if let Some(query_start) = last_word.chars().next() {
17149            matches.retain(|string_match| {
17150                split_words(&string_match.string).any(|word| {
17151                    // Check that the first codepoint of the word as lowercase matches the first
17152                    // codepoint of the query as lowercase
17153                    word.chars()
17154                        .flat_map(|codepoint| codepoint.to_lowercase())
17155                        .zip(query_start.to_lowercase())
17156                        .all(|(word_cp, query_cp)| word_cp == query_cp)
17157                })
17158            });
17159        }
17160
17161        let matched_strings = matches
17162            .into_iter()
17163            .map(|m| m.string)
17164            .collect::<HashSet<_>>();
17165
17166        let result: Vec<Completion> = snippets
17167            .into_iter()
17168            .filter_map(|snippet| {
17169                let matching_prefix = snippet
17170                    .prefix
17171                    .iter()
17172                    .find(|prefix| matched_strings.contains(*prefix))?;
17173                let start = as_offset - last_word.len();
17174                let start = snapshot.anchor_before(start);
17175                let range = start..buffer_position;
17176                let lsp_start = to_lsp(&start);
17177                let lsp_range = lsp::Range {
17178                    start: lsp_start,
17179                    end: lsp_end,
17180                };
17181                Some(Completion {
17182                    old_range: range,
17183                    new_text: snippet.body.clone(),
17184                    source: CompletionSource::Lsp {
17185                        server_id: LanguageServerId(usize::MAX),
17186                        resolved: true,
17187                        lsp_completion: Box::new(lsp::CompletionItem {
17188                            label: snippet.prefix.first().unwrap().clone(),
17189                            kind: Some(CompletionItemKind::SNIPPET),
17190                            label_details: snippet.description.as_ref().map(|description| {
17191                                lsp::CompletionItemLabelDetails {
17192                                    detail: Some(description.clone()),
17193                                    description: None,
17194                                }
17195                            }),
17196                            insert_text_format: Some(InsertTextFormat::SNIPPET),
17197                            text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
17198                                lsp::InsertReplaceEdit {
17199                                    new_text: snippet.body.clone(),
17200                                    insert: lsp_range,
17201                                    replace: lsp_range,
17202                                },
17203                            )),
17204                            filter_text: Some(snippet.body.clone()),
17205                            sort_text: Some(char::MAX.to_string()),
17206                            ..lsp::CompletionItem::default()
17207                        }),
17208                        lsp_defaults: None,
17209                    },
17210                    label: CodeLabel {
17211                        text: matching_prefix.clone(),
17212                        runs: Vec::new(),
17213                        filter_range: 0..matching_prefix.len(),
17214                    },
17215                    documentation: snippet
17216                        .description
17217                        .clone()
17218                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
17219                    confirm: None,
17220                })
17221            })
17222            .collect();
17223
17224        Ok(result)
17225    })
17226}
17227
17228impl CompletionProvider for Entity<Project> {
17229    fn completions(
17230        &self,
17231        buffer: &Entity<Buffer>,
17232        buffer_position: text::Anchor,
17233        options: CompletionContext,
17234        _window: &mut Window,
17235        cx: &mut Context<Editor>,
17236    ) -> Task<Result<Option<Vec<Completion>>>> {
17237        self.update(cx, |project, cx| {
17238            let snippets = snippet_completions(project, buffer, buffer_position, cx);
17239            let project_completions = project.completions(buffer, buffer_position, options, cx);
17240            cx.background_spawn(async move {
17241                let snippets_completions = snippets.await?;
17242                match project_completions.await? {
17243                    Some(mut completions) => {
17244                        completions.extend(snippets_completions);
17245                        Ok(Some(completions))
17246                    }
17247                    None => {
17248                        if snippets_completions.is_empty() {
17249                            Ok(None)
17250                        } else {
17251                            Ok(Some(snippets_completions))
17252                        }
17253                    }
17254                }
17255            })
17256        })
17257    }
17258
17259    fn resolve_completions(
17260        &self,
17261        buffer: Entity<Buffer>,
17262        completion_indices: Vec<usize>,
17263        completions: Rc<RefCell<Box<[Completion]>>>,
17264        cx: &mut Context<Editor>,
17265    ) -> Task<Result<bool>> {
17266        self.update(cx, |project, cx| {
17267            project.lsp_store().update(cx, |lsp_store, cx| {
17268                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
17269            })
17270        })
17271    }
17272
17273    fn apply_additional_edits_for_completion(
17274        &self,
17275        buffer: Entity<Buffer>,
17276        completions: Rc<RefCell<Box<[Completion]>>>,
17277        completion_index: usize,
17278        push_to_history: bool,
17279        cx: &mut Context<Editor>,
17280    ) -> Task<Result<Option<language::Transaction>>> {
17281        self.update(cx, |project, cx| {
17282            project.lsp_store().update(cx, |lsp_store, cx| {
17283                lsp_store.apply_additional_edits_for_completion(
17284                    buffer,
17285                    completions,
17286                    completion_index,
17287                    push_to_history,
17288                    cx,
17289                )
17290            })
17291        })
17292    }
17293
17294    fn is_completion_trigger(
17295        &self,
17296        buffer: &Entity<Buffer>,
17297        position: language::Anchor,
17298        text: &str,
17299        trigger_in_words: bool,
17300        cx: &mut Context<Editor>,
17301    ) -> bool {
17302        let mut chars = text.chars();
17303        let char = if let Some(char) = chars.next() {
17304            char
17305        } else {
17306            return false;
17307        };
17308        if chars.next().is_some() {
17309            return false;
17310        }
17311
17312        let buffer = buffer.read(cx);
17313        let snapshot = buffer.snapshot();
17314        if !snapshot.settings_at(position, cx).show_completions_on_input {
17315            return false;
17316        }
17317        let classifier = snapshot.char_classifier_at(position).for_completion(true);
17318        if trigger_in_words && classifier.is_word(char) {
17319            return true;
17320        }
17321
17322        buffer.completion_triggers().contains(text)
17323    }
17324}
17325
17326impl SemanticsProvider for Entity<Project> {
17327    fn hover(
17328        &self,
17329        buffer: &Entity<Buffer>,
17330        position: text::Anchor,
17331        cx: &mut App,
17332    ) -> Option<Task<Vec<project::Hover>>> {
17333        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
17334    }
17335
17336    fn document_highlights(
17337        &self,
17338        buffer: &Entity<Buffer>,
17339        position: text::Anchor,
17340        cx: &mut App,
17341    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
17342        Some(self.update(cx, |project, cx| {
17343            project.document_highlights(buffer, position, cx)
17344        }))
17345    }
17346
17347    fn definitions(
17348        &self,
17349        buffer: &Entity<Buffer>,
17350        position: text::Anchor,
17351        kind: GotoDefinitionKind,
17352        cx: &mut App,
17353    ) -> Option<Task<Result<Vec<LocationLink>>>> {
17354        Some(self.update(cx, |project, cx| match kind {
17355            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
17356            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
17357            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
17358            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
17359        }))
17360    }
17361
17362    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
17363        // TODO: make this work for remote projects
17364        self.update(cx, |this, cx| {
17365            buffer.update(cx, |buffer, cx| {
17366                this.any_language_server_supports_inlay_hints(buffer, cx)
17367            })
17368        })
17369    }
17370
17371    fn inlay_hints(
17372        &self,
17373        buffer_handle: Entity<Buffer>,
17374        range: Range<text::Anchor>,
17375        cx: &mut App,
17376    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
17377        Some(self.update(cx, |project, cx| {
17378            project.inlay_hints(buffer_handle, range, cx)
17379        }))
17380    }
17381
17382    fn resolve_inlay_hint(
17383        &self,
17384        hint: InlayHint,
17385        buffer_handle: Entity<Buffer>,
17386        server_id: LanguageServerId,
17387        cx: &mut App,
17388    ) -> Option<Task<anyhow::Result<InlayHint>>> {
17389        Some(self.update(cx, |project, cx| {
17390            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
17391        }))
17392    }
17393
17394    fn range_for_rename(
17395        &self,
17396        buffer: &Entity<Buffer>,
17397        position: text::Anchor,
17398        cx: &mut App,
17399    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17400        Some(self.update(cx, |project, cx| {
17401            let buffer = buffer.clone();
17402            let task = project.prepare_rename(buffer.clone(), position, cx);
17403            cx.spawn(|_, mut cx| async move {
17404                Ok(match task.await? {
17405                    PrepareRenameResponse::Success(range) => Some(range),
17406                    PrepareRenameResponse::InvalidPosition => None,
17407                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17408                        // Fallback on using TreeSitter info to determine identifier range
17409                        buffer.update(&mut cx, |buffer, _| {
17410                            let snapshot = buffer.snapshot();
17411                            let (range, kind) = snapshot.surrounding_word(position);
17412                            if kind != Some(CharKind::Word) {
17413                                return None;
17414                            }
17415                            Some(
17416                                snapshot.anchor_before(range.start)
17417                                    ..snapshot.anchor_after(range.end),
17418                            )
17419                        })?
17420                    }
17421                })
17422            })
17423        }))
17424    }
17425
17426    fn perform_rename(
17427        &self,
17428        buffer: &Entity<Buffer>,
17429        position: text::Anchor,
17430        new_name: String,
17431        cx: &mut App,
17432    ) -> Option<Task<Result<ProjectTransaction>>> {
17433        Some(self.update(cx, |project, cx| {
17434            project.perform_rename(buffer.clone(), position, new_name, cx)
17435        }))
17436    }
17437}
17438
17439fn inlay_hint_settings(
17440    location: Anchor,
17441    snapshot: &MultiBufferSnapshot,
17442    cx: &mut Context<Editor>,
17443) -> InlayHintSettings {
17444    let file = snapshot.file_at(location);
17445    let language = snapshot.language_at(location).map(|l| l.name());
17446    language_settings(language, file, cx).inlay_hints
17447}
17448
17449fn consume_contiguous_rows(
17450    contiguous_row_selections: &mut Vec<Selection<Point>>,
17451    selection: &Selection<Point>,
17452    display_map: &DisplaySnapshot,
17453    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17454) -> (MultiBufferRow, MultiBufferRow) {
17455    contiguous_row_selections.push(selection.clone());
17456    let start_row = MultiBufferRow(selection.start.row);
17457    let mut end_row = ending_row(selection, display_map);
17458
17459    while let Some(next_selection) = selections.peek() {
17460        if next_selection.start.row <= end_row.0 {
17461            end_row = ending_row(next_selection, display_map);
17462            contiguous_row_selections.push(selections.next().unwrap().clone());
17463        } else {
17464            break;
17465        }
17466    }
17467    (start_row, end_row)
17468}
17469
17470fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17471    if next_selection.end.column > 0 || next_selection.is_empty() {
17472        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17473    } else {
17474        MultiBufferRow(next_selection.end.row)
17475    }
17476}
17477
17478impl EditorSnapshot {
17479    pub fn remote_selections_in_range<'a>(
17480        &'a self,
17481        range: &'a Range<Anchor>,
17482        collaboration_hub: &dyn CollaborationHub,
17483        cx: &'a App,
17484    ) -> impl 'a + Iterator<Item = RemoteSelection> {
17485        let participant_names = collaboration_hub.user_names(cx);
17486        let participant_indices = collaboration_hub.user_participant_indices(cx);
17487        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17488        let collaborators_by_replica_id = collaborators_by_peer_id
17489            .iter()
17490            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17491            .collect::<HashMap<_, _>>();
17492        self.buffer_snapshot
17493            .selections_in_range(range, false)
17494            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17495                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17496                let participant_index = participant_indices.get(&collaborator.user_id).copied();
17497                let user_name = participant_names.get(&collaborator.user_id).cloned();
17498                Some(RemoteSelection {
17499                    replica_id,
17500                    selection,
17501                    cursor_shape,
17502                    line_mode,
17503                    participant_index,
17504                    peer_id: collaborator.peer_id,
17505                    user_name,
17506                })
17507            })
17508    }
17509
17510    pub fn hunks_for_ranges(
17511        &self,
17512        ranges: impl IntoIterator<Item = Range<Point>>,
17513    ) -> Vec<MultiBufferDiffHunk> {
17514        let mut hunks = Vec::new();
17515        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17516            HashMap::default();
17517        for query_range in ranges {
17518            let query_rows =
17519                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17520            for hunk in self.buffer_snapshot.diff_hunks_in_range(
17521                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17522            ) {
17523                // Include deleted hunks that are adjacent to the query range, because
17524                // otherwise they would be missed.
17525                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
17526                if hunk.status().is_deleted() {
17527                    intersects_range |= hunk.row_range.start == query_rows.end;
17528                    intersects_range |= hunk.row_range.end == query_rows.start;
17529                }
17530                if intersects_range {
17531                    if !processed_buffer_rows
17532                        .entry(hunk.buffer_id)
17533                        .or_default()
17534                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17535                    {
17536                        continue;
17537                    }
17538                    hunks.push(hunk);
17539                }
17540            }
17541        }
17542
17543        hunks
17544    }
17545
17546    fn display_diff_hunks_for_rows<'a>(
17547        &'a self,
17548        display_rows: Range<DisplayRow>,
17549        folded_buffers: &'a HashSet<BufferId>,
17550    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17551        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17552        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17553
17554        self.buffer_snapshot
17555            .diff_hunks_in_range(buffer_start..buffer_end)
17556            .filter_map(|hunk| {
17557                if folded_buffers.contains(&hunk.buffer_id) {
17558                    return None;
17559                }
17560
17561                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17562                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17563
17564                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17565                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17566
17567                let display_hunk = if hunk_display_start.column() != 0 {
17568                    DisplayDiffHunk::Folded {
17569                        display_row: hunk_display_start.row(),
17570                    }
17571                } else {
17572                    let mut end_row = hunk_display_end.row();
17573                    if hunk_display_end.column() > 0 {
17574                        end_row.0 += 1;
17575                    }
17576                    let is_created_file = hunk.is_created_file();
17577                    DisplayDiffHunk::Unfolded {
17578                        status: hunk.status(),
17579                        diff_base_byte_range: hunk.diff_base_byte_range,
17580                        display_row_range: hunk_display_start.row()..end_row,
17581                        multi_buffer_range: Anchor::range_in_buffer(
17582                            hunk.excerpt_id,
17583                            hunk.buffer_id,
17584                            hunk.buffer_range,
17585                        ),
17586                        is_created_file,
17587                    }
17588                };
17589
17590                Some(display_hunk)
17591            })
17592    }
17593
17594    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17595        self.display_snapshot.buffer_snapshot.language_at(position)
17596    }
17597
17598    pub fn is_focused(&self) -> bool {
17599        self.is_focused
17600    }
17601
17602    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17603        self.placeholder_text.as_ref()
17604    }
17605
17606    pub fn scroll_position(&self) -> gpui::Point<f32> {
17607        self.scroll_anchor.scroll_position(&self.display_snapshot)
17608    }
17609
17610    fn gutter_dimensions(
17611        &self,
17612        font_id: FontId,
17613        font_size: Pixels,
17614        max_line_number_width: Pixels,
17615        cx: &App,
17616    ) -> Option<GutterDimensions> {
17617        if !self.show_gutter {
17618            return None;
17619        }
17620
17621        let descent = cx.text_system().descent(font_id, font_size);
17622        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17623        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17624
17625        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17626            matches!(
17627                ProjectSettings::get_global(cx).git.git_gutter,
17628                Some(GitGutterSetting::TrackedFiles)
17629            )
17630        });
17631        let gutter_settings = EditorSettings::get_global(cx).gutter;
17632        let show_line_numbers = self
17633            .show_line_numbers
17634            .unwrap_or(gutter_settings.line_numbers);
17635        let line_gutter_width = if show_line_numbers {
17636            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17637            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
17638            max_line_number_width.max(min_width_for_number_on_gutter)
17639        } else {
17640            0.0.into()
17641        };
17642
17643        let show_code_actions = self
17644            .show_code_actions
17645            .unwrap_or(gutter_settings.code_actions);
17646
17647        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17648
17649        let git_blame_entries_width =
17650            self.git_blame_gutter_max_author_length
17651                .map(|max_author_length| {
17652                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17653
17654                    /// The number of characters to dedicate to gaps and margins.
17655                    const SPACING_WIDTH: usize = 4;
17656
17657                    let max_char_count = max_author_length
17658                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17659                        + ::git::SHORT_SHA_LENGTH
17660                        + MAX_RELATIVE_TIMESTAMP.len()
17661                        + SPACING_WIDTH;
17662
17663                    em_advance * max_char_count
17664                });
17665
17666        let is_singleton = self.buffer_snapshot.is_singleton();
17667
17668        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17669        left_padding += if !is_singleton {
17670            em_width * 4.0
17671        } else if show_code_actions || show_runnables {
17672            em_width * 3.0
17673        } else if show_git_gutter && show_line_numbers {
17674            em_width * 2.0
17675        } else if show_git_gutter || show_line_numbers {
17676            em_width
17677        } else {
17678            px(0.)
17679        };
17680
17681        let shows_folds = is_singleton && gutter_settings.folds;
17682
17683        let right_padding = if shows_folds && show_line_numbers {
17684            em_width * 4.0
17685        } else if shows_folds || (!is_singleton && show_line_numbers) {
17686            em_width * 3.0
17687        } else if show_line_numbers {
17688            em_width
17689        } else {
17690            px(0.)
17691        };
17692
17693        Some(GutterDimensions {
17694            left_padding,
17695            right_padding,
17696            width: line_gutter_width + left_padding + right_padding,
17697            margin: -descent,
17698            git_blame_entries_width,
17699        })
17700    }
17701
17702    pub fn render_crease_toggle(
17703        &self,
17704        buffer_row: MultiBufferRow,
17705        row_contains_cursor: bool,
17706        editor: Entity<Editor>,
17707        window: &mut Window,
17708        cx: &mut App,
17709    ) -> Option<AnyElement> {
17710        let folded = self.is_line_folded(buffer_row);
17711        let mut is_foldable = false;
17712
17713        if let Some(crease) = self
17714            .crease_snapshot
17715            .query_row(buffer_row, &self.buffer_snapshot)
17716        {
17717            is_foldable = true;
17718            match crease {
17719                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17720                    if let Some(render_toggle) = render_toggle {
17721                        let toggle_callback =
17722                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17723                                if folded {
17724                                    editor.update(cx, |editor, cx| {
17725                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17726                                    });
17727                                } else {
17728                                    editor.update(cx, |editor, cx| {
17729                                        editor.unfold_at(
17730                                            &crate::UnfoldAt { buffer_row },
17731                                            window,
17732                                            cx,
17733                                        )
17734                                    });
17735                                }
17736                            });
17737                        return Some((render_toggle)(
17738                            buffer_row,
17739                            folded,
17740                            toggle_callback,
17741                            window,
17742                            cx,
17743                        ));
17744                    }
17745                }
17746            }
17747        }
17748
17749        is_foldable |= self.starts_indent(buffer_row);
17750
17751        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17752            Some(
17753                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17754                    .toggle_state(folded)
17755                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17756                        if folded {
17757                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17758                        } else {
17759                            this.fold_at(&FoldAt { buffer_row }, window, cx);
17760                        }
17761                    }))
17762                    .into_any_element(),
17763            )
17764        } else {
17765            None
17766        }
17767    }
17768
17769    pub fn render_crease_trailer(
17770        &self,
17771        buffer_row: MultiBufferRow,
17772        window: &mut Window,
17773        cx: &mut App,
17774    ) -> Option<AnyElement> {
17775        let folded = self.is_line_folded(buffer_row);
17776        if let Crease::Inline { render_trailer, .. } = self
17777            .crease_snapshot
17778            .query_row(buffer_row, &self.buffer_snapshot)?
17779        {
17780            let render_trailer = render_trailer.as_ref()?;
17781            Some(render_trailer(buffer_row, folded, window, cx))
17782        } else {
17783            None
17784        }
17785    }
17786}
17787
17788impl Deref for EditorSnapshot {
17789    type Target = DisplaySnapshot;
17790
17791    fn deref(&self) -> &Self::Target {
17792        &self.display_snapshot
17793    }
17794}
17795
17796#[derive(Clone, Debug, PartialEq, Eq)]
17797pub enum EditorEvent {
17798    InputIgnored {
17799        text: Arc<str>,
17800    },
17801    InputHandled {
17802        utf16_range_to_replace: Option<Range<isize>>,
17803        text: Arc<str>,
17804    },
17805    ExcerptsAdded {
17806        buffer: Entity<Buffer>,
17807        predecessor: ExcerptId,
17808        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17809    },
17810    ExcerptsRemoved {
17811        ids: Vec<ExcerptId>,
17812    },
17813    BufferFoldToggled {
17814        ids: Vec<ExcerptId>,
17815        folded: bool,
17816    },
17817    ExcerptsEdited {
17818        ids: Vec<ExcerptId>,
17819    },
17820    ExcerptsExpanded {
17821        ids: Vec<ExcerptId>,
17822    },
17823    BufferEdited,
17824    Edited {
17825        transaction_id: clock::Lamport,
17826    },
17827    Reparsed(BufferId),
17828    Focused,
17829    FocusedIn,
17830    Blurred,
17831    DirtyChanged,
17832    Saved,
17833    TitleChanged,
17834    DiffBaseChanged,
17835    SelectionsChanged {
17836        local: bool,
17837    },
17838    ScrollPositionChanged {
17839        local: bool,
17840        autoscroll: bool,
17841    },
17842    Closed,
17843    TransactionUndone {
17844        transaction_id: clock::Lamport,
17845    },
17846    TransactionBegun {
17847        transaction_id: clock::Lamport,
17848    },
17849    Reloaded,
17850    CursorShapeChanged,
17851}
17852
17853impl EventEmitter<EditorEvent> for Editor {}
17854
17855impl Focusable for Editor {
17856    fn focus_handle(&self, _cx: &App) -> FocusHandle {
17857        self.focus_handle.clone()
17858    }
17859}
17860
17861impl Render for Editor {
17862    fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17863        let settings = ThemeSettings::get_global(cx);
17864
17865        let mut text_style = match self.mode {
17866            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17867                color: cx.theme().colors().editor_foreground,
17868                font_family: settings.ui_font.family.clone(),
17869                font_features: settings.ui_font.features.clone(),
17870                font_fallbacks: settings.ui_font.fallbacks.clone(),
17871                font_size: rems(0.875).into(),
17872                font_weight: settings.ui_font.weight,
17873                line_height: relative(settings.buffer_line_height.value()),
17874                ..Default::default()
17875            },
17876            EditorMode::Full => TextStyle {
17877                color: cx.theme().colors().editor_foreground,
17878                font_family: settings.buffer_font.family.clone(),
17879                font_features: settings.buffer_font.features.clone(),
17880                font_fallbacks: settings.buffer_font.fallbacks.clone(),
17881                font_size: settings.buffer_font_size(cx).into(),
17882                font_weight: settings.buffer_font.weight,
17883                line_height: relative(settings.buffer_line_height.value()),
17884                ..Default::default()
17885            },
17886        };
17887        if let Some(text_style_refinement) = &self.text_style_refinement {
17888            text_style.refine(text_style_refinement)
17889        }
17890
17891        let background = match self.mode {
17892            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17893            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17894            EditorMode::Full => cx.theme().colors().editor_background,
17895        };
17896
17897        EditorElement::new(
17898            &cx.entity(),
17899            EditorStyle {
17900                background,
17901                local_player: cx.theme().players().local(),
17902                text: text_style,
17903                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17904                syntax: cx.theme().syntax().clone(),
17905                status: cx.theme().status().clone(),
17906                inlay_hints_style: make_inlay_hints_style(cx),
17907                inline_completion_styles: make_suggestion_styles(cx),
17908                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17909            },
17910        )
17911    }
17912}
17913
17914impl EntityInputHandler for Editor {
17915    fn text_for_range(
17916        &mut self,
17917        range_utf16: Range<usize>,
17918        adjusted_range: &mut Option<Range<usize>>,
17919        _: &mut Window,
17920        cx: &mut Context<Self>,
17921    ) -> Option<String> {
17922        let snapshot = self.buffer.read(cx).read(cx);
17923        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17924        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17925        if (start.0..end.0) != range_utf16 {
17926            adjusted_range.replace(start.0..end.0);
17927        }
17928        Some(snapshot.text_for_range(start..end).collect())
17929    }
17930
17931    fn selected_text_range(
17932        &mut self,
17933        ignore_disabled_input: bool,
17934        _: &mut Window,
17935        cx: &mut Context<Self>,
17936    ) -> Option<UTF16Selection> {
17937        // Prevent the IME menu from appearing when holding down an alphabetic key
17938        // while input is disabled.
17939        if !ignore_disabled_input && !self.input_enabled {
17940            return None;
17941        }
17942
17943        let selection = self.selections.newest::<OffsetUtf16>(cx);
17944        let range = selection.range();
17945
17946        Some(UTF16Selection {
17947            range: range.start.0..range.end.0,
17948            reversed: selection.reversed,
17949        })
17950    }
17951
17952    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17953        let snapshot = self.buffer.read(cx).read(cx);
17954        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17955        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17956    }
17957
17958    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17959        self.clear_highlights::<InputComposition>(cx);
17960        self.ime_transaction.take();
17961    }
17962
17963    fn replace_text_in_range(
17964        &mut self,
17965        range_utf16: Option<Range<usize>>,
17966        text: &str,
17967        window: &mut Window,
17968        cx: &mut Context<Self>,
17969    ) {
17970        if !self.input_enabled {
17971            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17972            return;
17973        }
17974
17975        self.transact(window, cx, |this, window, cx| {
17976            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17977                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17978                Some(this.selection_replacement_ranges(range_utf16, cx))
17979            } else {
17980                this.marked_text_ranges(cx)
17981            };
17982
17983            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17984                let newest_selection_id = this.selections.newest_anchor().id;
17985                this.selections
17986                    .all::<OffsetUtf16>(cx)
17987                    .iter()
17988                    .zip(ranges_to_replace.iter())
17989                    .find_map(|(selection, range)| {
17990                        if selection.id == newest_selection_id {
17991                            Some(
17992                                (range.start.0 as isize - selection.head().0 as isize)
17993                                    ..(range.end.0 as isize - selection.head().0 as isize),
17994                            )
17995                        } else {
17996                            None
17997                        }
17998                    })
17999            });
18000
18001            cx.emit(EditorEvent::InputHandled {
18002                utf16_range_to_replace: range_to_replace,
18003                text: text.into(),
18004            });
18005
18006            if let Some(new_selected_ranges) = new_selected_ranges {
18007                this.change_selections(None, window, cx, |selections| {
18008                    selections.select_ranges(new_selected_ranges)
18009                });
18010                this.backspace(&Default::default(), window, cx);
18011            }
18012
18013            this.handle_input(text, window, cx);
18014        });
18015
18016        if let Some(transaction) = self.ime_transaction {
18017            self.buffer.update(cx, |buffer, cx| {
18018                buffer.group_until_transaction(transaction, cx);
18019            });
18020        }
18021
18022        self.unmark_text(window, cx);
18023    }
18024
18025    fn replace_and_mark_text_in_range(
18026        &mut self,
18027        range_utf16: Option<Range<usize>>,
18028        text: &str,
18029        new_selected_range_utf16: Option<Range<usize>>,
18030        window: &mut Window,
18031        cx: &mut Context<Self>,
18032    ) {
18033        if !self.input_enabled {
18034            return;
18035        }
18036
18037        let transaction = self.transact(window, cx, |this, window, cx| {
18038            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
18039                let snapshot = this.buffer.read(cx).read(cx);
18040                if let Some(relative_range_utf16) = range_utf16.as_ref() {
18041                    for marked_range in &mut marked_ranges {
18042                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
18043                        marked_range.start.0 += relative_range_utf16.start;
18044                        marked_range.start =
18045                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
18046                        marked_range.end =
18047                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
18048                    }
18049                }
18050                Some(marked_ranges)
18051            } else if let Some(range_utf16) = range_utf16 {
18052                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
18053                Some(this.selection_replacement_ranges(range_utf16, cx))
18054            } else {
18055                None
18056            };
18057
18058            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
18059                let newest_selection_id = this.selections.newest_anchor().id;
18060                this.selections
18061                    .all::<OffsetUtf16>(cx)
18062                    .iter()
18063                    .zip(ranges_to_replace.iter())
18064                    .find_map(|(selection, range)| {
18065                        if selection.id == newest_selection_id {
18066                            Some(
18067                                (range.start.0 as isize - selection.head().0 as isize)
18068                                    ..(range.end.0 as isize - selection.head().0 as isize),
18069                            )
18070                        } else {
18071                            None
18072                        }
18073                    })
18074            });
18075
18076            cx.emit(EditorEvent::InputHandled {
18077                utf16_range_to_replace: range_to_replace,
18078                text: text.into(),
18079            });
18080
18081            if let Some(ranges) = ranges_to_replace {
18082                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
18083            }
18084
18085            let marked_ranges = {
18086                let snapshot = this.buffer.read(cx).read(cx);
18087                this.selections
18088                    .disjoint_anchors()
18089                    .iter()
18090                    .map(|selection| {
18091                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
18092                    })
18093                    .collect::<Vec<_>>()
18094            };
18095
18096            if text.is_empty() {
18097                this.unmark_text(window, cx);
18098            } else {
18099                this.highlight_text::<InputComposition>(
18100                    marked_ranges.clone(),
18101                    HighlightStyle {
18102                        underline: Some(UnderlineStyle {
18103                            thickness: px(1.),
18104                            color: None,
18105                            wavy: false,
18106                        }),
18107                        ..Default::default()
18108                    },
18109                    cx,
18110                );
18111            }
18112
18113            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
18114            let use_autoclose = this.use_autoclose;
18115            let use_auto_surround = this.use_auto_surround;
18116            this.set_use_autoclose(false);
18117            this.set_use_auto_surround(false);
18118            this.handle_input(text, window, cx);
18119            this.set_use_autoclose(use_autoclose);
18120            this.set_use_auto_surround(use_auto_surround);
18121
18122            if let Some(new_selected_range) = new_selected_range_utf16 {
18123                let snapshot = this.buffer.read(cx).read(cx);
18124                let new_selected_ranges = marked_ranges
18125                    .into_iter()
18126                    .map(|marked_range| {
18127                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
18128                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
18129                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
18130                        snapshot.clip_offset_utf16(new_start, Bias::Left)
18131                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
18132                    })
18133                    .collect::<Vec<_>>();
18134
18135                drop(snapshot);
18136                this.change_selections(None, window, cx, |selections| {
18137                    selections.select_ranges(new_selected_ranges)
18138                });
18139            }
18140        });
18141
18142        self.ime_transaction = self.ime_transaction.or(transaction);
18143        if let Some(transaction) = self.ime_transaction {
18144            self.buffer.update(cx, |buffer, cx| {
18145                buffer.group_until_transaction(transaction, cx);
18146            });
18147        }
18148
18149        if self.text_highlights::<InputComposition>(cx).is_none() {
18150            self.ime_transaction.take();
18151        }
18152    }
18153
18154    fn bounds_for_range(
18155        &mut self,
18156        range_utf16: Range<usize>,
18157        element_bounds: gpui::Bounds<Pixels>,
18158        window: &mut Window,
18159        cx: &mut Context<Self>,
18160    ) -> Option<gpui::Bounds<Pixels>> {
18161        let text_layout_details = self.text_layout_details(window);
18162        let gpui::Size {
18163            width: em_width,
18164            height: line_height,
18165        } = self.character_size(window);
18166
18167        let snapshot = self.snapshot(window, cx);
18168        let scroll_position = snapshot.scroll_position();
18169        let scroll_left = scroll_position.x * em_width;
18170
18171        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
18172        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
18173            + self.gutter_dimensions.width
18174            + self.gutter_dimensions.margin;
18175        let y = line_height * (start.row().as_f32() - scroll_position.y);
18176
18177        Some(Bounds {
18178            origin: element_bounds.origin + point(x, y),
18179            size: size(em_width, line_height),
18180        })
18181    }
18182
18183    fn character_index_for_point(
18184        &mut self,
18185        point: gpui::Point<Pixels>,
18186        _window: &mut Window,
18187        _cx: &mut Context<Self>,
18188    ) -> Option<usize> {
18189        let position_map = self.last_position_map.as_ref()?;
18190        if !position_map.text_hitbox.contains(&point) {
18191            return None;
18192        }
18193        let display_point = position_map.point_for_position(point).previous_valid;
18194        let anchor = position_map
18195            .snapshot
18196            .display_point_to_anchor(display_point, Bias::Left);
18197        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
18198        Some(utf16_offset.0)
18199    }
18200}
18201
18202trait SelectionExt {
18203    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
18204    fn spanned_rows(
18205        &self,
18206        include_end_if_at_line_start: bool,
18207        map: &DisplaySnapshot,
18208    ) -> Range<MultiBufferRow>;
18209}
18210
18211impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
18212    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
18213        let start = self
18214            .start
18215            .to_point(&map.buffer_snapshot)
18216            .to_display_point(map);
18217        let end = self
18218            .end
18219            .to_point(&map.buffer_snapshot)
18220            .to_display_point(map);
18221        if self.reversed {
18222            end..start
18223        } else {
18224            start..end
18225        }
18226    }
18227
18228    fn spanned_rows(
18229        &self,
18230        include_end_if_at_line_start: bool,
18231        map: &DisplaySnapshot,
18232    ) -> Range<MultiBufferRow> {
18233        let start = self.start.to_point(&map.buffer_snapshot);
18234        let mut end = self.end.to_point(&map.buffer_snapshot);
18235        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
18236            end.row -= 1;
18237        }
18238
18239        let buffer_start = map.prev_line_boundary(start).0;
18240        let buffer_end = map.next_line_boundary(end).0;
18241        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
18242    }
18243}
18244
18245impl<T: InvalidationRegion> InvalidationStack<T> {
18246    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
18247    where
18248        S: Clone + ToOffset,
18249    {
18250        while let Some(region) = self.last() {
18251            let all_selections_inside_invalidation_ranges =
18252                if selections.len() == region.ranges().len() {
18253                    selections
18254                        .iter()
18255                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
18256                        .all(|(selection, invalidation_range)| {
18257                            let head = selection.head().to_offset(buffer);
18258                            invalidation_range.start <= head && invalidation_range.end >= head
18259                        })
18260                } else {
18261                    false
18262                };
18263
18264            if all_selections_inside_invalidation_ranges {
18265                break;
18266            } else {
18267                self.pop();
18268            }
18269        }
18270    }
18271}
18272
18273impl<T> Default for InvalidationStack<T> {
18274    fn default() -> Self {
18275        Self(Default::default())
18276    }
18277}
18278
18279impl<T> Deref for InvalidationStack<T> {
18280    type Target = Vec<T>;
18281
18282    fn deref(&self) -> &Self::Target {
18283        &self.0
18284    }
18285}
18286
18287impl<T> DerefMut for InvalidationStack<T> {
18288    fn deref_mut(&mut self) -> &mut Self::Target {
18289        &mut self.0
18290    }
18291}
18292
18293impl InvalidationRegion for SnippetState {
18294    fn ranges(&self) -> &[Range<Anchor>] {
18295        &self.ranges[self.active_index]
18296    }
18297}
18298
18299pub fn diagnostic_block_renderer(
18300    diagnostic: Diagnostic,
18301    max_message_rows: Option<u8>,
18302    allow_closing: bool,
18303) -> RenderBlock {
18304    let (text_without_backticks, code_ranges) =
18305        highlight_diagnostic_message(&diagnostic, max_message_rows);
18306
18307    Arc::new(move |cx: &mut BlockContext| {
18308        let group_id: SharedString = cx.block_id.to_string().into();
18309
18310        let mut text_style = cx.window.text_style().clone();
18311        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
18312        let theme_settings = ThemeSettings::get_global(cx);
18313        text_style.font_family = theme_settings.buffer_font.family.clone();
18314        text_style.font_style = theme_settings.buffer_font.style;
18315        text_style.font_features = theme_settings.buffer_font.features.clone();
18316        text_style.font_weight = theme_settings.buffer_font.weight;
18317
18318        let multi_line_diagnostic = diagnostic.message.contains('\n');
18319
18320        let buttons = |diagnostic: &Diagnostic| {
18321            if multi_line_diagnostic {
18322                v_flex()
18323            } else {
18324                h_flex()
18325            }
18326            .when(allow_closing, |div| {
18327                div.children(diagnostic.is_primary.then(|| {
18328                    IconButton::new("close-block", IconName::XCircle)
18329                        .icon_color(Color::Muted)
18330                        .size(ButtonSize::Compact)
18331                        .style(ButtonStyle::Transparent)
18332                        .visible_on_hover(group_id.clone())
18333                        .on_click(move |_click, window, cx| {
18334                            window.dispatch_action(Box::new(Cancel), cx)
18335                        })
18336                        .tooltip(|window, cx| {
18337                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
18338                        })
18339                }))
18340            })
18341            .child(
18342                IconButton::new("copy-block", IconName::Copy)
18343                    .icon_color(Color::Muted)
18344                    .size(ButtonSize::Compact)
18345                    .style(ButtonStyle::Transparent)
18346                    .visible_on_hover(group_id.clone())
18347                    .on_click({
18348                        let message = diagnostic.message.clone();
18349                        move |_click, _, cx| {
18350                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
18351                        }
18352                    })
18353                    .tooltip(Tooltip::text("Copy diagnostic message")),
18354            )
18355        };
18356
18357        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
18358            AvailableSpace::min_size(),
18359            cx.window,
18360            cx.app,
18361        );
18362
18363        h_flex()
18364            .id(cx.block_id)
18365            .group(group_id.clone())
18366            .relative()
18367            .size_full()
18368            .block_mouse_down()
18369            .pl(cx.gutter_dimensions.width)
18370            .w(cx.max_width - cx.gutter_dimensions.full_width())
18371            .child(
18372                div()
18373                    .flex()
18374                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
18375                    .flex_shrink(),
18376            )
18377            .child(buttons(&diagnostic))
18378            .child(div().flex().flex_shrink_0().child(
18379                StyledText::new(text_without_backticks.clone()).with_default_highlights(
18380                    &text_style,
18381                    code_ranges.iter().map(|range| {
18382                        (
18383                            range.clone(),
18384                            HighlightStyle {
18385                                font_weight: Some(FontWeight::BOLD),
18386                                ..Default::default()
18387                            },
18388                        )
18389                    }),
18390                ),
18391            ))
18392            .into_any_element()
18393    })
18394}
18395
18396fn inline_completion_edit_text(
18397    current_snapshot: &BufferSnapshot,
18398    edits: &[(Range<Anchor>, String)],
18399    edit_preview: &EditPreview,
18400    include_deletions: bool,
18401    cx: &App,
18402) -> HighlightedText {
18403    let edits = edits
18404        .iter()
18405        .map(|(anchor, text)| {
18406            (
18407                anchor.start.text_anchor..anchor.end.text_anchor,
18408                text.clone(),
18409            )
18410        })
18411        .collect::<Vec<_>>();
18412
18413    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18414}
18415
18416pub fn highlight_diagnostic_message(
18417    diagnostic: &Diagnostic,
18418    mut max_message_rows: Option<u8>,
18419) -> (SharedString, Vec<Range<usize>>) {
18420    let mut text_without_backticks = String::new();
18421    let mut code_ranges = Vec::new();
18422
18423    if let Some(source) = &diagnostic.source {
18424        text_without_backticks.push_str(source);
18425        code_ranges.push(0..source.len());
18426        text_without_backticks.push_str(": ");
18427    }
18428
18429    let mut prev_offset = 0;
18430    let mut in_code_block = false;
18431    let has_row_limit = max_message_rows.is_some();
18432    let mut newline_indices = diagnostic
18433        .message
18434        .match_indices('\n')
18435        .filter(|_| has_row_limit)
18436        .map(|(ix, _)| ix)
18437        .fuse()
18438        .peekable();
18439
18440    for (quote_ix, _) in diagnostic
18441        .message
18442        .match_indices('`')
18443        .chain([(diagnostic.message.len(), "")])
18444    {
18445        let mut first_newline_ix = None;
18446        let mut last_newline_ix = None;
18447        while let Some(newline_ix) = newline_indices.peek() {
18448            if *newline_ix < quote_ix {
18449                if first_newline_ix.is_none() {
18450                    first_newline_ix = Some(*newline_ix);
18451                }
18452                last_newline_ix = Some(*newline_ix);
18453
18454                if let Some(rows_left) = &mut max_message_rows {
18455                    if *rows_left == 0 {
18456                        break;
18457                    } else {
18458                        *rows_left -= 1;
18459                    }
18460                }
18461                let _ = newline_indices.next();
18462            } else {
18463                break;
18464            }
18465        }
18466        let prev_len = text_without_backticks.len();
18467        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18468        text_without_backticks.push_str(new_text);
18469        if in_code_block {
18470            code_ranges.push(prev_len..text_without_backticks.len());
18471        }
18472        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18473        in_code_block = !in_code_block;
18474        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18475            text_without_backticks.push_str("...");
18476            break;
18477        }
18478    }
18479
18480    (text_without_backticks.into(), code_ranges)
18481}
18482
18483fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18484    match severity {
18485        DiagnosticSeverity::ERROR => colors.error,
18486        DiagnosticSeverity::WARNING => colors.warning,
18487        DiagnosticSeverity::INFORMATION => colors.info,
18488        DiagnosticSeverity::HINT => colors.info,
18489        _ => colors.ignored,
18490    }
18491}
18492
18493pub fn styled_runs_for_code_label<'a>(
18494    label: &'a CodeLabel,
18495    syntax_theme: &'a theme::SyntaxTheme,
18496) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18497    let fade_out = HighlightStyle {
18498        fade_out: Some(0.35),
18499        ..Default::default()
18500    };
18501
18502    let mut prev_end = label.filter_range.end;
18503    label
18504        .runs
18505        .iter()
18506        .enumerate()
18507        .flat_map(move |(ix, (range, highlight_id))| {
18508            let style = if let Some(style) = highlight_id.style(syntax_theme) {
18509                style
18510            } else {
18511                return Default::default();
18512            };
18513            let mut muted_style = style;
18514            muted_style.highlight(fade_out);
18515
18516            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18517            if range.start >= label.filter_range.end {
18518                if range.start > prev_end {
18519                    runs.push((prev_end..range.start, fade_out));
18520                }
18521                runs.push((range.clone(), muted_style));
18522            } else if range.end <= label.filter_range.end {
18523                runs.push((range.clone(), style));
18524            } else {
18525                runs.push((range.start..label.filter_range.end, style));
18526                runs.push((label.filter_range.end..range.end, muted_style));
18527            }
18528            prev_end = cmp::max(prev_end, range.end);
18529
18530            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18531                runs.push((prev_end..label.text.len(), fade_out));
18532            }
18533
18534            runs
18535        })
18536}
18537
18538pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18539    let mut prev_index = 0;
18540    let mut prev_codepoint: Option<char> = None;
18541    text.char_indices()
18542        .chain([(text.len(), '\0')])
18543        .filter_map(move |(index, codepoint)| {
18544            let prev_codepoint = prev_codepoint.replace(codepoint)?;
18545            let is_boundary = index == text.len()
18546                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18547                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18548            if is_boundary {
18549                let chunk = &text[prev_index..index];
18550                prev_index = index;
18551                Some(chunk)
18552            } else {
18553                None
18554            }
18555        })
18556}
18557
18558pub trait RangeToAnchorExt: Sized {
18559    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18560
18561    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18562        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18563        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18564    }
18565}
18566
18567impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18568    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18569        let start_offset = self.start.to_offset(snapshot);
18570        let end_offset = self.end.to_offset(snapshot);
18571        if start_offset == end_offset {
18572            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18573        } else {
18574            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18575        }
18576    }
18577}
18578
18579pub trait RowExt {
18580    fn as_f32(&self) -> f32;
18581
18582    fn next_row(&self) -> Self;
18583
18584    fn previous_row(&self) -> Self;
18585
18586    fn minus(&self, other: Self) -> u32;
18587}
18588
18589impl RowExt for DisplayRow {
18590    fn as_f32(&self) -> f32 {
18591        self.0 as f32
18592    }
18593
18594    fn next_row(&self) -> Self {
18595        Self(self.0 + 1)
18596    }
18597
18598    fn previous_row(&self) -> Self {
18599        Self(self.0.saturating_sub(1))
18600    }
18601
18602    fn minus(&self, other: Self) -> u32 {
18603        self.0 - other.0
18604    }
18605}
18606
18607impl RowExt for MultiBufferRow {
18608    fn as_f32(&self) -> f32 {
18609        self.0 as f32
18610    }
18611
18612    fn next_row(&self) -> Self {
18613        Self(self.0 + 1)
18614    }
18615
18616    fn previous_row(&self) -> Self {
18617        Self(self.0.saturating_sub(1))
18618    }
18619
18620    fn minus(&self, other: Self) -> u32 {
18621        self.0 - other.0
18622    }
18623}
18624
18625trait RowRangeExt {
18626    type Row;
18627
18628    fn len(&self) -> usize;
18629
18630    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18631}
18632
18633impl RowRangeExt for Range<MultiBufferRow> {
18634    type Row = MultiBufferRow;
18635
18636    fn len(&self) -> usize {
18637        (self.end.0 - self.start.0) as usize
18638    }
18639
18640    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18641        (self.start.0..self.end.0).map(MultiBufferRow)
18642    }
18643}
18644
18645impl RowRangeExt for Range<DisplayRow> {
18646    type Row = DisplayRow;
18647
18648    fn len(&self) -> usize {
18649        (self.end.0 - self.start.0) as usize
18650    }
18651
18652    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18653        (self.start.0..self.end.0).map(DisplayRow)
18654    }
18655}
18656
18657/// If select range has more than one line, we
18658/// just point the cursor to range.start.
18659fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18660    if range.start.row == range.end.row {
18661        range
18662    } else {
18663        range.start..range.start
18664    }
18665}
18666pub struct KillRing(ClipboardItem);
18667impl Global for KillRing {}
18668
18669const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18670
18671fn all_edits_insertions_or_deletions(
18672    edits: &Vec<(Range<Anchor>, String)>,
18673    snapshot: &MultiBufferSnapshot,
18674) -> bool {
18675    let mut all_insertions = true;
18676    let mut all_deletions = true;
18677
18678    for (range, new_text) in edits.iter() {
18679        let range_is_empty = range.to_offset(&snapshot).is_empty();
18680        let text_is_empty = new_text.is_empty();
18681
18682        if range_is_empty != text_is_empty {
18683            if range_is_empty {
18684                all_deletions = false;
18685            } else {
18686                all_insertions = false;
18687            }
18688        } else {
18689            return false;
18690        }
18691
18692        if !all_insertions && !all_deletions {
18693            return false;
18694        }
18695    }
18696    all_insertions || all_deletions
18697}
18698
18699struct MissingEditPredictionKeybindingTooltip;
18700
18701impl Render for MissingEditPredictionKeybindingTooltip {
18702    fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18703        ui::tooltip_container(window, cx, |container, _, cx| {
18704            container
18705                .flex_shrink_0()
18706                .max_w_80()
18707                .min_h(rems_from_px(124.))
18708                .justify_between()
18709                .child(
18710                    v_flex()
18711                        .flex_1()
18712                        .text_ui_sm(cx)
18713                        .child(Label::new("Conflict with Accept Keybinding"))
18714                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
18715                )
18716                .child(
18717                    h_flex()
18718                        .pb_1()
18719                        .gap_1()
18720                        .items_end()
18721                        .w_full()
18722                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
18723                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
18724                        }))
18725                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
18726                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
18727                        })),
18728                )
18729        })
18730    }
18731}
18732
18733#[derive(Debug, Clone, Copy, PartialEq)]
18734pub struct LineHighlight {
18735    pub background: Background,
18736    pub border: Option<gpui::Hsla>,
18737}
18738
18739impl From<Hsla> for LineHighlight {
18740    fn from(hsla: Hsla) -> Self {
18741        Self {
18742            background: hsla.into(),
18743            border: None,
18744        }
18745    }
18746}
18747
18748impl From<Background> for LineHighlight {
18749    fn from(background: Background) -> Self {
18750        Self {
18751            background,
18752            border: None,
18753        }
18754    }
18755}