editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod commit_tooltip;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use buffer_diff::{DiffHunkSecondaryStatus, DiffHunkStatus};
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{
   71    future::{self, Shared},
   72    FutureExt,
   73};
   74use fuzzy::StringMatchCandidate;
   75
   76use ::git::{status::FileStatus, Restore};
   77use code_context_menus::{
   78    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   79    CompletionsMenu, ContextMenuOrigin,
   80};
   81use git::blame::GitBlame;
   82use gpui::{
   83    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   84    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   85    ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler,
   86    EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
   87    HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
   88    ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription, Task,
   89    TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   90    WeakEntity, WeakFocusHandle, Window,
   91};
   92use highlight_matching_bracket::refresh_matching_bracket_highlights;
   93use hover_popover::{hide_hover, HoverState};
   94use indent_guides::ActiveIndentGuidesState;
   95use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   96pub use inline_completion::Direction;
   97use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   98pub use items::MAX_TAB_TITLE_LEN;
   99use itertools::Itertools;
  100use language::{
  101    language_settings::{
  102        self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
  103    },
  104    point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
  105    Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, EditPredictionsMode,
  106    EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
  107    Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
  108};
  109use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  110use linked_editing_ranges::refresh_linked_ranges;
  111use mouse_context_menu::MouseContextMenu;
  112use persistence::DB;
  113pub use proposed_changes_editor::{
  114    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  115};
  116use smallvec::smallvec;
  117use std::iter::Peekable;
  118use task::{ResolvedTask, TaskTemplate, TaskVariables};
  119
  120use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  121pub use lsp::CompletionContext;
  122use lsp::{
  123    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  124    LanguageServerId, LanguageServerName,
  125};
  126
  127use language::BufferSnapshot;
  128use movement::TextLayoutDetails;
  129pub use multi_buffer::{
  130    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  131    ToOffset, ToPoint,
  132};
  133use multi_buffer::{
  134    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  135    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  136};
  137use project::{
  138    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  139    project_settings::{GitGutterSetting, ProjectSettings},
  140    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  141    PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  142};
  143use rand::prelude::*;
  144use rpc::{proto::*, ErrorExt};
  145use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  146use selections_collection::{
  147    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  148};
  149use serde::{Deserialize, Serialize};
  150use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  151use smallvec::SmallVec;
  152use snippet::Snippet;
  153use std::{
  154    any::TypeId,
  155    borrow::Cow,
  156    cell::RefCell,
  157    cmp::{self, Ordering, Reverse},
  158    mem,
  159    num::NonZeroU32,
  160    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  161    path::{Path, PathBuf},
  162    rc::Rc,
  163    sync::Arc,
  164    time::{Duration, Instant},
  165};
  166pub use sum_tree::Bias;
  167use sum_tree::TreeMap;
  168use text::{BufferId, OffsetUtf16, Rope};
  169use theme::{
  170    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  171    ThemeColors, ThemeSettings,
  172};
  173use ui::{
  174    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  175    Tooltip,
  176};
  177use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  178use workspace::{
  179    item::{ItemHandle, PreviewTabsSettings},
  180    ItemId, RestoreOnStartupBehavior,
  181};
  182use workspace::{
  183    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  184    WorkspaceSettings,
  185};
  186use workspace::{
  187    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  188};
  189use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  190
  191use crate::hover_links::{find_url, find_url_from_range};
  192use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  193
  194pub const FILE_HEADER_HEIGHT: u32 = 2;
  195pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  196pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  197pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  198const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  199const MAX_LINE_LEN: usize = 1024;
  200const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  201const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  202pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  203#[doc(hidden)]
  204pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  205
  206pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  207pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  208
  209pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  210pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  211
  212const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  213    alt: true,
  214    shift: true,
  215    control: false,
  216    platform: false,
  217    function: false,
  218};
  219
  220#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  221pub enum InlayId {
  222    InlineCompletion(usize),
  223    Hint(usize),
  224}
  225
  226impl InlayId {
  227    fn id(&self) -> usize {
  228        match self {
  229            Self::InlineCompletion(id) => *id,
  230            Self::Hint(id) => *id,
  231        }
  232    }
  233}
  234
  235enum DocumentHighlightRead {}
  236enum DocumentHighlightWrite {}
  237enum InputComposition {}
  238enum SelectedTextHighlight {}
  239
  240#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  241pub enum Navigated {
  242    Yes,
  243    No,
  244}
  245
  246impl Navigated {
  247    pub fn from_bool(yes: bool) -> Navigated {
  248        if yes {
  249            Navigated::Yes
  250        } else {
  251            Navigated::No
  252        }
  253    }
  254}
  255
  256#[derive(Debug, Clone, PartialEq, Eq)]
  257enum DisplayDiffHunk {
  258    Folded {
  259        display_row: DisplayRow,
  260    },
  261    Unfolded {
  262        diff_base_byte_range: Range<usize>,
  263        display_row_range: Range<DisplayRow>,
  264        multi_buffer_range: Range<Anchor>,
  265        status: DiffHunkStatus,
  266    },
  267}
  268
  269pub fn init_settings(cx: &mut App) {
  270    EditorSettings::register(cx);
  271}
  272
  273pub fn init(cx: &mut App) {
  274    init_settings(cx);
  275
  276    workspace::register_project_item::<Editor>(cx);
  277    workspace::FollowableViewRegistry::register::<Editor>(cx);
  278    workspace::register_serializable_item::<Editor>(cx);
  279
  280    cx.observe_new(
  281        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  282            workspace.register_action(Editor::new_file);
  283            workspace.register_action(Editor::new_file_vertical);
  284            workspace.register_action(Editor::new_file_horizontal);
  285            workspace.register_action(Editor::cancel_language_server_work);
  286        },
  287    )
  288    .detach();
  289
  290    cx.on_action(move |_: &workspace::NewFile, cx| {
  291        let app_state = workspace::AppState::global(cx);
  292        if let Some(app_state) = app_state.upgrade() {
  293            workspace::open_new(
  294                Default::default(),
  295                app_state,
  296                cx,
  297                |workspace, window, cx| {
  298                    Editor::new_file(workspace, &Default::default(), window, cx)
  299                },
  300            )
  301            .detach();
  302        }
  303    });
  304    cx.on_action(move |_: &workspace::NewWindow, cx| {
  305        let app_state = workspace::AppState::global(cx);
  306        if let Some(app_state) = app_state.upgrade() {
  307            workspace::open_new(
  308                Default::default(),
  309                app_state,
  310                cx,
  311                |workspace, window, cx| {
  312                    cx.activate(true);
  313                    Editor::new_file(workspace, &Default::default(), window, cx)
  314                },
  315            )
  316            .detach();
  317        }
  318    });
  319}
  320
  321pub struct SearchWithinRange;
  322
  323trait InvalidationRegion {
  324    fn ranges(&self) -> &[Range<Anchor>];
  325}
  326
  327#[derive(Clone, Debug, PartialEq)]
  328pub enum SelectPhase {
  329    Begin {
  330        position: DisplayPoint,
  331        add: bool,
  332        click_count: usize,
  333    },
  334    BeginColumnar {
  335        position: DisplayPoint,
  336        reset: bool,
  337        goal_column: u32,
  338    },
  339    Extend {
  340        position: DisplayPoint,
  341        click_count: usize,
  342    },
  343    Update {
  344        position: DisplayPoint,
  345        goal_column: u32,
  346        scroll_delta: gpui::Point<f32>,
  347    },
  348    End,
  349}
  350
  351#[derive(Clone, Debug)]
  352pub enum SelectMode {
  353    Character,
  354    Word(Range<Anchor>),
  355    Line(Range<Anchor>),
  356    All,
  357}
  358
  359#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  360pub enum EditorMode {
  361    SingleLine { auto_width: bool },
  362    AutoHeight { max_lines: usize },
  363    Full,
  364}
  365
  366#[derive(Copy, Clone, Debug)]
  367pub enum SoftWrap {
  368    /// Prefer not to wrap at all.
  369    ///
  370    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  371    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  372    GitDiff,
  373    /// Prefer a single line generally, unless an overly long line is encountered.
  374    None,
  375    /// Soft wrap lines that exceed the editor width.
  376    EditorWidth,
  377    /// Soft wrap lines at the preferred line length.
  378    Column(u32),
  379    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  380    Bounded(u32),
  381}
  382
  383#[derive(Clone)]
  384pub struct EditorStyle {
  385    pub background: Hsla,
  386    pub local_player: PlayerColor,
  387    pub text: TextStyle,
  388    pub scrollbar_width: Pixels,
  389    pub syntax: Arc<SyntaxTheme>,
  390    pub status: StatusColors,
  391    pub inlay_hints_style: HighlightStyle,
  392    pub inline_completion_styles: InlineCompletionStyles,
  393    pub unnecessary_code_fade: f32,
  394}
  395
  396impl Default for EditorStyle {
  397    fn default() -> Self {
  398        Self {
  399            background: Hsla::default(),
  400            local_player: PlayerColor::default(),
  401            text: TextStyle::default(),
  402            scrollbar_width: Pixels::default(),
  403            syntax: Default::default(),
  404            // HACK: Status colors don't have a real default.
  405            // We should look into removing the status colors from the editor
  406            // style and retrieve them directly from the theme.
  407            status: StatusColors::dark(),
  408            inlay_hints_style: HighlightStyle::default(),
  409            inline_completion_styles: InlineCompletionStyles {
  410                insertion: HighlightStyle::default(),
  411                whitespace: HighlightStyle::default(),
  412            },
  413            unnecessary_code_fade: Default::default(),
  414        }
  415    }
  416}
  417
  418pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  419    let show_background = language_settings::language_settings(None, None, cx)
  420        .inlay_hints
  421        .show_background;
  422
  423    HighlightStyle {
  424        color: Some(cx.theme().status().hint),
  425        background_color: show_background.then(|| cx.theme().status().hint_background),
  426        ..HighlightStyle::default()
  427    }
  428}
  429
  430pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  431    InlineCompletionStyles {
  432        insertion: HighlightStyle {
  433            color: Some(cx.theme().status().predictive),
  434            ..HighlightStyle::default()
  435        },
  436        whitespace: HighlightStyle {
  437            background_color: Some(cx.theme().status().created_background),
  438            ..HighlightStyle::default()
  439        },
  440    }
  441}
  442
  443type CompletionId = usize;
  444
  445pub(crate) enum EditDisplayMode {
  446    TabAccept,
  447    DiffPopover,
  448    Inline,
  449}
  450
  451enum InlineCompletion {
  452    Edit {
  453        edits: Vec<(Range<Anchor>, String)>,
  454        edit_preview: Option<EditPreview>,
  455        display_mode: EditDisplayMode,
  456        snapshot: BufferSnapshot,
  457    },
  458    Move {
  459        target: Anchor,
  460        snapshot: BufferSnapshot,
  461    },
  462}
  463
  464struct InlineCompletionState {
  465    inlay_ids: Vec<InlayId>,
  466    completion: InlineCompletion,
  467    completion_id: Option<SharedString>,
  468    invalidation_range: Range<Anchor>,
  469}
  470
  471enum EditPredictionSettings {
  472    Disabled,
  473    Enabled {
  474        show_in_menu: bool,
  475        preview_requires_modifier: bool,
  476    },
  477}
  478
  479enum InlineCompletionHighlight {}
  480
  481#[derive(Debug, Clone)]
  482struct InlineDiagnostic {
  483    message: SharedString,
  484    group_id: usize,
  485    is_primary: bool,
  486    start: Point,
  487    severity: DiagnosticSeverity,
  488}
  489
  490pub enum MenuInlineCompletionsPolicy {
  491    Never,
  492    ByProvider,
  493}
  494
  495pub enum EditPredictionPreview {
  496    /// Modifier is not pressed
  497    Inactive { released_too_fast: bool },
  498    /// Modifier pressed
  499    Active {
  500        since: Instant,
  501        previous_scroll_position: Option<ScrollAnchor>,
  502    },
  503}
  504
  505impl EditPredictionPreview {
  506    pub fn released_too_fast(&self) -> bool {
  507        match self {
  508            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  509            EditPredictionPreview::Active { .. } => false,
  510        }
  511    }
  512
  513    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  514        if let EditPredictionPreview::Active {
  515            previous_scroll_position,
  516            ..
  517        } = self
  518        {
  519            *previous_scroll_position = scroll_position;
  520        }
  521    }
  522}
  523
  524#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  525struct EditorActionId(usize);
  526
  527impl EditorActionId {
  528    pub fn post_inc(&mut self) -> Self {
  529        let answer = self.0;
  530
  531        *self = Self(answer + 1);
  532
  533        Self(answer)
  534    }
  535}
  536
  537// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  538// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  539
  540type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  541type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  542
  543#[derive(Default)]
  544struct ScrollbarMarkerState {
  545    scrollbar_size: Size<Pixels>,
  546    dirty: bool,
  547    markers: Arc<[PaintQuad]>,
  548    pending_refresh: Option<Task<Result<()>>>,
  549}
  550
  551impl ScrollbarMarkerState {
  552    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  553        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  554    }
  555}
  556
  557#[derive(Clone, Debug)]
  558struct RunnableTasks {
  559    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  560    offset: multi_buffer::Anchor,
  561    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  562    column: u32,
  563    // Values of all named captures, including those starting with '_'
  564    extra_variables: HashMap<String, String>,
  565    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  566    context_range: Range<BufferOffset>,
  567}
  568
  569impl RunnableTasks {
  570    fn resolve<'a>(
  571        &'a self,
  572        cx: &'a task::TaskContext,
  573    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  574        self.templates.iter().filter_map(|(kind, template)| {
  575            template
  576                .resolve_task(&kind.to_id_base(), cx)
  577                .map(|task| (kind.clone(), task))
  578        })
  579    }
  580}
  581
  582#[derive(Clone)]
  583struct ResolvedTasks {
  584    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  585    position: Anchor,
  586}
  587#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  588struct BufferOffset(usize);
  589
  590// Addons allow storing per-editor state in other crates (e.g. Vim)
  591pub trait Addon: 'static {
  592    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  593
  594    fn render_buffer_header_controls(
  595        &self,
  596        _: &ExcerptInfo,
  597        _: &Window,
  598        _: &App,
  599    ) -> Option<AnyElement> {
  600        None
  601    }
  602
  603    fn to_any(&self) -> &dyn std::any::Any;
  604}
  605
  606#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  607pub enum IsVimMode {
  608    Yes,
  609    No,
  610}
  611
  612/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  613///
  614/// See the [module level documentation](self) for more information.
  615pub struct Editor {
  616    focus_handle: FocusHandle,
  617    last_focused_descendant: Option<WeakFocusHandle>,
  618    /// The text buffer being edited
  619    buffer: Entity<MultiBuffer>,
  620    /// Map of how text in the buffer should be displayed.
  621    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  622    pub display_map: Entity<DisplayMap>,
  623    pub selections: SelectionsCollection,
  624    pub scroll_manager: ScrollManager,
  625    /// When inline assist editors are linked, they all render cursors because
  626    /// typing enters text into each of them, even the ones that aren't focused.
  627    pub(crate) show_cursor_when_unfocused: bool,
  628    columnar_selection_tail: Option<Anchor>,
  629    add_selections_state: Option<AddSelectionsState>,
  630    select_next_state: Option<SelectNextState>,
  631    select_prev_state: Option<SelectNextState>,
  632    selection_history: SelectionHistory,
  633    autoclose_regions: Vec<AutocloseRegion>,
  634    snippet_stack: InvalidationStack<SnippetState>,
  635    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  636    ime_transaction: Option<TransactionId>,
  637    active_diagnostics: Option<ActiveDiagnosticGroup>,
  638    show_inline_diagnostics: bool,
  639    inline_diagnostics_update: Task<()>,
  640    inline_diagnostics_enabled: bool,
  641    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  642    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  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    show_git_blame_gutter: bool,
  727    show_git_blame_inline: bool,
  728    show_git_blame_inline_delay_task: Option<Task<()>>,
  729    git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
  730    git_blame_inline_enabled: bool,
  731    serialize_dirty_buffers: bool,
  732    show_selection_menu: Option<bool>,
  733    blame: Option<Entity<GitBlame>>,
  734    blame_subscription: Option<Subscription>,
  735    custom_context_menu: Option<
  736        Box<
  737            dyn 'static
  738                + Fn(
  739                    &mut Self,
  740                    DisplayPoint,
  741                    &mut Window,
  742                    &mut Context<Self>,
  743                ) -> Option<Entity<ui::ContextMenu>>,
  744        >,
  745    >,
  746    last_bounds: Option<Bounds<Pixels>>,
  747    last_position_map: Option<Rc<PositionMap>>,
  748    expect_bounds_change: Option<Bounds<Pixels>>,
  749    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  750    tasks_update_task: Option<Task<()>>,
  751    in_project_search: bool,
  752    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  753    breadcrumb_header: Option<String>,
  754    focused_block: Option<FocusedBlock>,
  755    next_scroll_position: NextScrollCursorCenterTopBottom,
  756    addons: HashMap<TypeId, Box<dyn Addon>>,
  757    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  758    load_diff_task: Option<Shared<Task<()>>>,
  759    selection_mark_mode: bool,
  760    toggle_fold_multiple_buffers: Task<()>,
  761    _scroll_cursor_center_top_bottom_task: Task<()>,
  762    serialize_selections: Task<()>,
  763}
  764
  765#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  766enum NextScrollCursorCenterTopBottom {
  767    #[default]
  768    Center,
  769    Top,
  770    Bottom,
  771}
  772
  773impl NextScrollCursorCenterTopBottom {
  774    fn next(&self) -> Self {
  775        match self {
  776            Self::Center => Self::Top,
  777            Self::Top => Self::Bottom,
  778            Self::Bottom => Self::Center,
  779        }
  780    }
  781}
  782
  783#[derive(Clone)]
  784pub struct EditorSnapshot {
  785    pub mode: EditorMode,
  786    show_gutter: bool,
  787    show_line_numbers: Option<bool>,
  788    show_git_diff_gutter: Option<bool>,
  789    show_code_actions: Option<bool>,
  790    show_runnables: Option<bool>,
  791    git_blame_gutter_max_author_length: Option<usize>,
  792    pub display_snapshot: DisplaySnapshot,
  793    pub placeholder_text: Option<Arc<str>>,
  794    is_focused: bool,
  795    scroll_anchor: ScrollAnchor,
  796    ongoing_scroll: OngoingScroll,
  797    current_line_highlight: CurrentLineHighlight,
  798    gutter_hovered: bool,
  799}
  800
  801const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  802
  803#[derive(Default, Debug, Clone, Copy)]
  804pub struct GutterDimensions {
  805    pub left_padding: Pixels,
  806    pub right_padding: Pixels,
  807    pub width: Pixels,
  808    pub margin: Pixels,
  809    pub git_blame_entries_width: Option<Pixels>,
  810}
  811
  812impl GutterDimensions {
  813    /// The full width of the space taken up by the gutter.
  814    pub fn full_width(&self) -> Pixels {
  815        self.margin + self.width
  816    }
  817
  818    /// The width of the space reserved for the fold indicators,
  819    /// use alongside 'justify_end' and `gutter_width` to
  820    /// right align content with the line numbers
  821    pub fn fold_area_width(&self) -> Pixels {
  822        self.margin + self.right_padding
  823    }
  824}
  825
  826#[derive(Debug)]
  827pub struct RemoteSelection {
  828    pub replica_id: ReplicaId,
  829    pub selection: Selection<Anchor>,
  830    pub cursor_shape: CursorShape,
  831    pub peer_id: PeerId,
  832    pub line_mode: bool,
  833    pub participant_index: Option<ParticipantIndex>,
  834    pub user_name: Option<SharedString>,
  835}
  836
  837#[derive(Clone, Debug)]
  838struct SelectionHistoryEntry {
  839    selections: Arc<[Selection<Anchor>]>,
  840    select_next_state: Option<SelectNextState>,
  841    select_prev_state: Option<SelectNextState>,
  842    add_selections_state: Option<AddSelectionsState>,
  843}
  844
  845enum SelectionHistoryMode {
  846    Normal,
  847    Undoing,
  848    Redoing,
  849}
  850
  851#[derive(Clone, PartialEq, Eq, Hash)]
  852struct HoveredCursor {
  853    replica_id: u16,
  854    selection_id: usize,
  855}
  856
  857impl Default for SelectionHistoryMode {
  858    fn default() -> Self {
  859        Self::Normal
  860    }
  861}
  862
  863#[derive(Default)]
  864struct SelectionHistory {
  865    #[allow(clippy::type_complexity)]
  866    selections_by_transaction:
  867        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  868    mode: SelectionHistoryMode,
  869    undo_stack: VecDeque<SelectionHistoryEntry>,
  870    redo_stack: VecDeque<SelectionHistoryEntry>,
  871}
  872
  873impl SelectionHistory {
  874    fn insert_transaction(
  875        &mut self,
  876        transaction_id: TransactionId,
  877        selections: Arc<[Selection<Anchor>]>,
  878    ) {
  879        self.selections_by_transaction
  880            .insert(transaction_id, (selections, None));
  881    }
  882
  883    #[allow(clippy::type_complexity)]
  884    fn transaction(
  885        &self,
  886        transaction_id: TransactionId,
  887    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  888        self.selections_by_transaction.get(&transaction_id)
  889    }
  890
  891    #[allow(clippy::type_complexity)]
  892    fn transaction_mut(
  893        &mut self,
  894        transaction_id: TransactionId,
  895    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  896        self.selections_by_transaction.get_mut(&transaction_id)
  897    }
  898
  899    fn push(&mut self, entry: SelectionHistoryEntry) {
  900        if !entry.selections.is_empty() {
  901            match self.mode {
  902                SelectionHistoryMode::Normal => {
  903                    self.push_undo(entry);
  904                    self.redo_stack.clear();
  905                }
  906                SelectionHistoryMode::Undoing => self.push_redo(entry),
  907                SelectionHistoryMode::Redoing => self.push_undo(entry),
  908            }
  909        }
  910    }
  911
  912    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  913        if self
  914            .undo_stack
  915            .back()
  916            .map_or(true, |e| e.selections != entry.selections)
  917        {
  918            self.undo_stack.push_back(entry);
  919            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  920                self.undo_stack.pop_front();
  921            }
  922        }
  923    }
  924
  925    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  926        if self
  927            .redo_stack
  928            .back()
  929            .map_or(true, |e| e.selections != entry.selections)
  930        {
  931            self.redo_stack.push_back(entry);
  932            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  933                self.redo_stack.pop_front();
  934            }
  935        }
  936    }
  937}
  938
  939struct RowHighlight {
  940    index: usize,
  941    range: Range<Anchor>,
  942    color: Hsla,
  943    should_autoscroll: bool,
  944}
  945
  946#[derive(Clone, Debug)]
  947struct AddSelectionsState {
  948    above: bool,
  949    stack: Vec<usize>,
  950}
  951
  952#[derive(Clone)]
  953struct SelectNextState {
  954    query: AhoCorasick,
  955    wordwise: bool,
  956    done: bool,
  957}
  958
  959impl std::fmt::Debug for SelectNextState {
  960    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  961        f.debug_struct(std::any::type_name::<Self>())
  962            .field("wordwise", &self.wordwise)
  963            .field("done", &self.done)
  964            .finish()
  965    }
  966}
  967
  968#[derive(Debug)]
  969struct AutocloseRegion {
  970    selection_id: usize,
  971    range: Range<Anchor>,
  972    pair: BracketPair,
  973}
  974
  975#[derive(Debug)]
  976struct SnippetState {
  977    ranges: Vec<Vec<Range<Anchor>>>,
  978    active_index: usize,
  979    choices: Vec<Option<Vec<String>>>,
  980}
  981
  982#[doc(hidden)]
  983pub struct RenameState {
  984    pub range: Range<Anchor>,
  985    pub old_name: Arc<str>,
  986    pub editor: Entity<Editor>,
  987    block_id: CustomBlockId,
  988}
  989
  990struct InvalidationStack<T>(Vec<T>);
  991
  992struct RegisteredInlineCompletionProvider {
  993    provider: Arc<dyn InlineCompletionProviderHandle>,
  994    _subscription: Subscription,
  995}
  996
  997#[derive(Debug, PartialEq, Eq)]
  998struct ActiveDiagnosticGroup {
  999    primary_range: Range<Anchor>,
 1000    primary_message: String,
 1001    group_id: usize,
 1002    blocks: HashMap<CustomBlockId, Diagnostic>,
 1003    is_valid: bool,
 1004}
 1005
 1006#[derive(Serialize, Deserialize, Clone, Debug)]
 1007pub struct ClipboardSelection {
 1008    /// The number of bytes in this selection.
 1009    pub len: usize,
 1010    /// Whether this was a full-line selection.
 1011    pub is_entire_line: bool,
 1012    /// The column where this selection originally started.
 1013    pub start_column: u32,
 1014}
 1015
 1016#[derive(Debug)]
 1017pub(crate) struct NavigationData {
 1018    cursor_anchor: Anchor,
 1019    cursor_position: Point,
 1020    scroll_anchor: ScrollAnchor,
 1021    scroll_top_row: u32,
 1022}
 1023
 1024#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1025pub enum GotoDefinitionKind {
 1026    Symbol,
 1027    Declaration,
 1028    Type,
 1029    Implementation,
 1030}
 1031
 1032#[derive(Debug, Clone)]
 1033enum InlayHintRefreshReason {
 1034    Toggle(bool),
 1035    SettingsChange(InlayHintSettings),
 1036    NewLinesShown,
 1037    BufferEdited(HashSet<Arc<Language>>),
 1038    RefreshRequested,
 1039    ExcerptsRemoved(Vec<ExcerptId>),
 1040}
 1041
 1042impl InlayHintRefreshReason {
 1043    fn description(&self) -> &'static str {
 1044        match self {
 1045            Self::Toggle(_) => "toggle",
 1046            Self::SettingsChange(_) => "settings change",
 1047            Self::NewLinesShown => "new lines shown",
 1048            Self::BufferEdited(_) => "buffer edited",
 1049            Self::RefreshRequested => "refresh requested",
 1050            Self::ExcerptsRemoved(_) => "excerpts removed",
 1051        }
 1052    }
 1053}
 1054
 1055pub enum FormatTarget {
 1056    Buffers,
 1057    Ranges(Vec<Range<MultiBufferPoint>>),
 1058}
 1059
 1060pub(crate) struct FocusedBlock {
 1061    id: BlockId,
 1062    focus_handle: WeakFocusHandle,
 1063}
 1064
 1065#[derive(Clone)]
 1066enum JumpData {
 1067    MultiBufferRow {
 1068        row: MultiBufferRow,
 1069        line_offset_from_top: u32,
 1070    },
 1071    MultiBufferPoint {
 1072        excerpt_id: ExcerptId,
 1073        position: Point,
 1074        anchor: text::Anchor,
 1075        line_offset_from_top: u32,
 1076    },
 1077}
 1078
 1079pub enum MultibufferSelectionMode {
 1080    First,
 1081    All,
 1082}
 1083
 1084impl Editor {
 1085    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1086        let buffer = cx.new(|cx| Buffer::local("", cx));
 1087        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1088        Self::new(
 1089            EditorMode::SingleLine { auto_width: false },
 1090            buffer,
 1091            None,
 1092            false,
 1093            window,
 1094            cx,
 1095        )
 1096    }
 1097
 1098    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1099        let buffer = cx.new(|cx| Buffer::local("", cx));
 1100        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1101        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1102    }
 1103
 1104    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1105        let buffer = cx.new(|cx| Buffer::local("", cx));
 1106        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1107        Self::new(
 1108            EditorMode::SingleLine { auto_width: true },
 1109            buffer,
 1110            None,
 1111            false,
 1112            window,
 1113            cx,
 1114        )
 1115    }
 1116
 1117    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1118        let buffer = cx.new(|cx| Buffer::local("", cx));
 1119        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1120        Self::new(
 1121            EditorMode::AutoHeight { max_lines },
 1122            buffer,
 1123            None,
 1124            false,
 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, false, window, cx)
 1138    }
 1139
 1140    pub fn for_multibuffer(
 1141        buffer: Entity<MultiBuffer>,
 1142        project: Option<Entity<Project>>,
 1143        show_excerpt_controls: bool,
 1144        window: &mut Window,
 1145        cx: &mut Context<Self>,
 1146    ) -> Self {
 1147        Self::new(
 1148            EditorMode::Full,
 1149            buffer,
 1150            project,
 1151            show_excerpt_controls,
 1152            window,
 1153            cx,
 1154        )
 1155    }
 1156
 1157    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1158        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1159        let mut clone = Self::new(
 1160            self.mode,
 1161            self.buffer.clone(),
 1162            self.project.clone(),
 1163            show_excerpt_controls,
 1164            window,
 1165            cx,
 1166        );
 1167        self.display_map.update(cx, |display_map, cx| {
 1168            let snapshot = display_map.snapshot(cx);
 1169            clone.display_map.update(cx, |display_map, cx| {
 1170                display_map.set_state(&snapshot, cx);
 1171            });
 1172        });
 1173        clone.selections.clone_state(&self.selections);
 1174        clone.scroll_manager.clone_state(&self.scroll_manager);
 1175        clone.searchable = self.searchable;
 1176        clone
 1177    }
 1178
 1179    pub fn new(
 1180        mode: EditorMode,
 1181        buffer: Entity<MultiBuffer>,
 1182        project: Option<Entity<Project>>,
 1183        show_excerpt_controls: bool,
 1184        window: &mut Window,
 1185        cx: &mut Context<Self>,
 1186    ) -> Self {
 1187        let style = window.text_style();
 1188        let font_size = style.font_size.to_pixels(window.rem_size());
 1189        let editor = cx.entity().downgrade();
 1190        let fold_placeholder = FoldPlaceholder {
 1191            constrain_width: true,
 1192            render: Arc::new(move |fold_id, fold_range, cx| {
 1193                let editor = editor.clone();
 1194                div()
 1195                    .id(fold_id)
 1196                    .bg(cx.theme().colors().ghost_element_background)
 1197                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1198                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1199                    .rounded_sm()
 1200                    .size_full()
 1201                    .cursor_pointer()
 1202                    .child("")
 1203                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1204                    .on_click(move |_, _window, cx| {
 1205                        editor
 1206                            .update(cx, |editor, cx| {
 1207                                editor.unfold_ranges(
 1208                                    &[fold_range.start..fold_range.end],
 1209                                    true,
 1210                                    false,
 1211                                    cx,
 1212                                );
 1213                                cx.stop_propagation();
 1214                            })
 1215                            .ok();
 1216                    })
 1217                    .into_any()
 1218            }),
 1219            merge_adjacent: true,
 1220            ..Default::default()
 1221        };
 1222        let display_map = cx.new(|cx| {
 1223            DisplayMap::new(
 1224                buffer.clone(),
 1225                style.font(),
 1226                font_size,
 1227                None,
 1228                show_excerpt_controls,
 1229                FILE_HEADER_HEIGHT,
 1230                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1231                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1232                fold_placeholder,
 1233                cx,
 1234            )
 1235        });
 1236
 1237        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1238
 1239        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1240
 1241        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1242            .then(|| language_settings::SoftWrap::None);
 1243
 1244        let mut project_subscriptions = Vec::new();
 1245        if mode == EditorMode::Full {
 1246            if let Some(project) = project.as_ref() {
 1247                if buffer.read(cx).is_singleton() {
 1248                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1249                        cx.emit(EditorEvent::TitleChanged);
 1250                    }));
 1251                }
 1252                project_subscriptions.push(cx.subscribe_in(
 1253                    project,
 1254                    window,
 1255                    |editor, _, event, window, cx| {
 1256                        if let project::Event::RefreshInlayHints = event {
 1257                            editor
 1258                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1259                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1260                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1261                                let focus_handle = editor.focus_handle(cx);
 1262                                if focus_handle.is_focused(window) {
 1263                                    let snapshot = buffer.read(cx).snapshot();
 1264                                    for (range, snippet) in snippet_edits {
 1265                                        let editor_range =
 1266                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1267                                        editor
 1268                                            .insert_snippet(
 1269                                                &[editor_range],
 1270                                                snippet.clone(),
 1271                                                window,
 1272                                                cx,
 1273                                            )
 1274                                            .ok();
 1275                                    }
 1276                                }
 1277                            }
 1278                        }
 1279                    },
 1280                ));
 1281                if let Some(task_inventory) = project
 1282                    .read(cx)
 1283                    .task_store()
 1284                    .read(cx)
 1285                    .task_inventory()
 1286                    .cloned()
 1287                {
 1288                    project_subscriptions.push(cx.observe_in(
 1289                        &task_inventory,
 1290                        window,
 1291                        |editor, _, window, cx| {
 1292                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1293                        },
 1294                    ));
 1295                }
 1296            }
 1297        }
 1298
 1299        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1300
 1301        let inlay_hint_settings =
 1302            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1303        let focus_handle = cx.focus_handle();
 1304        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1305            .detach();
 1306        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1307            .detach();
 1308        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1309            .detach();
 1310        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1311            .detach();
 1312
 1313        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1314            Some(false)
 1315        } else {
 1316            None
 1317        };
 1318
 1319        let mut code_action_providers = Vec::new();
 1320        let mut load_uncommitted_diff = None;
 1321        if let Some(project) = project.clone() {
 1322            load_uncommitted_diff = Some(
 1323                get_uncommitted_diff_for_buffer(
 1324                    &project,
 1325                    buffer.read(cx).all_buffers(),
 1326                    buffer.clone(),
 1327                    cx,
 1328                )
 1329                .shared(),
 1330            );
 1331            code_action_providers.push(Rc::new(project) as Rc<_>);
 1332        }
 1333
 1334        let mut this = Self {
 1335            focus_handle,
 1336            show_cursor_when_unfocused: false,
 1337            last_focused_descendant: None,
 1338            buffer: buffer.clone(),
 1339            display_map: display_map.clone(),
 1340            selections,
 1341            scroll_manager: ScrollManager::new(cx),
 1342            columnar_selection_tail: None,
 1343            add_selections_state: None,
 1344            select_next_state: None,
 1345            select_prev_state: None,
 1346            selection_history: Default::default(),
 1347            autoclose_regions: Default::default(),
 1348            snippet_stack: Default::default(),
 1349            select_larger_syntax_node_stack: Vec::new(),
 1350            ime_transaction: Default::default(),
 1351            active_diagnostics: None,
 1352            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1353            inline_diagnostics_update: Task::ready(()),
 1354            inline_diagnostics: Vec::new(),
 1355            soft_wrap_mode_override,
 1356            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1357            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1358            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1359            project,
 1360            blink_manager: blink_manager.clone(),
 1361            show_local_selections: true,
 1362            show_scrollbars: true,
 1363            mode,
 1364            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1365            show_gutter: mode == EditorMode::Full,
 1366            show_line_numbers: None,
 1367            use_relative_line_numbers: None,
 1368            show_git_diff_gutter: None,
 1369            show_code_actions: None,
 1370            show_runnables: None,
 1371            show_wrap_guides: None,
 1372            show_indent_guides,
 1373            placeholder_text: None,
 1374            highlight_order: 0,
 1375            highlighted_rows: HashMap::default(),
 1376            background_highlights: Default::default(),
 1377            gutter_highlights: TreeMap::default(),
 1378            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1379            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1380            nav_history: None,
 1381            context_menu: RefCell::new(None),
 1382            mouse_context_menu: None,
 1383            completion_tasks: Default::default(),
 1384            signature_help_state: SignatureHelpState::default(),
 1385            auto_signature_help: None,
 1386            find_all_references_task_sources: Vec::new(),
 1387            next_completion_id: 0,
 1388            next_inlay_id: 0,
 1389            code_action_providers,
 1390            available_code_actions: Default::default(),
 1391            code_actions_task: Default::default(),
 1392            selection_highlight_task: Default::default(),
 1393            document_highlights_task: Default::default(),
 1394            linked_editing_range_task: Default::default(),
 1395            pending_rename: Default::default(),
 1396            searchable: true,
 1397            cursor_shape: EditorSettings::get_global(cx)
 1398                .cursor_shape
 1399                .unwrap_or_default(),
 1400            current_line_highlight: None,
 1401            autoindent_mode: Some(AutoindentMode::EachLine),
 1402            collapse_matches: false,
 1403            workspace: None,
 1404            input_enabled: true,
 1405            use_modal_editing: mode == EditorMode::Full,
 1406            read_only: false,
 1407            use_autoclose: true,
 1408            use_auto_surround: true,
 1409            auto_replace_emoji_shortcode: false,
 1410            leader_peer_id: None,
 1411            remote_id: None,
 1412            hover_state: Default::default(),
 1413            pending_mouse_down: None,
 1414            hovered_link_state: Default::default(),
 1415            edit_prediction_provider: None,
 1416            active_inline_completion: None,
 1417            stale_inline_completion_in_menu: None,
 1418            edit_prediction_preview: EditPredictionPreview::Inactive {
 1419                released_too_fast: false,
 1420            },
 1421            inline_diagnostics_enabled: mode == EditorMode::Full,
 1422            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1423
 1424            gutter_hovered: false,
 1425            pixel_position_of_newest_cursor: None,
 1426            last_bounds: None,
 1427            last_position_map: None,
 1428            expect_bounds_change: None,
 1429            gutter_dimensions: GutterDimensions::default(),
 1430            style: None,
 1431            show_cursor_names: false,
 1432            hovered_cursors: Default::default(),
 1433            next_editor_action_id: EditorActionId::default(),
 1434            editor_actions: Rc::default(),
 1435            inline_completions_hidden_for_vim_mode: false,
 1436            show_inline_completions_override: None,
 1437            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1438            edit_prediction_settings: EditPredictionSettings::Disabled,
 1439            edit_prediction_indent_conflict: false,
 1440            edit_prediction_requires_modifier_in_indent_conflict: true,
 1441            custom_context_menu: None,
 1442            show_git_blame_gutter: false,
 1443            show_git_blame_inline: false,
 1444            show_selection_menu: None,
 1445            show_git_blame_inline_delay_task: None,
 1446            git_blame_inline_tooltip: None,
 1447            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1448            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1449                .session
 1450                .restore_unsaved_buffers,
 1451            blame: None,
 1452            blame_subscription: None,
 1453            tasks: Default::default(),
 1454            _subscriptions: vec![
 1455                cx.observe(&buffer, Self::on_buffer_changed),
 1456                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1457                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1458                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1459                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1460                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1461                cx.observe_window_activation(window, |editor, window, cx| {
 1462                    let active = window.is_window_active();
 1463                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1464                        if active {
 1465                            blink_manager.enable(cx);
 1466                        } else {
 1467                            blink_manager.disable(cx);
 1468                        }
 1469                    });
 1470                }),
 1471            ],
 1472            tasks_update_task: None,
 1473            linked_edit_ranges: Default::default(),
 1474            in_project_search: false,
 1475            previous_search_ranges: None,
 1476            breadcrumb_header: None,
 1477            focused_block: None,
 1478            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1479            addons: HashMap::default(),
 1480            registered_buffers: HashMap::default(),
 1481            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1482            selection_mark_mode: false,
 1483            toggle_fold_multiple_buffers: Task::ready(()),
 1484            serialize_selections: Task::ready(()),
 1485            text_style_refinement: None,
 1486            load_diff_task: load_uncommitted_diff,
 1487        };
 1488        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1489        this._subscriptions.extend(project_subscriptions);
 1490
 1491        this.end_selection(window, cx);
 1492        this.scroll_manager.show_scrollbar(window, cx);
 1493
 1494        if mode == EditorMode::Full {
 1495            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1496            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1497
 1498            if this.git_blame_inline_enabled {
 1499                this.git_blame_inline_enabled = true;
 1500                this.start_git_blame_inline(false, window, cx);
 1501            }
 1502
 1503            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1504                if let Some(project) = this.project.as_ref() {
 1505                    let handle = project.update(cx, |project, cx| {
 1506                        project.register_buffer_with_language_servers(&buffer, cx)
 1507                    });
 1508                    this.registered_buffers
 1509                        .insert(buffer.read(cx).remote_id(), handle);
 1510                }
 1511            }
 1512        }
 1513
 1514        this.report_editor_event("Editor Opened", None, cx);
 1515        this
 1516    }
 1517
 1518    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1519        self.mouse_context_menu
 1520            .as_ref()
 1521            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1522    }
 1523
 1524    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1525        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1526    }
 1527
 1528    fn key_context_internal(
 1529        &self,
 1530        has_active_edit_prediction: bool,
 1531        window: &Window,
 1532        cx: &App,
 1533    ) -> KeyContext {
 1534        let mut key_context = KeyContext::new_with_defaults();
 1535        key_context.add("Editor");
 1536        let mode = match self.mode {
 1537            EditorMode::SingleLine { .. } => "single_line",
 1538            EditorMode::AutoHeight { .. } => "auto_height",
 1539            EditorMode::Full => "full",
 1540        };
 1541
 1542        if EditorSettings::jupyter_enabled(cx) {
 1543            key_context.add("jupyter");
 1544        }
 1545
 1546        key_context.set("mode", mode);
 1547        if self.pending_rename.is_some() {
 1548            key_context.add("renaming");
 1549        }
 1550
 1551        match self.context_menu.borrow().as_ref() {
 1552            Some(CodeContextMenu::Completions(_)) => {
 1553                key_context.add("menu");
 1554                key_context.add("showing_completions");
 1555            }
 1556            Some(CodeContextMenu::CodeActions(_)) => {
 1557                key_context.add("menu");
 1558                key_context.add("showing_code_actions")
 1559            }
 1560            None => {}
 1561        }
 1562
 1563        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1564        if !self.focus_handle(cx).contains_focused(window, cx)
 1565            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1566        {
 1567            for addon in self.addons.values() {
 1568                addon.extend_key_context(&mut key_context, cx)
 1569            }
 1570        }
 1571
 1572        if let Some(extension) = self
 1573            .buffer
 1574            .read(cx)
 1575            .as_singleton()
 1576            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1577        {
 1578            key_context.set("extension", extension.to_string());
 1579        }
 1580
 1581        if has_active_edit_prediction {
 1582            if self.edit_prediction_in_conflict() {
 1583                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1584            } else {
 1585                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1586                key_context.add("copilot_suggestion");
 1587            }
 1588        }
 1589
 1590        if self.selection_mark_mode {
 1591            key_context.add("selection_mode");
 1592        }
 1593
 1594        key_context
 1595    }
 1596
 1597    pub fn edit_prediction_in_conflict(&self) -> bool {
 1598        if !self.show_edit_predictions_in_menu() {
 1599            return false;
 1600        }
 1601
 1602        let showing_completions = self
 1603            .context_menu
 1604            .borrow()
 1605            .as_ref()
 1606            .map_or(false, |context| {
 1607                matches!(context, CodeContextMenu::Completions(_))
 1608            });
 1609
 1610        showing_completions
 1611            || self.edit_prediction_requires_modifier()
 1612            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1613            // bindings to insert tab characters.
 1614            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1615    }
 1616
 1617    pub fn accept_edit_prediction_keybind(
 1618        &self,
 1619        window: &Window,
 1620        cx: &App,
 1621    ) -> AcceptEditPredictionBinding {
 1622        let key_context = self.key_context_internal(true, window, cx);
 1623        let in_conflict = self.edit_prediction_in_conflict();
 1624
 1625        AcceptEditPredictionBinding(
 1626            window
 1627                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1628                .into_iter()
 1629                .filter(|binding| {
 1630                    !in_conflict
 1631                        || binding
 1632                            .keystrokes()
 1633                            .first()
 1634                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1635                })
 1636                .rev()
 1637                .min_by_key(|binding| {
 1638                    binding
 1639                        .keystrokes()
 1640                        .first()
 1641                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1642                }),
 1643        )
 1644    }
 1645
 1646    pub fn new_file(
 1647        workspace: &mut Workspace,
 1648        _: &workspace::NewFile,
 1649        window: &mut Window,
 1650        cx: &mut Context<Workspace>,
 1651    ) {
 1652        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1653            "Failed to create buffer",
 1654            window,
 1655            cx,
 1656            |e, _, _| match e.error_code() {
 1657                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1658                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1659                e.error_tag("required").unwrap_or("the latest version")
 1660            )),
 1661                _ => None,
 1662            },
 1663        );
 1664    }
 1665
 1666    pub fn new_in_workspace(
 1667        workspace: &mut Workspace,
 1668        window: &mut Window,
 1669        cx: &mut Context<Workspace>,
 1670    ) -> Task<Result<Entity<Editor>>> {
 1671        let project = workspace.project().clone();
 1672        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1673
 1674        cx.spawn_in(window, |workspace, mut cx| async move {
 1675            let buffer = create.await?;
 1676            workspace.update_in(&mut cx, |workspace, window, cx| {
 1677                let editor =
 1678                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1679                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1680                editor
 1681            })
 1682        })
 1683    }
 1684
 1685    fn new_file_vertical(
 1686        workspace: &mut Workspace,
 1687        _: &workspace::NewFileSplitVertical,
 1688        window: &mut Window,
 1689        cx: &mut Context<Workspace>,
 1690    ) {
 1691        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1692    }
 1693
 1694    fn new_file_horizontal(
 1695        workspace: &mut Workspace,
 1696        _: &workspace::NewFileSplitHorizontal,
 1697        window: &mut Window,
 1698        cx: &mut Context<Workspace>,
 1699    ) {
 1700        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1701    }
 1702
 1703    fn new_file_in_direction(
 1704        workspace: &mut Workspace,
 1705        direction: SplitDirection,
 1706        window: &mut Window,
 1707        cx: &mut Context<Workspace>,
 1708    ) {
 1709        let project = workspace.project().clone();
 1710        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1711
 1712        cx.spawn_in(window, |workspace, mut cx| async move {
 1713            let buffer = create.await?;
 1714            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1715                workspace.split_item(
 1716                    direction,
 1717                    Box::new(
 1718                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1719                    ),
 1720                    window,
 1721                    cx,
 1722                )
 1723            })?;
 1724            anyhow::Ok(())
 1725        })
 1726        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1727            match e.error_code() {
 1728                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1729                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1730                e.error_tag("required").unwrap_or("the latest version")
 1731            )),
 1732                _ => None,
 1733            }
 1734        });
 1735    }
 1736
 1737    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1738        self.leader_peer_id
 1739    }
 1740
 1741    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1742        &self.buffer
 1743    }
 1744
 1745    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1746        self.workspace.as_ref()?.0.upgrade()
 1747    }
 1748
 1749    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1750        self.buffer().read(cx).title(cx)
 1751    }
 1752
 1753    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1754        let git_blame_gutter_max_author_length = self
 1755            .render_git_blame_gutter(cx)
 1756            .then(|| {
 1757                if let Some(blame) = self.blame.as_ref() {
 1758                    let max_author_length =
 1759                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1760                    Some(max_author_length)
 1761                } else {
 1762                    None
 1763                }
 1764            })
 1765            .flatten();
 1766
 1767        EditorSnapshot {
 1768            mode: self.mode,
 1769            show_gutter: self.show_gutter,
 1770            show_line_numbers: self.show_line_numbers,
 1771            show_git_diff_gutter: self.show_git_diff_gutter,
 1772            show_code_actions: self.show_code_actions,
 1773            show_runnables: self.show_runnables,
 1774            git_blame_gutter_max_author_length,
 1775            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1776            scroll_anchor: self.scroll_manager.anchor(),
 1777            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1778            placeholder_text: self.placeholder_text.clone(),
 1779            is_focused: self.focus_handle.is_focused(window),
 1780            current_line_highlight: self
 1781                .current_line_highlight
 1782                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1783            gutter_hovered: self.gutter_hovered,
 1784        }
 1785    }
 1786
 1787    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1788        self.buffer.read(cx).language_at(point, cx)
 1789    }
 1790
 1791    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1792        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1793    }
 1794
 1795    pub fn active_excerpt(
 1796        &self,
 1797        cx: &App,
 1798    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1799        self.buffer
 1800            .read(cx)
 1801            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1802    }
 1803
 1804    pub fn mode(&self) -> EditorMode {
 1805        self.mode
 1806    }
 1807
 1808    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1809        self.collaboration_hub.as_deref()
 1810    }
 1811
 1812    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1813        self.collaboration_hub = Some(hub);
 1814    }
 1815
 1816    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1817        self.in_project_search = in_project_search;
 1818    }
 1819
 1820    pub fn set_custom_context_menu(
 1821        &mut self,
 1822        f: impl 'static
 1823            + Fn(
 1824                &mut Self,
 1825                DisplayPoint,
 1826                &mut Window,
 1827                &mut Context<Self>,
 1828            ) -> Option<Entity<ui::ContextMenu>>,
 1829    ) {
 1830        self.custom_context_menu = Some(Box::new(f))
 1831    }
 1832
 1833    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1834        self.completion_provider = provider;
 1835    }
 1836
 1837    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1838        self.semantics_provider.clone()
 1839    }
 1840
 1841    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1842        self.semantics_provider = provider;
 1843    }
 1844
 1845    pub fn set_edit_prediction_provider<T>(
 1846        &mut self,
 1847        provider: Option<Entity<T>>,
 1848        window: &mut Window,
 1849        cx: &mut Context<Self>,
 1850    ) where
 1851        T: EditPredictionProvider,
 1852    {
 1853        self.edit_prediction_provider =
 1854            provider.map(|provider| RegisteredInlineCompletionProvider {
 1855                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1856                    if this.focus_handle.is_focused(window) {
 1857                        this.update_visible_inline_completion(window, cx);
 1858                    }
 1859                }),
 1860                provider: Arc::new(provider),
 1861            });
 1862        self.update_edit_prediction_settings(cx);
 1863        self.refresh_inline_completion(false, false, window, cx);
 1864    }
 1865
 1866    pub fn placeholder_text(&self) -> Option<&str> {
 1867        self.placeholder_text.as_deref()
 1868    }
 1869
 1870    pub fn set_placeholder_text(
 1871        &mut self,
 1872        placeholder_text: impl Into<Arc<str>>,
 1873        cx: &mut Context<Self>,
 1874    ) {
 1875        let placeholder_text = Some(placeholder_text.into());
 1876        if self.placeholder_text != placeholder_text {
 1877            self.placeholder_text = placeholder_text;
 1878            cx.notify();
 1879        }
 1880    }
 1881
 1882    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1883        self.cursor_shape = cursor_shape;
 1884
 1885        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1886        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1887
 1888        cx.notify();
 1889    }
 1890
 1891    pub fn set_current_line_highlight(
 1892        &mut self,
 1893        current_line_highlight: Option<CurrentLineHighlight>,
 1894    ) {
 1895        self.current_line_highlight = current_line_highlight;
 1896    }
 1897
 1898    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1899        self.collapse_matches = collapse_matches;
 1900    }
 1901
 1902    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1903        let buffers = self.buffer.read(cx).all_buffers();
 1904        let Some(project) = self.project.as_ref() else {
 1905            return;
 1906        };
 1907        project.update(cx, |project, cx| {
 1908            for buffer in buffers {
 1909                self.registered_buffers
 1910                    .entry(buffer.read(cx).remote_id())
 1911                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1912            }
 1913        })
 1914    }
 1915
 1916    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1917        if self.collapse_matches {
 1918            return range.start..range.start;
 1919        }
 1920        range.clone()
 1921    }
 1922
 1923    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1924        if self.display_map.read(cx).clip_at_line_ends != clip {
 1925            self.display_map
 1926                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1927        }
 1928    }
 1929
 1930    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1931        self.input_enabled = input_enabled;
 1932    }
 1933
 1934    pub fn set_inline_completions_hidden_for_vim_mode(
 1935        &mut self,
 1936        hidden: bool,
 1937        window: &mut Window,
 1938        cx: &mut Context<Self>,
 1939    ) {
 1940        if hidden != self.inline_completions_hidden_for_vim_mode {
 1941            self.inline_completions_hidden_for_vim_mode = hidden;
 1942            if hidden {
 1943                self.update_visible_inline_completion(window, cx);
 1944            } else {
 1945                self.refresh_inline_completion(true, false, window, cx);
 1946            }
 1947        }
 1948    }
 1949
 1950    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1951        self.menu_inline_completions_policy = value;
 1952    }
 1953
 1954    pub fn set_autoindent(&mut self, autoindent: bool) {
 1955        if autoindent {
 1956            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1957        } else {
 1958            self.autoindent_mode = None;
 1959        }
 1960    }
 1961
 1962    pub fn read_only(&self, cx: &App) -> bool {
 1963        self.read_only || self.buffer.read(cx).read_only()
 1964    }
 1965
 1966    pub fn set_read_only(&mut self, read_only: bool) {
 1967        self.read_only = read_only;
 1968    }
 1969
 1970    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1971        self.use_autoclose = autoclose;
 1972    }
 1973
 1974    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1975        self.use_auto_surround = auto_surround;
 1976    }
 1977
 1978    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1979        self.auto_replace_emoji_shortcode = auto_replace;
 1980    }
 1981
 1982    pub fn toggle_edit_predictions(
 1983        &mut self,
 1984        _: &ToggleEditPrediction,
 1985        window: &mut Window,
 1986        cx: &mut Context<Self>,
 1987    ) {
 1988        if self.show_inline_completions_override.is_some() {
 1989            self.set_show_edit_predictions(None, window, cx);
 1990        } else {
 1991            let show_edit_predictions = !self.edit_predictions_enabled();
 1992            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1993        }
 1994    }
 1995
 1996    pub fn set_show_edit_predictions(
 1997        &mut self,
 1998        show_edit_predictions: Option<bool>,
 1999        window: &mut Window,
 2000        cx: &mut Context<Self>,
 2001    ) {
 2002        self.show_inline_completions_override = show_edit_predictions;
 2003        self.update_edit_prediction_settings(cx);
 2004
 2005        if let Some(false) = show_edit_predictions {
 2006            self.discard_inline_completion(false, cx);
 2007        } else {
 2008            self.refresh_inline_completion(false, true, window, cx);
 2009        }
 2010    }
 2011
 2012    fn inline_completions_disabled_in_scope(
 2013        &self,
 2014        buffer: &Entity<Buffer>,
 2015        buffer_position: language::Anchor,
 2016        cx: &App,
 2017    ) -> bool {
 2018        let snapshot = buffer.read(cx).snapshot();
 2019        let settings = snapshot.settings_at(buffer_position, cx);
 2020
 2021        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2022            return false;
 2023        };
 2024
 2025        scope.override_name().map_or(false, |scope_name| {
 2026            settings
 2027                .edit_predictions_disabled_in
 2028                .iter()
 2029                .any(|s| s == scope_name)
 2030        })
 2031    }
 2032
 2033    pub fn set_use_modal_editing(&mut self, to: bool) {
 2034        self.use_modal_editing = to;
 2035    }
 2036
 2037    pub fn use_modal_editing(&self) -> bool {
 2038        self.use_modal_editing
 2039    }
 2040
 2041    fn selections_did_change(
 2042        &mut self,
 2043        local: bool,
 2044        old_cursor_position: &Anchor,
 2045        show_completions: bool,
 2046        window: &mut Window,
 2047        cx: &mut Context<Self>,
 2048    ) {
 2049        window.invalidate_character_coordinates();
 2050
 2051        // Copy selections to primary selection buffer
 2052        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2053        if local {
 2054            let selections = self.selections.all::<usize>(cx);
 2055            let buffer_handle = self.buffer.read(cx).read(cx);
 2056
 2057            let mut text = String::new();
 2058            for (index, selection) in selections.iter().enumerate() {
 2059                let text_for_selection = buffer_handle
 2060                    .text_for_range(selection.start..selection.end)
 2061                    .collect::<String>();
 2062
 2063                text.push_str(&text_for_selection);
 2064                if index != selections.len() - 1 {
 2065                    text.push('\n');
 2066                }
 2067            }
 2068
 2069            if !text.is_empty() {
 2070                cx.write_to_primary(ClipboardItem::new_string(text));
 2071            }
 2072        }
 2073
 2074        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2075            self.buffer.update(cx, |buffer, cx| {
 2076                buffer.set_active_selections(
 2077                    &self.selections.disjoint_anchors(),
 2078                    self.selections.line_mode,
 2079                    self.cursor_shape,
 2080                    cx,
 2081                )
 2082            });
 2083        }
 2084        let display_map = self
 2085            .display_map
 2086            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2087        let buffer = &display_map.buffer_snapshot;
 2088        self.add_selections_state = None;
 2089        self.select_next_state = None;
 2090        self.select_prev_state = None;
 2091        self.select_larger_syntax_node_stack.clear();
 2092        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2093        self.snippet_stack
 2094            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2095        self.take_rename(false, window, cx);
 2096
 2097        let new_cursor_position = self.selections.newest_anchor().head();
 2098
 2099        self.push_to_nav_history(
 2100            *old_cursor_position,
 2101            Some(new_cursor_position.to_point(buffer)),
 2102            cx,
 2103        );
 2104
 2105        if local {
 2106            let new_cursor_position = self.selections.newest_anchor().head();
 2107            let mut context_menu = self.context_menu.borrow_mut();
 2108            let completion_menu = match context_menu.as_ref() {
 2109                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2110                _ => {
 2111                    *context_menu = None;
 2112                    None
 2113                }
 2114            };
 2115            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2116                if !self.registered_buffers.contains_key(&buffer_id) {
 2117                    if let Some(project) = self.project.as_ref() {
 2118                        project.update(cx, |project, cx| {
 2119                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2120                                return;
 2121                            };
 2122                            self.registered_buffers.insert(
 2123                                buffer_id,
 2124                                project.register_buffer_with_language_servers(&buffer, cx),
 2125                            );
 2126                        })
 2127                    }
 2128                }
 2129            }
 2130
 2131            if let Some(completion_menu) = completion_menu {
 2132                let cursor_position = new_cursor_position.to_offset(buffer);
 2133                let (word_range, kind) =
 2134                    buffer.surrounding_word(completion_menu.initial_position, true);
 2135                if kind == Some(CharKind::Word)
 2136                    && word_range.to_inclusive().contains(&cursor_position)
 2137                {
 2138                    let mut completion_menu = completion_menu.clone();
 2139                    drop(context_menu);
 2140
 2141                    let query = Self::completion_query(buffer, cursor_position);
 2142                    cx.spawn(move |this, mut cx| async move {
 2143                        completion_menu
 2144                            .filter(query.as_deref(), cx.background_executor().clone())
 2145                            .await;
 2146
 2147                        this.update(&mut cx, |this, cx| {
 2148                            let mut context_menu = this.context_menu.borrow_mut();
 2149                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2150                            else {
 2151                                return;
 2152                            };
 2153
 2154                            if menu.id > completion_menu.id {
 2155                                return;
 2156                            }
 2157
 2158                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2159                            drop(context_menu);
 2160                            cx.notify();
 2161                        })
 2162                    })
 2163                    .detach();
 2164
 2165                    if show_completions {
 2166                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2167                    }
 2168                } else {
 2169                    drop(context_menu);
 2170                    self.hide_context_menu(window, cx);
 2171                }
 2172            } else {
 2173                drop(context_menu);
 2174            }
 2175
 2176            hide_hover(self, cx);
 2177
 2178            if old_cursor_position.to_display_point(&display_map).row()
 2179                != new_cursor_position.to_display_point(&display_map).row()
 2180            {
 2181                self.available_code_actions.take();
 2182            }
 2183            self.refresh_code_actions(window, cx);
 2184            self.refresh_document_highlights(cx);
 2185            self.refresh_selected_text_highlights(window, cx);
 2186            refresh_matching_bracket_highlights(self, window, cx);
 2187            self.update_visible_inline_completion(window, cx);
 2188            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2189            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2190            if self.git_blame_inline_enabled {
 2191                self.start_inline_blame_timer(window, cx);
 2192            }
 2193        }
 2194
 2195        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2196        cx.emit(EditorEvent::SelectionsChanged { local });
 2197
 2198        let selections = &self.selections.disjoint;
 2199        if selections.len() == 1 {
 2200            cx.emit(SearchEvent::ActiveMatchChanged)
 2201        }
 2202        if local
 2203            && self.is_singleton(cx)
 2204            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2205        {
 2206            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2207                let background_executor = cx.background_executor().clone();
 2208                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2209                let snapshot = self.buffer().read(cx).snapshot(cx);
 2210                let selections = selections.clone();
 2211                self.serialize_selections = cx.background_spawn(async move {
 2212                    background_executor.timer(Duration::from_millis(100)).await;
 2213                    let selections = selections
 2214                        .iter()
 2215                        .map(|selection| {
 2216                            (
 2217                                selection.start.to_offset(&snapshot),
 2218                                selection.end.to_offset(&snapshot),
 2219                            )
 2220                        })
 2221                        .collect();
 2222                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2223                        .await
 2224                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2225                        .log_err();
 2226                });
 2227            }
 2228        }
 2229
 2230        cx.notify();
 2231    }
 2232
 2233    pub fn change_selections<R>(
 2234        &mut self,
 2235        autoscroll: Option<Autoscroll>,
 2236        window: &mut Window,
 2237        cx: &mut Context<Self>,
 2238        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2239    ) -> R {
 2240        self.change_selections_inner(autoscroll, true, window, cx, change)
 2241    }
 2242
 2243    fn change_selections_inner<R>(
 2244        &mut self,
 2245        autoscroll: Option<Autoscroll>,
 2246        request_completions: bool,
 2247        window: &mut Window,
 2248        cx: &mut Context<Self>,
 2249        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2250    ) -> R {
 2251        let old_cursor_position = self.selections.newest_anchor().head();
 2252        self.push_to_selection_history();
 2253
 2254        let (changed, result) = self.selections.change_with(cx, change);
 2255
 2256        if changed {
 2257            if let Some(autoscroll) = autoscroll {
 2258                self.request_autoscroll(autoscroll, cx);
 2259            }
 2260            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2261
 2262            if self.should_open_signature_help_automatically(
 2263                &old_cursor_position,
 2264                self.signature_help_state.backspace_pressed(),
 2265                cx,
 2266            ) {
 2267                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2268            }
 2269            self.signature_help_state.set_backspace_pressed(false);
 2270        }
 2271
 2272        result
 2273    }
 2274
 2275    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2276    where
 2277        I: IntoIterator<Item = (Range<S>, T)>,
 2278        S: ToOffset,
 2279        T: Into<Arc<str>>,
 2280    {
 2281        if self.read_only(cx) {
 2282            return;
 2283        }
 2284
 2285        self.buffer
 2286            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2287    }
 2288
 2289    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2290    where
 2291        I: IntoIterator<Item = (Range<S>, T)>,
 2292        S: ToOffset,
 2293        T: Into<Arc<str>>,
 2294    {
 2295        if self.read_only(cx) {
 2296            return;
 2297        }
 2298
 2299        self.buffer.update(cx, |buffer, cx| {
 2300            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2301        });
 2302    }
 2303
 2304    pub fn edit_with_block_indent<I, S, T>(
 2305        &mut self,
 2306        edits: I,
 2307        original_start_columns: Vec<u32>,
 2308        cx: &mut Context<Self>,
 2309    ) where
 2310        I: IntoIterator<Item = (Range<S>, T)>,
 2311        S: ToOffset,
 2312        T: Into<Arc<str>>,
 2313    {
 2314        if self.read_only(cx) {
 2315            return;
 2316        }
 2317
 2318        self.buffer.update(cx, |buffer, cx| {
 2319            buffer.edit(
 2320                edits,
 2321                Some(AutoindentMode::Block {
 2322                    original_start_columns,
 2323                }),
 2324                cx,
 2325            )
 2326        });
 2327    }
 2328
 2329    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2330        self.hide_context_menu(window, cx);
 2331
 2332        match phase {
 2333            SelectPhase::Begin {
 2334                position,
 2335                add,
 2336                click_count,
 2337            } => self.begin_selection(position, add, click_count, window, cx),
 2338            SelectPhase::BeginColumnar {
 2339                position,
 2340                goal_column,
 2341                reset,
 2342            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2343            SelectPhase::Extend {
 2344                position,
 2345                click_count,
 2346            } => self.extend_selection(position, click_count, window, cx),
 2347            SelectPhase::Update {
 2348                position,
 2349                goal_column,
 2350                scroll_delta,
 2351            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2352            SelectPhase::End => self.end_selection(window, cx),
 2353        }
 2354    }
 2355
 2356    fn extend_selection(
 2357        &mut self,
 2358        position: DisplayPoint,
 2359        click_count: usize,
 2360        window: &mut Window,
 2361        cx: &mut Context<Self>,
 2362    ) {
 2363        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2364        let tail = self.selections.newest::<usize>(cx).tail();
 2365        self.begin_selection(position, false, click_count, window, cx);
 2366
 2367        let position = position.to_offset(&display_map, Bias::Left);
 2368        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2369
 2370        let mut pending_selection = self
 2371            .selections
 2372            .pending_anchor()
 2373            .expect("extend_selection not called with pending selection");
 2374        if position >= tail {
 2375            pending_selection.start = tail_anchor;
 2376        } else {
 2377            pending_selection.end = tail_anchor;
 2378            pending_selection.reversed = true;
 2379        }
 2380
 2381        let mut pending_mode = self.selections.pending_mode().unwrap();
 2382        match &mut pending_mode {
 2383            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2384            _ => {}
 2385        }
 2386
 2387        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2388            s.set_pending(pending_selection, pending_mode)
 2389        });
 2390    }
 2391
 2392    fn begin_selection(
 2393        &mut self,
 2394        position: DisplayPoint,
 2395        add: bool,
 2396        click_count: usize,
 2397        window: &mut Window,
 2398        cx: &mut Context<Self>,
 2399    ) {
 2400        if !self.focus_handle.is_focused(window) {
 2401            self.last_focused_descendant = None;
 2402            window.focus(&self.focus_handle);
 2403        }
 2404
 2405        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2406        let buffer = &display_map.buffer_snapshot;
 2407        let newest_selection = self.selections.newest_anchor().clone();
 2408        let position = display_map.clip_point(position, Bias::Left);
 2409
 2410        let start;
 2411        let end;
 2412        let mode;
 2413        let mut auto_scroll;
 2414        match click_count {
 2415            1 => {
 2416                start = buffer.anchor_before(position.to_point(&display_map));
 2417                end = start;
 2418                mode = SelectMode::Character;
 2419                auto_scroll = true;
 2420            }
 2421            2 => {
 2422                let range = movement::surrounding_word(&display_map, position);
 2423                start = buffer.anchor_before(range.start.to_point(&display_map));
 2424                end = buffer.anchor_before(range.end.to_point(&display_map));
 2425                mode = SelectMode::Word(start..end);
 2426                auto_scroll = true;
 2427            }
 2428            3 => {
 2429                let position = display_map
 2430                    .clip_point(position, Bias::Left)
 2431                    .to_point(&display_map);
 2432                let line_start = display_map.prev_line_boundary(position).0;
 2433                let next_line_start = buffer.clip_point(
 2434                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2435                    Bias::Left,
 2436                );
 2437                start = buffer.anchor_before(line_start);
 2438                end = buffer.anchor_before(next_line_start);
 2439                mode = SelectMode::Line(start..end);
 2440                auto_scroll = true;
 2441            }
 2442            _ => {
 2443                start = buffer.anchor_before(0);
 2444                end = buffer.anchor_before(buffer.len());
 2445                mode = SelectMode::All;
 2446                auto_scroll = false;
 2447            }
 2448        }
 2449        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2450
 2451        let point_to_delete: Option<usize> = {
 2452            let selected_points: Vec<Selection<Point>> =
 2453                self.selections.disjoint_in_range(start..end, cx);
 2454
 2455            if !add || click_count > 1 {
 2456                None
 2457            } else if !selected_points.is_empty() {
 2458                Some(selected_points[0].id)
 2459            } else {
 2460                let clicked_point_already_selected =
 2461                    self.selections.disjoint.iter().find(|selection| {
 2462                        selection.start.to_point(buffer) == start.to_point(buffer)
 2463                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2464                    });
 2465
 2466                clicked_point_already_selected.map(|selection| selection.id)
 2467            }
 2468        };
 2469
 2470        let selections_count = self.selections.count();
 2471
 2472        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2473            if let Some(point_to_delete) = point_to_delete {
 2474                s.delete(point_to_delete);
 2475
 2476                if selections_count == 1 {
 2477                    s.set_pending_anchor_range(start..end, mode);
 2478                }
 2479            } else {
 2480                if !add {
 2481                    s.clear_disjoint();
 2482                } else if click_count > 1 {
 2483                    s.delete(newest_selection.id)
 2484                }
 2485
 2486                s.set_pending_anchor_range(start..end, mode);
 2487            }
 2488        });
 2489    }
 2490
 2491    fn begin_columnar_selection(
 2492        &mut self,
 2493        position: DisplayPoint,
 2494        goal_column: u32,
 2495        reset: bool,
 2496        window: &mut Window,
 2497        cx: &mut Context<Self>,
 2498    ) {
 2499        if !self.focus_handle.is_focused(window) {
 2500            self.last_focused_descendant = None;
 2501            window.focus(&self.focus_handle);
 2502        }
 2503
 2504        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2505
 2506        if reset {
 2507            let pointer_position = display_map
 2508                .buffer_snapshot
 2509                .anchor_before(position.to_point(&display_map));
 2510
 2511            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2512                s.clear_disjoint();
 2513                s.set_pending_anchor_range(
 2514                    pointer_position..pointer_position,
 2515                    SelectMode::Character,
 2516                );
 2517            });
 2518        }
 2519
 2520        let tail = self.selections.newest::<Point>(cx).tail();
 2521        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2522
 2523        if !reset {
 2524            self.select_columns(
 2525                tail.to_display_point(&display_map),
 2526                position,
 2527                goal_column,
 2528                &display_map,
 2529                window,
 2530                cx,
 2531            );
 2532        }
 2533    }
 2534
 2535    fn update_selection(
 2536        &mut self,
 2537        position: DisplayPoint,
 2538        goal_column: u32,
 2539        scroll_delta: gpui::Point<f32>,
 2540        window: &mut Window,
 2541        cx: &mut Context<Self>,
 2542    ) {
 2543        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2544
 2545        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2546            let tail = tail.to_display_point(&display_map);
 2547            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2548        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2549            let buffer = self.buffer.read(cx).snapshot(cx);
 2550            let head;
 2551            let tail;
 2552            let mode = self.selections.pending_mode().unwrap();
 2553            match &mode {
 2554                SelectMode::Character => {
 2555                    head = position.to_point(&display_map);
 2556                    tail = pending.tail().to_point(&buffer);
 2557                }
 2558                SelectMode::Word(original_range) => {
 2559                    let original_display_range = original_range.start.to_display_point(&display_map)
 2560                        ..original_range.end.to_display_point(&display_map);
 2561                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2562                        ..original_display_range.end.to_point(&display_map);
 2563                    if movement::is_inside_word(&display_map, position)
 2564                        || original_display_range.contains(&position)
 2565                    {
 2566                        let word_range = movement::surrounding_word(&display_map, position);
 2567                        if word_range.start < original_display_range.start {
 2568                            head = word_range.start.to_point(&display_map);
 2569                        } else {
 2570                            head = word_range.end.to_point(&display_map);
 2571                        }
 2572                    } else {
 2573                        head = position.to_point(&display_map);
 2574                    }
 2575
 2576                    if head <= original_buffer_range.start {
 2577                        tail = original_buffer_range.end;
 2578                    } else {
 2579                        tail = original_buffer_range.start;
 2580                    }
 2581                }
 2582                SelectMode::Line(original_range) => {
 2583                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2584
 2585                    let position = display_map
 2586                        .clip_point(position, Bias::Left)
 2587                        .to_point(&display_map);
 2588                    let line_start = display_map.prev_line_boundary(position).0;
 2589                    let next_line_start = buffer.clip_point(
 2590                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2591                        Bias::Left,
 2592                    );
 2593
 2594                    if line_start < original_range.start {
 2595                        head = line_start
 2596                    } else {
 2597                        head = next_line_start
 2598                    }
 2599
 2600                    if head <= original_range.start {
 2601                        tail = original_range.end;
 2602                    } else {
 2603                        tail = original_range.start;
 2604                    }
 2605                }
 2606                SelectMode::All => {
 2607                    return;
 2608                }
 2609            };
 2610
 2611            if head < tail {
 2612                pending.start = buffer.anchor_before(head);
 2613                pending.end = buffer.anchor_before(tail);
 2614                pending.reversed = true;
 2615            } else {
 2616                pending.start = buffer.anchor_before(tail);
 2617                pending.end = buffer.anchor_before(head);
 2618                pending.reversed = false;
 2619            }
 2620
 2621            self.change_selections(None, window, cx, |s| {
 2622                s.set_pending(pending, mode);
 2623            });
 2624        } else {
 2625            log::error!("update_selection dispatched with no pending selection");
 2626            return;
 2627        }
 2628
 2629        self.apply_scroll_delta(scroll_delta, window, cx);
 2630        cx.notify();
 2631    }
 2632
 2633    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2634        self.columnar_selection_tail.take();
 2635        if self.selections.pending_anchor().is_some() {
 2636            let selections = self.selections.all::<usize>(cx);
 2637            self.change_selections(None, window, cx, |s| {
 2638                s.select(selections);
 2639                s.clear_pending();
 2640            });
 2641        }
 2642    }
 2643
 2644    fn select_columns(
 2645        &mut self,
 2646        tail: DisplayPoint,
 2647        head: DisplayPoint,
 2648        goal_column: u32,
 2649        display_map: &DisplaySnapshot,
 2650        window: &mut Window,
 2651        cx: &mut Context<Self>,
 2652    ) {
 2653        let start_row = cmp::min(tail.row(), head.row());
 2654        let end_row = cmp::max(tail.row(), head.row());
 2655        let start_column = cmp::min(tail.column(), goal_column);
 2656        let end_column = cmp::max(tail.column(), goal_column);
 2657        let reversed = start_column < tail.column();
 2658
 2659        let selection_ranges = (start_row.0..=end_row.0)
 2660            .map(DisplayRow)
 2661            .filter_map(|row| {
 2662                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2663                    let start = display_map
 2664                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2665                        .to_point(display_map);
 2666                    let end = display_map
 2667                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2668                        .to_point(display_map);
 2669                    if reversed {
 2670                        Some(end..start)
 2671                    } else {
 2672                        Some(start..end)
 2673                    }
 2674                } else {
 2675                    None
 2676                }
 2677            })
 2678            .collect::<Vec<_>>();
 2679
 2680        self.change_selections(None, window, cx, |s| {
 2681            s.select_ranges(selection_ranges);
 2682        });
 2683        cx.notify();
 2684    }
 2685
 2686    pub fn has_pending_nonempty_selection(&self) -> bool {
 2687        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2688            Some(Selection { start, end, .. }) => start != end,
 2689            None => false,
 2690        };
 2691
 2692        pending_nonempty_selection
 2693            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2694    }
 2695
 2696    pub fn has_pending_selection(&self) -> bool {
 2697        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2698    }
 2699
 2700    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2701        self.selection_mark_mode = false;
 2702
 2703        if self.clear_expanded_diff_hunks(cx) {
 2704            cx.notify();
 2705            return;
 2706        }
 2707        if self.dismiss_menus_and_popups(true, window, cx) {
 2708            return;
 2709        }
 2710
 2711        if self.mode == EditorMode::Full
 2712            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2713        {
 2714            return;
 2715        }
 2716
 2717        cx.propagate();
 2718    }
 2719
 2720    pub fn dismiss_menus_and_popups(
 2721        &mut self,
 2722        is_user_requested: bool,
 2723        window: &mut Window,
 2724        cx: &mut Context<Self>,
 2725    ) -> bool {
 2726        if self.take_rename(false, window, cx).is_some() {
 2727            return true;
 2728        }
 2729
 2730        if hide_hover(self, cx) {
 2731            return true;
 2732        }
 2733
 2734        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2735            return true;
 2736        }
 2737
 2738        if self.hide_context_menu(window, cx).is_some() {
 2739            return true;
 2740        }
 2741
 2742        if self.mouse_context_menu.take().is_some() {
 2743            return true;
 2744        }
 2745
 2746        if is_user_requested && self.discard_inline_completion(true, cx) {
 2747            return true;
 2748        }
 2749
 2750        if self.snippet_stack.pop().is_some() {
 2751            return true;
 2752        }
 2753
 2754        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2755            self.dismiss_diagnostics(cx);
 2756            return true;
 2757        }
 2758
 2759        false
 2760    }
 2761
 2762    fn linked_editing_ranges_for(
 2763        &self,
 2764        selection: Range<text::Anchor>,
 2765        cx: &App,
 2766    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2767        if self.linked_edit_ranges.is_empty() {
 2768            return None;
 2769        }
 2770        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2771            selection.end.buffer_id.and_then(|end_buffer_id| {
 2772                if selection.start.buffer_id != Some(end_buffer_id) {
 2773                    return None;
 2774                }
 2775                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2776                let snapshot = buffer.read(cx).snapshot();
 2777                self.linked_edit_ranges
 2778                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2779                    .map(|ranges| (ranges, snapshot, buffer))
 2780            })?;
 2781        use text::ToOffset as TO;
 2782        // find offset from the start of current range to current cursor position
 2783        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2784
 2785        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2786        let start_difference = start_offset - start_byte_offset;
 2787        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2788        let end_difference = end_offset - start_byte_offset;
 2789        // Current range has associated linked ranges.
 2790        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2791        for range in linked_ranges.iter() {
 2792            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2793            let end_offset = start_offset + end_difference;
 2794            let start_offset = start_offset + start_difference;
 2795            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2796                continue;
 2797            }
 2798            if self.selections.disjoint_anchor_ranges().any(|s| {
 2799                if s.start.buffer_id != selection.start.buffer_id
 2800                    || s.end.buffer_id != selection.end.buffer_id
 2801                {
 2802                    return false;
 2803                }
 2804                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2805                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2806            }) {
 2807                continue;
 2808            }
 2809            let start = buffer_snapshot.anchor_after(start_offset);
 2810            let end = buffer_snapshot.anchor_after(end_offset);
 2811            linked_edits
 2812                .entry(buffer.clone())
 2813                .or_default()
 2814                .push(start..end);
 2815        }
 2816        Some(linked_edits)
 2817    }
 2818
 2819    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2820        let text: Arc<str> = text.into();
 2821
 2822        if self.read_only(cx) {
 2823            return;
 2824        }
 2825
 2826        let selections = self.selections.all_adjusted(cx);
 2827        let mut bracket_inserted = false;
 2828        let mut edits = Vec::new();
 2829        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2830        let mut new_selections = Vec::with_capacity(selections.len());
 2831        let mut new_autoclose_regions = Vec::new();
 2832        let snapshot = self.buffer.read(cx).read(cx);
 2833
 2834        for (selection, autoclose_region) in
 2835            self.selections_with_autoclose_regions(selections, &snapshot)
 2836        {
 2837            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2838                // Determine if the inserted text matches the opening or closing
 2839                // bracket of any of this language's bracket pairs.
 2840                let mut bracket_pair = None;
 2841                let mut is_bracket_pair_start = false;
 2842                let mut is_bracket_pair_end = false;
 2843                if !text.is_empty() {
 2844                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2845                    //  and they are removing the character that triggered IME popup.
 2846                    for (pair, enabled) in scope.brackets() {
 2847                        if !pair.close && !pair.surround {
 2848                            continue;
 2849                        }
 2850
 2851                        if enabled && pair.start.ends_with(text.as_ref()) {
 2852                            let prefix_len = pair.start.len() - text.len();
 2853                            let preceding_text_matches_prefix = prefix_len == 0
 2854                                || (selection.start.column >= (prefix_len as u32)
 2855                                    && snapshot.contains_str_at(
 2856                                        Point::new(
 2857                                            selection.start.row,
 2858                                            selection.start.column - (prefix_len as u32),
 2859                                        ),
 2860                                        &pair.start[..prefix_len],
 2861                                    ));
 2862                            if preceding_text_matches_prefix {
 2863                                bracket_pair = Some(pair.clone());
 2864                                is_bracket_pair_start = true;
 2865                                break;
 2866                            }
 2867                        }
 2868                        if pair.end.as_str() == text.as_ref() {
 2869                            bracket_pair = Some(pair.clone());
 2870                            is_bracket_pair_end = true;
 2871                            break;
 2872                        }
 2873                    }
 2874                }
 2875
 2876                if let Some(bracket_pair) = bracket_pair {
 2877                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2878                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2879                    let auto_surround =
 2880                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2881                    if selection.is_empty() {
 2882                        if is_bracket_pair_start {
 2883                            // If the inserted text is a suffix of an opening bracket and the
 2884                            // selection is preceded by the rest of the opening bracket, then
 2885                            // insert the closing bracket.
 2886                            let following_text_allows_autoclose = snapshot
 2887                                .chars_at(selection.start)
 2888                                .next()
 2889                                .map_or(true, |c| scope.should_autoclose_before(c));
 2890
 2891                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2892                                && bracket_pair.start.len() == 1
 2893                            {
 2894                                let target = bracket_pair.start.chars().next().unwrap();
 2895                                let current_line_count = snapshot
 2896                                    .reversed_chars_at(selection.start)
 2897                                    .take_while(|&c| c != '\n')
 2898                                    .filter(|&c| c == target)
 2899                                    .count();
 2900                                current_line_count % 2 == 1
 2901                            } else {
 2902                                false
 2903                            };
 2904
 2905                            if autoclose
 2906                                && bracket_pair.close
 2907                                && following_text_allows_autoclose
 2908                                && !is_closing_quote
 2909                            {
 2910                                let anchor = snapshot.anchor_before(selection.end);
 2911                                new_selections.push((selection.map(|_| anchor), text.len()));
 2912                                new_autoclose_regions.push((
 2913                                    anchor,
 2914                                    text.len(),
 2915                                    selection.id,
 2916                                    bracket_pair.clone(),
 2917                                ));
 2918                                edits.push((
 2919                                    selection.range(),
 2920                                    format!("{}{}", text, bracket_pair.end).into(),
 2921                                ));
 2922                                bracket_inserted = true;
 2923                                continue;
 2924                            }
 2925                        }
 2926
 2927                        if let Some(region) = autoclose_region {
 2928                            // If the selection is followed by an auto-inserted closing bracket,
 2929                            // then don't insert that closing bracket again; just move the selection
 2930                            // past the closing bracket.
 2931                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2932                                && text.as_ref() == region.pair.end.as_str();
 2933                            if should_skip {
 2934                                let anchor = snapshot.anchor_after(selection.end);
 2935                                new_selections
 2936                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2937                                continue;
 2938                            }
 2939                        }
 2940
 2941                        let always_treat_brackets_as_autoclosed = snapshot
 2942                            .settings_at(selection.start, cx)
 2943                            .always_treat_brackets_as_autoclosed;
 2944                        if always_treat_brackets_as_autoclosed
 2945                            && is_bracket_pair_end
 2946                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2947                        {
 2948                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2949                            // and the inserted text is a closing bracket and the selection is followed
 2950                            // by the closing bracket then move the selection past the closing bracket.
 2951                            let anchor = snapshot.anchor_after(selection.end);
 2952                            new_selections.push((selection.map(|_| anchor), text.len()));
 2953                            continue;
 2954                        }
 2955                    }
 2956                    // If an opening bracket is 1 character long and is typed while
 2957                    // text is selected, then surround that text with the bracket pair.
 2958                    else if auto_surround
 2959                        && bracket_pair.surround
 2960                        && is_bracket_pair_start
 2961                        && bracket_pair.start.chars().count() == 1
 2962                    {
 2963                        edits.push((selection.start..selection.start, text.clone()));
 2964                        edits.push((
 2965                            selection.end..selection.end,
 2966                            bracket_pair.end.as_str().into(),
 2967                        ));
 2968                        bracket_inserted = true;
 2969                        new_selections.push((
 2970                            Selection {
 2971                                id: selection.id,
 2972                                start: snapshot.anchor_after(selection.start),
 2973                                end: snapshot.anchor_before(selection.end),
 2974                                reversed: selection.reversed,
 2975                                goal: selection.goal,
 2976                            },
 2977                            0,
 2978                        ));
 2979                        continue;
 2980                    }
 2981                }
 2982            }
 2983
 2984            if self.auto_replace_emoji_shortcode
 2985                && selection.is_empty()
 2986                && text.as_ref().ends_with(':')
 2987            {
 2988                if let Some(possible_emoji_short_code) =
 2989                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2990                {
 2991                    if !possible_emoji_short_code.is_empty() {
 2992                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2993                            let emoji_shortcode_start = Point::new(
 2994                                selection.start.row,
 2995                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2996                            );
 2997
 2998                            // Remove shortcode from buffer
 2999                            edits.push((
 3000                                emoji_shortcode_start..selection.start,
 3001                                "".to_string().into(),
 3002                            ));
 3003                            new_selections.push((
 3004                                Selection {
 3005                                    id: selection.id,
 3006                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3007                                    end: snapshot.anchor_before(selection.start),
 3008                                    reversed: selection.reversed,
 3009                                    goal: selection.goal,
 3010                                },
 3011                                0,
 3012                            ));
 3013
 3014                            // Insert emoji
 3015                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3016                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3017                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3018
 3019                            continue;
 3020                        }
 3021                    }
 3022                }
 3023            }
 3024
 3025            // If not handling any auto-close operation, then just replace the selected
 3026            // text with the given input and move the selection to the end of the
 3027            // newly inserted text.
 3028            let anchor = snapshot.anchor_after(selection.end);
 3029            if !self.linked_edit_ranges.is_empty() {
 3030                let start_anchor = snapshot.anchor_before(selection.start);
 3031
 3032                let is_word_char = text.chars().next().map_or(true, |char| {
 3033                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3034                    classifier.is_word(char)
 3035                });
 3036
 3037                if is_word_char {
 3038                    if let Some(ranges) = self
 3039                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3040                    {
 3041                        for (buffer, edits) in ranges {
 3042                            linked_edits
 3043                                .entry(buffer.clone())
 3044                                .or_default()
 3045                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3046                        }
 3047                    }
 3048                }
 3049            }
 3050
 3051            new_selections.push((selection.map(|_| anchor), 0));
 3052            edits.push((selection.start..selection.end, text.clone()));
 3053        }
 3054
 3055        drop(snapshot);
 3056
 3057        self.transact(window, cx, |this, window, cx| {
 3058            this.buffer.update(cx, |buffer, cx| {
 3059                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3060            });
 3061            for (buffer, edits) in linked_edits {
 3062                buffer.update(cx, |buffer, cx| {
 3063                    let snapshot = buffer.snapshot();
 3064                    let edits = edits
 3065                        .into_iter()
 3066                        .map(|(range, text)| {
 3067                            use text::ToPoint as TP;
 3068                            let end_point = TP::to_point(&range.end, &snapshot);
 3069                            let start_point = TP::to_point(&range.start, &snapshot);
 3070                            (start_point..end_point, text)
 3071                        })
 3072                        .sorted_by_key(|(range, _)| range.start)
 3073                        .collect::<Vec<_>>();
 3074                    buffer.edit(edits, None, cx);
 3075                })
 3076            }
 3077            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3078            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3079            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3080            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3081                .zip(new_selection_deltas)
 3082                .map(|(selection, delta)| Selection {
 3083                    id: selection.id,
 3084                    start: selection.start + delta,
 3085                    end: selection.end + delta,
 3086                    reversed: selection.reversed,
 3087                    goal: SelectionGoal::None,
 3088                })
 3089                .collect::<Vec<_>>();
 3090
 3091            let mut i = 0;
 3092            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3093                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3094                let start = map.buffer_snapshot.anchor_before(position);
 3095                let end = map.buffer_snapshot.anchor_after(position);
 3096                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3097                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3098                        Ordering::Less => i += 1,
 3099                        Ordering::Greater => break,
 3100                        Ordering::Equal => {
 3101                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3102                                Ordering::Less => i += 1,
 3103                                Ordering::Equal => break,
 3104                                Ordering::Greater => break,
 3105                            }
 3106                        }
 3107                    }
 3108                }
 3109                this.autoclose_regions.insert(
 3110                    i,
 3111                    AutocloseRegion {
 3112                        selection_id,
 3113                        range: start..end,
 3114                        pair,
 3115                    },
 3116                );
 3117            }
 3118
 3119            let had_active_inline_completion = this.has_active_inline_completion();
 3120            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3121                s.select(new_selections)
 3122            });
 3123
 3124            if !bracket_inserted {
 3125                if let Some(on_type_format_task) =
 3126                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3127                {
 3128                    on_type_format_task.detach_and_log_err(cx);
 3129                }
 3130            }
 3131
 3132            let editor_settings = EditorSettings::get_global(cx);
 3133            if bracket_inserted
 3134                && (editor_settings.auto_signature_help
 3135                    || editor_settings.show_signature_help_after_edits)
 3136            {
 3137                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3138            }
 3139
 3140            let trigger_in_words =
 3141                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3142            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3143            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3144            this.refresh_inline_completion(true, false, window, cx);
 3145        });
 3146    }
 3147
 3148    fn find_possible_emoji_shortcode_at_position(
 3149        snapshot: &MultiBufferSnapshot,
 3150        position: Point,
 3151    ) -> Option<String> {
 3152        let mut chars = Vec::new();
 3153        let mut found_colon = false;
 3154        for char in snapshot.reversed_chars_at(position).take(100) {
 3155            // Found a possible emoji shortcode in the middle of the buffer
 3156            if found_colon {
 3157                if char.is_whitespace() {
 3158                    chars.reverse();
 3159                    return Some(chars.iter().collect());
 3160                }
 3161                // If the previous character is not a whitespace, we are in the middle of a word
 3162                // and we only want to complete the shortcode if the word is made up of other emojis
 3163                let mut containing_word = String::new();
 3164                for ch in snapshot
 3165                    .reversed_chars_at(position)
 3166                    .skip(chars.len() + 1)
 3167                    .take(100)
 3168                {
 3169                    if ch.is_whitespace() {
 3170                        break;
 3171                    }
 3172                    containing_word.push(ch);
 3173                }
 3174                let containing_word = containing_word.chars().rev().collect::<String>();
 3175                if util::word_consists_of_emojis(containing_word.as_str()) {
 3176                    chars.reverse();
 3177                    return Some(chars.iter().collect());
 3178                }
 3179            }
 3180
 3181            if char.is_whitespace() || !char.is_ascii() {
 3182                return None;
 3183            }
 3184            if char == ':' {
 3185                found_colon = true;
 3186            } else {
 3187                chars.push(char);
 3188            }
 3189        }
 3190        // Found a possible emoji shortcode at the beginning of the buffer
 3191        chars.reverse();
 3192        Some(chars.iter().collect())
 3193    }
 3194
 3195    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3196        self.transact(window, cx, |this, window, cx| {
 3197            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3198                let selections = this.selections.all::<usize>(cx);
 3199                let multi_buffer = this.buffer.read(cx);
 3200                let buffer = multi_buffer.snapshot(cx);
 3201                selections
 3202                    .iter()
 3203                    .map(|selection| {
 3204                        let start_point = selection.start.to_point(&buffer);
 3205                        let mut indent =
 3206                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3207                        indent.len = cmp::min(indent.len, start_point.column);
 3208                        let start = selection.start;
 3209                        let end = selection.end;
 3210                        let selection_is_empty = start == end;
 3211                        let language_scope = buffer.language_scope_at(start);
 3212                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3213                            &language_scope
 3214                        {
 3215                            let insert_extra_newline =
 3216                                insert_extra_newline_brackets(&buffer, start..end, language)
 3217                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3218
 3219                            // Comment extension on newline is allowed only for cursor selections
 3220                            let comment_delimiter = maybe!({
 3221                                if !selection_is_empty {
 3222                                    return None;
 3223                                }
 3224
 3225                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3226                                    return None;
 3227                                }
 3228
 3229                                let delimiters = language.line_comment_prefixes();
 3230                                let max_len_of_delimiter =
 3231                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3232                                let (snapshot, range) =
 3233                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3234
 3235                                let mut index_of_first_non_whitespace = 0;
 3236                                let comment_candidate = snapshot
 3237                                    .chars_for_range(range)
 3238                                    .skip_while(|c| {
 3239                                        let should_skip = c.is_whitespace();
 3240                                        if should_skip {
 3241                                            index_of_first_non_whitespace += 1;
 3242                                        }
 3243                                        should_skip
 3244                                    })
 3245                                    .take(max_len_of_delimiter)
 3246                                    .collect::<String>();
 3247                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3248                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3249                                })?;
 3250                                let cursor_is_placed_after_comment_marker =
 3251                                    index_of_first_non_whitespace + comment_prefix.len()
 3252                                        <= start_point.column as usize;
 3253                                if cursor_is_placed_after_comment_marker {
 3254                                    Some(comment_prefix.clone())
 3255                                } else {
 3256                                    None
 3257                                }
 3258                            });
 3259                            (comment_delimiter, insert_extra_newline)
 3260                        } else {
 3261                            (None, false)
 3262                        };
 3263
 3264                        let capacity_for_delimiter = comment_delimiter
 3265                            .as_deref()
 3266                            .map(str::len)
 3267                            .unwrap_or_default();
 3268                        let mut new_text =
 3269                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3270                        new_text.push('\n');
 3271                        new_text.extend(indent.chars());
 3272                        if let Some(delimiter) = &comment_delimiter {
 3273                            new_text.push_str(delimiter);
 3274                        }
 3275                        if insert_extra_newline {
 3276                            new_text = new_text.repeat(2);
 3277                        }
 3278
 3279                        let anchor = buffer.anchor_after(end);
 3280                        let new_selection = selection.map(|_| anchor);
 3281                        (
 3282                            (start..end, new_text),
 3283                            (insert_extra_newline, new_selection),
 3284                        )
 3285                    })
 3286                    .unzip()
 3287            };
 3288
 3289            this.edit_with_autoindent(edits, cx);
 3290            let buffer = this.buffer.read(cx).snapshot(cx);
 3291            let new_selections = selection_fixup_info
 3292                .into_iter()
 3293                .map(|(extra_newline_inserted, new_selection)| {
 3294                    let mut cursor = new_selection.end.to_point(&buffer);
 3295                    if extra_newline_inserted {
 3296                        cursor.row -= 1;
 3297                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3298                    }
 3299                    new_selection.map(|_| cursor)
 3300                })
 3301                .collect();
 3302
 3303            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3304                s.select(new_selections)
 3305            });
 3306            this.refresh_inline_completion(true, false, window, cx);
 3307        });
 3308    }
 3309
 3310    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3311        let buffer = self.buffer.read(cx);
 3312        let snapshot = buffer.snapshot(cx);
 3313
 3314        let mut edits = Vec::new();
 3315        let mut rows = Vec::new();
 3316
 3317        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3318            let cursor = selection.head();
 3319            let row = cursor.row;
 3320
 3321            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3322
 3323            let newline = "\n".to_string();
 3324            edits.push((start_of_line..start_of_line, newline));
 3325
 3326            rows.push(row + rows_inserted as u32);
 3327        }
 3328
 3329        self.transact(window, cx, |editor, window, cx| {
 3330            editor.edit(edits, cx);
 3331
 3332            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3333                let mut index = 0;
 3334                s.move_cursors_with(|map, _, _| {
 3335                    let row = rows[index];
 3336                    index += 1;
 3337
 3338                    let point = Point::new(row, 0);
 3339                    let boundary = map.next_line_boundary(point).1;
 3340                    let clipped = map.clip_point(boundary, Bias::Left);
 3341
 3342                    (clipped, SelectionGoal::None)
 3343                });
 3344            });
 3345
 3346            let mut indent_edits = Vec::new();
 3347            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3348            for row in rows {
 3349                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3350                for (row, indent) in indents {
 3351                    if indent.len == 0 {
 3352                        continue;
 3353                    }
 3354
 3355                    let text = match indent.kind {
 3356                        IndentKind::Space => " ".repeat(indent.len as usize),
 3357                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3358                    };
 3359                    let point = Point::new(row.0, 0);
 3360                    indent_edits.push((point..point, text));
 3361                }
 3362            }
 3363            editor.edit(indent_edits, cx);
 3364        });
 3365    }
 3366
 3367    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3368        let buffer = self.buffer.read(cx);
 3369        let snapshot = buffer.snapshot(cx);
 3370
 3371        let mut edits = Vec::new();
 3372        let mut rows = Vec::new();
 3373        let mut rows_inserted = 0;
 3374
 3375        for selection in self.selections.all_adjusted(cx) {
 3376            let cursor = selection.head();
 3377            let row = cursor.row;
 3378
 3379            let point = Point::new(row + 1, 0);
 3380            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3381
 3382            let newline = "\n".to_string();
 3383            edits.push((start_of_line..start_of_line, newline));
 3384
 3385            rows_inserted += 1;
 3386            rows.push(row + rows_inserted);
 3387        }
 3388
 3389        self.transact(window, cx, |editor, window, cx| {
 3390            editor.edit(edits, cx);
 3391
 3392            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3393                let mut index = 0;
 3394                s.move_cursors_with(|map, _, _| {
 3395                    let row = rows[index];
 3396                    index += 1;
 3397
 3398                    let point = Point::new(row, 0);
 3399                    let boundary = map.next_line_boundary(point).1;
 3400                    let clipped = map.clip_point(boundary, Bias::Left);
 3401
 3402                    (clipped, SelectionGoal::None)
 3403                });
 3404            });
 3405
 3406            let mut indent_edits = Vec::new();
 3407            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3408            for row in rows {
 3409                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3410                for (row, indent) in indents {
 3411                    if indent.len == 0 {
 3412                        continue;
 3413                    }
 3414
 3415                    let text = match indent.kind {
 3416                        IndentKind::Space => " ".repeat(indent.len as usize),
 3417                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3418                    };
 3419                    let point = Point::new(row.0, 0);
 3420                    indent_edits.push((point..point, text));
 3421                }
 3422            }
 3423            editor.edit(indent_edits, cx);
 3424        });
 3425    }
 3426
 3427    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3428        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3429            original_start_columns: Vec::new(),
 3430        });
 3431        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3432    }
 3433
 3434    fn insert_with_autoindent_mode(
 3435        &mut self,
 3436        text: &str,
 3437        autoindent_mode: Option<AutoindentMode>,
 3438        window: &mut Window,
 3439        cx: &mut Context<Self>,
 3440    ) {
 3441        if self.read_only(cx) {
 3442            return;
 3443        }
 3444
 3445        let text: Arc<str> = text.into();
 3446        self.transact(window, cx, |this, window, cx| {
 3447            let old_selections = this.selections.all_adjusted(cx);
 3448            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3449                let anchors = {
 3450                    let snapshot = buffer.read(cx);
 3451                    old_selections
 3452                        .iter()
 3453                        .map(|s| {
 3454                            let anchor = snapshot.anchor_after(s.head());
 3455                            s.map(|_| anchor)
 3456                        })
 3457                        .collect::<Vec<_>>()
 3458                };
 3459                buffer.edit(
 3460                    old_selections
 3461                        .iter()
 3462                        .map(|s| (s.start..s.end, text.clone())),
 3463                    autoindent_mode,
 3464                    cx,
 3465                );
 3466                anchors
 3467            });
 3468
 3469            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3470                s.select_anchors(selection_anchors);
 3471            });
 3472
 3473            cx.notify();
 3474        });
 3475    }
 3476
 3477    fn trigger_completion_on_input(
 3478        &mut self,
 3479        text: &str,
 3480        trigger_in_words: bool,
 3481        window: &mut Window,
 3482        cx: &mut Context<Self>,
 3483    ) {
 3484        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3485            self.show_completions(
 3486                &ShowCompletions {
 3487                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3488                },
 3489                window,
 3490                cx,
 3491            );
 3492        } else {
 3493            self.hide_context_menu(window, cx);
 3494        }
 3495    }
 3496
 3497    fn is_completion_trigger(
 3498        &self,
 3499        text: &str,
 3500        trigger_in_words: bool,
 3501        cx: &mut Context<Self>,
 3502    ) -> bool {
 3503        let position = self.selections.newest_anchor().head();
 3504        let multibuffer = self.buffer.read(cx);
 3505        let Some(buffer) = position
 3506            .buffer_id
 3507            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3508        else {
 3509            return false;
 3510        };
 3511
 3512        if let Some(completion_provider) = &self.completion_provider {
 3513            completion_provider.is_completion_trigger(
 3514                &buffer,
 3515                position.text_anchor,
 3516                text,
 3517                trigger_in_words,
 3518                cx,
 3519            )
 3520        } else {
 3521            false
 3522        }
 3523    }
 3524
 3525    /// If any empty selections is touching the start of its innermost containing autoclose
 3526    /// region, expand it to select the brackets.
 3527    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3528        let selections = self.selections.all::<usize>(cx);
 3529        let buffer = self.buffer.read(cx).read(cx);
 3530        let new_selections = self
 3531            .selections_with_autoclose_regions(selections, &buffer)
 3532            .map(|(mut selection, region)| {
 3533                if !selection.is_empty() {
 3534                    return selection;
 3535                }
 3536
 3537                if let Some(region) = region {
 3538                    let mut range = region.range.to_offset(&buffer);
 3539                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3540                        range.start -= region.pair.start.len();
 3541                        if buffer.contains_str_at(range.start, &region.pair.start)
 3542                            && buffer.contains_str_at(range.end, &region.pair.end)
 3543                        {
 3544                            range.end += region.pair.end.len();
 3545                            selection.start = range.start;
 3546                            selection.end = range.end;
 3547
 3548                            return selection;
 3549                        }
 3550                    }
 3551                }
 3552
 3553                let always_treat_brackets_as_autoclosed = buffer
 3554                    .settings_at(selection.start, cx)
 3555                    .always_treat_brackets_as_autoclosed;
 3556
 3557                if !always_treat_brackets_as_autoclosed {
 3558                    return selection;
 3559                }
 3560
 3561                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3562                    for (pair, enabled) in scope.brackets() {
 3563                        if !enabled || !pair.close {
 3564                            continue;
 3565                        }
 3566
 3567                        if buffer.contains_str_at(selection.start, &pair.end) {
 3568                            let pair_start_len = pair.start.len();
 3569                            if buffer.contains_str_at(
 3570                                selection.start.saturating_sub(pair_start_len),
 3571                                &pair.start,
 3572                            ) {
 3573                                selection.start -= pair_start_len;
 3574                                selection.end += pair.end.len();
 3575
 3576                                return selection;
 3577                            }
 3578                        }
 3579                    }
 3580                }
 3581
 3582                selection
 3583            })
 3584            .collect();
 3585
 3586        drop(buffer);
 3587        self.change_selections(None, window, cx, |selections| {
 3588            selections.select(new_selections)
 3589        });
 3590    }
 3591
 3592    /// Iterate the given selections, and for each one, find the smallest surrounding
 3593    /// autoclose region. This uses the ordering of the selections and the autoclose
 3594    /// regions to avoid repeated comparisons.
 3595    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3596        &'a self,
 3597        selections: impl IntoIterator<Item = Selection<D>>,
 3598        buffer: &'a MultiBufferSnapshot,
 3599    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3600        let mut i = 0;
 3601        let mut regions = self.autoclose_regions.as_slice();
 3602        selections.into_iter().map(move |selection| {
 3603            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3604
 3605            let mut enclosing = None;
 3606            while let Some(pair_state) = regions.get(i) {
 3607                if pair_state.range.end.to_offset(buffer) < range.start {
 3608                    regions = &regions[i + 1..];
 3609                    i = 0;
 3610                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3611                    break;
 3612                } else {
 3613                    if pair_state.selection_id == selection.id {
 3614                        enclosing = Some(pair_state);
 3615                    }
 3616                    i += 1;
 3617                }
 3618            }
 3619
 3620            (selection, enclosing)
 3621        })
 3622    }
 3623
 3624    /// Remove any autoclose regions that no longer contain their selection.
 3625    fn invalidate_autoclose_regions(
 3626        &mut self,
 3627        mut selections: &[Selection<Anchor>],
 3628        buffer: &MultiBufferSnapshot,
 3629    ) {
 3630        self.autoclose_regions.retain(|state| {
 3631            let mut i = 0;
 3632            while let Some(selection) = selections.get(i) {
 3633                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3634                    selections = &selections[1..];
 3635                    continue;
 3636                }
 3637                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3638                    break;
 3639                }
 3640                if selection.id == state.selection_id {
 3641                    return true;
 3642                } else {
 3643                    i += 1;
 3644                }
 3645            }
 3646            false
 3647        });
 3648    }
 3649
 3650    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3651        let offset = position.to_offset(buffer);
 3652        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3653        if offset > word_range.start && kind == Some(CharKind::Word) {
 3654            Some(
 3655                buffer
 3656                    .text_for_range(word_range.start..offset)
 3657                    .collect::<String>(),
 3658            )
 3659        } else {
 3660            None
 3661        }
 3662    }
 3663
 3664    pub fn toggle_inlay_hints(
 3665        &mut self,
 3666        _: &ToggleInlayHints,
 3667        _: &mut Window,
 3668        cx: &mut Context<Self>,
 3669    ) {
 3670        self.refresh_inlay_hints(
 3671            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3672            cx,
 3673        );
 3674    }
 3675
 3676    pub fn inlay_hints_enabled(&self) -> bool {
 3677        self.inlay_hint_cache.enabled
 3678    }
 3679
 3680    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3681        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3682            return;
 3683        }
 3684
 3685        let reason_description = reason.description();
 3686        let ignore_debounce = matches!(
 3687            reason,
 3688            InlayHintRefreshReason::SettingsChange(_)
 3689                | InlayHintRefreshReason::Toggle(_)
 3690                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3691        );
 3692        let (invalidate_cache, required_languages) = match reason {
 3693            InlayHintRefreshReason::Toggle(enabled) => {
 3694                self.inlay_hint_cache.enabled = enabled;
 3695                if enabled {
 3696                    (InvalidationStrategy::RefreshRequested, None)
 3697                } else {
 3698                    self.inlay_hint_cache.clear();
 3699                    self.splice_inlays(
 3700                        &self
 3701                            .visible_inlay_hints(cx)
 3702                            .iter()
 3703                            .map(|inlay| inlay.id)
 3704                            .collect::<Vec<InlayId>>(),
 3705                        Vec::new(),
 3706                        cx,
 3707                    );
 3708                    return;
 3709                }
 3710            }
 3711            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3712                match self.inlay_hint_cache.update_settings(
 3713                    &self.buffer,
 3714                    new_settings,
 3715                    self.visible_inlay_hints(cx),
 3716                    cx,
 3717                ) {
 3718                    ControlFlow::Break(Some(InlaySplice {
 3719                        to_remove,
 3720                        to_insert,
 3721                    })) => {
 3722                        self.splice_inlays(&to_remove, to_insert, cx);
 3723                        return;
 3724                    }
 3725                    ControlFlow::Break(None) => return,
 3726                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3727                }
 3728            }
 3729            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3730                if let Some(InlaySplice {
 3731                    to_remove,
 3732                    to_insert,
 3733                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3734                {
 3735                    self.splice_inlays(&to_remove, to_insert, cx);
 3736                }
 3737                return;
 3738            }
 3739            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3740            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3741                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3742            }
 3743            InlayHintRefreshReason::RefreshRequested => {
 3744                (InvalidationStrategy::RefreshRequested, None)
 3745            }
 3746        };
 3747
 3748        if let Some(InlaySplice {
 3749            to_remove,
 3750            to_insert,
 3751        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3752            reason_description,
 3753            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3754            invalidate_cache,
 3755            ignore_debounce,
 3756            cx,
 3757        ) {
 3758            self.splice_inlays(&to_remove, to_insert, cx);
 3759        }
 3760    }
 3761
 3762    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3763        self.display_map
 3764            .read(cx)
 3765            .current_inlays()
 3766            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3767            .cloned()
 3768            .collect()
 3769    }
 3770
 3771    pub fn excerpts_for_inlay_hints_query(
 3772        &self,
 3773        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3774        cx: &mut Context<Editor>,
 3775    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3776        let Some(project) = self.project.as_ref() else {
 3777            return HashMap::default();
 3778        };
 3779        let project = project.read(cx);
 3780        let multi_buffer = self.buffer().read(cx);
 3781        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3782        let multi_buffer_visible_start = self
 3783            .scroll_manager
 3784            .anchor()
 3785            .anchor
 3786            .to_point(&multi_buffer_snapshot);
 3787        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3788            multi_buffer_visible_start
 3789                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3790            Bias::Left,
 3791        );
 3792        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3793        multi_buffer_snapshot
 3794            .range_to_buffer_ranges(multi_buffer_visible_range)
 3795            .into_iter()
 3796            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3797            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3798                let buffer_file = project::File::from_dyn(buffer.file())?;
 3799                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3800                let worktree_entry = buffer_worktree
 3801                    .read(cx)
 3802                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3803                if worktree_entry.is_ignored {
 3804                    return None;
 3805                }
 3806
 3807                let language = buffer.language()?;
 3808                if let Some(restrict_to_languages) = restrict_to_languages {
 3809                    if !restrict_to_languages.contains(language) {
 3810                        return None;
 3811                    }
 3812                }
 3813                Some((
 3814                    excerpt_id,
 3815                    (
 3816                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3817                        buffer.version().clone(),
 3818                        excerpt_visible_range,
 3819                    ),
 3820                ))
 3821            })
 3822            .collect()
 3823    }
 3824
 3825    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3826        TextLayoutDetails {
 3827            text_system: window.text_system().clone(),
 3828            editor_style: self.style.clone().unwrap(),
 3829            rem_size: window.rem_size(),
 3830            scroll_anchor: self.scroll_manager.anchor(),
 3831            visible_rows: self.visible_line_count(),
 3832            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3833        }
 3834    }
 3835
 3836    pub fn splice_inlays(
 3837        &self,
 3838        to_remove: &[InlayId],
 3839        to_insert: Vec<Inlay>,
 3840        cx: &mut Context<Self>,
 3841    ) {
 3842        self.display_map.update(cx, |display_map, cx| {
 3843            display_map.splice_inlays(to_remove, to_insert, cx)
 3844        });
 3845        cx.notify();
 3846    }
 3847
 3848    fn trigger_on_type_formatting(
 3849        &self,
 3850        input: String,
 3851        window: &mut Window,
 3852        cx: &mut Context<Self>,
 3853    ) -> Option<Task<Result<()>>> {
 3854        if input.len() != 1 {
 3855            return None;
 3856        }
 3857
 3858        let project = self.project.as_ref()?;
 3859        let position = self.selections.newest_anchor().head();
 3860        let (buffer, buffer_position) = self
 3861            .buffer
 3862            .read(cx)
 3863            .text_anchor_for_position(position, cx)?;
 3864
 3865        let settings = language_settings::language_settings(
 3866            buffer
 3867                .read(cx)
 3868                .language_at(buffer_position)
 3869                .map(|l| l.name()),
 3870            buffer.read(cx).file(),
 3871            cx,
 3872        );
 3873        if !settings.use_on_type_format {
 3874            return None;
 3875        }
 3876
 3877        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3878        // hence we do LSP request & edit on host side only — add formats to host's history.
 3879        let push_to_lsp_host_history = true;
 3880        // If this is not the host, append its history with new edits.
 3881        let push_to_client_history = project.read(cx).is_via_collab();
 3882
 3883        let on_type_formatting = project.update(cx, |project, cx| {
 3884            project.on_type_format(
 3885                buffer.clone(),
 3886                buffer_position,
 3887                input,
 3888                push_to_lsp_host_history,
 3889                cx,
 3890            )
 3891        });
 3892        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3893            if let Some(transaction) = on_type_formatting.await? {
 3894                if push_to_client_history {
 3895                    buffer
 3896                        .update(&mut cx, |buffer, _| {
 3897                            buffer.push_transaction(transaction, Instant::now());
 3898                        })
 3899                        .ok();
 3900                }
 3901                editor.update(&mut cx, |editor, cx| {
 3902                    editor.refresh_document_highlights(cx);
 3903                })?;
 3904            }
 3905            Ok(())
 3906        }))
 3907    }
 3908
 3909    pub fn show_completions(
 3910        &mut self,
 3911        options: &ShowCompletions,
 3912        window: &mut Window,
 3913        cx: &mut Context<Self>,
 3914    ) {
 3915        if self.pending_rename.is_some() {
 3916            return;
 3917        }
 3918
 3919        let Some(provider) = self.completion_provider.as_ref() else {
 3920            return;
 3921        };
 3922
 3923        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3924            return;
 3925        }
 3926
 3927        let position = self.selections.newest_anchor().head();
 3928        if position.diff_base_anchor.is_some() {
 3929            return;
 3930        }
 3931        let (buffer, buffer_position) =
 3932            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3933                output
 3934            } else {
 3935                return;
 3936            };
 3937        let show_completion_documentation = buffer
 3938            .read(cx)
 3939            .snapshot()
 3940            .settings_at(buffer_position, cx)
 3941            .show_completion_documentation;
 3942
 3943        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3944
 3945        let trigger_kind = match &options.trigger {
 3946            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3947                CompletionTriggerKind::TRIGGER_CHARACTER
 3948            }
 3949            _ => CompletionTriggerKind::INVOKED,
 3950        };
 3951        let completion_context = CompletionContext {
 3952            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3953                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3954                    Some(String::from(trigger))
 3955                } else {
 3956                    None
 3957                }
 3958            }),
 3959            trigger_kind,
 3960        };
 3961        let completions =
 3962            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3963        let sort_completions = provider.sort_completions();
 3964
 3965        let id = post_inc(&mut self.next_completion_id);
 3966        let task = cx.spawn_in(window, |editor, mut cx| {
 3967            async move {
 3968                editor.update(&mut cx, |this, _| {
 3969                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3970                })?;
 3971                let completions = completions.await.log_err();
 3972                let menu = if let Some(completions) = completions {
 3973                    let mut menu = CompletionsMenu::new(
 3974                        id,
 3975                        sort_completions,
 3976                        show_completion_documentation,
 3977                        position,
 3978                        buffer.clone(),
 3979                        completions.into(),
 3980                    );
 3981
 3982                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3983                        .await;
 3984
 3985                    menu.visible().then_some(menu)
 3986                } else {
 3987                    None
 3988                };
 3989
 3990                editor.update_in(&mut cx, |editor, window, cx| {
 3991                    match editor.context_menu.borrow().as_ref() {
 3992                        None => {}
 3993                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3994                            if prev_menu.id > id {
 3995                                return;
 3996                            }
 3997                        }
 3998                        _ => return,
 3999                    }
 4000
 4001                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4002                        let mut menu = menu.unwrap();
 4003                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4004
 4005                        *editor.context_menu.borrow_mut() =
 4006                            Some(CodeContextMenu::Completions(menu));
 4007
 4008                        if editor.show_edit_predictions_in_menu() {
 4009                            editor.update_visible_inline_completion(window, cx);
 4010                        } else {
 4011                            editor.discard_inline_completion(false, cx);
 4012                        }
 4013
 4014                        cx.notify();
 4015                    } else if editor.completion_tasks.len() <= 1 {
 4016                        // If there are no more completion tasks and the last menu was
 4017                        // empty, we should hide it.
 4018                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4019                        // If it was already hidden and we don't show inline
 4020                        // completions in the menu, we should also show the
 4021                        // inline-completion when available.
 4022                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4023                            editor.update_visible_inline_completion(window, cx);
 4024                        }
 4025                    }
 4026                })?;
 4027
 4028                Ok::<_, anyhow::Error>(())
 4029            }
 4030            .log_err()
 4031        });
 4032
 4033        self.completion_tasks.push((id, task));
 4034    }
 4035
 4036    pub fn confirm_completion(
 4037        &mut self,
 4038        action: &ConfirmCompletion,
 4039        window: &mut Window,
 4040        cx: &mut Context<Self>,
 4041    ) -> Option<Task<Result<()>>> {
 4042        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4043    }
 4044
 4045    pub fn compose_completion(
 4046        &mut self,
 4047        action: &ComposeCompletion,
 4048        window: &mut Window,
 4049        cx: &mut Context<Self>,
 4050    ) -> Option<Task<Result<()>>> {
 4051        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4052    }
 4053
 4054    fn do_completion(
 4055        &mut self,
 4056        item_ix: Option<usize>,
 4057        intent: CompletionIntent,
 4058        window: &mut Window,
 4059        cx: &mut Context<Editor>,
 4060    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4061        use language::ToOffset as _;
 4062
 4063        let completions_menu =
 4064            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4065                menu
 4066            } else {
 4067                return None;
 4068            };
 4069
 4070        let entries = completions_menu.entries.borrow();
 4071        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4072        if self.show_edit_predictions_in_menu() {
 4073            self.discard_inline_completion(true, cx);
 4074        }
 4075        let candidate_id = mat.candidate_id;
 4076        drop(entries);
 4077
 4078        let buffer_handle = completions_menu.buffer;
 4079        let completion = completions_menu
 4080            .completions
 4081            .borrow()
 4082            .get(candidate_id)?
 4083            .clone();
 4084        cx.stop_propagation();
 4085
 4086        let snippet;
 4087        let text;
 4088
 4089        if completion.is_snippet() {
 4090            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4091            text = snippet.as_ref().unwrap().text.clone();
 4092        } else {
 4093            snippet = None;
 4094            text = completion.new_text.clone();
 4095        };
 4096        let selections = self.selections.all::<usize>(cx);
 4097        let buffer = buffer_handle.read(cx);
 4098        let old_range = completion.old_range.to_offset(buffer);
 4099        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4100
 4101        let newest_selection = self.selections.newest_anchor();
 4102        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4103            return None;
 4104        }
 4105
 4106        let lookbehind = newest_selection
 4107            .start
 4108            .text_anchor
 4109            .to_offset(buffer)
 4110            .saturating_sub(old_range.start);
 4111        let lookahead = old_range
 4112            .end
 4113            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4114        let mut common_prefix_len = old_text
 4115            .bytes()
 4116            .zip(text.bytes())
 4117            .take_while(|(a, b)| a == b)
 4118            .count();
 4119
 4120        let snapshot = self.buffer.read(cx).snapshot(cx);
 4121        let mut range_to_replace: Option<Range<isize>> = None;
 4122        let mut ranges = Vec::new();
 4123        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4124        for selection in &selections {
 4125            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4126                let start = selection.start.saturating_sub(lookbehind);
 4127                let end = selection.end + lookahead;
 4128                if selection.id == newest_selection.id {
 4129                    range_to_replace = Some(
 4130                        ((start + common_prefix_len) as isize - selection.start as isize)
 4131                            ..(end as isize - selection.start as isize),
 4132                    );
 4133                }
 4134                ranges.push(start + common_prefix_len..end);
 4135            } else {
 4136                common_prefix_len = 0;
 4137                ranges.clear();
 4138                ranges.extend(selections.iter().map(|s| {
 4139                    if s.id == newest_selection.id {
 4140                        range_to_replace = Some(
 4141                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4142                                - selection.start as isize
 4143                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4144                                    - selection.start as isize,
 4145                        );
 4146                        old_range.clone()
 4147                    } else {
 4148                        s.start..s.end
 4149                    }
 4150                }));
 4151                break;
 4152            }
 4153            if !self.linked_edit_ranges.is_empty() {
 4154                let start_anchor = snapshot.anchor_before(selection.head());
 4155                let end_anchor = snapshot.anchor_after(selection.tail());
 4156                if let Some(ranges) = self
 4157                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4158                {
 4159                    for (buffer, edits) in ranges {
 4160                        linked_edits.entry(buffer.clone()).or_default().extend(
 4161                            edits
 4162                                .into_iter()
 4163                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4164                        );
 4165                    }
 4166                }
 4167            }
 4168        }
 4169        let text = &text[common_prefix_len..];
 4170
 4171        cx.emit(EditorEvent::InputHandled {
 4172            utf16_range_to_replace: range_to_replace,
 4173            text: text.into(),
 4174        });
 4175
 4176        self.transact(window, cx, |this, window, cx| {
 4177            if let Some(mut snippet) = snippet {
 4178                snippet.text = text.to_string();
 4179                for tabstop in snippet
 4180                    .tabstops
 4181                    .iter_mut()
 4182                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4183                {
 4184                    tabstop.start -= common_prefix_len as isize;
 4185                    tabstop.end -= common_prefix_len as isize;
 4186                }
 4187
 4188                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4189            } else {
 4190                this.buffer.update(cx, |buffer, cx| {
 4191                    buffer.edit(
 4192                        ranges.iter().map(|range| (range.clone(), text)),
 4193                        this.autoindent_mode.clone(),
 4194                        cx,
 4195                    );
 4196                });
 4197            }
 4198            for (buffer, edits) in linked_edits {
 4199                buffer.update(cx, |buffer, cx| {
 4200                    let snapshot = buffer.snapshot();
 4201                    let edits = edits
 4202                        .into_iter()
 4203                        .map(|(range, text)| {
 4204                            use text::ToPoint as TP;
 4205                            let end_point = TP::to_point(&range.end, &snapshot);
 4206                            let start_point = TP::to_point(&range.start, &snapshot);
 4207                            (start_point..end_point, text)
 4208                        })
 4209                        .sorted_by_key(|(range, _)| range.start)
 4210                        .collect::<Vec<_>>();
 4211                    buffer.edit(edits, None, cx);
 4212                })
 4213            }
 4214
 4215            this.refresh_inline_completion(true, false, window, cx);
 4216        });
 4217
 4218        let show_new_completions_on_confirm = completion
 4219            .confirm
 4220            .as_ref()
 4221            .map_or(false, |confirm| confirm(intent, window, cx));
 4222        if show_new_completions_on_confirm {
 4223            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4224        }
 4225
 4226        let provider = self.completion_provider.as_ref()?;
 4227        drop(completion);
 4228        let apply_edits = provider.apply_additional_edits_for_completion(
 4229            buffer_handle,
 4230            completions_menu.completions.clone(),
 4231            candidate_id,
 4232            true,
 4233            cx,
 4234        );
 4235
 4236        let editor_settings = EditorSettings::get_global(cx);
 4237        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4238            // After the code completion is finished, users often want to know what signatures are needed.
 4239            // so we should automatically call signature_help
 4240            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4241        }
 4242
 4243        Some(cx.foreground_executor().spawn(async move {
 4244            apply_edits.await?;
 4245            Ok(())
 4246        }))
 4247    }
 4248
 4249    pub fn toggle_code_actions(
 4250        &mut self,
 4251        action: &ToggleCodeActions,
 4252        window: &mut Window,
 4253        cx: &mut Context<Self>,
 4254    ) {
 4255        let mut context_menu = self.context_menu.borrow_mut();
 4256        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4257            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4258                // Toggle if we're selecting the same one
 4259                *context_menu = None;
 4260                cx.notify();
 4261                return;
 4262            } else {
 4263                // Otherwise, clear it and start a new one
 4264                *context_menu = None;
 4265                cx.notify();
 4266            }
 4267        }
 4268        drop(context_menu);
 4269        let snapshot = self.snapshot(window, cx);
 4270        let deployed_from_indicator = action.deployed_from_indicator;
 4271        let mut task = self.code_actions_task.take();
 4272        let action = action.clone();
 4273        cx.spawn_in(window, |editor, mut cx| async move {
 4274            while let Some(prev_task) = task {
 4275                prev_task.await.log_err();
 4276                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4277            }
 4278
 4279            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4280                if editor.focus_handle.is_focused(window) {
 4281                    let multibuffer_point = action
 4282                        .deployed_from_indicator
 4283                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4284                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4285                    let (buffer, buffer_row) = snapshot
 4286                        .buffer_snapshot
 4287                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4288                        .and_then(|(buffer_snapshot, range)| {
 4289                            editor
 4290                                .buffer
 4291                                .read(cx)
 4292                                .buffer(buffer_snapshot.remote_id())
 4293                                .map(|buffer| (buffer, range.start.row))
 4294                        })?;
 4295                    let (_, code_actions) = editor
 4296                        .available_code_actions
 4297                        .clone()
 4298                        .and_then(|(location, code_actions)| {
 4299                            let snapshot = location.buffer.read(cx).snapshot();
 4300                            let point_range = location.range.to_point(&snapshot);
 4301                            let point_range = point_range.start.row..=point_range.end.row;
 4302                            if point_range.contains(&buffer_row) {
 4303                                Some((location, code_actions))
 4304                            } else {
 4305                                None
 4306                            }
 4307                        })
 4308                        .unzip();
 4309                    let buffer_id = buffer.read(cx).remote_id();
 4310                    let tasks = editor
 4311                        .tasks
 4312                        .get(&(buffer_id, buffer_row))
 4313                        .map(|t| Arc::new(t.to_owned()));
 4314                    if tasks.is_none() && code_actions.is_none() {
 4315                        return None;
 4316                    }
 4317
 4318                    editor.completion_tasks.clear();
 4319                    editor.discard_inline_completion(false, cx);
 4320                    let task_context =
 4321                        tasks
 4322                            .as_ref()
 4323                            .zip(editor.project.clone())
 4324                            .map(|(tasks, project)| {
 4325                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4326                            });
 4327
 4328                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4329                        let task_context = match task_context {
 4330                            Some(task_context) => task_context.await,
 4331                            None => None,
 4332                        };
 4333                        let resolved_tasks =
 4334                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4335                                Rc::new(ResolvedTasks {
 4336                                    templates: tasks.resolve(&task_context).collect(),
 4337                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4338                                        multibuffer_point.row,
 4339                                        tasks.column,
 4340                                    )),
 4341                                })
 4342                            });
 4343                        let spawn_straight_away = resolved_tasks
 4344                            .as_ref()
 4345                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4346                            && code_actions
 4347                                .as_ref()
 4348                                .map_or(true, |actions| actions.is_empty());
 4349                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4350                            *editor.context_menu.borrow_mut() =
 4351                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4352                                    buffer,
 4353                                    actions: CodeActionContents {
 4354                                        tasks: resolved_tasks,
 4355                                        actions: code_actions,
 4356                                    },
 4357                                    selected_item: Default::default(),
 4358                                    scroll_handle: UniformListScrollHandle::default(),
 4359                                    deployed_from_indicator,
 4360                                }));
 4361                            if spawn_straight_away {
 4362                                if let Some(task) = editor.confirm_code_action(
 4363                                    &ConfirmCodeAction { item_ix: Some(0) },
 4364                                    window,
 4365                                    cx,
 4366                                ) {
 4367                                    cx.notify();
 4368                                    return task;
 4369                                }
 4370                            }
 4371                            cx.notify();
 4372                            Task::ready(Ok(()))
 4373                        }) {
 4374                            task.await
 4375                        } else {
 4376                            Ok(())
 4377                        }
 4378                    }))
 4379                } else {
 4380                    Some(Task::ready(Ok(())))
 4381                }
 4382            })?;
 4383            if let Some(task) = spawned_test_task {
 4384                task.await?;
 4385            }
 4386
 4387            Ok::<_, anyhow::Error>(())
 4388        })
 4389        .detach_and_log_err(cx);
 4390    }
 4391
 4392    pub fn confirm_code_action(
 4393        &mut self,
 4394        action: &ConfirmCodeAction,
 4395        window: &mut Window,
 4396        cx: &mut Context<Self>,
 4397    ) -> Option<Task<Result<()>>> {
 4398        let actions_menu =
 4399            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4400                menu
 4401            } else {
 4402                return None;
 4403            };
 4404        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4405        let action = actions_menu.actions.get(action_ix)?;
 4406        let title = action.label();
 4407        let buffer = actions_menu.buffer;
 4408        let workspace = self.workspace()?;
 4409
 4410        match action {
 4411            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4412                workspace.update(cx, |workspace, cx| {
 4413                    workspace::tasks::schedule_resolved_task(
 4414                        workspace,
 4415                        task_source_kind,
 4416                        resolved_task,
 4417                        false,
 4418                        cx,
 4419                    );
 4420
 4421                    Some(Task::ready(Ok(())))
 4422                })
 4423            }
 4424            CodeActionsItem::CodeAction {
 4425                excerpt_id,
 4426                action,
 4427                provider,
 4428            } => {
 4429                let apply_code_action =
 4430                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4431                let workspace = workspace.downgrade();
 4432                Some(cx.spawn_in(window, |editor, cx| async move {
 4433                    let project_transaction = apply_code_action.await?;
 4434                    Self::open_project_transaction(
 4435                        &editor,
 4436                        workspace,
 4437                        project_transaction,
 4438                        title,
 4439                        cx,
 4440                    )
 4441                    .await
 4442                }))
 4443            }
 4444        }
 4445    }
 4446
 4447    pub async fn open_project_transaction(
 4448        this: &WeakEntity<Editor>,
 4449        workspace: WeakEntity<Workspace>,
 4450        transaction: ProjectTransaction,
 4451        title: String,
 4452        mut cx: AsyncWindowContext,
 4453    ) -> Result<()> {
 4454        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4455        cx.update(|_, cx| {
 4456            entries.sort_unstable_by_key(|(buffer, _)| {
 4457                buffer.read(cx).file().map(|f| f.path().clone())
 4458            });
 4459        })?;
 4460
 4461        // If the project transaction's edits are all contained within this editor, then
 4462        // avoid opening a new editor to display them.
 4463
 4464        if let Some((buffer, transaction)) = entries.first() {
 4465            if entries.len() == 1 {
 4466                let excerpt = this.update(&mut cx, |editor, cx| {
 4467                    editor
 4468                        .buffer()
 4469                        .read(cx)
 4470                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4471                })?;
 4472                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4473                    if excerpted_buffer == *buffer {
 4474                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4475                            let excerpt_range = excerpt_range.to_offset(buffer);
 4476                            buffer
 4477                                .edited_ranges_for_transaction::<usize>(transaction)
 4478                                .all(|range| {
 4479                                    excerpt_range.start <= range.start
 4480                                        && excerpt_range.end >= range.end
 4481                                })
 4482                        })?;
 4483
 4484                        if all_edits_within_excerpt {
 4485                            return Ok(());
 4486                        }
 4487                    }
 4488                }
 4489            }
 4490        } else {
 4491            return Ok(());
 4492        }
 4493
 4494        let mut ranges_to_highlight = Vec::new();
 4495        let excerpt_buffer = cx.new(|cx| {
 4496            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4497            for (buffer_handle, transaction) in &entries {
 4498                let buffer = buffer_handle.read(cx);
 4499                ranges_to_highlight.extend(
 4500                    multibuffer.push_excerpts_with_context_lines(
 4501                        buffer_handle.clone(),
 4502                        buffer
 4503                            .edited_ranges_for_transaction::<usize>(transaction)
 4504                            .collect(),
 4505                        DEFAULT_MULTIBUFFER_CONTEXT,
 4506                        cx,
 4507                    ),
 4508                );
 4509            }
 4510            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4511            multibuffer
 4512        })?;
 4513
 4514        workspace.update_in(&mut cx, |workspace, window, cx| {
 4515            let project = workspace.project().clone();
 4516            let editor = cx
 4517                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4518            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4519            editor.update(cx, |editor, cx| {
 4520                editor.highlight_background::<Self>(
 4521                    &ranges_to_highlight,
 4522                    |theme| theme.editor_highlighted_line_background,
 4523                    cx,
 4524                );
 4525            });
 4526        })?;
 4527
 4528        Ok(())
 4529    }
 4530
 4531    pub fn clear_code_action_providers(&mut self) {
 4532        self.code_action_providers.clear();
 4533        self.available_code_actions.take();
 4534    }
 4535
 4536    pub fn add_code_action_provider(
 4537        &mut self,
 4538        provider: Rc<dyn CodeActionProvider>,
 4539        window: &mut Window,
 4540        cx: &mut Context<Self>,
 4541    ) {
 4542        if self
 4543            .code_action_providers
 4544            .iter()
 4545            .any(|existing_provider| existing_provider.id() == provider.id())
 4546        {
 4547            return;
 4548        }
 4549
 4550        self.code_action_providers.push(provider);
 4551        self.refresh_code_actions(window, cx);
 4552    }
 4553
 4554    pub fn remove_code_action_provider(
 4555        &mut self,
 4556        id: Arc<str>,
 4557        window: &mut Window,
 4558        cx: &mut Context<Self>,
 4559    ) {
 4560        self.code_action_providers
 4561            .retain(|provider| provider.id() != id);
 4562        self.refresh_code_actions(window, cx);
 4563    }
 4564
 4565    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4566        let buffer = self.buffer.read(cx);
 4567        let newest_selection = self.selections.newest_anchor().clone();
 4568        if newest_selection.head().diff_base_anchor.is_some() {
 4569            return None;
 4570        }
 4571        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4572        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4573        if start_buffer != end_buffer {
 4574            return None;
 4575        }
 4576
 4577        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4578            cx.background_executor()
 4579                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4580                .await;
 4581
 4582            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4583                let providers = this.code_action_providers.clone();
 4584                let tasks = this
 4585                    .code_action_providers
 4586                    .iter()
 4587                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4588                    .collect::<Vec<_>>();
 4589                (providers, tasks)
 4590            })?;
 4591
 4592            let mut actions = Vec::new();
 4593            for (provider, provider_actions) in
 4594                providers.into_iter().zip(future::join_all(tasks).await)
 4595            {
 4596                if let Some(provider_actions) = provider_actions.log_err() {
 4597                    actions.extend(provider_actions.into_iter().map(|action| {
 4598                        AvailableCodeAction {
 4599                            excerpt_id: newest_selection.start.excerpt_id,
 4600                            action,
 4601                            provider: provider.clone(),
 4602                        }
 4603                    }));
 4604                }
 4605            }
 4606
 4607            this.update(&mut cx, |this, cx| {
 4608                this.available_code_actions = if actions.is_empty() {
 4609                    None
 4610                } else {
 4611                    Some((
 4612                        Location {
 4613                            buffer: start_buffer,
 4614                            range: start..end,
 4615                        },
 4616                        actions.into(),
 4617                    ))
 4618                };
 4619                cx.notify();
 4620            })
 4621        }));
 4622        None
 4623    }
 4624
 4625    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4626        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4627            self.show_git_blame_inline = false;
 4628
 4629            self.show_git_blame_inline_delay_task =
 4630                Some(cx.spawn_in(window, |this, mut cx| async move {
 4631                    cx.background_executor().timer(delay).await;
 4632
 4633                    this.update(&mut cx, |this, cx| {
 4634                        this.show_git_blame_inline = true;
 4635                        cx.notify();
 4636                    })
 4637                    .log_err();
 4638                }));
 4639        }
 4640    }
 4641
 4642    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4643        if self.pending_rename.is_some() {
 4644            return None;
 4645        }
 4646
 4647        let provider = self.semantics_provider.clone()?;
 4648        let buffer = self.buffer.read(cx);
 4649        let newest_selection = self.selections.newest_anchor().clone();
 4650        let cursor_position = newest_selection.head();
 4651        let (cursor_buffer, cursor_buffer_position) =
 4652            buffer.text_anchor_for_position(cursor_position, cx)?;
 4653        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4654        if cursor_buffer != tail_buffer {
 4655            return None;
 4656        }
 4657        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4658        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4659            cx.background_executor()
 4660                .timer(Duration::from_millis(debounce))
 4661                .await;
 4662
 4663            let highlights = if let Some(highlights) = cx
 4664                .update(|cx| {
 4665                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4666                })
 4667                .ok()
 4668                .flatten()
 4669            {
 4670                highlights.await.log_err()
 4671            } else {
 4672                None
 4673            };
 4674
 4675            if let Some(highlights) = highlights {
 4676                this.update(&mut cx, |this, cx| {
 4677                    if this.pending_rename.is_some() {
 4678                        return;
 4679                    }
 4680
 4681                    let buffer_id = cursor_position.buffer_id;
 4682                    let buffer = this.buffer.read(cx);
 4683                    if !buffer
 4684                        .text_anchor_for_position(cursor_position, cx)
 4685                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4686                    {
 4687                        return;
 4688                    }
 4689
 4690                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4691                    let mut write_ranges = Vec::new();
 4692                    let mut read_ranges = Vec::new();
 4693                    for highlight in highlights {
 4694                        for (excerpt_id, excerpt_range) in
 4695                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4696                        {
 4697                            let start = highlight
 4698                                .range
 4699                                .start
 4700                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4701                            let end = highlight
 4702                                .range
 4703                                .end
 4704                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4705                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4706                                continue;
 4707                            }
 4708
 4709                            let range = Anchor {
 4710                                buffer_id,
 4711                                excerpt_id,
 4712                                text_anchor: start,
 4713                                diff_base_anchor: None,
 4714                            }..Anchor {
 4715                                buffer_id,
 4716                                excerpt_id,
 4717                                text_anchor: end,
 4718                                diff_base_anchor: None,
 4719                            };
 4720                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4721                                write_ranges.push(range);
 4722                            } else {
 4723                                read_ranges.push(range);
 4724                            }
 4725                        }
 4726                    }
 4727
 4728                    this.highlight_background::<DocumentHighlightRead>(
 4729                        &read_ranges,
 4730                        |theme| theme.editor_document_highlight_read_background,
 4731                        cx,
 4732                    );
 4733                    this.highlight_background::<DocumentHighlightWrite>(
 4734                        &write_ranges,
 4735                        |theme| theme.editor_document_highlight_write_background,
 4736                        cx,
 4737                    );
 4738                    cx.notify();
 4739                })
 4740                .log_err();
 4741            }
 4742        }));
 4743        None
 4744    }
 4745
 4746    pub fn refresh_selected_text_highlights(
 4747        &mut self,
 4748        window: &mut Window,
 4749        cx: &mut Context<Editor>,
 4750    ) {
 4751        self.selection_highlight_task.take();
 4752        if !EditorSettings::get_global(cx).selection_highlight {
 4753            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4754            return;
 4755        }
 4756        if self.selections.count() != 1 || self.selections.line_mode {
 4757            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4758            return;
 4759        }
 4760        let selection = self.selections.newest::<Point>(cx);
 4761        if selection.is_empty() || selection.start.row != selection.end.row {
 4762            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4763            return;
 4764        }
 4765        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4766        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4767            cx.background_executor()
 4768                .timer(Duration::from_millis(debounce))
 4769                .await;
 4770            let Some(Some(matches_task)) = editor
 4771                .update_in(&mut cx, |editor, _, cx| {
 4772                    if editor.selections.count() != 1 || editor.selections.line_mode {
 4773                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4774                        return None;
 4775                    }
 4776                    let selection = editor.selections.newest::<Point>(cx);
 4777                    if selection.is_empty() || selection.start.row != selection.end.row {
 4778                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4779                        return None;
 4780                    }
 4781                    let buffer = editor.buffer().read(cx).snapshot(cx);
 4782                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 4783                    if query.trim().is_empty() {
 4784                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4785                        return None;
 4786                    }
 4787                    Some(cx.background_spawn(async move {
 4788                        let mut ranges = Vec::new();
 4789                        let selection_anchors = selection.range().to_anchors(&buffer);
 4790                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 4791                            for (search_buffer, search_range, excerpt_id) in
 4792                                buffer.range_to_buffer_ranges(range)
 4793                            {
 4794                                ranges.extend(
 4795                                    project::search::SearchQuery::text(
 4796                                        query.clone(),
 4797                                        false,
 4798                                        false,
 4799                                        false,
 4800                                        Default::default(),
 4801                                        Default::default(),
 4802                                        None,
 4803                                    )
 4804                                    .unwrap()
 4805                                    .search(search_buffer, Some(search_range.clone()))
 4806                                    .await
 4807                                    .into_iter()
 4808                                    .filter_map(
 4809                                        |match_range| {
 4810                                            let start = search_buffer.anchor_after(
 4811                                                search_range.start + match_range.start,
 4812                                            );
 4813                                            let end = search_buffer.anchor_before(
 4814                                                search_range.start + match_range.end,
 4815                                            );
 4816                                            let range = Anchor::range_in_buffer(
 4817                                                excerpt_id,
 4818                                                search_buffer.remote_id(),
 4819                                                start..end,
 4820                                            );
 4821                                            (range != selection_anchors).then_some(range)
 4822                                        },
 4823                                    ),
 4824                                );
 4825                            }
 4826                        }
 4827                        ranges
 4828                    }))
 4829                })
 4830                .log_err()
 4831            else {
 4832                return;
 4833            };
 4834            let matches = matches_task.await;
 4835            editor
 4836                .update_in(&mut cx, |editor, _, cx| {
 4837                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4838                    if !matches.is_empty() {
 4839                        editor.highlight_background::<SelectedTextHighlight>(
 4840                            &matches,
 4841                            |theme| theme.editor_document_highlight_bracket_background,
 4842                            cx,
 4843                        )
 4844                    }
 4845                })
 4846                .log_err();
 4847        }));
 4848    }
 4849
 4850    pub fn refresh_inline_completion(
 4851        &mut self,
 4852        debounce: bool,
 4853        user_requested: bool,
 4854        window: &mut Window,
 4855        cx: &mut Context<Self>,
 4856    ) -> Option<()> {
 4857        let provider = self.edit_prediction_provider()?;
 4858        let cursor = self.selections.newest_anchor().head();
 4859        let (buffer, cursor_buffer_position) =
 4860            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4861
 4862        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4863            self.discard_inline_completion(false, cx);
 4864            return None;
 4865        }
 4866
 4867        if !user_requested
 4868            && (!self.should_show_edit_predictions()
 4869                || !self.is_focused(window)
 4870                || buffer.read(cx).is_empty())
 4871        {
 4872            self.discard_inline_completion(false, cx);
 4873            return None;
 4874        }
 4875
 4876        self.update_visible_inline_completion(window, cx);
 4877        provider.refresh(
 4878            self.project.clone(),
 4879            buffer,
 4880            cursor_buffer_position,
 4881            debounce,
 4882            cx,
 4883        );
 4884        Some(())
 4885    }
 4886
 4887    fn show_edit_predictions_in_menu(&self) -> bool {
 4888        match self.edit_prediction_settings {
 4889            EditPredictionSettings::Disabled => false,
 4890            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4891        }
 4892    }
 4893
 4894    pub fn edit_predictions_enabled(&self) -> bool {
 4895        match self.edit_prediction_settings {
 4896            EditPredictionSettings::Disabled => false,
 4897            EditPredictionSettings::Enabled { .. } => true,
 4898        }
 4899    }
 4900
 4901    fn edit_prediction_requires_modifier(&self) -> bool {
 4902        match self.edit_prediction_settings {
 4903            EditPredictionSettings::Disabled => false,
 4904            EditPredictionSettings::Enabled {
 4905                preview_requires_modifier,
 4906                ..
 4907            } => preview_requires_modifier,
 4908        }
 4909    }
 4910
 4911    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 4912        if self.edit_prediction_provider.is_none() {
 4913            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 4914        } else {
 4915            let selection = self.selections.newest_anchor();
 4916            let cursor = selection.head();
 4917
 4918            if let Some((buffer, cursor_buffer_position)) =
 4919                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4920            {
 4921                self.edit_prediction_settings =
 4922                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 4923            }
 4924        }
 4925    }
 4926
 4927    fn edit_prediction_settings_at_position(
 4928        &self,
 4929        buffer: &Entity<Buffer>,
 4930        buffer_position: language::Anchor,
 4931        cx: &App,
 4932    ) -> EditPredictionSettings {
 4933        if self.mode != EditorMode::Full
 4934            || !self.show_inline_completions_override.unwrap_or(true)
 4935            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4936        {
 4937            return EditPredictionSettings::Disabled;
 4938        }
 4939
 4940        let buffer = buffer.read(cx);
 4941
 4942        let file = buffer.file();
 4943
 4944        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4945            return EditPredictionSettings::Disabled;
 4946        };
 4947
 4948        let by_provider = matches!(
 4949            self.menu_inline_completions_policy,
 4950            MenuInlineCompletionsPolicy::ByProvider
 4951        );
 4952
 4953        let show_in_menu = by_provider
 4954            && self
 4955                .edit_prediction_provider
 4956                .as_ref()
 4957                .map_or(false, |provider| {
 4958                    provider.provider.show_completions_in_menu()
 4959                });
 4960
 4961        let preview_requires_modifier =
 4962            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 4963
 4964        EditPredictionSettings::Enabled {
 4965            show_in_menu,
 4966            preview_requires_modifier,
 4967        }
 4968    }
 4969
 4970    fn should_show_edit_predictions(&self) -> bool {
 4971        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4972    }
 4973
 4974    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4975        matches!(
 4976            self.edit_prediction_preview,
 4977            EditPredictionPreview::Active { .. }
 4978        )
 4979    }
 4980
 4981    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 4982        let cursor = self.selections.newest_anchor().head();
 4983        if let Some((buffer, cursor_position)) =
 4984            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4985        {
 4986            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 4987        } else {
 4988            false
 4989        }
 4990    }
 4991
 4992    fn edit_predictions_enabled_in_buffer(
 4993        &self,
 4994        buffer: &Entity<Buffer>,
 4995        buffer_position: language::Anchor,
 4996        cx: &App,
 4997    ) -> bool {
 4998        maybe!({
 4999            let provider = self.edit_prediction_provider()?;
 5000            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5001                return Some(false);
 5002            }
 5003            let buffer = buffer.read(cx);
 5004            let Some(file) = buffer.file() else {
 5005                return Some(true);
 5006            };
 5007            let settings = all_language_settings(Some(file), cx);
 5008            Some(settings.inline_completions_enabled_for_path(file.path()))
 5009        })
 5010        .unwrap_or(false)
 5011    }
 5012
 5013    fn cycle_inline_completion(
 5014        &mut self,
 5015        direction: Direction,
 5016        window: &mut Window,
 5017        cx: &mut Context<Self>,
 5018    ) -> Option<()> {
 5019        let provider = self.edit_prediction_provider()?;
 5020        let cursor = self.selections.newest_anchor().head();
 5021        let (buffer, cursor_buffer_position) =
 5022            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5023        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5024            return None;
 5025        }
 5026
 5027        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5028        self.update_visible_inline_completion(window, cx);
 5029
 5030        Some(())
 5031    }
 5032
 5033    pub fn show_inline_completion(
 5034        &mut self,
 5035        _: &ShowEditPrediction,
 5036        window: &mut Window,
 5037        cx: &mut Context<Self>,
 5038    ) {
 5039        if !self.has_active_inline_completion() {
 5040            self.refresh_inline_completion(false, true, window, cx);
 5041            return;
 5042        }
 5043
 5044        self.update_visible_inline_completion(window, cx);
 5045    }
 5046
 5047    pub fn display_cursor_names(
 5048        &mut self,
 5049        _: &DisplayCursorNames,
 5050        window: &mut Window,
 5051        cx: &mut Context<Self>,
 5052    ) {
 5053        self.show_cursor_names(window, cx);
 5054    }
 5055
 5056    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5057        self.show_cursor_names = true;
 5058        cx.notify();
 5059        cx.spawn_in(window, |this, mut cx| async move {
 5060            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5061            this.update(&mut cx, |this, cx| {
 5062                this.show_cursor_names = false;
 5063                cx.notify()
 5064            })
 5065            .ok()
 5066        })
 5067        .detach();
 5068    }
 5069
 5070    pub fn next_edit_prediction(
 5071        &mut self,
 5072        _: &NextEditPrediction,
 5073        window: &mut Window,
 5074        cx: &mut Context<Self>,
 5075    ) {
 5076        if self.has_active_inline_completion() {
 5077            self.cycle_inline_completion(Direction::Next, window, cx);
 5078        } else {
 5079            let is_copilot_disabled = self
 5080                .refresh_inline_completion(false, true, window, cx)
 5081                .is_none();
 5082            if is_copilot_disabled {
 5083                cx.propagate();
 5084            }
 5085        }
 5086    }
 5087
 5088    pub fn previous_edit_prediction(
 5089        &mut self,
 5090        _: &PreviousEditPrediction,
 5091        window: &mut Window,
 5092        cx: &mut Context<Self>,
 5093    ) {
 5094        if self.has_active_inline_completion() {
 5095            self.cycle_inline_completion(Direction::Prev, window, cx);
 5096        } else {
 5097            let is_copilot_disabled = self
 5098                .refresh_inline_completion(false, true, window, cx)
 5099                .is_none();
 5100            if is_copilot_disabled {
 5101                cx.propagate();
 5102            }
 5103        }
 5104    }
 5105
 5106    pub fn accept_edit_prediction(
 5107        &mut self,
 5108        _: &AcceptEditPrediction,
 5109        window: &mut Window,
 5110        cx: &mut Context<Self>,
 5111    ) {
 5112        if self.show_edit_predictions_in_menu() {
 5113            self.hide_context_menu(window, cx);
 5114        }
 5115
 5116        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5117            return;
 5118        };
 5119
 5120        self.report_inline_completion_event(
 5121            active_inline_completion.completion_id.clone(),
 5122            true,
 5123            cx,
 5124        );
 5125
 5126        match &active_inline_completion.completion {
 5127            InlineCompletion::Move { target, .. } => {
 5128                let target = *target;
 5129
 5130                if let Some(position_map) = &self.last_position_map {
 5131                    if position_map
 5132                        .visible_row_range
 5133                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5134                        || !self.edit_prediction_requires_modifier()
 5135                    {
 5136                        self.unfold_ranges(&[target..target], true, false, cx);
 5137                        // Note that this is also done in vim's handler of the Tab action.
 5138                        self.change_selections(
 5139                            Some(Autoscroll::newest()),
 5140                            window,
 5141                            cx,
 5142                            |selections| {
 5143                                selections.select_anchor_ranges([target..target]);
 5144                            },
 5145                        );
 5146                        self.clear_row_highlights::<EditPredictionPreview>();
 5147
 5148                        self.edit_prediction_preview
 5149                            .set_previous_scroll_position(None);
 5150                    } else {
 5151                        self.edit_prediction_preview
 5152                            .set_previous_scroll_position(Some(
 5153                                position_map.snapshot.scroll_anchor,
 5154                            ));
 5155
 5156                        self.highlight_rows::<EditPredictionPreview>(
 5157                            target..target,
 5158                            cx.theme().colors().editor_highlighted_line_background,
 5159                            true,
 5160                            cx,
 5161                        );
 5162                        self.request_autoscroll(Autoscroll::fit(), cx);
 5163                    }
 5164                }
 5165            }
 5166            InlineCompletion::Edit { edits, .. } => {
 5167                if let Some(provider) = self.edit_prediction_provider() {
 5168                    provider.accept(cx);
 5169                }
 5170
 5171                let snapshot = self.buffer.read(cx).snapshot(cx);
 5172                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5173
 5174                self.buffer.update(cx, |buffer, cx| {
 5175                    buffer.edit(edits.iter().cloned(), None, cx)
 5176                });
 5177
 5178                self.change_selections(None, window, cx, |s| {
 5179                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5180                });
 5181
 5182                self.update_visible_inline_completion(window, cx);
 5183                if self.active_inline_completion.is_none() {
 5184                    self.refresh_inline_completion(true, true, window, cx);
 5185                }
 5186
 5187                cx.notify();
 5188            }
 5189        }
 5190
 5191        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5192    }
 5193
 5194    pub fn accept_partial_inline_completion(
 5195        &mut self,
 5196        _: &AcceptPartialEditPrediction,
 5197        window: &mut Window,
 5198        cx: &mut Context<Self>,
 5199    ) {
 5200        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5201            return;
 5202        };
 5203        if self.selections.count() != 1 {
 5204            return;
 5205        }
 5206
 5207        self.report_inline_completion_event(
 5208            active_inline_completion.completion_id.clone(),
 5209            true,
 5210            cx,
 5211        );
 5212
 5213        match &active_inline_completion.completion {
 5214            InlineCompletion::Move { target, .. } => {
 5215                let target = *target;
 5216                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5217                    selections.select_anchor_ranges([target..target]);
 5218                });
 5219            }
 5220            InlineCompletion::Edit { edits, .. } => {
 5221                // Find an insertion that starts at the cursor position.
 5222                let snapshot = self.buffer.read(cx).snapshot(cx);
 5223                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5224                let insertion = edits.iter().find_map(|(range, text)| {
 5225                    let range = range.to_offset(&snapshot);
 5226                    if range.is_empty() && range.start == cursor_offset {
 5227                        Some(text)
 5228                    } else {
 5229                        None
 5230                    }
 5231                });
 5232
 5233                if let Some(text) = insertion {
 5234                    let mut partial_completion = text
 5235                        .chars()
 5236                        .by_ref()
 5237                        .take_while(|c| c.is_alphabetic())
 5238                        .collect::<String>();
 5239                    if partial_completion.is_empty() {
 5240                        partial_completion = text
 5241                            .chars()
 5242                            .by_ref()
 5243                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5244                            .collect::<String>();
 5245                    }
 5246
 5247                    cx.emit(EditorEvent::InputHandled {
 5248                        utf16_range_to_replace: None,
 5249                        text: partial_completion.clone().into(),
 5250                    });
 5251
 5252                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5253
 5254                    self.refresh_inline_completion(true, true, window, cx);
 5255                    cx.notify();
 5256                } else {
 5257                    self.accept_edit_prediction(&Default::default(), window, cx);
 5258                }
 5259            }
 5260        }
 5261    }
 5262
 5263    fn discard_inline_completion(
 5264        &mut self,
 5265        should_report_inline_completion_event: bool,
 5266        cx: &mut Context<Self>,
 5267    ) -> bool {
 5268        if should_report_inline_completion_event {
 5269            let completion_id = self
 5270                .active_inline_completion
 5271                .as_ref()
 5272                .and_then(|active_completion| active_completion.completion_id.clone());
 5273
 5274            self.report_inline_completion_event(completion_id, false, cx);
 5275        }
 5276
 5277        if let Some(provider) = self.edit_prediction_provider() {
 5278            provider.discard(cx);
 5279        }
 5280
 5281        self.take_active_inline_completion(cx)
 5282    }
 5283
 5284    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5285        let Some(provider) = self.edit_prediction_provider() else {
 5286            return;
 5287        };
 5288
 5289        let Some((_, buffer, _)) = self
 5290            .buffer
 5291            .read(cx)
 5292            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5293        else {
 5294            return;
 5295        };
 5296
 5297        let extension = buffer
 5298            .read(cx)
 5299            .file()
 5300            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5301
 5302        let event_type = match accepted {
 5303            true => "Edit Prediction Accepted",
 5304            false => "Edit Prediction Discarded",
 5305        };
 5306        telemetry::event!(
 5307            event_type,
 5308            provider = provider.name(),
 5309            prediction_id = id,
 5310            suggestion_accepted = accepted,
 5311            file_extension = extension,
 5312        );
 5313    }
 5314
 5315    pub fn has_active_inline_completion(&self) -> bool {
 5316        self.active_inline_completion.is_some()
 5317    }
 5318
 5319    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5320        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5321            return false;
 5322        };
 5323
 5324        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5325        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5326        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5327        true
 5328    }
 5329
 5330    /// Returns true when we're displaying the edit prediction popover below the cursor
 5331    /// like we are not previewing and the LSP autocomplete menu is visible
 5332    /// or we are in `when_holding_modifier` mode.
 5333    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5334        if self.edit_prediction_preview_is_active()
 5335            || !self.show_edit_predictions_in_menu()
 5336            || !self.edit_predictions_enabled()
 5337        {
 5338            return false;
 5339        }
 5340
 5341        if self.has_visible_completions_menu() {
 5342            return true;
 5343        }
 5344
 5345        has_completion && self.edit_prediction_requires_modifier()
 5346    }
 5347
 5348    fn handle_modifiers_changed(
 5349        &mut self,
 5350        modifiers: Modifiers,
 5351        position_map: &PositionMap,
 5352        window: &mut Window,
 5353        cx: &mut Context<Self>,
 5354    ) {
 5355        if self.show_edit_predictions_in_menu() {
 5356            self.update_edit_prediction_preview(&modifiers, window, cx);
 5357        }
 5358
 5359        self.update_selection_mode(&modifiers, position_map, window, cx);
 5360
 5361        let mouse_position = window.mouse_position();
 5362        if !position_map.text_hitbox.is_hovered(window) {
 5363            return;
 5364        }
 5365
 5366        self.update_hovered_link(
 5367            position_map.point_for_position(mouse_position),
 5368            &position_map.snapshot,
 5369            modifiers,
 5370            window,
 5371            cx,
 5372        )
 5373    }
 5374
 5375    fn update_selection_mode(
 5376        &mut self,
 5377        modifiers: &Modifiers,
 5378        position_map: &PositionMap,
 5379        window: &mut Window,
 5380        cx: &mut Context<Self>,
 5381    ) {
 5382        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5383            return;
 5384        }
 5385
 5386        let mouse_position = window.mouse_position();
 5387        let point_for_position = position_map.point_for_position(mouse_position);
 5388        let position = point_for_position.previous_valid;
 5389
 5390        self.select(
 5391            SelectPhase::BeginColumnar {
 5392                position,
 5393                reset: false,
 5394                goal_column: point_for_position.exact_unclipped.column(),
 5395            },
 5396            window,
 5397            cx,
 5398        );
 5399    }
 5400
 5401    fn update_edit_prediction_preview(
 5402        &mut self,
 5403        modifiers: &Modifiers,
 5404        window: &mut Window,
 5405        cx: &mut Context<Self>,
 5406    ) {
 5407        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5408        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5409            return;
 5410        };
 5411
 5412        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5413            if matches!(
 5414                self.edit_prediction_preview,
 5415                EditPredictionPreview::Inactive { .. }
 5416            ) {
 5417                self.edit_prediction_preview = EditPredictionPreview::Active {
 5418                    previous_scroll_position: None,
 5419                    since: Instant::now(),
 5420                };
 5421
 5422                self.update_visible_inline_completion(window, cx);
 5423                cx.notify();
 5424            }
 5425        } else if let EditPredictionPreview::Active {
 5426            previous_scroll_position,
 5427            since,
 5428        } = self.edit_prediction_preview
 5429        {
 5430            if let (Some(previous_scroll_position), Some(position_map)) =
 5431                (previous_scroll_position, self.last_position_map.as_ref())
 5432            {
 5433                self.set_scroll_position(
 5434                    previous_scroll_position
 5435                        .scroll_position(&position_map.snapshot.display_snapshot),
 5436                    window,
 5437                    cx,
 5438                );
 5439            }
 5440
 5441            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 5442                released_too_fast: since.elapsed() < Duration::from_millis(200),
 5443            };
 5444            self.clear_row_highlights::<EditPredictionPreview>();
 5445            self.update_visible_inline_completion(window, cx);
 5446            cx.notify();
 5447        }
 5448    }
 5449
 5450    fn update_visible_inline_completion(
 5451        &mut self,
 5452        _window: &mut Window,
 5453        cx: &mut Context<Self>,
 5454    ) -> Option<()> {
 5455        let selection = self.selections.newest_anchor();
 5456        let cursor = selection.head();
 5457        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5458        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5459        let excerpt_id = cursor.excerpt_id;
 5460
 5461        let show_in_menu = self.show_edit_predictions_in_menu();
 5462        let completions_menu_has_precedence = !show_in_menu
 5463            && (self.context_menu.borrow().is_some()
 5464                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5465
 5466        if completions_menu_has_precedence
 5467            || !offset_selection.is_empty()
 5468            || self
 5469                .active_inline_completion
 5470                .as_ref()
 5471                .map_or(false, |completion| {
 5472                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5473                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5474                    !invalidation_range.contains(&offset_selection.head())
 5475                })
 5476        {
 5477            self.discard_inline_completion(false, cx);
 5478            return None;
 5479        }
 5480
 5481        self.take_active_inline_completion(cx);
 5482        let Some(provider) = self.edit_prediction_provider() else {
 5483            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5484            return None;
 5485        };
 5486
 5487        let (buffer, cursor_buffer_position) =
 5488            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5489
 5490        self.edit_prediction_settings =
 5491            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5492
 5493        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 5494
 5495        if self.edit_prediction_indent_conflict {
 5496            let cursor_point = cursor.to_point(&multibuffer);
 5497
 5498            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 5499
 5500            if let Some((_, indent)) = indents.iter().next() {
 5501                if indent.len == cursor_point.column {
 5502                    self.edit_prediction_indent_conflict = false;
 5503                }
 5504            }
 5505        }
 5506
 5507        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5508        let edits = inline_completion
 5509            .edits
 5510            .into_iter()
 5511            .flat_map(|(range, new_text)| {
 5512                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5513                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5514                Some((start..end, new_text))
 5515            })
 5516            .collect::<Vec<_>>();
 5517        if edits.is_empty() {
 5518            return None;
 5519        }
 5520
 5521        let first_edit_start = edits.first().unwrap().0.start;
 5522        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5523        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5524
 5525        let last_edit_end = edits.last().unwrap().0.end;
 5526        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5527        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5528
 5529        let cursor_row = cursor.to_point(&multibuffer).row;
 5530
 5531        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5532
 5533        let mut inlay_ids = Vec::new();
 5534        let invalidation_row_range;
 5535        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5536            Some(cursor_row..edit_end_row)
 5537        } else if cursor_row > edit_end_row {
 5538            Some(edit_start_row..cursor_row)
 5539        } else {
 5540            None
 5541        };
 5542        let is_move =
 5543            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5544        let completion = if is_move {
 5545            invalidation_row_range =
 5546                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5547            let target = first_edit_start;
 5548            InlineCompletion::Move { target, snapshot }
 5549        } else {
 5550            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5551                && !self.inline_completions_hidden_for_vim_mode;
 5552
 5553            if show_completions_in_buffer {
 5554                if edits
 5555                    .iter()
 5556                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5557                {
 5558                    let mut inlays = Vec::new();
 5559                    for (range, new_text) in &edits {
 5560                        let inlay = Inlay::inline_completion(
 5561                            post_inc(&mut self.next_inlay_id),
 5562                            range.start,
 5563                            new_text.as_str(),
 5564                        );
 5565                        inlay_ids.push(inlay.id);
 5566                        inlays.push(inlay);
 5567                    }
 5568
 5569                    self.splice_inlays(&[], inlays, cx);
 5570                } else {
 5571                    let background_color = cx.theme().status().deleted_background;
 5572                    self.highlight_text::<InlineCompletionHighlight>(
 5573                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5574                        HighlightStyle {
 5575                            background_color: Some(background_color),
 5576                            ..Default::default()
 5577                        },
 5578                        cx,
 5579                    );
 5580                }
 5581            }
 5582
 5583            invalidation_row_range = edit_start_row..edit_end_row;
 5584
 5585            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5586                if provider.show_tab_accept_marker() {
 5587                    EditDisplayMode::TabAccept
 5588                } else {
 5589                    EditDisplayMode::Inline
 5590                }
 5591            } else {
 5592                EditDisplayMode::DiffPopover
 5593            };
 5594
 5595            InlineCompletion::Edit {
 5596                edits,
 5597                edit_preview: inline_completion.edit_preview,
 5598                display_mode,
 5599                snapshot,
 5600            }
 5601        };
 5602
 5603        let invalidation_range = multibuffer
 5604            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5605            ..multibuffer.anchor_after(Point::new(
 5606                invalidation_row_range.end,
 5607                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5608            ));
 5609
 5610        self.stale_inline_completion_in_menu = None;
 5611        self.active_inline_completion = Some(InlineCompletionState {
 5612            inlay_ids,
 5613            completion,
 5614            completion_id: inline_completion.id,
 5615            invalidation_range,
 5616        });
 5617
 5618        cx.notify();
 5619
 5620        Some(())
 5621    }
 5622
 5623    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5624        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5625    }
 5626
 5627    fn render_code_actions_indicator(
 5628        &self,
 5629        _style: &EditorStyle,
 5630        row: DisplayRow,
 5631        is_active: bool,
 5632        cx: &mut Context<Self>,
 5633    ) -> Option<IconButton> {
 5634        if self.available_code_actions.is_some() {
 5635            Some(
 5636                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5637                    .shape(ui::IconButtonShape::Square)
 5638                    .icon_size(IconSize::XSmall)
 5639                    .icon_color(Color::Muted)
 5640                    .toggle_state(is_active)
 5641                    .tooltip({
 5642                        let focus_handle = self.focus_handle.clone();
 5643                        move |window, cx| {
 5644                            Tooltip::for_action_in(
 5645                                "Toggle Code Actions",
 5646                                &ToggleCodeActions {
 5647                                    deployed_from_indicator: None,
 5648                                },
 5649                                &focus_handle,
 5650                                window,
 5651                                cx,
 5652                            )
 5653                        }
 5654                    })
 5655                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5656                        window.focus(&editor.focus_handle(cx));
 5657                        editor.toggle_code_actions(
 5658                            &ToggleCodeActions {
 5659                                deployed_from_indicator: Some(row),
 5660                            },
 5661                            window,
 5662                            cx,
 5663                        );
 5664                    })),
 5665            )
 5666        } else {
 5667            None
 5668        }
 5669    }
 5670
 5671    fn clear_tasks(&mut self) {
 5672        self.tasks.clear()
 5673    }
 5674
 5675    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5676        if self.tasks.insert(key, value).is_some() {
 5677            // This case should hopefully be rare, but just in case...
 5678            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5679        }
 5680    }
 5681
 5682    fn build_tasks_context(
 5683        project: &Entity<Project>,
 5684        buffer: &Entity<Buffer>,
 5685        buffer_row: u32,
 5686        tasks: &Arc<RunnableTasks>,
 5687        cx: &mut Context<Self>,
 5688    ) -> Task<Option<task::TaskContext>> {
 5689        let position = Point::new(buffer_row, tasks.column);
 5690        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5691        let location = Location {
 5692            buffer: buffer.clone(),
 5693            range: range_start..range_start,
 5694        };
 5695        // Fill in the environmental variables from the tree-sitter captures
 5696        let mut captured_task_variables = TaskVariables::default();
 5697        for (capture_name, value) in tasks.extra_variables.clone() {
 5698            captured_task_variables.insert(
 5699                task::VariableName::Custom(capture_name.into()),
 5700                value.clone(),
 5701            );
 5702        }
 5703        project.update(cx, |project, cx| {
 5704            project.task_store().update(cx, |task_store, cx| {
 5705                task_store.task_context_for_location(captured_task_variables, location, cx)
 5706            })
 5707        })
 5708    }
 5709
 5710    pub fn spawn_nearest_task(
 5711        &mut self,
 5712        action: &SpawnNearestTask,
 5713        window: &mut Window,
 5714        cx: &mut Context<Self>,
 5715    ) {
 5716        let Some((workspace, _)) = self.workspace.clone() else {
 5717            return;
 5718        };
 5719        let Some(project) = self.project.clone() else {
 5720            return;
 5721        };
 5722
 5723        // Try to find a closest, enclosing node using tree-sitter that has a
 5724        // task
 5725        let Some((buffer, buffer_row, tasks)) = self
 5726            .find_enclosing_node_task(cx)
 5727            // Or find the task that's closest in row-distance.
 5728            .or_else(|| self.find_closest_task(cx))
 5729        else {
 5730            return;
 5731        };
 5732
 5733        let reveal_strategy = action.reveal;
 5734        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5735        cx.spawn_in(window, |_, mut cx| async move {
 5736            let context = task_context.await?;
 5737            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5738
 5739            let resolved = resolved_task.resolved.as_mut()?;
 5740            resolved.reveal = reveal_strategy;
 5741
 5742            workspace
 5743                .update(&mut cx, |workspace, cx| {
 5744                    workspace::tasks::schedule_resolved_task(
 5745                        workspace,
 5746                        task_source_kind,
 5747                        resolved_task,
 5748                        false,
 5749                        cx,
 5750                    );
 5751                })
 5752                .ok()
 5753        })
 5754        .detach();
 5755    }
 5756
 5757    fn find_closest_task(
 5758        &mut self,
 5759        cx: &mut Context<Self>,
 5760    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5761        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5762
 5763        let ((buffer_id, row), tasks) = self
 5764            .tasks
 5765            .iter()
 5766            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5767
 5768        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5769        let tasks = Arc::new(tasks.to_owned());
 5770        Some((buffer, *row, tasks))
 5771    }
 5772
 5773    fn find_enclosing_node_task(
 5774        &mut self,
 5775        cx: &mut Context<Self>,
 5776    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5777        let snapshot = self.buffer.read(cx).snapshot(cx);
 5778        let offset = self.selections.newest::<usize>(cx).head();
 5779        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5780        let buffer_id = excerpt.buffer().remote_id();
 5781
 5782        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5783        let mut cursor = layer.node().walk();
 5784
 5785        while cursor.goto_first_child_for_byte(offset).is_some() {
 5786            if cursor.node().end_byte() == offset {
 5787                cursor.goto_next_sibling();
 5788            }
 5789        }
 5790
 5791        // Ascend to the smallest ancestor that contains the range and has a task.
 5792        loop {
 5793            let node = cursor.node();
 5794            let node_range = node.byte_range();
 5795            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5796
 5797            // Check if this node contains our offset
 5798            if node_range.start <= offset && node_range.end >= offset {
 5799                // If it contains offset, check for task
 5800                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5801                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5802                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5803                }
 5804            }
 5805
 5806            if !cursor.goto_parent() {
 5807                break;
 5808            }
 5809        }
 5810        None
 5811    }
 5812
 5813    fn render_run_indicator(
 5814        &self,
 5815        _style: &EditorStyle,
 5816        is_active: bool,
 5817        row: DisplayRow,
 5818        cx: &mut Context<Self>,
 5819    ) -> IconButton {
 5820        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5821            .shape(ui::IconButtonShape::Square)
 5822            .icon_size(IconSize::XSmall)
 5823            .icon_color(Color::Muted)
 5824            .toggle_state(is_active)
 5825            .on_click(cx.listener(move |editor, _e, window, cx| {
 5826                window.focus(&editor.focus_handle(cx));
 5827                editor.toggle_code_actions(
 5828                    &ToggleCodeActions {
 5829                        deployed_from_indicator: Some(row),
 5830                    },
 5831                    window,
 5832                    cx,
 5833                );
 5834            }))
 5835    }
 5836
 5837    pub fn context_menu_visible(&self) -> bool {
 5838        !self.edit_prediction_preview_is_active()
 5839            && self
 5840                .context_menu
 5841                .borrow()
 5842                .as_ref()
 5843                .map_or(false, |menu| menu.visible())
 5844    }
 5845
 5846    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5847        self.context_menu
 5848            .borrow()
 5849            .as_ref()
 5850            .map(|menu| menu.origin())
 5851    }
 5852
 5853    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 5854    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 5855
 5856    #[allow(clippy::too_many_arguments)]
 5857    fn render_edit_prediction_popover(
 5858        &mut self,
 5859        text_bounds: &Bounds<Pixels>,
 5860        content_origin: gpui::Point<Pixels>,
 5861        editor_snapshot: &EditorSnapshot,
 5862        visible_row_range: Range<DisplayRow>,
 5863        scroll_top: f32,
 5864        scroll_bottom: f32,
 5865        line_layouts: &[LineWithInvisibles],
 5866        line_height: Pixels,
 5867        scroll_pixel_position: gpui::Point<Pixels>,
 5868        newest_selection_head: Option<DisplayPoint>,
 5869        editor_width: Pixels,
 5870        style: &EditorStyle,
 5871        window: &mut Window,
 5872        cx: &mut App,
 5873    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5874        let active_inline_completion = self.active_inline_completion.as_ref()?;
 5875
 5876        if self.edit_prediction_visible_in_cursor_popover(true) {
 5877            return None;
 5878        }
 5879
 5880        match &active_inline_completion.completion {
 5881            InlineCompletion::Move { target, .. } => {
 5882                let target_display_point = target.to_display_point(editor_snapshot);
 5883
 5884                if self.edit_prediction_requires_modifier() {
 5885                    if !self.edit_prediction_preview_is_active() {
 5886                        return None;
 5887                    }
 5888
 5889                    self.render_edit_prediction_modifier_jump_popover(
 5890                        text_bounds,
 5891                        content_origin,
 5892                        visible_row_range,
 5893                        line_layouts,
 5894                        line_height,
 5895                        scroll_pixel_position,
 5896                        newest_selection_head,
 5897                        target_display_point,
 5898                        window,
 5899                        cx,
 5900                    )
 5901                } else {
 5902                    self.render_edit_prediction_eager_jump_popover(
 5903                        text_bounds,
 5904                        content_origin,
 5905                        editor_snapshot,
 5906                        visible_row_range,
 5907                        scroll_top,
 5908                        scroll_bottom,
 5909                        line_height,
 5910                        scroll_pixel_position,
 5911                        target_display_point,
 5912                        editor_width,
 5913                        window,
 5914                        cx,
 5915                    )
 5916                }
 5917            }
 5918            InlineCompletion::Edit {
 5919                display_mode: EditDisplayMode::Inline,
 5920                ..
 5921            } => None,
 5922            InlineCompletion::Edit {
 5923                display_mode: EditDisplayMode::TabAccept,
 5924                edits,
 5925                ..
 5926            } => {
 5927                let range = &edits.first()?.0;
 5928                let target_display_point = range.end.to_display_point(editor_snapshot);
 5929
 5930                self.render_edit_prediction_end_of_line_popover(
 5931                    "Accept",
 5932                    editor_snapshot,
 5933                    visible_row_range,
 5934                    target_display_point,
 5935                    line_height,
 5936                    scroll_pixel_position,
 5937                    content_origin,
 5938                    editor_width,
 5939                    window,
 5940                    cx,
 5941                )
 5942            }
 5943            InlineCompletion::Edit {
 5944                edits,
 5945                edit_preview,
 5946                display_mode: EditDisplayMode::DiffPopover,
 5947                snapshot,
 5948            } => self.render_edit_prediction_diff_popover(
 5949                text_bounds,
 5950                content_origin,
 5951                editor_snapshot,
 5952                visible_row_range,
 5953                line_layouts,
 5954                line_height,
 5955                scroll_pixel_position,
 5956                newest_selection_head,
 5957                editor_width,
 5958                style,
 5959                edits,
 5960                edit_preview,
 5961                snapshot,
 5962                window,
 5963                cx,
 5964            ),
 5965        }
 5966    }
 5967
 5968    #[allow(clippy::too_many_arguments)]
 5969    fn render_edit_prediction_modifier_jump_popover(
 5970        &mut self,
 5971        text_bounds: &Bounds<Pixels>,
 5972        content_origin: gpui::Point<Pixels>,
 5973        visible_row_range: Range<DisplayRow>,
 5974        line_layouts: &[LineWithInvisibles],
 5975        line_height: Pixels,
 5976        scroll_pixel_position: gpui::Point<Pixels>,
 5977        newest_selection_head: Option<DisplayPoint>,
 5978        target_display_point: DisplayPoint,
 5979        window: &mut Window,
 5980        cx: &mut App,
 5981    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5982        let scrolled_content_origin =
 5983            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 5984
 5985        const SCROLL_PADDING_Y: Pixels = px(12.);
 5986
 5987        if target_display_point.row() < visible_row_range.start {
 5988            return self.render_edit_prediction_scroll_popover(
 5989                |_| SCROLL_PADDING_Y,
 5990                IconName::ArrowUp,
 5991                visible_row_range,
 5992                line_layouts,
 5993                newest_selection_head,
 5994                scrolled_content_origin,
 5995                window,
 5996                cx,
 5997            );
 5998        } else if target_display_point.row() >= visible_row_range.end {
 5999            return self.render_edit_prediction_scroll_popover(
 6000                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 6001                IconName::ArrowDown,
 6002                visible_row_range,
 6003                line_layouts,
 6004                newest_selection_head,
 6005                scrolled_content_origin,
 6006                window,
 6007                cx,
 6008            );
 6009        }
 6010
 6011        const POLE_WIDTH: Pixels = px(2.);
 6012
 6013        let line_layout =
 6014            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 6015        let target_column = target_display_point.column() as usize;
 6016
 6017        let target_x = line_layout.x_for_index(target_column);
 6018        let target_y =
 6019            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 6020
 6021        let flag_on_right = target_x < text_bounds.size.width / 2.;
 6022
 6023        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 6024        border_color.l += 0.001;
 6025
 6026        let mut element = v_flex()
 6027            .items_end()
 6028            .when(flag_on_right, |el| el.items_start())
 6029            .child(if flag_on_right {
 6030                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6031                    .rounded_bl(px(0.))
 6032                    .rounded_tl(px(0.))
 6033                    .border_l_2()
 6034                    .border_color(border_color)
 6035            } else {
 6036                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6037                    .rounded_br(px(0.))
 6038                    .rounded_tr(px(0.))
 6039                    .border_r_2()
 6040                    .border_color(border_color)
 6041            })
 6042            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 6043            .into_any();
 6044
 6045        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6046
 6047        let mut origin = scrolled_content_origin + point(target_x, target_y)
 6048            - point(
 6049                if flag_on_right {
 6050                    POLE_WIDTH
 6051                } else {
 6052                    size.width - POLE_WIDTH
 6053                },
 6054                size.height - line_height,
 6055            );
 6056
 6057        origin.x = origin.x.max(content_origin.x);
 6058
 6059        element.prepaint_at(origin, window, cx);
 6060
 6061        Some((element, origin))
 6062    }
 6063
 6064    #[allow(clippy::too_many_arguments)]
 6065    fn render_edit_prediction_scroll_popover(
 6066        &mut self,
 6067        to_y: impl Fn(Size<Pixels>) -> Pixels,
 6068        scroll_icon: IconName,
 6069        visible_row_range: Range<DisplayRow>,
 6070        line_layouts: &[LineWithInvisibles],
 6071        newest_selection_head: Option<DisplayPoint>,
 6072        scrolled_content_origin: gpui::Point<Pixels>,
 6073        window: &mut Window,
 6074        cx: &mut App,
 6075    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6076        let mut element = self
 6077            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 6078            .into_any();
 6079
 6080        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6081
 6082        let cursor = newest_selection_head?;
 6083        let cursor_row_layout =
 6084            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6085        let cursor_column = cursor.column() as usize;
 6086
 6087        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6088
 6089        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6090
 6091        element.prepaint_at(origin, window, cx);
 6092        Some((element, origin))
 6093    }
 6094
 6095    #[allow(clippy::too_many_arguments)]
 6096    fn render_edit_prediction_eager_jump_popover(
 6097        &mut self,
 6098        text_bounds: &Bounds<Pixels>,
 6099        content_origin: gpui::Point<Pixels>,
 6100        editor_snapshot: &EditorSnapshot,
 6101        visible_row_range: Range<DisplayRow>,
 6102        scroll_top: f32,
 6103        scroll_bottom: f32,
 6104        line_height: Pixels,
 6105        scroll_pixel_position: gpui::Point<Pixels>,
 6106        target_display_point: DisplayPoint,
 6107        editor_width: Pixels,
 6108        window: &mut Window,
 6109        cx: &mut App,
 6110    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6111        if target_display_point.row().as_f32() < scroll_top {
 6112            let mut element = self
 6113                .render_edit_prediction_line_popover(
 6114                    "Jump to Edit",
 6115                    Some(IconName::ArrowUp),
 6116                    window,
 6117                    cx,
 6118                )?
 6119                .into_any();
 6120
 6121            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6122            let offset = point(
 6123                (text_bounds.size.width - size.width) / 2.,
 6124                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6125            );
 6126
 6127            let origin = text_bounds.origin + offset;
 6128            element.prepaint_at(origin, window, cx);
 6129            Some((element, origin))
 6130        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6131            let mut element = self
 6132                .render_edit_prediction_line_popover(
 6133                    "Jump to Edit",
 6134                    Some(IconName::ArrowDown),
 6135                    window,
 6136                    cx,
 6137                )?
 6138                .into_any();
 6139
 6140            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6141            let offset = point(
 6142                (text_bounds.size.width - size.width) / 2.,
 6143                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6144            );
 6145
 6146            let origin = text_bounds.origin + offset;
 6147            element.prepaint_at(origin, window, cx);
 6148            Some((element, origin))
 6149        } else {
 6150            self.render_edit_prediction_end_of_line_popover(
 6151                "Jump to Edit",
 6152                editor_snapshot,
 6153                visible_row_range,
 6154                target_display_point,
 6155                line_height,
 6156                scroll_pixel_position,
 6157                content_origin,
 6158                editor_width,
 6159                window,
 6160                cx,
 6161            )
 6162        }
 6163    }
 6164
 6165    #[allow(clippy::too_many_arguments)]
 6166    fn render_edit_prediction_end_of_line_popover(
 6167        self: &mut Editor,
 6168        label: &'static str,
 6169        editor_snapshot: &EditorSnapshot,
 6170        visible_row_range: Range<DisplayRow>,
 6171        target_display_point: DisplayPoint,
 6172        line_height: Pixels,
 6173        scroll_pixel_position: gpui::Point<Pixels>,
 6174        content_origin: gpui::Point<Pixels>,
 6175        editor_width: Pixels,
 6176        window: &mut Window,
 6177        cx: &mut App,
 6178    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6179        let target_line_end = DisplayPoint::new(
 6180            target_display_point.row(),
 6181            editor_snapshot.line_len(target_display_point.row()),
 6182        );
 6183
 6184        let mut element = self
 6185            .render_edit_prediction_line_popover(label, None, window, cx)?
 6186            .into_any();
 6187
 6188        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6189
 6190        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 6191
 6192        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 6193        let mut origin = start_point
 6194            + line_origin
 6195            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 6196        origin.x = origin.x.max(content_origin.x);
 6197
 6198        let max_x = content_origin.x + editor_width - size.width;
 6199
 6200        if origin.x > max_x {
 6201            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 6202
 6203            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 6204                origin.y += offset;
 6205                IconName::ArrowUp
 6206            } else {
 6207                origin.y -= offset;
 6208                IconName::ArrowDown
 6209            };
 6210
 6211            element = self
 6212                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 6213                .into_any();
 6214
 6215            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6216
 6217            origin.x = content_origin.x + editor_width - size.width - px(2.);
 6218        }
 6219
 6220        element.prepaint_at(origin, window, cx);
 6221        Some((element, origin))
 6222    }
 6223
 6224    #[allow(clippy::too_many_arguments)]
 6225    fn render_edit_prediction_diff_popover(
 6226        self: &Editor,
 6227        text_bounds: &Bounds<Pixels>,
 6228        content_origin: gpui::Point<Pixels>,
 6229        editor_snapshot: &EditorSnapshot,
 6230        visible_row_range: Range<DisplayRow>,
 6231        line_layouts: &[LineWithInvisibles],
 6232        line_height: Pixels,
 6233        scroll_pixel_position: gpui::Point<Pixels>,
 6234        newest_selection_head: Option<DisplayPoint>,
 6235        editor_width: Pixels,
 6236        style: &EditorStyle,
 6237        edits: &Vec<(Range<Anchor>, String)>,
 6238        edit_preview: &Option<language::EditPreview>,
 6239        snapshot: &language::BufferSnapshot,
 6240        window: &mut Window,
 6241        cx: &mut App,
 6242    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6243        let edit_start = edits
 6244            .first()
 6245            .unwrap()
 6246            .0
 6247            .start
 6248            .to_display_point(editor_snapshot);
 6249        let edit_end = edits
 6250            .last()
 6251            .unwrap()
 6252            .0
 6253            .end
 6254            .to_display_point(editor_snapshot);
 6255
 6256        let is_visible = visible_row_range.contains(&edit_start.row())
 6257            || visible_row_range.contains(&edit_end.row());
 6258        if !is_visible {
 6259            return None;
 6260        }
 6261
 6262        let highlighted_edits =
 6263            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 6264
 6265        let styled_text = highlighted_edits.to_styled_text(&style.text);
 6266        let line_count = highlighted_edits.text.lines().count();
 6267
 6268        const BORDER_WIDTH: Pixels = px(1.);
 6269
 6270        let mut element = h_flex()
 6271            .items_start()
 6272            .child(
 6273                h_flex()
 6274                    .bg(cx.theme().colors().editor_background)
 6275                    .border(BORDER_WIDTH)
 6276                    .shadow_sm()
 6277                    .border_color(cx.theme().colors().border)
 6278                    .rounded_l_lg()
 6279                    .when(line_count > 1, |el| el.rounded_br_lg())
 6280                    .pr_1()
 6281                    .child(styled_text),
 6282            )
 6283            .child(
 6284                h_flex()
 6285                    .h(line_height + BORDER_WIDTH * px(2.))
 6286                    .px_1p5()
 6287                    .gap_1()
 6288                    // Workaround: For some reason, there's a gap if we don't do this
 6289                    .ml(-BORDER_WIDTH)
 6290                    .shadow(smallvec![gpui::BoxShadow {
 6291                        color: gpui::black().opacity(0.05),
 6292                        offset: point(px(1.), px(1.)),
 6293                        blur_radius: px(2.),
 6294                        spread_radius: px(0.),
 6295                    }])
 6296                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 6297                    .border(BORDER_WIDTH)
 6298                    .border_color(cx.theme().colors().border)
 6299                    .rounded_r_lg()
 6300                    .children(self.render_edit_prediction_accept_keybind(window, cx)),
 6301            )
 6302            .into_any();
 6303
 6304        let longest_row =
 6305            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 6306        let longest_line_width = if visible_row_range.contains(&longest_row) {
 6307            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 6308        } else {
 6309            layout_line(
 6310                longest_row,
 6311                editor_snapshot,
 6312                style,
 6313                editor_width,
 6314                |_| false,
 6315                window,
 6316                cx,
 6317            )
 6318            .width
 6319        };
 6320
 6321        let viewport_bounds =
 6322            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 6323                right: -EditorElement::SCROLLBAR_WIDTH,
 6324                ..Default::default()
 6325            });
 6326
 6327        let x_after_longest =
 6328            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 6329                - scroll_pixel_position.x;
 6330
 6331        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6332
 6333        // Fully visible if it can be displayed within the window (allow overlapping other
 6334        // panes). However, this is only allowed if the popover starts within text_bounds.
 6335        let can_position_to_the_right = x_after_longest < text_bounds.right()
 6336            && x_after_longest + element_bounds.width < viewport_bounds.right();
 6337
 6338        let mut origin = if can_position_to_the_right {
 6339            point(
 6340                x_after_longest,
 6341                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 6342                    - scroll_pixel_position.y,
 6343            )
 6344        } else {
 6345            let cursor_row = newest_selection_head.map(|head| head.row());
 6346            let above_edit = edit_start
 6347                .row()
 6348                .0
 6349                .checked_sub(line_count as u32)
 6350                .map(DisplayRow);
 6351            let below_edit = Some(edit_end.row() + 1);
 6352            let above_cursor =
 6353                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 6354            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 6355
 6356            // Place the edit popover adjacent to the edit if there is a location
 6357            // available that is onscreen and does not obscure the cursor. Otherwise,
 6358            // place it adjacent to the cursor.
 6359            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 6360                .into_iter()
 6361                .flatten()
 6362                .find(|&start_row| {
 6363                    let end_row = start_row + line_count as u32;
 6364                    visible_row_range.contains(&start_row)
 6365                        && visible_row_range.contains(&end_row)
 6366                        && cursor_row.map_or(true, |cursor_row| {
 6367                            !((start_row..end_row).contains(&cursor_row))
 6368                        })
 6369                })?;
 6370
 6371            content_origin
 6372                + point(
 6373                    -scroll_pixel_position.x,
 6374                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 6375                )
 6376        };
 6377
 6378        origin.x -= BORDER_WIDTH;
 6379
 6380        window.defer_draw(element, origin, 1);
 6381
 6382        // Do not return an element, since it will already be drawn due to defer_draw.
 6383        None
 6384    }
 6385
 6386    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 6387        px(30.)
 6388    }
 6389
 6390    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 6391        if self.read_only(cx) {
 6392            cx.theme().players().read_only()
 6393        } else {
 6394            self.style.as_ref().unwrap().local_player
 6395        }
 6396    }
 6397
 6398    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 6399        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 6400        let accept_keystroke = accept_binding.keystroke()?;
 6401
 6402        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6403
 6404        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 6405            Color::Accent
 6406        } else {
 6407            Color::Muted
 6408        };
 6409
 6410        h_flex()
 6411            .px_0p5()
 6412            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 6413            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6414            .text_size(TextSize::XSmall.rems(cx))
 6415            .child(h_flex().children(ui::render_modifiers(
 6416                &accept_keystroke.modifiers,
 6417                PlatformStyle::platform(),
 6418                Some(modifiers_color),
 6419                Some(IconSize::XSmall.rems().into()),
 6420                true,
 6421            )))
 6422            .when(is_platform_style_mac, |parent| {
 6423                parent.child(accept_keystroke.key.clone())
 6424            })
 6425            .when(!is_platform_style_mac, |parent| {
 6426                parent.child(
 6427                    Key::new(
 6428                        util::capitalize(&accept_keystroke.key),
 6429                        Some(Color::Default),
 6430                    )
 6431                    .size(Some(IconSize::XSmall.rems().into())),
 6432                )
 6433            })
 6434            .into()
 6435    }
 6436
 6437    fn render_edit_prediction_line_popover(
 6438        &self,
 6439        label: impl Into<SharedString>,
 6440        icon: Option<IconName>,
 6441        window: &mut Window,
 6442        cx: &App,
 6443    ) -> Option<Div> {
 6444        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 6445
 6446        let result = h_flex()
 6447            .py_0p5()
 6448            .pl_1()
 6449            .pr(padding_right)
 6450            .gap_1()
 6451            .rounded(px(6.))
 6452            .border_1()
 6453            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6454            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 6455            .shadow_sm()
 6456            .children(self.render_edit_prediction_accept_keybind(window, cx))
 6457            .child(Label::new(label).size(LabelSize::Small))
 6458            .when_some(icon, |element, icon| {
 6459                element.child(
 6460                    div()
 6461                        .mt(px(1.5))
 6462                        .child(Icon::new(icon).size(IconSize::Small)),
 6463                )
 6464            });
 6465
 6466        Some(result)
 6467    }
 6468
 6469    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 6470        let accent_color = cx.theme().colors().text_accent;
 6471        let editor_bg_color = cx.theme().colors().editor_background;
 6472        editor_bg_color.blend(accent_color.opacity(0.1))
 6473    }
 6474
 6475    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 6476        let accent_color = cx.theme().colors().text_accent;
 6477        let editor_bg_color = cx.theme().colors().editor_background;
 6478        editor_bg_color.blend(accent_color.opacity(0.6))
 6479    }
 6480
 6481    #[allow(clippy::too_many_arguments)]
 6482    fn render_edit_prediction_cursor_popover(
 6483        &self,
 6484        min_width: Pixels,
 6485        max_width: Pixels,
 6486        cursor_point: Point,
 6487        style: &EditorStyle,
 6488        accept_keystroke: Option<&gpui::Keystroke>,
 6489        _window: &Window,
 6490        cx: &mut Context<Editor>,
 6491    ) -> Option<AnyElement> {
 6492        let provider = self.edit_prediction_provider.as_ref()?;
 6493
 6494        if provider.provider.needs_terms_acceptance(cx) {
 6495            return Some(
 6496                h_flex()
 6497                    .min_w(min_width)
 6498                    .flex_1()
 6499                    .px_2()
 6500                    .py_1()
 6501                    .gap_3()
 6502                    .elevation_2(cx)
 6503                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 6504                    .id("accept-terms")
 6505                    .cursor_pointer()
 6506                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 6507                    .on_click(cx.listener(|this, _event, window, cx| {
 6508                        cx.stop_propagation();
 6509                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 6510                        window.dispatch_action(
 6511                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 6512                            cx,
 6513                        );
 6514                    }))
 6515                    .child(
 6516                        h_flex()
 6517                            .flex_1()
 6518                            .gap_2()
 6519                            .child(Icon::new(IconName::ZedPredict))
 6520                            .child(Label::new("Accept Terms of Service"))
 6521                            .child(div().w_full())
 6522                            .child(
 6523                                Icon::new(IconName::ArrowUpRight)
 6524                                    .color(Color::Muted)
 6525                                    .size(IconSize::Small),
 6526                            )
 6527                            .into_any_element(),
 6528                    )
 6529                    .into_any(),
 6530            );
 6531        }
 6532
 6533        let is_refreshing = provider.provider.is_refreshing(cx);
 6534
 6535        fn pending_completion_container() -> Div {
 6536            h_flex()
 6537                .h_full()
 6538                .flex_1()
 6539                .gap_2()
 6540                .child(Icon::new(IconName::ZedPredict))
 6541        }
 6542
 6543        let completion = match &self.active_inline_completion {
 6544            Some(prediction) => {
 6545                if !self.has_visible_completions_menu() {
 6546                    const RADIUS: Pixels = px(6.);
 6547                    const BORDER_WIDTH: Pixels = px(1.);
 6548
 6549                    return Some(
 6550                        h_flex()
 6551                            .elevation_2(cx)
 6552                            .border(BORDER_WIDTH)
 6553                            .border_color(cx.theme().colors().border)
 6554                            .rounded(RADIUS)
 6555                            .rounded_tl(px(0.))
 6556                            .overflow_hidden()
 6557                            .child(div().px_1p5().child(match &prediction.completion {
 6558                                InlineCompletion::Move { target, snapshot } => {
 6559                                    use text::ToPoint as _;
 6560                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 6561                                    {
 6562                                        Icon::new(IconName::ZedPredictDown)
 6563                                    } else {
 6564                                        Icon::new(IconName::ZedPredictUp)
 6565                                    }
 6566                                }
 6567                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 6568                            }))
 6569                            .child(
 6570                                h_flex()
 6571                                    .gap_1()
 6572                                    .py_1()
 6573                                    .px_2()
 6574                                    .rounded_r(RADIUS - BORDER_WIDTH)
 6575                                    .border_l_1()
 6576                                    .border_color(cx.theme().colors().border)
 6577                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6578                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 6579                                        el.child(
 6580                                            Label::new("Hold")
 6581                                                .size(LabelSize::Small)
 6582                                                .line_height_style(LineHeightStyle::UiLabel),
 6583                                        )
 6584                                    })
 6585                                    .child(h_flex().children(ui::render_modifiers(
 6586                                        &accept_keystroke?.modifiers,
 6587                                        PlatformStyle::platform(),
 6588                                        Some(Color::Default),
 6589                                        Some(IconSize::XSmall.rems().into()),
 6590                                        false,
 6591                                    ))),
 6592                            )
 6593                            .into_any(),
 6594                    );
 6595                }
 6596
 6597                self.render_edit_prediction_cursor_popover_preview(
 6598                    prediction,
 6599                    cursor_point,
 6600                    style,
 6601                    cx,
 6602                )?
 6603            }
 6604
 6605            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 6606                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 6607                    stale_completion,
 6608                    cursor_point,
 6609                    style,
 6610                    cx,
 6611                )?,
 6612
 6613                None => {
 6614                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6615                }
 6616            },
 6617
 6618            None => pending_completion_container().child(Label::new("No Prediction")),
 6619        };
 6620
 6621        let completion = if is_refreshing {
 6622            completion
 6623                .with_animation(
 6624                    "loading-completion",
 6625                    Animation::new(Duration::from_secs(2))
 6626                        .repeat()
 6627                        .with_easing(pulsating_between(0.4, 0.8)),
 6628                    |label, delta| label.opacity(delta),
 6629                )
 6630                .into_any_element()
 6631        } else {
 6632            completion.into_any_element()
 6633        };
 6634
 6635        let has_completion = self.active_inline_completion.is_some();
 6636
 6637        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6638        Some(
 6639            h_flex()
 6640                .min_w(min_width)
 6641                .max_w(max_width)
 6642                .flex_1()
 6643                .elevation_2(cx)
 6644                .border_color(cx.theme().colors().border)
 6645                .child(
 6646                    div()
 6647                        .flex_1()
 6648                        .py_1()
 6649                        .px_2()
 6650                        .overflow_hidden()
 6651                        .child(completion),
 6652                )
 6653                .when_some(accept_keystroke, |el, accept_keystroke| {
 6654                    if !accept_keystroke.modifiers.modified() {
 6655                        return el;
 6656                    }
 6657
 6658                    el.child(
 6659                        h_flex()
 6660                            .h_full()
 6661                            .border_l_1()
 6662                            .rounded_r_lg()
 6663                            .border_color(cx.theme().colors().border)
 6664                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6665                            .gap_1()
 6666                            .py_1()
 6667                            .px_2()
 6668                            .child(
 6669                                h_flex()
 6670                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6671                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6672                                    .child(h_flex().children(ui::render_modifiers(
 6673                                        &accept_keystroke.modifiers,
 6674                                        PlatformStyle::platform(),
 6675                                        Some(if !has_completion {
 6676                                            Color::Muted
 6677                                        } else {
 6678                                            Color::Default
 6679                                        }),
 6680                                        None,
 6681                                        false,
 6682                                    ))),
 6683                            )
 6684                            .child(Label::new("Preview").into_any_element())
 6685                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6686                    )
 6687                })
 6688                .into_any(),
 6689        )
 6690    }
 6691
 6692    fn render_edit_prediction_cursor_popover_preview(
 6693        &self,
 6694        completion: &InlineCompletionState,
 6695        cursor_point: Point,
 6696        style: &EditorStyle,
 6697        cx: &mut Context<Editor>,
 6698    ) -> Option<Div> {
 6699        use text::ToPoint as _;
 6700
 6701        fn render_relative_row_jump(
 6702            prefix: impl Into<String>,
 6703            current_row: u32,
 6704            target_row: u32,
 6705        ) -> Div {
 6706            let (row_diff, arrow) = if target_row < current_row {
 6707                (current_row - target_row, IconName::ArrowUp)
 6708            } else {
 6709                (target_row - current_row, IconName::ArrowDown)
 6710            };
 6711
 6712            h_flex()
 6713                .child(
 6714                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6715                        .color(Color::Muted)
 6716                        .size(LabelSize::Small),
 6717                )
 6718                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6719        }
 6720
 6721        match &completion.completion {
 6722            InlineCompletion::Move {
 6723                target, snapshot, ..
 6724            } => Some(
 6725                h_flex()
 6726                    .px_2()
 6727                    .gap_2()
 6728                    .flex_1()
 6729                    .child(
 6730                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6731                            Icon::new(IconName::ZedPredictDown)
 6732                        } else {
 6733                            Icon::new(IconName::ZedPredictUp)
 6734                        },
 6735                    )
 6736                    .child(Label::new("Jump to Edit")),
 6737            ),
 6738
 6739            InlineCompletion::Edit {
 6740                edits,
 6741                edit_preview,
 6742                snapshot,
 6743                display_mode: _,
 6744            } => {
 6745                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6746
 6747                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6748                    &snapshot,
 6749                    &edits,
 6750                    edit_preview.as_ref()?,
 6751                    true,
 6752                    cx,
 6753                )
 6754                .first_line_preview();
 6755
 6756                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6757                    .with_highlights(&style.text, highlighted_edits.highlights);
 6758
 6759                let preview = h_flex()
 6760                    .gap_1()
 6761                    .min_w_16()
 6762                    .child(styled_text)
 6763                    .when(has_more_lines, |parent| parent.child(""));
 6764
 6765                let left = if first_edit_row != cursor_point.row {
 6766                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6767                        .into_any_element()
 6768                } else {
 6769                    Icon::new(IconName::ZedPredict).into_any_element()
 6770                };
 6771
 6772                Some(
 6773                    h_flex()
 6774                        .h_full()
 6775                        .flex_1()
 6776                        .gap_2()
 6777                        .pr_1()
 6778                        .overflow_x_hidden()
 6779                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6780                        .child(left)
 6781                        .child(preview),
 6782                )
 6783            }
 6784        }
 6785    }
 6786
 6787    fn render_context_menu(
 6788        &self,
 6789        style: &EditorStyle,
 6790        max_height_in_lines: u32,
 6791        y_flipped: bool,
 6792        window: &mut Window,
 6793        cx: &mut Context<Editor>,
 6794    ) -> Option<AnyElement> {
 6795        let menu = self.context_menu.borrow();
 6796        let menu = menu.as_ref()?;
 6797        if !menu.visible() {
 6798            return None;
 6799        };
 6800        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6801    }
 6802
 6803    fn render_context_menu_aside(
 6804        &mut self,
 6805        max_size: Size<Pixels>,
 6806        window: &mut Window,
 6807        cx: &mut Context<Editor>,
 6808    ) -> Option<AnyElement> {
 6809        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 6810            if menu.visible() {
 6811                menu.render_aside(self, max_size, window, cx)
 6812            } else {
 6813                None
 6814            }
 6815        })
 6816    }
 6817
 6818    fn hide_context_menu(
 6819        &mut self,
 6820        window: &mut Window,
 6821        cx: &mut Context<Self>,
 6822    ) -> Option<CodeContextMenu> {
 6823        cx.notify();
 6824        self.completion_tasks.clear();
 6825        let context_menu = self.context_menu.borrow_mut().take();
 6826        self.stale_inline_completion_in_menu.take();
 6827        self.update_visible_inline_completion(window, cx);
 6828        context_menu
 6829    }
 6830
 6831    fn show_snippet_choices(
 6832        &mut self,
 6833        choices: &Vec<String>,
 6834        selection: Range<Anchor>,
 6835        cx: &mut Context<Self>,
 6836    ) {
 6837        if selection.start.buffer_id.is_none() {
 6838            return;
 6839        }
 6840        let buffer_id = selection.start.buffer_id.unwrap();
 6841        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6842        let id = post_inc(&mut self.next_completion_id);
 6843
 6844        if let Some(buffer) = buffer {
 6845            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6846                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6847            ));
 6848        }
 6849    }
 6850
 6851    pub fn insert_snippet(
 6852        &mut self,
 6853        insertion_ranges: &[Range<usize>],
 6854        snippet: Snippet,
 6855        window: &mut Window,
 6856        cx: &mut Context<Self>,
 6857    ) -> Result<()> {
 6858        struct Tabstop<T> {
 6859            is_end_tabstop: bool,
 6860            ranges: Vec<Range<T>>,
 6861            choices: Option<Vec<String>>,
 6862        }
 6863
 6864        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6865            let snippet_text: Arc<str> = snippet.text.clone().into();
 6866            buffer.edit(
 6867                insertion_ranges
 6868                    .iter()
 6869                    .cloned()
 6870                    .map(|range| (range, snippet_text.clone())),
 6871                Some(AutoindentMode::EachLine),
 6872                cx,
 6873            );
 6874
 6875            let snapshot = &*buffer.read(cx);
 6876            let snippet = &snippet;
 6877            snippet
 6878                .tabstops
 6879                .iter()
 6880                .map(|tabstop| {
 6881                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6882                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6883                    });
 6884                    let mut tabstop_ranges = tabstop
 6885                        .ranges
 6886                        .iter()
 6887                        .flat_map(|tabstop_range| {
 6888                            let mut delta = 0_isize;
 6889                            insertion_ranges.iter().map(move |insertion_range| {
 6890                                let insertion_start = insertion_range.start as isize + delta;
 6891                                delta +=
 6892                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6893
 6894                                let start = ((insertion_start + tabstop_range.start) as usize)
 6895                                    .min(snapshot.len());
 6896                                let end = ((insertion_start + tabstop_range.end) as usize)
 6897                                    .min(snapshot.len());
 6898                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6899                            })
 6900                        })
 6901                        .collect::<Vec<_>>();
 6902                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6903
 6904                    Tabstop {
 6905                        is_end_tabstop,
 6906                        ranges: tabstop_ranges,
 6907                        choices: tabstop.choices.clone(),
 6908                    }
 6909                })
 6910                .collect::<Vec<_>>()
 6911        });
 6912        if let Some(tabstop) = tabstops.first() {
 6913            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6914                s.select_ranges(tabstop.ranges.iter().cloned());
 6915            });
 6916
 6917            if let Some(choices) = &tabstop.choices {
 6918                if let Some(selection) = tabstop.ranges.first() {
 6919                    self.show_snippet_choices(choices, selection.clone(), cx)
 6920                }
 6921            }
 6922
 6923            // If we're already at the last tabstop and it's at the end of the snippet,
 6924            // we're done, we don't need to keep the state around.
 6925            if !tabstop.is_end_tabstop {
 6926                let choices = tabstops
 6927                    .iter()
 6928                    .map(|tabstop| tabstop.choices.clone())
 6929                    .collect();
 6930
 6931                let ranges = tabstops
 6932                    .into_iter()
 6933                    .map(|tabstop| tabstop.ranges)
 6934                    .collect::<Vec<_>>();
 6935
 6936                self.snippet_stack.push(SnippetState {
 6937                    active_index: 0,
 6938                    ranges,
 6939                    choices,
 6940                });
 6941            }
 6942
 6943            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6944            if self.autoclose_regions.is_empty() {
 6945                let snapshot = self.buffer.read(cx).snapshot(cx);
 6946                for selection in &mut self.selections.all::<Point>(cx) {
 6947                    let selection_head = selection.head();
 6948                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6949                        continue;
 6950                    };
 6951
 6952                    let mut bracket_pair = None;
 6953                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6954                    let prev_chars = snapshot
 6955                        .reversed_chars_at(selection_head)
 6956                        .collect::<String>();
 6957                    for (pair, enabled) in scope.brackets() {
 6958                        if enabled
 6959                            && pair.close
 6960                            && prev_chars.starts_with(pair.start.as_str())
 6961                            && next_chars.starts_with(pair.end.as_str())
 6962                        {
 6963                            bracket_pair = Some(pair.clone());
 6964                            break;
 6965                        }
 6966                    }
 6967                    if let Some(pair) = bracket_pair {
 6968                        let start = snapshot.anchor_after(selection_head);
 6969                        let end = snapshot.anchor_after(selection_head);
 6970                        self.autoclose_regions.push(AutocloseRegion {
 6971                            selection_id: selection.id,
 6972                            range: start..end,
 6973                            pair,
 6974                        });
 6975                    }
 6976                }
 6977            }
 6978        }
 6979        Ok(())
 6980    }
 6981
 6982    pub fn move_to_next_snippet_tabstop(
 6983        &mut self,
 6984        window: &mut Window,
 6985        cx: &mut Context<Self>,
 6986    ) -> bool {
 6987        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6988    }
 6989
 6990    pub fn move_to_prev_snippet_tabstop(
 6991        &mut self,
 6992        window: &mut Window,
 6993        cx: &mut Context<Self>,
 6994    ) -> bool {
 6995        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6996    }
 6997
 6998    pub fn move_to_snippet_tabstop(
 6999        &mut self,
 7000        bias: Bias,
 7001        window: &mut Window,
 7002        cx: &mut Context<Self>,
 7003    ) -> bool {
 7004        if let Some(mut snippet) = self.snippet_stack.pop() {
 7005            match bias {
 7006                Bias::Left => {
 7007                    if snippet.active_index > 0 {
 7008                        snippet.active_index -= 1;
 7009                    } else {
 7010                        self.snippet_stack.push(snippet);
 7011                        return false;
 7012                    }
 7013                }
 7014                Bias::Right => {
 7015                    if snippet.active_index + 1 < snippet.ranges.len() {
 7016                        snippet.active_index += 1;
 7017                    } else {
 7018                        self.snippet_stack.push(snippet);
 7019                        return false;
 7020                    }
 7021                }
 7022            }
 7023            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 7024                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7025                    s.select_anchor_ranges(current_ranges.iter().cloned())
 7026                });
 7027
 7028                if let Some(choices) = &snippet.choices[snippet.active_index] {
 7029                    if let Some(selection) = current_ranges.first() {
 7030                        self.show_snippet_choices(&choices, selection.clone(), cx);
 7031                    }
 7032                }
 7033
 7034                // If snippet state is not at the last tabstop, push it back on the stack
 7035                if snippet.active_index + 1 < snippet.ranges.len() {
 7036                    self.snippet_stack.push(snippet);
 7037                }
 7038                return true;
 7039            }
 7040        }
 7041
 7042        false
 7043    }
 7044
 7045    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 7046        self.transact(window, cx, |this, window, cx| {
 7047            this.select_all(&SelectAll, window, cx);
 7048            this.insert("", window, cx);
 7049        });
 7050    }
 7051
 7052    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 7053        self.transact(window, cx, |this, window, cx| {
 7054            this.select_autoclose_pair(window, cx);
 7055            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 7056            if !this.linked_edit_ranges.is_empty() {
 7057                let selections = this.selections.all::<MultiBufferPoint>(cx);
 7058                let snapshot = this.buffer.read(cx).snapshot(cx);
 7059
 7060                for selection in selections.iter() {
 7061                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 7062                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 7063                    if selection_start.buffer_id != selection_end.buffer_id {
 7064                        continue;
 7065                    }
 7066                    if let Some(ranges) =
 7067                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 7068                    {
 7069                        for (buffer, entries) in ranges {
 7070                            linked_ranges.entry(buffer).or_default().extend(entries);
 7071                        }
 7072                    }
 7073                }
 7074            }
 7075
 7076            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7077            if !this.selections.line_mode {
 7078                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 7079                for selection in &mut selections {
 7080                    if selection.is_empty() {
 7081                        let old_head = selection.head();
 7082                        let mut new_head =
 7083                            movement::left(&display_map, old_head.to_display_point(&display_map))
 7084                                .to_point(&display_map);
 7085                        if let Some((buffer, line_buffer_range)) = display_map
 7086                            .buffer_snapshot
 7087                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 7088                        {
 7089                            let indent_size =
 7090                                buffer.indent_size_for_line(line_buffer_range.start.row);
 7091                            let indent_len = match indent_size.kind {
 7092                                IndentKind::Space => {
 7093                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 7094                                }
 7095                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 7096                            };
 7097                            if old_head.column <= indent_size.len && old_head.column > 0 {
 7098                                let indent_len = indent_len.get();
 7099                                new_head = cmp::min(
 7100                                    new_head,
 7101                                    MultiBufferPoint::new(
 7102                                        old_head.row,
 7103                                        ((old_head.column - 1) / indent_len) * indent_len,
 7104                                    ),
 7105                                );
 7106                            }
 7107                        }
 7108
 7109                        selection.set_head(new_head, SelectionGoal::None);
 7110                    }
 7111                }
 7112            }
 7113
 7114            this.signature_help_state.set_backspace_pressed(true);
 7115            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7116                s.select(selections)
 7117            });
 7118            this.insert("", window, cx);
 7119            let empty_str: Arc<str> = Arc::from("");
 7120            for (buffer, edits) in linked_ranges {
 7121                let snapshot = buffer.read(cx).snapshot();
 7122                use text::ToPoint as TP;
 7123
 7124                let edits = edits
 7125                    .into_iter()
 7126                    .map(|range| {
 7127                        let end_point = TP::to_point(&range.end, &snapshot);
 7128                        let mut start_point = TP::to_point(&range.start, &snapshot);
 7129
 7130                        if end_point == start_point {
 7131                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 7132                                .saturating_sub(1);
 7133                            start_point =
 7134                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 7135                        };
 7136
 7137                        (start_point..end_point, empty_str.clone())
 7138                    })
 7139                    .sorted_by_key(|(range, _)| range.start)
 7140                    .collect::<Vec<_>>();
 7141                buffer.update(cx, |this, cx| {
 7142                    this.edit(edits, None, cx);
 7143                })
 7144            }
 7145            this.refresh_inline_completion(true, false, window, cx);
 7146            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 7147        });
 7148    }
 7149
 7150    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 7151        self.transact(window, cx, |this, window, cx| {
 7152            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7153                let line_mode = s.line_mode;
 7154                s.move_with(|map, selection| {
 7155                    if selection.is_empty() && !line_mode {
 7156                        let cursor = movement::right(map, selection.head());
 7157                        selection.end = cursor;
 7158                        selection.reversed = true;
 7159                        selection.goal = SelectionGoal::None;
 7160                    }
 7161                })
 7162            });
 7163            this.insert("", window, cx);
 7164            this.refresh_inline_completion(true, false, window, cx);
 7165        });
 7166    }
 7167
 7168    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 7169        if self.move_to_prev_snippet_tabstop(window, cx) {
 7170            return;
 7171        }
 7172
 7173        self.outdent(&Outdent, window, cx);
 7174    }
 7175
 7176    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 7177        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 7178            return;
 7179        }
 7180
 7181        let mut selections = self.selections.all_adjusted(cx);
 7182        let buffer = self.buffer.read(cx);
 7183        let snapshot = buffer.snapshot(cx);
 7184        let rows_iter = selections.iter().map(|s| s.head().row);
 7185        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 7186
 7187        let mut edits = Vec::new();
 7188        let mut prev_edited_row = 0;
 7189        let mut row_delta = 0;
 7190        for selection in &mut selections {
 7191            if selection.start.row != prev_edited_row {
 7192                row_delta = 0;
 7193            }
 7194            prev_edited_row = selection.end.row;
 7195
 7196            // If the selection is non-empty, then increase the indentation of the selected lines.
 7197            if !selection.is_empty() {
 7198                row_delta =
 7199                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7200                continue;
 7201            }
 7202
 7203            // If the selection is empty and the cursor is in the leading whitespace before the
 7204            // suggested indentation, then auto-indent the line.
 7205            let cursor = selection.head();
 7206            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 7207            if let Some(suggested_indent) =
 7208                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 7209            {
 7210                if cursor.column < suggested_indent.len
 7211                    && cursor.column <= current_indent.len
 7212                    && current_indent.len <= suggested_indent.len
 7213                {
 7214                    selection.start = Point::new(cursor.row, suggested_indent.len);
 7215                    selection.end = selection.start;
 7216                    if row_delta == 0 {
 7217                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 7218                            cursor.row,
 7219                            current_indent,
 7220                            suggested_indent,
 7221                        ));
 7222                        row_delta = suggested_indent.len - current_indent.len;
 7223                    }
 7224                    continue;
 7225                }
 7226            }
 7227
 7228            // Otherwise, insert a hard or soft tab.
 7229            let settings = buffer.settings_at(cursor, cx);
 7230            let tab_size = if settings.hard_tabs {
 7231                IndentSize::tab()
 7232            } else {
 7233                let tab_size = settings.tab_size.get();
 7234                let char_column = snapshot
 7235                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 7236                    .flat_map(str::chars)
 7237                    .count()
 7238                    + row_delta as usize;
 7239                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 7240                IndentSize::spaces(chars_to_next_tab_stop)
 7241            };
 7242            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 7243            selection.end = selection.start;
 7244            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 7245            row_delta += tab_size.len;
 7246        }
 7247
 7248        self.transact(window, cx, |this, window, cx| {
 7249            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7250            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7251                s.select(selections)
 7252            });
 7253            this.refresh_inline_completion(true, false, window, cx);
 7254        });
 7255    }
 7256
 7257    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 7258        if self.read_only(cx) {
 7259            return;
 7260        }
 7261        let mut selections = self.selections.all::<Point>(cx);
 7262        let mut prev_edited_row = 0;
 7263        let mut row_delta = 0;
 7264        let mut edits = Vec::new();
 7265        let buffer = self.buffer.read(cx);
 7266        let snapshot = buffer.snapshot(cx);
 7267        for selection in &mut selections {
 7268            if selection.start.row != prev_edited_row {
 7269                row_delta = 0;
 7270            }
 7271            prev_edited_row = selection.end.row;
 7272
 7273            row_delta =
 7274                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7275        }
 7276
 7277        self.transact(window, cx, |this, window, cx| {
 7278            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7279            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7280                s.select(selections)
 7281            });
 7282        });
 7283    }
 7284
 7285    fn indent_selection(
 7286        buffer: &MultiBuffer,
 7287        snapshot: &MultiBufferSnapshot,
 7288        selection: &mut Selection<Point>,
 7289        edits: &mut Vec<(Range<Point>, String)>,
 7290        delta_for_start_row: u32,
 7291        cx: &App,
 7292    ) -> u32 {
 7293        let settings = buffer.settings_at(selection.start, cx);
 7294        let tab_size = settings.tab_size.get();
 7295        let indent_kind = if settings.hard_tabs {
 7296            IndentKind::Tab
 7297        } else {
 7298            IndentKind::Space
 7299        };
 7300        let mut start_row = selection.start.row;
 7301        let mut end_row = selection.end.row + 1;
 7302
 7303        // If a selection ends at the beginning of a line, don't indent
 7304        // that last line.
 7305        if selection.end.column == 0 && selection.end.row > selection.start.row {
 7306            end_row -= 1;
 7307        }
 7308
 7309        // Avoid re-indenting a row that has already been indented by a
 7310        // previous selection, but still update this selection's column
 7311        // to reflect that indentation.
 7312        if delta_for_start_row > 0 {
 7313            start_row += 1;
 7314            selection.start.column += delta_for_start_row;
 7315            if selection.end.row == selection.start.row {
 7316                selection.end.column += delta_for_start_row;
 7317            }
 7318        }
 7319
 7320        let mut delta_for_end_row = 0;
 7321        let has_multiple_rows = start_row + 1 != end_row;
 7322        for row in start_row..end_row {
 7323            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 7324            let indent_delta = match (current_indent.kind, indent_kind) {
 7325                (IndentKind::Space, IndentKind::Space) => {
 7326                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 7327                    IndentSize::spaces(columns_to_next_tab_stop)
 7328                }
 7329                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 7330                (_, IndentKind::Tab) => IndentSize::tab(),
 7331            };
 7332
 7333            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 7334                0
 7335            } else {
 7336                selection.start.column
 7337            };
 7338            let row_start = Point::new(row, start);
 7339            edits.push((
 7340                row_start..row_start,
 7341                indent_delta.chars().collect::<String>(),
 7342            ));
 7343
 7344            // Update this selection's endpoints to reflect the indentation.
 7345            if row == selection.start.row {
 7346                selection.start.column += indent_delta.len;
 7347            }
 7348            if row == selection.end.row {
 7349                selection.end.column += indent_delta.len;
 7350                delta_for_end_row = indent_delta.len;
 7351            }
 7352        }
 7353
 7354        if selection.start.row == selection.end.row {
 7355            delta_for_start_row + delta_for_end_row
 7356        } else {
 7357            delta_for_end_row
 7358        }
 7359    }
 7360
 7361    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 7362        if self.read_only(cx) {
 7363            return;
 7364        }
 7365        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7366        let selections = self.selections.all::<Point>(cx);
 7367        let mut deletion_ranges = Vec::new();
 7368        let mut last_outdent = None;
 7369        {
 7370            let buffer = self.buffer.read(cx);
 7371            let snapshot = buffer.snapshot(cx);
 7372            for selection in &selections {
 7373                let settings = buffer.settings_at(selection.start, cx);
 7374                let tab_size = settings.tab_size.get();
 7375                let mut rows = selection.spanned_rows(false, &display_map);
 7376
 7377                // Avoid re-outdenting a row that has already been outdented by a
 7378                // previous selection.
 7379                if let Some(last_row) = last_outdent {
 7380                    if last_row == rows.start {
 7381                        rows.start = rows.start.next_row();
 7382                    }
 7383                }
 7384                let has_multiple_rows = rows.len() > 1;
 7385                for row in rows.iter_rows() {
 7386                    let indent_size = snapshot.indent_size_for_line(row);
 7387                    if indent_size.len > 0 {
 7388                        let deletion_len = match indent_size.kind {
 7389                            IndentKind::Space => {
 7390                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 7391                                if columns_to_prev_tab_stop == 0 {
 7392                                    tab_size
 7393                                } else {
 7394                                    columns_to_prev_tab_stop
 7395                                }
 7396                            }
 7397                            IndentKind::Tab => 1,
 7398                        };
 7399                        let start = if has_multiple_rows
 7400                            || deletion_len > selection.start.column
 7401                            || indent_size.len < selection.start.column
 7402                        {
 7403                            0
 7404                        } else {
 7405                            selection.start.column - deletion_len
 7406                        };
 7407                        deletion_ranges.push(
 7408                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 7409                        );
 7410                        last_outdent = Some(row);
 7411                    }
 7412                }
 7413            }
 7414        }
 7415
 7416        self.transact(window, cx, |this, window, cx| {
 7417            this.buffer.update(cx, |buffer, cx| {
 7418                let empty_str: Arc<str> = Arc::default();
 7419                buffer.edit(
 7420                    deletion_ranges
 7421                        .into_iter()
 7422                        .map(|range| (range, empty_str.clone())),
 7423                    None,
 7424                    cx,
 7425                );
 7426            });
 7427            let selections = this.selections.all::<usize>(cx);
 7428            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7429                s.select(selections)
 7430            });
 7431        });
 7432    }
 7433
 7434    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 7435        if self.read_only(cx) {
 7436            return;
 7437        }
 7438        let selections = self
 7439            .selections
 7440            .all::<usize>(cx)
 7441            .into_iter()
 7442            .map(|s| s.range());
 7443
 7444        self.transact(window, cx, |this, window, cx| {
 7445            this.buffer.update(cx, |buffer, cx| {
 7446                buffer.autoindent_ranges(selections, cx);
 7447            });
 7448            let selections = this.selections.all::<usize>(cx);
 7449            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7450                s.select(selections)
 7451            });
 7452        });
 7453    }
 7454
 7455    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 7456        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7457        let selections = self.selections.all::<Point>(cx);
 7458
 7459        let mut new_cursors = Vec::new();
 7460        let mut edit_ranges = Vec::new();
 7461        let mut selections = selections.iter().peekable();
 7462        while let Some(selection) = selections.next() {
 7463            let mut rows = selection.spanned_rows(false, &display_map);
 7464            let goal_display_column = selection.head().to_display_point(&display_map).column();
 7465
 7466            // Accumulate contiguous regions of rows that we want to delete.
 7467            while let Some(next_selection) = selections.peek() {
 7468                let next_rows = next_selection.spanned_rows(false, &display_map);
 7469                if next_rows.start <= rows.end {
 7470                    rows.end = next_rows.end;
 7471                    selections.next().unwrap();
 7472                } else {
 7473                    break;
 7474                }
 7475            }
 7476
 7477            let buffer = &display_map.buffer_snapshot;
 7478            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 7479            let edit_end;
 7480            let cursor_buffer_row;
 7481            if buffer.max_point().row >= rows.end.0 {
 7482                // If there's a line after the range, delete the \n from the end of the row range
 7483                // and position the cursor on the next line.
 7484                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 7485                cursor_buffer_row = rows.end;
 7486            } else {
 7487                // If there isn't a line after the range, delete the \n from the line before the
 7488                // start of the row range and position the cursor there.
 7489                edit_start = edit_start.saturating_sub(1);
 7490                edit_end = buffer.len();
 7491                cursor_buffer_row = rows.start.previous_row();
 7492            }
 7493
 7494            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 7495            *cursor.column_mut() =
 7496                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 7497
 7498            new_cursors.push((
 7499                selection.id,
 7500                buffer.anchor_after(cursor.to_point(&display_map)),
 7501            ));
 7502            edit_ranges.push(edit_start..edit_end);
 7503        }
 7504
 7505        self.transact(window, cx, |this, window, cx| {
 7506            let buffer = this.buffer.update(cx, |buffer, cx| {
 7507                let empty_str: Arc<str> = Arc::default();
 7508                buffer.edit(
 7509                    edit_ranges
 7510                        .into_iter()
 7511                        .map(|range| (range, empty_str.clone())),
 7512                    None,
 7513                    cx,
 7514                );
 7515                buffer.snapshot(cx)
 7516            });
 7517            let new_selections = new_cursors
 7518                .into_iter()
 7519                .map(|(id, cursor)| {
 7520                    let cursor = cursor.to_point(&buffer);
 7521                    Selection {
 7522                        id,
 7523                        start: cursor,
 7524                        end: cursor,
 7525                        reversed: false,
 7526                        goal: SelectionGoal::None,
 7527                    }
 7528                })
 7529                .collect();
 7530
 7531            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7532                s.select(new_selections);
 7533            });
 7534        });
 7535    }
 7536
 7537    pub fn join_lines_impl(
 7538        &mut self,
 7539        insert_whitespace: bool,
 7540        window: &mut Window,
 7541        cx: &mut Context<Self>,
 7542    ) {
 7543        if self.read_only(cx) {
 7544            return;
 7545        }
 7546        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 7547        for selection in self.selections.all::<Point>(cx) {
 7548            let start = MultiBufferRow(selection.start.row);
 7549            // Treat single line selections as if they include the next line. Otherwise this action
 7550            // would do nothing for single line selections individual cursors.
 7551            let end = if selection.start.row == selection.end.row {
 7552                MultiBufferRow(selection.start.row + 1)
 7553            } else {
 7554                MultiBufferRow(selection.end.row)
 7555            };
 7556
 7557            if let Some(last_row_range) = row_ranges.last_mut() {
 7558                if start <= last_row_range.end {
 7559                    last_row_range.end = end;
 7560                    continue;
 7561                }
 7562            }
 7563            row_ranges.push(start..end);
 7564        }
 7565
 7566        let snapshot = self.buffer.read(cx).snapshot(cx);
 7567        let mut cursor_positions = Vec::new();
 7568        for row_range in &row_ranges {
 7569            let anchor = snapshot.anchor_before(Point::new(
 7570                row_range.end.previous_row().0,
 7571                snapshot.line_len(row_range.end.previous_row()),
 7572            ));
 7573            cursor_positions.push(anchor..anchor);
 7574        }
 7575
 7576        self.transact(window, cx, |this, window, cx| {
 7577            for row_range in row_ranges.into_iter().rev() {
 7578                for row in row_range.iter_rows().rev() {
 7579                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 7580                    let next_line_row = row.next_row();
 7581                    let indent = snapshot.indent_size_for_line(next_line_row);
 7582                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7583
 7584                    let replace =
 7585                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7586                            " "
 7587                        } else {
 7588                            ""
 7589                        };
 7590
 7591                    this.buffer.update(cx, |buffer, cx| {
 7592                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7593                    });
 7594                }
 7595            }
 7596
 7597            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7598                s.select_anchor_ranges(cursor_positions)
 7599            });
 7600        });
 7601    }
 7602
 7603    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7604        self.join_lines_impl(true, window, cx);
 7605    }
 7606
 7607    pub fn sort_lines_case_sensitive(
 7608        &mut self,
 7609        _: &SortLinesCaseSensitive,
 7610        window: &mut Window,
 7611        cx: &mut Context<Self>,
 7612    ) {
 7613        self.manipulate_lines(window, cx, |lines| lines.sort())
 7614    }
 7615
 7616    pub fn sort_lines_case_insensitive(
 7617        &mut self,
 7618        _: &SortLinesCaseInsensitive,
 7619        window: &mut Window,
 7620        cx: &mut Context<Self>,
 7621    ) {
 7622        self.manipulate_lines(window, cx, |lines| {
 7623            lines.sort_by_key(|line| line.to_lowercase())
 7624        })
 7625    }
 7626
 7627    pub fn unique_lines_case_insensitive(
 7628        &mut self,
 7629        _: &UniqueLinesCaseInsensitive,
 7630        window: &mut Window,
 7631        cx: &mut Context<Self>,
 7632    ) {
 7633        self.manipulate_lines(window, cx, |lines| {
 7634            let mut seen = HashSet::default();
 7635            lines.retain(|line| seen.insert(line.to_lowercase()));
 7636        })
 7637    }
 7638
 7639    pub fn unique_lines_case_sensitive(
 7640        &mut self,
 7641        _: &UniqueLinesCaseSensitive,
 7642        window: &mut Window,
 7643        cx: &mut Context<Self>,
 7644    ) {
 7645        self.manipulate_lines(window, cx, |lines| {
 7646            let mut seen = HashSet::default();
 7647            lines.retain(|line| seen.insert(*line));
 7648        })
 7649    }
 7650
 7651    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7652        let Some(project) = self.project.clone() else {
 7653            return;
 7654        };
 7655        self.reload(project, window, cx)
 7656            .detach_and_notify_err(window, cx);
 7657    }
 7658
 7659    pub fn restore_file(
 7660        &mut self,
 7661        _: &::git::RestoreFile,
 7662        window: &mut Window,
 7663        cx: &mut Context<Self>,
 7664    ) {
 7665        let mut buffer_ids = HashSet::default();
 7666        let snapshot = self.buffer().read(cx).snapshot(cx);
 7667        for selection in self.selections.all::<usize>(cx) {
 7668            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 7669        }
 7670
 7671        let buffer = self.buffer().read(cx);
 7672        let ranges = buffer_ids
 7673            .into_iter()
 7674            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 7675            .collect::<Vec<_>>();
 7676
 7677        self.restore_hunks_in_ranges(ranges, window, cx);
 7678    }
 7679
 7680    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 7681        let selections = self
 7682            .selections
 7683            .all(cx)
 7684            .into_iter()
 7685            .map(|s| s.range())
 7686            .collect();
 7687        self.restore_hunks_in_ranges(selections, window, cx);
 7688    }
 7689
 7690    fn restore_hunks_in_ranges(
 7691        &mut self,
 7692        ranges: Vec<Range<Point>>,
 7693        window: &mut Window,
 7694        cx: &mut Context<Editor>,
 7695    ) {
 7696        let mut revert_changes = HashMap::default();
 7697        let snapshot = self.buffer.read(cx).snapshot(cx);
 7698        let Some(project) = &self.project else {
 7699            return;
 7700        };
 7701
 7702        let chunk_by = self
 7703            .snapshot(window, cx)
 7704            .hunks_for_ranges(ranges.into_iter())
 7705            .into_iter()
 7706            .chunk_by(|hunk| hunk.buffer_id);
 7707        for (buffer_id, hunks) in &chunk_by {
 7708            let hunks = hunks.collect::<Vec<_>>();
 7709            for hunk in &hunks {
 7710                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 7711            }
 7712            Self::do_stage_or_unstage(
 7713                project,
 7714                false,
 7715                buffer_id,
 7716                hunks.into_iter(),
 7717                &snapshot,
 7718                window,
 7719                cx,
 7720            );
 7721        }
 7722        drop(chunk_by);
 7723        if !revert_changes.is_empty() {
 7724            self.transact(window, cx, |editor, window, cx| {
 7725                editor.restore(revert_changes, window, cx);
 7726            });
 7727        }
 7728    }
 7729
 7730    pub fn open_active_item_in_terminal(
 7731        &mut self,
 7732        _: &OpenInTerminal,
 7733        window: &mut Window,
 7734        cx: &mut Context<Self>,
 7735    ) {
 7736        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7737            let project_path = buffer.read(cx).project_path(cx)?;
 7738            let project = self.project.as_ref()?.read(cx);
 7739            let entry = project.entry_for_path(&project_path, cx)?;
 7740            let parent = match &entry.canonical_path {
 7741                Some(canonical_path) => canonical_path.to_path_buf(),
 7742                None => project.absolute_path(&project_path, cx)?,
 7743            }
 7744            .parent()?
 7745            .to_path_buf();
 7746            Some(parent)
 7747        }) {
 7748            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7749        }
 7750    }
 7751
 7752    pub fn prepare_restore_change(
 7753        &self,
 7754        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7755        hunk: &MultiBufferDiffHunk,
 7756        cx: &mut App,
 7757    ) -> Option<()> {
 7758        let buffer = self.buffer.read(cx);
 7759        let diff = buffer.diff_for(hunk.buffer_id)?;
 7760        let buffer = buffer.buffer(hunk.buffer_id)?;
 7761        let buffer = buffer.read(cx);
 7762        let original_text = diff
 7763            .read(cx)
 7764            .base_text()
 7765            .as_ref()?
 7766            .as_rope()
 7767            .slice(hunk.diff_base_byte_range.clone());
 7768        let buffer_snapshot = buffer.snapshot();
 7769        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7770        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7771            probe
 7772                .0
 7773                .start
 7774                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7775                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7776        }) {
 7777            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7778            Some(())
 7779        } else {
 7780            None
 7781        }
 7782    }
 7783
 7784    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7785        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7786    }
 7787
 7788    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7789        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7790    }
 7791
 7792    fn manipulate_lines<Fn>(
 7793        &mut self,
 7794        window: &mut Window,
 7795        cx: &mut Context<Self>,
 7796        mut callback: Fn,
 7797    ) where
 7798        Fn: FnMut(&mut Vec<&str>),
 7799    {
 7800        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7801        let buffer = self.buffer.read(cx).snapshot(cx);
 7802
 7803        let mut edits = Vec::new();
 7804
 7805        let selections = self.selections.all::<Point>(cx);
 7806        let mut selections = selections.iter().peekable();
 7807        let mut contiguous_row_selections = Vec::new();
 7808        let mut new_selections = Vec::new();
 7809        let mut added_lines = 0;
 7810        let mut removed_lines = 0;
 7811
 7812        while let Some(selection) = selections.next() {
 7813            let (start_row, end_row) = consume_contiguous_rows(
 7814                &mut contiguous_row_selections,
 7815                selection,
 7816                &display_map,
 7817                &mut selections,
 7818            );
 7819
 7820            let start_point = Point::new(start_row.0, 0);
 7821            let end_point = Point::new(
 7822                end_row.previous_row().0,
 7823                buffer.line_len(end_row.previous_row()),
 7824            );
 7825            let text = buffer
 7826                .text_for_range(start_point..end_point)
 7827                .collect::<String>();
 7828
 7829            let mut lines = text.split('\n').collect_vec();
 7830
 7831            let lines_before = lines.len();
 7832            callback(&mut lines);
 7833            let lines_after = lines.len();
 7834
 7835            edits.push((start_point..end_point, lines.join("\n")));
 7836
 7837            // Selections must change based on added and removed line count
 7838            let start_row =
 7839                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7840            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7841            new_selections.push(Selection {
 7842                id: selection.id,
 7843                start: start_row,
 7844                end: end_row,
 7845                goal: SelectionGoal::None,
 7846                reversed: selection.reversed,
 7847            });
 7848
 7849            if lines_after > lines_before {
 7850                added_lines += lines_after - lines_before;
 7851            } else if lines_before > lines_after {
 7852                removed_lines += lines_before - lines_after;
 7853            }
 7854        }
 7855
 7856        self.transact(window, cx, |this, window, cx| {
 7857            let buffer = this.buffer.update(cx, |buffer, cx| {
 7858                buffer.edit(edits, None, cx);
 7859                buffer.snapshot(cx)
 7860            });
 7861
 7862            // Recalculate offsets on newly edited buffer
 7863            let new_selections = new_selections
 7864                .iter()
 7865                .map(|s| {
 7866                    let start_point = Point::new(s.start.0, 0);
 7867                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7868                    Selection {
 7869                        id: s.id,
 7870                        start: buffer.point_to_offset(start_point),
 7871                        end: buffer.point_to_offset(end_point),
 7872                        goal: s.goal,
 7873                        reversed: s.reversed,
 7874                    }
 7875                })
 7876                .collect();
 7877
 7878            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7879                s.select(new_selections);
 7880            });
 7881
 7882            this.request_autoscroll(Autoscroll::fit(), cx);
 7883        });
 7884    }
 7885
 7886    pub fn convert_to_upper_case(
 7887        &mut self,
 7888        _: &ConvertToUpperCase,
 7889        window: &mut Window,
 7890        cx: &mut Context<Self>,
 7891    ) {
 7892        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7893    }
 7894
 7895    pub fn convert_to_lower_case(
 7896        &mut self,
 7897        _: &ConvertToLowerCase,
 7898        window: &mut Window,
 7899        cx: &mut Context<Self>,
 7900    ) {
 7901        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7902    }
 7903
 7904    pub fn convert_to_title_case(
 7905        &mut self,
 7906        _: &ConvertToTitleCase,
 7907        window: &mut Window,
 7908        cx: &mut Context<Self>,
 7909    ) {
 7910        self.manipulate_text(window, cx, |text| {
 7911            text.split('\n')
 7912                .map(|line| line.to_case(Case::Title))
 7913                .join("\n")
 7914        })
 7915    }
 7916
 7917    pub fn convert_to_snake_case(
 7918        &mut self,
 7919        _: &ConvertToSnakeCase,
 7920        window: &mut Window,
 7921        cx: &mut Context<Self>,
 7922    ) {
 7923        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7924    }
 7925
 7926    pub fn convert_to_kebab_case(
 7927        &mut self,
 7928        _: &ConvertToKebabCase,
 7929        window: &mut Window,
 7930        cx: &mut Context<Self>,
 7931    ) {
 7932        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7933    }
 7934
 7935    pub fn convert_to_upper_camel_case(
 7936        &mut self,
 7937        _: &ConvertToUpperCamelCase,
 7938        window: &mut Window,
 7939        cx: &mut Context<Self>,
 7940    ) {
 7941        self.manipulate_text(window, cx, |text| {
 7942            text.split('\n')
 7943                .map(|line| line.to_case(Case::UpperCamel))
 7944                .join("\n")
 7945        })
 7946    }
 7947
 7948    pub fn convert_to_lower_camel_case(
 7949        &mut self,
 7950        _: &ConvertToLowerCamelCase,
 7951        window: &mut Window,
 7952        cx: &mut Context<Self>,
 7953    ) {
 7954        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7955    }
 7956
 7957    pub fn convert_to_opposite_case(
 7958        &mut self,
 7959        _: &ConvertToOppositeCase,
 7960        window: &mut Window,
 7961        cx: &mut Context<Self>,
 7962    ) {
 7963        self.manipulate_text(window, cx, |text| {
 7964            text.chars()
 7965                .fold(String::with_capacity(text.len()), |mut t, c| {
 7966                    if c.is_uppercase() {
 7967                        t.extend(c.to_lowercase());
 7968                    } else {
 7969                        t.extend(c.to_uppercase());
 7970                    }
 7971                    t
 7972                })
 7973        })
 7974    }
 7975
 7976    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7977    where
 7978        Fn: FnMut(&str) -> String,
 7979    {
 7980        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7981        let buffer = self.buffer.read(cx).snapshot(cx);
 7982
 7983        let mut new_selections = Vec::new();
 7984        let mut edits = Vec::new();
 7985        let mut selection_adjustment = 0i32;
 7986
 7987        for selection in self.selections.all::<usize>(cx) {
 7988            let selection_is_empty = selection.is_empty();
 7989
 7990            let (start, end) = if selection_is_empty {
 7991                let word_range = movement::surrounding_word(
 7992                    &display_map,
 7993                    selection.start.to_display_point(&display_map),
 7994                );
 7995                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7996                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7997                (start, end)
 7998            } else {
 7999                (selection.start, selection.end)
 8000            };
 8001
 8002            let text = buffer.text_for_range(start..end).collect::<String>();
 8003            let old_length = text.len() as i32;
 8004            let text = callback(&text);
 8005
 8006            new_selections.push(Selection {
 8007                start: (start as i32 - selection_adjustment) as usize,
 8008                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 8009                goal: SelectionGoal::None,
 8010                ..selection
 8011            });
 8012
 8013            selection_adjustment += old_length - text.len() as i32;
 8014
 8015            edits.push((start..end, text));
 8016        }
 8017
 8018        self.transact(window, cx, |this, window, cx| {
 8019            this.buffer.update(cx, |buffer, cx| {
 8020                buffer.edit(edits, None, cx);
 8021            });
 8022
 8023            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8024                s.select(new_selections);
 8025            });
 8026
 8027            this.request_autoscroll(Autoscroll::fit(), cx);
 8028        });
 8029    }
 8030
 8031    pub fn duplicate(
 8032        &mut self,
 8033        upwards: bool,
 8034        whole_lines: bool,
 8035        window: &mut Window,
 8036        cx: &mut Context<Self>,
 8037    ) {
 8038        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8039        let buffer = &display_map.buffer_snapshot;
 8040        let selections = self.selections.all::<Point>(cx);
 8041
 8042        let mut edits = Vec::new();
 8043        let mut selections_iter = selections.iter().peekable();
 8044        while let Some(selection) = selections_iter.next() {
 8045            let mut rows = selection.spanned_rows(false, &display_map);
 8046            // duplicate line-wise
 8047            if whole_lines || selection.start == selection.end {
 8048                // Avoid duplicating the same lines twice.
 8049                while let Some(next_selection) = selections_iter.peek() {
 8050                    let next_rows = next_selection.spanned_rows(false, &display_map);
 8051                    if next_rows.start < rows.end {
 8052                        rows.end = next_rows.end;
 8053                        selections_iter.next().unwrap();
 8054                    } else {
 8055                        break;
 8056                    }
 8057                }
 8058
 8059                // Copy the text from the selected row region and splice it either at the start
 8060                // or end of the region.
 8061                let start = Point::new(rows.start.0, 0);
 8062                let end = Point::new(
 8063                    rows.end.previous_row().0,
 8064                    buffer.line_len(rows.end.previous_row()),
 8065                );
 8066                let text = buffer
 8067                    .text_for_range(start..end)
 8068                    .chain(Some("\n"))
 8069                    .collect::<String>();
 8070                let insert_location = if upwards {
 8071                    Point::new(rows.end.0, 0)
 8072                } else {
 8073                    start
 8074                };
 8075                edits.push((insert_location..insert_location, text));
 8076            } else {
 8077                // duplicate character-wise
 8078                let start = selection.start;
 8079                let end = selection.end;
 8080                let text = buffer.text_for_range(start..end).collect::<String>();
 8081                edits.push((selection.end..selection.end, text));
 8082            }
 8083        }
 8084
 8085        self.transact(window, cx, |this, _, cx| {
 8086            this.buffer.update(cx, |buffer, cx| {
 8087                buffer.edit(edits, None, cx);
 8088            });
 8089
 8090            this.request_autoscroll(Autoscroll::fit(), cx);
 8091        });
 8092    }
 8093
 8094    pub fn duplicate_line_up(
 8095        &mut self,
 8096        _: &DuplicateLineUp,
 8097        window: &mut Window,
 8098        cx: &mut Context<Self>,
 8099    ) {
 8100        self.duplicate(true, true, window, cx);
 8101    }
 8102
 8103    pub fn duplicate_line_down(
 8104        &mut self,
 8105        _: &DuplicateLineDown,
 8106        window: &mut Window,
 8107        cx: &mut Context<Self>,
 8108    ) {
 8109        self.duplicate(false, true, window, cx);
 8110    }
 8111
 8112    pub fn duplicate_selection(
 8113        &mut self,
 8114        _: &DuplicateSelection,
 8115        window: &mut Window,
 8116        cx: &mut Context<Self>,
 8117    ) {
 8118        self.duplicate(false, false, window, cx);
 8119    }
 8120
 8121    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 8122        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8123        let buffer = self.buffer.read(cx).snapshot(cx);
 8124
 8125        let mut edits = Vec::new();
 8126        let mut unfold_ranges = Vec::new();
 8127        let mut refold_creases = Vec::new();
 8128
 8129        let selections = self.selections.all::<Point>(cx);
 8130        let mut selections = selections.iter().peekable();
 8131        let mut contiguous_row_selections = Vec::new();
 8132        let mut new_selections = Vec::new();
 8133
 8134        while let Some(selection) = selections.next() {
 8135            // Find all the selections that span a contiguous row range
 8136            let (start_row, end_row) = consume_contiguous_rows(
 8137                &mut contiguous_row_selections,
 8138                selection,
 8139                &display_map,
 8140                &mut selections,
 8141            );
 8142
 8143            // Move the text spanned by the row range to be before the line preceding the row range
 8144            if start_row.0 > 0 {
 8145                let range_to_move = Point::new(
 8146                    start_row.previous_row().0,
 8147                    buffer.line_len(start_row.previous_row()),
 8148                )
 8149                    ..Point::new(
 8150                        end_row.previous_row().0,
 8151                        buffer.line_len(end_row.previous_row()),
 8152                    );
 8153                let insertion_point = display_map
 8154                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 8155                    .0;
 8156
 8157                // Don't move lines across excerpts
 8158                if buffer
 8159                    .excerpt_containing(insertion_point..range_to_move.end)
 8160                    .is_some()
 8161                {
 8162                    let text = buffer
 8163                        .text_for_range(range_to_move.clone())
 8164                        .flat_map(|s| s.chars())
 8165                        .skip(1)
 8166                        .chain(['\n'])
 8167                        .collect::<String>();
 8168
 8169                    edits.push((
 8170                        buffer.anchor_after(range_to_move.start)
 8171                            ..buffer.anchor_before(range_to_move.end),
 8172                        String::new(),
 8173                    ));
 8174                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8175                    edits.push((insertion_anchor..insertion_anchor, text));
 8176
 8177                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 8178
 8179                    // Move selections up
 8180                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8181                        |mut selection| {
 8182                            selection.start.row -= row_delta;
 8183                            selection.end.row -= row_delta;
 8184                            selection
 8185                        },
 8186                    ));
 8187
 8188                    // Move folds up
 8189                    unfold_ranges.push(range_to_move.clone());
 8190                    for fold in display_map.folds_in_range(
 8191                        buffer.anchor_before(range_to_move.start)
 8192                            ..buffer.anchor_after(range_to_move.end),
 8193                    ) {
 8194                        let mut start = fold.range.start.to_point(&buffer);
 8195                        let mut end = fold.range.end.to_point(&buffer);
 8196                        start.row -= row_delta;
 8197                        end.row -= row_delta;
 8198                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8199                    }
 8200                }
 8201            }
 8202
 8203            // If we didn't move line(s), preserve the existing selections
 8204            new_selections.append(&mut contiguous_row_selections);
 8205        }
 8206
 8207        self.transact(window, cx, |this, window, cx| {
 8208            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8209            this.buffer.update(cx, |buffer, cx| {
 8210                for (range, text) in edits {
 8211                    buffer.edit([(range, text)], None, cx);
 8212                }
 8213            });
 8214            this.fold_creases(refold_creases, true, window, cx);
 8215            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8216                s.select(new_selections);
 8217            })
 8218        });
 8219    }
 8220
 8221    pub fn move_line_down(
 8222        &mut self,
 8223        _: &MoveLineDown,
 8224        window: &mut Window,
 8225        cx: &mut Context<Self>,
 8226    ) {
 8227        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8228        let buffer = self.buffer.read(cx).snapshot(cx);
 8229
 8230        let mut edits = Vec::new();
 8231        let mut unfold_ranges = Vec::new();
 8232        let mut refold_creases = Vec::new();
 8233
 8234        let selections = self.selections.all::<Point>(cx);
 8235        let mut selections = selections.iter().peekable();
 8236        let mut contiguous_row_selections = Vec::new();
 8237        let mut new_selections = Vec::new();
 8238
 8239        while let Some(selection) = selections.next() {
 8240            // Find all the selections that span a contiguous row range
 8241            let (start_row, end_row) = consume_contiguous_rows(
 8242                &mut contiguous_row_selections,
 8243                selection,
 8244                &display_map,
 8245                &mut selections,
 8246            );
 8247
 8248            // Move the text spanned by the row range to be after the last line of the row range
 8249            if end_row.0 <= buffer.max_point().row {
 8250                let range_to_move =
 8251                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 8252                let insertion_point = display_map
 8253                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 8254                    .0;
 8255
 8256                // Don't move lines across excerpt boundaries
 8257                if buffer
 8258                    .excerpt_containing(range_to_move.start..insertion_point)
 8259                    .is_some()
 8260                {
 8261                    let mut text = String::from("\n");
 8262                    text.extend(buffer.text_for_range(range_to_move.clone()));
 8263                    text.pop(); // Drop trailing newline
 8264                    edits.push((
 8265                        buffer.anchor_after(range_to_move.start)
 8266                            ..buffer.anchor_before(range_to_move.end),
 8267                        String::new(),
 8268                    ));
 8269                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8270                    edits.push((insertion_anchor..insertion_anchor, text));
 8271
 8272                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 8273
 8274                    // Move selections down
 8275                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8276                        |mut selection| {
 8277                            selection.start.row += row_delta;
 8278                            selection.end.row += row_delta;
 8279                            selection
 8280                        },
 8281                    ));
 8282
 8283                    // Move folds down
 8284                    unfold_ranges.push(range_to_move.clone());
 8285                    for fold in display_map.folds_in_range(
 8286                        buffer.anchor_before(range_to_move.start)
 8287                            ..buffer.anchor_after(range_to_move.end),
 8288                    ) {
 8289                        let mut start = fold.range.start.to_point(&buffer);
 8290                        let mut end = fold.range.end.to_point(&buffer);
 8291                        start.row += row_delta;
 8292                        end.row += row_delta;
 8293                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8294                    }
 8295                }
 8296            }
 8297
 8298            // If we didn't move line(s), preserve the existing selections
 8299            new_selections.append(&mut contiguous_row_selections);
 8300        }
 8301
 8302        self.transact(window, cx, |this, window, cx| {
 8303            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8304            this.buffer.update(cx, |buffer, cx| {
 8305                for (range, text) in edits {
 8306                    buffer.edit([(range, text)], None, cx);
 8307                }
 8308            });
 8309            this.fold_creases(refold_creases, true, window, cx);
 8310            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8311                s.select(new_selections)
 8312            });
 8313        });
 8314    }
 8315
 8316    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 8317        let text_layout_details = &self.text_layout_details(window);
 8318        self.transact(window, cx, |this, window, cx| {
 8319            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8320                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 8321                let line_mode = s.line_mode;
 8322                s.move_with(|display_map, selection| {
 8323                    if !selection.is_empty() || line_mode {
 8324                        return;
 8325                    }
 8326
 8327                    let mut head = selection.head();
 8328                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 8329                    if head.column() == display_map.line_len(head.row()) {
 8330                        transpose_offset = display_map
 8331                            .buffer_snapshot
 8332                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8333                    }
 8334
 8335                    if transpose_offset == 0 {
 8336                        return;
 8337                    }
 8338
 8339                    *head.column_mut() += 1;
 8340                    head = display_map.clip_point(head, Bias::Right);
 8341                    let goal = SelectionGoal::HorizontalPosition(
 8342                        display_map
 8343                            .x_for_display_point(head, text_layout_details)
 8344                            .into(),
 8345                    );
 8346                    selection.collapse_to(head, goal);
 8347
 8348                    let transpose_start = display_map
 8349                        .buffer_snapshot
 8350                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8351                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 8352                        let transpose_end = display_map
 8353                            .buffer_snapshot
 8354                            .clip_offset(transpose_offset + 1, Bias::Right);
 8355                        if let Some(ch) =
 8356                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 8357                        {
 8358                            edits.push((transpose_start..transpose_offset, String::new()));
 8359                            edits.push((transpose_end..transpose_end, ch.to_string()));
 8360                        }
 8361                    }
 8362                });
 8363                edits
 8364            });
 8365            this.buffer
 8366                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8367            let selections = this.selections.all::<usize>(cx);
 8368            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8369                s.select(selections);
 8370            });
 8371        });
 8372    }
 8373
 8374    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 8375        self.rewrap_impl(IsVimMode::No, cx)
 8376    }
 8377
 8378    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 8379        let buffer = self.buffer.read(cx).snapshot(cx);
 8380        let selections = self.selections.all::<Point>(cx);
 8381        let mut selections = selections.iter().peekable();
 8382
 8383        let mut edits = Vec::new();
 8384        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 8385
 8386        while let Some(selection) = selections.next() {
 8387            let mut start_row = selection.start.row;
 8388            let mut end_row = selection.end.row;
 8389
 8390            // Skip selections that overlap with a range that has already been rewrapped.
 8391            let selection_range = start_row..end_row;
 8392            if rewrapped_row_ranges
 8393                .iter()
 8394                .any(|range| range.overlaps(&selection_range))
 8395            {
 8396                continue;
 8397            }
 8398
 8399            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 8400
 8401            // Since not all lines in the selection may be at the same indent
 8402            // level, choose the indent size that is the most common between all
 8403            // of the lines.
 8404            //
 8405            // If there is a tie, we use the deepest indent.
 8406            let (indent_size, indent_end) = {
 8407                let mut indent_size_occurrences = HashMap::default();
 8408                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 8409
 8410                for row in start_row..=end_row {
 8411                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 8412                    rows_by_indent_size.entry(indent).or_default().push(row);
 8413                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 8414                }
 8415
 8416                let indent_size = indent_size_occurrences
 8417                    .into_iter()
 8418                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 8419                    .map(|(indent, _)| indent)
 8420                    .unwrap_or_default();
 8421                let row = rows_by_indent_size[&indent_size][0];
 8422                let indent_end = Point::new(row, indent_size.len);
 8423
 8424                (indent_size, indent_end)
 8425            };
 8426
 8427            let mut line_prefix = indent_size.chars().collect::<String>();
 8428
 8429            let mut inside_comment = false;
 8430            if let Some(comment_prefix) =
 8431                buffer
 8432                    .language_scope_at(selection.head())
 8433                    .and_then(|language| {
 8434                        language
 8435                            .line_comment_prefixes()
 8436                            .iter()
 8437                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 8438                            .cloned()
 8439                    })
 8440            {
 8441                line_prefix.push_str(&comment_prefix);
 8442                inside_comment = true;
 8443            }
 8444
 8445            let language_settings = buffer.settings_at(selection.head(), cx);
 8446            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 8447                RewrapBehavior::InComments => inside_comment,
 8448                RewrapBehavior::InSelections => !selection.is_empty(),
 8449                RewrapBehavior::Anywhere => true,
 8450            };
 8451
 8452            let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
 8453            if !should_rewrap {
 8454                continue;
 8455            }
 8456
 8457            if selection.is_empty() {
 8458                'expand_upwards: while start_row > 0 {
 8459                    let prev_row = start_row - 1;
 8460                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 8461                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 8462                    {
 8463                        start_row = prev_row;
 8464                    } else {
 8465                        break 'expand_upwards;
 8466                    }
 8467                }
 8468
 8469                'expand_downwards: while end_row < buffer.max_point().row {
 8470                    let next_row = end_row + 1;
 8471                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 8472                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 8473                    {
 8474                        end_row = next_row;
 8475                    } else {
 8476                        break 'expand_downwards;
 8477                    }
 8478                }
 8479            }
 8480
 8481            let start = Point::new(start_row, 0);
 8482            let start_offset = start.to_offset(&buffer);
 8483            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 8484            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 8485            let Some(lines_without_prefixes) = selection_text
 8486                .lines()
 8487                .map(|line| {
 8488                    line.strip_prefix(&line_prefix)
 8489                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 8490                        .ok_or_else(|| {
 8491                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 8492                        })
 8493                })
 8494                .collect::<Result<Vec<_>, _>>()
 8495                .log_err()
 8496            else {
 8497                continue;
 8498            };
 8499
 8500            let wrap_column = buffer
 8501                .settings_at(Point::new(start_row, 0), cx)
 8502                .preferred_line_length as usize;
 8503            let wrapped_text = wrap_with_prefix(
 8504                line_prefix,
 8505                lines_without_prefixes.join(" "),
 8506                wrap_column,
 8507                tab_size,
 8508            );
 8509
 8510            // TODO: should always use char-based diff while still supporting cursor behavior that
 8511            // matches vim.
 8512            let mut diff_options = DiffOptions::default();
 8513            if is_vim_mode == IsVimMode::Yes {
 8514                diff_options.max_word_diff_len = 0;
 8515                diff_options.max_word_diff_line_count = 0;
 8516            } else {
 8517                diff_options.max_word_diff_len = usize::MAX;
 8518                diff_options.max_word_diff_line_count = usize::MAX;
 8519            }
 8520
 8521            for (old_range, new_text) in
 8522                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 8523            {
 8524                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 8525                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 8526                edits.push((edit_start..edit_end, new_text));
 8527            }
 8528
 8529            rewrapped_row_ranges.push(start_row..=end_row);
 8530        }
 8531
 8532        self.buffer
 8533            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8534    }
 8535
 8536    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 8537        let mut text = String::new();
 8538        let buffer = self.buffer.read(cx).snapshot(cx);
 8539        let mut selections = self.selections.all::<Point>(cx);
 8540        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8541        {
 8542            let max_point = buffer.max_point();
 8543            let mut is_first = true;
 8544            for selection in &mut selections {
 8545                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8546                if is_entire_line {
 8547                    selection.start = Point::new(selection.start.row, 0);
 8548                    if !selection.is_empty() && selection.end.column == 0 {
 8549                        selection.end = cmp::min(max_point, selection.end);
 8550                    } else {
 8551                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 8552                    }
 8553                    selection.goal = SelectionGoal::None;
 8554                }
 8555                if is_first {
 8556                    is_first = false;
 8557                } else {
 8558                    text += "\n";
 8559                }
 8560                let mut len = 0;
 8561                for chunk in buffer.text_for_range(selection.start..selection.end) {
 8562                    text.push_str(chunk);
 8563                    len += chunk.len();
 8564                }
 8565                clipboard_selections.push(ClipboardSelection {
 8566                    len,
 8567                    is_entire_line,
 8568                    start_column: selection.start.column,
 8569                });
 8570            }
 8571        }
 8572
 8573        self.transact(window, cx, |this, window, cx| {
 8574            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8575                s.select(selections);
 8576            });
 8577            this.insert("", window, cx);
 8578        });
 8579        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 8580    }
 8581
 8582    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8583        let item = self.cut_common(window, cx);
 8584        cx.write_to_clipboard(item);
 8585    }
 8586
 8587    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8588        self.change_selections(None, window, cx, |s| {
 8589            s.move_with(|snapshot, sel| {
 8590                if sel.is_empty() {
 8591                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8592                }
 8593            });
 8594        });
 8595        let item = self.cut_common(window, cx);
 8596        cx.set_global(KillRing(item))
 8597    }
 8598
 8599    pub fn kill_ring_yank(
 8600        &mut self,
 8601        _: &KillRingYank,
 8602        window: &mut Window,
 8603        cx: &mut Context<Self>,
 8604    ) {
 8605        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8606            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8607                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8608            } else {
 8609                return;
 8610            }
 8611        } else {
 8612            return;
 8613        };
 8614        self.do_paste(&text, metadata, false, window, cx);
 8615    }
 8616
 8617    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8618        let selections = self.selections.all::<Point>(cx);
 8619        let buffer = self.buffer.read(cx).read(cx);
 8620        let mut text = String::new();
 8621
 8622        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8623        {
 8624            let max_point = buffer.max_point();
 8625            let mut is_first = true;
 8626            for selection in selections.iter() {
 8627                let mut start = selection.start;
 8628                let mut end = selection.end;
 8629                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8630                if is_entire_line {
 8631                    start = Point::new(start.row, 0);
 8632                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8633                }
 8634                if is_first {
 8635                    is_first = false;
 8636                } else {
 8637                    text += "\n";
 8638                }
 8639                let mut len = 0;
 8640                for chunk in buffer.text_for_range(start..end) {
 8641                    text.push_str(chunk);
 8642                    len += chunk.len();
 8643                }
 8644                clipboard_selections.push(ClipboardSelection {
 8645                    len,
 8646                    is_entire_line,
 8647                    start_column: start.column,
 8648                });
 8649            }
 8650        }
 8651
 8652        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8653            text,
 8654            clipboard_selections,
 8655        ));
 8656    }
 8657
 8658    pub fn do_paste(
 8659        &mut self,
 8660        text: &String,
 8661        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8662        handle_entire_lines: bool,
 8663        window: &mut Window,
 8664        cx: &mut Context<Self>,
 8665    ) {
 8666        if self.read_only(cx) {
 8667            return;
 8668        }
 8669
 8670        let clipboard_text = Cow::Borrowed(text);
 8671
 8672        self.transact(window, cx, |this, window, cx| {
 8673            if let Some(mut clipboard_selections) = clipboard_selections {
 8674                let old_selections = this.selections.all::<usize>(cx);
 8675                let all_selections_were_entire_line =
 8676                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8677                let first_selection_start_column =
 8678                    clipboard_selections.first().map(|s| s.start_column);
 8679                if clipboard_selections.len() != old_selections.len() {
 8680                    clipboard_selections.drain(..);
 8681                }
 8682                let cursor_offset = this.selections.last::<usize>(cx).head();
 8683                let mut auto_indent_on_paste = true;
 8684
 8685                this.buffer.update(cx, |buffer, cx| {
 8686                    let snapshot = buffer.read(cx);
 8687                    auto_indent_on_paste =
 8688                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 8689
 8690                    let mut start_offset = 0;
 8691                    let mut edits = Vec::new();
 8692                    let mut original_start_columns = Vec::new();
 8693                    for (ix, selection) in old_selections.iter().enumerate() {
 8694                        let to_insert;
 8695                        let entire_line;
 8696                        let original_start_column;
 8697                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8698                            let end_offset = start_offset + clipboard_selection.len;
 8699                            to_insert = &clipboard_text[start_offset..end_offset];
 8700                            entire_line = clipboard_selection.is_entire_line;
 8701                            start_offset = end_offset + 1;
 8702                            original_start_column = Some(clipboard_selection.start_column);
 8703                        } else {
 8704                            to_insert = clipboard_text.as_str();
 8705                            entire_line = all_selections_were_entire_line;
 8706                            original_start_column = first_selection_start_column
 8707                        }
 8708
 8709                        // If the corresponding selection was empty when this slice of the
 8710                        // clipboard text was written, then the entire line containing the
 8711                        // selection was copied. If this selection is also currently empty,
 8712                        // then paste the line before the current line of the buffer.
 8713                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8714                            let column = selection.start.to_point(&snapshot).column as usize;
 8715                            let line_start = selection.start - column;
 8716                            line_start..line_start
 8717                        } else {
 8718                            selection.range()
 8719                        };
 8720
 8721                        edits.push((range, to_insert));
 8722                        original_start_columns.extend(original_start_column);
 8723                    }
 8724                    drop(snapshot);
 8725
 8726                    buffer.edit(
 8727                        edits,
 8728                        if auto_indent_on_paste {
 8729                            Some(AutoindentMode::Block {
 8730                                original_start_columns,
 8731                            })
 8732                        } else {
 8733                            None
 8734                        },
 8735                        cx,
 8736                    );
 8737                });
 8738
 8739                let selections = this.selections.all::<usize>(cx);
 8740                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8741                    s.select(selections)
 8742                });
 8743            } else {
 8744                this.insert(&clipboard_text, window, cx);
 8745            }
 8746        });
 8747    }
 8748
 8749    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8750        if let Some(item) = cx.read_from_clipboard() {
 8751            let entries = item.entries();
 8752
 8753            match entries.first() {
 8754                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8755                // of all the pasted entries.
 8756                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8757                    .do_paste(
 8758                        clipboard_string.text(),
 8759                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8760                        true,
 8761                        window,
 8762                        cx,
 8763                    ),
 8764                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8765            }
 8766        }
 8767    }
 8768
 8769    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8770        if self.read_only(cx) {
 8771            return;
 8772        }
 8773
 8774        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8775            if let Some((selections, _)) =
 8776                self.selection_history.transaction(transaction_id).cloned()
 8777            {
 8778                self.change_selections(None, window, cx, |s| {
 8779                    s.select_anchors(selections.to_vec());
 8780                });
 8781            } else {
 8782                log::error!(
 8783                    "No entry in selection_history found for undo. \
 8784                     This may correspond to a bug where undo does not update the selection. \
 8785                     If this is occurring, please add details to \
 8786                     https://github.com/zed-industries/zed/issues/22692"
 8787                );
 8788            }
 8789            self.request_autoscroll(Autoscroll::fit(), cx);
 8790            self.unmark_text(window, cx);
 8791            self.refresh_inline_completion(true, false, window, cx);
 8792            cx.emit(EditorEvent::Edited { transaction_id });
 8793            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8794        }
 8795    }
 8796
 8797    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8798        if self.read_only(cx) {
 8799            return;
 8800        }
 8801
 8802        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8803            if let Some((_, Some(selections))) =
 8804                self.selection_history.transaction(transaction_id).cloned()
 8805            {
 8806                self.change_selections(None, window, cx, |s| {
 8807                    s.select_anchors(selections.to_vec());
 8808                });
 8809            } else {
 8810                log::error!(
 8811                    "No entry in selection_history found for redo. \
 8812                     This may correspond to a bug where undo does not update the selection. \
 8813                     If this is occurring, please add details to \
 8814                     https://github.com/zed-industries/zed/issues/22692"
 8815                );
 8816            }
 8817            self.request_autoscroll(Autoscroll::fit(), cx);
 8818            self.unmark_text(window, cx);
 8819            self.refresh_inline_completion(true, false, window, cx);
 8820            cx.emit(EditorEvent::Edited { transaction_id });
 8821        }
 8822    }
 8823
 8824    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8825        self.buffer
 8826            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8827    }
 8828
 8829    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8830        self.buffer
 8831            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8832    }
 8833
 8834    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8835        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8836            let line_mode = s.line_mode;
 8837            s.move_with(|map, selection| {
 8838                let cursor = if selection.is_empty() && !line_mode {
 8839                    movement::left(map, selection.start)
 8840                } else {
 8841                    selection.start
 8842                };
 8843                selection.collapse_to(cursor, SelectionGoal::None);
 8844            });
 8845        })
 8846    }
 8847
 8848    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8849        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8850            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8851        })
 8852    }
 8853
 8854    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8855        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8856            let line_mode = s.line_mode;
 8857            s.move_with(|map, selection| {
 8858                let cursor = if selection.is_empty() && !line_mode {
 8859                    movement::right(map, selection.end)
 8860                } else {
 8861                    selection.end
 8862                };
 8863                selection.collapse_to(cursor, SelectionGoal::None)
 8864            });
 8865        })
 8866    }
 8867
 8868    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8869        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8870            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8871        })
 8872    }
 8873
 8874    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8875        if self.take_rename(true, window, cx).is_some() {
 8876            return;
 8877        }
 8878
 8879        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8880            cx.propagate();
 8881            return;
 8882        }
 8883
 8884        let text_layout_details = &self.text_layout_details(window);
 8885        let selection_count = self.selections.count();
 8886        let first_selection = self.selections.first_anchor();
 8887
 8888        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8889            let line_mode = s.line_mode;
 8890            s.move_with(|map, selection| {
 8891                if !selection.is_empty() && !line_mode {
 8892                    selection.goal = SelectionGoal::None;
 8893                }
 8894                let (cursor, goal) = movement::up(
 8895                    map,
 8896                    selection.start,
 8897                    selection.goal,
 8898                    false,
 8899                    text_layout_details,
 8900                );
 8901                selection.collapse_to(cursor, goal);
 8902            });
 8903        });
 8904
 8905        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8906        {
 8907            cx.propagate();
 8908        }
 8909    }
 8910
 8911    pub fn move_up_by_lines(
 8912        &mut self,
 8913        action: &MoveUpByLines,
 8914        window: &mut Window,
 8915        cx: &mut Context<Self>,
 8916    ) {
 8917        if self.take_rename(true, window, cx).is_some() {
 8918            return;
 8919        }
 8920
 8921        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8922            cx.propagate();
 8923            return;
 8924        }
 8925
 8926        let text_layout_details = &self.text_layout_details(window);
 8927
 8928        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8929            let line_mode = s.line_mode;
 8930            s.move_with(|map, selection| {
 8931                if !selection.is_empty() && !line_mode {
 8932                    selection.goal = SelectionGoal::None;
 8933                }
 8934                let (cursor, goal) = movement::up_by_rows(
 8935                    map,
 8936                    selection.start,
 8937                    action.lines,
 8938                    selection.goal,
 8939                    false,
 8940                    text_layout_details,
 8941                );
 8942                selection.collapse_to(cursor, goal);
 8943            });
 8944        })
 8945    }
 8946
 8947    pub fn move_down_by_lines(
 8948        &mut self,
 8949        action: &MoveDownByLines,
 8950        window: &mut Window,
 8951        cx: &mut Context<Self>,
 8952    ) {
 8953        if self.take_rename(true, window, cx).is_some() {
 8954            return;
 8955        }
 8956
 8957        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8958            cx.propagate();
 8959            return;
 8960        }
 8961
 8962        let text_layout_details = &self.text_layout_details(window);
 8963
 8964        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8965            let line_mode = s.line_mode;
 8966            s.move_with(|map, selection| {
 8967                if !selection.is_empty() && !line_mode {
 8968                    selection.goal = SelectionGoal::None;
 8969                }
 8970                let (cursor, goal) = movement::down_by_rows(
 8971                    map,
 8972                    selection.start,
 8973                    action.lines,
 8974                    selection.goal,
 8975                    false,
 8976                    text_layout_details,
 8977                );
 8978                selection.collapse_to(cursor, goal);
 8979            });
 8980        })
 8981    }
 8982
 8983    pub fn select_down_by_lines(
 8984        &mut self,
 8985        action: &SelectDownByLines,
 8986        window: &mut Window,
 8987        cx: &mut Context<Self>,
 8988    ) {
 8989        let text_layout_details = &self.text_layout_details(window);
 8990        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8991            s.move_heads_with(|map, head, goal| {
 8992                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8993            })
 8994        })
 8995    }
 8996
 8997    pub fn select_up_by_lines(
 8998        &mut self,
 8999        action: &SelectUpByLines,
 9000        window: &mut Window,
 9001        cx: &mut Context<Self>,
 9002    ) {
 9003        let text_layout_details = &self.text_layout_details(window);
 9004        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9005            s.move_heads_with(|map, head, goal| {
 9006                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9007            })
 9008        })
 9009    }
 9010
 9011    pub fn select_page_up(
 9012        &mut self,
 9013        _: &SelectPageUp,
 9014        window: &mut Window,
 9015        cx: &mut Context<Self>,
 9016    ) {
 9017        let Some(row_count) = self.visible_row_count() else {
 9018            return;
 9019        };
 9020
 9021        let text_layout_details = &self.text_layout_details(window);
 9022
 9023        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9024            s.move_heads_with(|map, head, goal| {
 9025                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 9026            })
 9027        })
 9028    }
 9029
 9030    pub fn move_page_up(
 9031        &mut self,
 9032        action: &MovePageUp,
 9033        window: &mut Window,
 9034        cx: &mut Context<Self>,
 9035    ) {
 9036        if self.take_rename(true, window, cx).is_some() {
 9037            return;
 9038        }
 9039
 9040        if self
 9041            .context_menu
 9042            .borrow_mut()
 9043            .as_mut()
 9044            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 9045            .unwrap_or(false)
 9046        {
 9047            return;
 9048        }
 9049
 9050        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9051            cx.propagate();
 9052            return;
 9053        }
 9054
 9055        let Some(row_count) = self.visible_row_count() else {
 9056            return;
 9057        };
 9058
 9059        let autoscroll = if action.center_cursor {
 9060            Autoscroll::center()
 9061        } else {
 9062            Autoscroll::fit()
 9063        };
 9064
 9065        let text_layout_details = &self.text_layout_details(window);
 9066
 9067        self.change_selections(Some(autoscroll), window, cx, |s| {
 9068            let line_mode = s.line_mode;
 9069            s.move_with(|map, selection| {
 9070                if !selection.is_empty() && !line_mode {
 9071                    selection.goal = SelectionGoal::None;
 9072                }
 9073                let (cursor, goal) = movement::up_by_rows(
 9074                    map,
 9075                    selection.end,
 9076                    row_count,
 9077                    selection.goal,
 9078                    false,
 9079                    text_layout_details,
 9080                );
 9081                selection.collapse_to(cursor, goal);
 9082            });
 9083        });
 9084    }
 9085
 9086    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 9087        let text_layout_details = &self.text_layout_details(window);
 9088        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9089            s.move_heads_with(|map, head, goal| {
 9090                movement::up(map, head, goal, false, text_layout_details)
 9091            })
 9092        })
 9093    }
 9094
 9095    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 9096        self.take_rename(true, window, cx);
 9097
 9098        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9099            cx.propagate();
 9100            return;
 9101        }
 9102
 9103        let text_layout_details = &self.text_layout_details(window);
 9104        let selection_count = self.selections.count();
 9105        let first_selection = self.selections.first_anchor();
 9106
 9107        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9108            let line_mode = s.line_mode;
 9109            s.move_with(|map, selection| {
 9110                if !selection.is_empty() && !line_mode {
 9111                    selection.goal = SelectionGoal::None;
 9112                }
 9113                let (cursor, goal) = movement::down(
 9114                    map,
 9115                    selection.end,
 9116                    selection.goal,
 9117                    false,
 9118                    text_layout_details,
 9119                );
 9120                selection.collapse_to(cursor, goal);
 9121            });
 9122        });
 9123
 9124        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9125        {
 9126            cx.propagate();
 9127        }
 9128    }
 9129
 9130    pub fn select_page_down(
 9131        &mut self,
 9132        _: &SelectPageDown,
 9133        window: &mut Window,
 9134        cx: &mut Context<Self>,
 9135    ) {
 9136        let Some(row_count) = self.visible_row_count() else {
 9137            return;
 9138        };
 9139
 9140        let text_layout_details = &self.text_layout_details(window);
 9141
 9142        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9143            s.move_heads_with(|map, head, goal| {
 9144                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 9145            })
 9146        })
 9147    }
 9148
 9149    pub fn move_page_down(
 9150        &mut self,
 9151        action: &MovePageDown,
 9152        window: &mut Window,
 9153        cx: &mut Context<Self>,
 9154    ) {
 9155        if self.take_rename(true, window, cx).is_some() {
 9156            return;
 9157        }
 9158
 9159        if self
 9160            .context_menu
 9161            .borrow_mut()
 9162            .as_mut()
 9163            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 9164            .unwrap_or(false)
 9165        {
 9166            return;
 9167        }
 9168
 9169        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9170            cx.propagate();
 9171            return;
 9172        }
 9173
 9174        let Some(row_count) = self.visible_row_count() else {
 9175            return;
 9176        };
 9177
 9178        let autoscroll = if action.center_cursor {
 9179            Autoscroll::center()
 9180        } else {
 9181            Autoscroll::fit()
 9182        };
 9183
 9184        let text_layout_details = &self.text_layout_details(window);
 9185        self.change_selections(Some(autoscroll), window, cx, |s| {
 9186            let line_mode = s.line_mode;
 9187            s.move_with(|map, selection| {
 9188                if !selection.is_empty() && !line_mode {
 9189                    selection.goal = SelectionGoal::None;
 9190                }
 9191                let (cursor, goal) = movement::down_by_rows(
 9192                    map,
 9193                    selection.end,
 9194                    row_count,
 9195                    selection.goal,
 9196                    false,
 9197                    text_layout_details,
 9198                );
 9199                selection.collapse_to(cursor, goal);
 9200            });
 9201        });
 9202    }
 9203
 9204    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 9205        let text_layout_details = &self.text_layout_details(window);
 9206        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9207            s.move_heads_with(|map, head, goal| {
 9208                movement::down(map, head, goal, false, text_layout_details)
 9209            })
 9210        });
 9211    }
 9212
 9213    pub fn context_menu_first(
 9214        &mut self,
 9215        _: &ContextMenuFirst,
 9216        _window: &mut Window,
 9217        cx: &mut Context<Self>,
 9218    ) {
 9219        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9220            context_menu.select_first(self.completion_provider.as_deref(), cx);
 9221        }
 9222    }
 9223
 9224    pub fn context_menu_prev(
 9225        &mut self,
 9226        _: &ContextMenuPrev,
 9227        _window: &mut Window,
 9228        cx: &mut Context<Self>,
 9229    ) {
 9230        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9231            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 9232        }
 9233    }
 9234
 9235    pub fn context_menu_next(
 9236        &mut self,
 9237        _: &ContextMenuNext,
 9238        _window: &mut Window,
 9239        cx: &mut Context<Self>,
 9240    ) {
 9241        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9242            context_menu.select_next(self.completion_provider.as_deref(), cx);
 9243        }
 9244    }
 9245
 9246    pub fn context_menu_last(
 9247        &mut self,
 9248        _: &ContextMenuLast,
 9249        _window: &mut Window,
 9250        cx: &mut Context<Self>,
 9251    ) {
 9252        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9253            context_menu.select_last(self.completion_provider.as_deref(), cx);
 9254        }
 9255    }
 9256
 9257    pub fn move_to_previous_word_start(
 9258        &mut self,
 9259        _: &MoveToPreviousWordStart,
 9260        window: &mut Window,
 9261        cx: &mut Context<Self>,
 9262    ) {
 9263        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9264            s.move_cursors_with(|map, head, _| {
 9265                (
 9266                    movement::previous_word_start(map, head),
 9267                    SelectionGoal::None,
 9268                )
 9269            });
 9270        })
 9271    }
 9272
 9273    pub fn move_to_previous_subword_start(
 9274        &mut self,
 9275        _: &MoveToPreviousSubwordStart,
 9276        window: &mut Window,
 9277        cx: &mut Context<Self>,
 9278    ) {
 9279        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9280            s.move_cursors_with(|map, head, _| {
 9281                (
 9282                    movement::previous_subword_start(map, head),
 9283                    SelectionGoal::None,
 9284                )
 9285            });
 9286        })
 9287    }
 9288
 9289    pub fn select_to_previous_word_start(
 9290        &mut self,
 9291        _: &SelectToPreviousWordStart,
 9292        window: &mut Window,
 9293        cx: &mut Context<Self>,
 9294    ) {
 9295        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9296            s.move_heads_with(|map, head, _| {
 9297                (
 9298                    movement::previous_word_start(map, head),
 9299                    SelectionGoal::None,
 9300                )
 9301            });
 9302        })
 9303    }
 9304
 9305    pub fn select_to_previous_subword_start(
 9306        &mut self,
 9307        _: &SelectToPreviousSubwordStart,
 9308        window: &mut Window,
 9309        cx: &mut Context<Self>,
 9310    ) {
 9311        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9312            s.move_heads_with(|map, head, _| {
 9313                (
 9314                    movement::previous_subword_start(map, head),
 9315                    SelectionGoal::None,
 9316                )
 9317            });
 9318        })
 9319    }
 9320
 9321    pub fn delete_to_previous_word_start(
 9322        &mut self,
 9323        action: &DeleteToPreviousWordStart,
 9324        window: &mut Window,
 9325        cx: &mut Context<Self>,
 9326    ) {
 9327        self.transact(window, cx, |this, window, cx| {
 9328            this.select_autoclose_pair(window, cx);
 9329            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9330                let line_mode = s.line_mode;
 9331                s.move_with(|map, selection| {
 9332                    if selection.is_empty() && !line_mode {
 9333                        let cursor = if action.ignore_newlines {
 9334                            movement::previous_word_start(map, selection.head())
 9335                        } else {
 9336                            movement::previous_word_start_or_newline(map, selection.head())
 9337                        };
 9338                        selection.set_head(cursor, SelectionGoal::None);
 9339                    }
 9340                });
 9341            });
 9342            this.insert("", window, cx);
 9343        });
 9344    }
 9345
 9346    pub fn delete_to_previous_subword_start(
 9347        &mut self,
 9348        _: &DeleteToPreviousSubwordStart,
 9349        window: &mut Window,
 9350        cx: &mut Context<Self>,
 9351    ) {
 9352        self.transact(window, cx, |this, window, cx| {
 9353            this.select_autoclose_pair(window, cx);
 9354            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9355                let line_mode = s.line_mode;
 9356                s.move_with(|map, selection| {
 9357                    if selection.is_empty() && !line_mode {
 9358                        let cursor = movement::previous_subword_start(map, selection.head());
 9359                        selection.set_head(cursor, SelectionGoal::None);
 9360                    }
 9361                });
 9362            });
 9363            this.insert("", window, cx);
 9364        });
 9365    }
 9366
 9367    pub fn move_to_next_word_end(
 9368        &mut self,
 9369        _: &MoveToNextWordEnd,
 9370        window: &mut Window,
 9371        cx: &mut Context<Self>,
 9372    ) {
 9373        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9374            s.move_cursors_with(|map, head, _| {
 9375                (movement::next_word_end(map, head), SelectionGoal::None)
 9376            });
 9377        })
 9378    }
 9379
 9380    pub fn move_to_next_subword_end(
 9381        &mut self,
 9382        _: &MoveToNextSubwordEnd,
 9383        window: &mut Window,
 9384        cx: &mut Context<Self>,
 9385    ) {
 9386        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9387            s.move_cursors_with(|map, head, _| {
 9388                (movement::next_subword_end(map, head), SelectionGoal::None)
 9389            });
 9390        })
 9391    }
 9392
 9393    pub fn select_to_next_word_end(
 9394        &mut self,
 9395        _: &SelectToNextWordEnd,
 9396        window: &mut Window,
 9397        cx: &mut Context<Self>,
 9398    ) {
 9399        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9400            s.move_heads_with(|map, head, _| {
 9401                (movement::next_word_end(map, head), SelectionGoal::None)
 9402            });
 9403        })
 9404    }
 9405
 9406    pub fn select_to_next_subword_end(
 9407        &mut self,
 9408        _: &SelectToNextSubwordEnd,
 9409        window: &mut Window,
 9410        cx: &mut Context<Self>,
 9411    ) {
 9412        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9413            s.move_heads_with(|map, head, _| {
 9414                (movement::next_subword_end(map, head), SelectionGoal::None)
 9415            });
 9416        })
 9417    }
 9418
 9419    pub fn delete_to_next_word_end(
 9420        &mut self,
 9421        action: &DeleteToNextWordEnd,
 9422        window: &mut Window,
 9423        cx: &mut Context<Self>,
 9424    ) {
 9425        self.transact(window, cx, |this, window, cx| {
 9426            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9427                let line_mode = s.line_mode;
 9428                s.move_with(|map, selection| {
 9429                    if selection.is_empty() && !line_mode {
 9430                        let cursor = if action.ignore_newlines {
 9431                            movement::next_word_end(map, selection.head())
 9432                        } else {
 9433                            movement::next_word_end_or_newline(map, selection.head())
 9434                        };
 9435                        selection.set_head(cursor, SelectionGoal::None);
 9436                    }
 9437                });
 9438            });
 9439            this.insert("", window, cx);
 9440        });
 9441    }
 9442
 9443    pub fn delete_to_next_subword_end(
 9444        &mut self,
 9445        _: &DeleteToNextSubwordEnd,
 9446        window: &mut Window,
 9447        cx: &mut Context<Self>,
 9448    ) {
 9449        self.transact(window, cx, |this, window, cx| {
 9450            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9451                s.move_with(|map, selection| {
 9452                    if selection.is_empty() {
 9453                        let cursor = movement::next_subword_end(map, selection.head());
 9454                        selection.set_head(cursor, SelectionGoal::None);
 9455                    }
 9456                });
 9457            });
 9458            this.insert("", window, cx);
 9459        });
 9460    }
 9461
 9462    pub fn move_to_beginning_of_line(
 9463        &mut self,
 9464        action: &MoveToBeginningOfLine,
 9465        window: &mut Window,
 9466        cx: &mut Context<Self>,
 9467    ) {
 9468        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9469            s.move_cursors_with(|map, head, _| {
 9470                (
 9471                    movement::indented_line_beginning(
 9472                        map,
 9473                        head,
 9474                        action.stop_at_soft_wraps,
 9475                        action.stop_at_indent,
 9476                    ),
 9477                    SelectionGoal::None,
 9478                )
 9479            });
 9480        })
 9481    }
 9482
 9483    pub fn select_to_beginning_of_line(
 9484        &mut self,
 9485        action: &SelectToBeginningOfLine,
 9486        window: &mut Window,
 9487        cx: &mut Context<Self>,
 9488    ) {
 9489        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9490            s.move_heads_with(|map, head, _| {
 9491                (
 9492                    movement::indented_line_beginning(
 9493                        map,
 9494                        head,
 9495                        action.stop_at_soft_wraps,
 9496                        action.stop_at_indent,
 9497                    ),
 9498                    SelectionGoal::None,
 9499                )
 9500            });
 9501        });
 9502    }
 9503
 9504    pub fn delete_to_beginning_of_line(
 9505        &mut self,
 9506        _: &DeleteToBeginningOfLine,
 9507        window: &mut Window,
 9508        cx: &mut Context<Self>,
 9509    ) {
 9510        self.transact(window, cx, |this, window, cx| {
 9511            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9512                s.move_with(|_, selection| {
 9513                    selection.reversed = true;
 9514                });
 9515            });
 9516
 9517            this.select_to_beginning_of_line(
 9518                &SelectToBeginningOfLine {
 9519                    stop_at_soft_wraps: false,
 9520                    stop_at_indent: false,
 9521                },
 9522                window,
 9523                cx,
 9524            );
 9525            this.backspace(&Backspace, window, cx);
 9526        });
 9527    }
 9528
 9529    pub fn move_to_end_of_line(
 9530        &mut self,
 9531        action: &MoveToEndOfLine,
 9532        window: &mut Window,
 9533        cx: &mut Context<Self>,
 9534    ) {
 9535        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9536            s.move_cursors_with(|map, head, _| {
 9537                (
 9538                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9539                    SelectionGoal::None,
 9540                )
 9541            });
 9542        })
 9543    }
 9544
 9545    pub fn select_to_end_of_line(
 9546        &mut self,
 9547        action: &SelectToEndOfLine,
 9548        window: &mut Window,
 9549        cx: &mut Context<Self>,
 9550    ) {
 9551        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9552            s.move_heads_with(|map, head, _| {
 9553                (
 9554                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9555                    SelectionGoal::None,
 9556                )
 9557            });
 9558        })
 9559    }
 9560
 9561    pub fn delete_to_end_of_line(
 9562        &mut self,
 9563        _: &DeleteToEndOfLine,
 9564        window: &mut Window,
 9565        cx: &mut Context<Self>,
 9566    ) {
 9567        self.transact(window, cx, |this, window, cx| {
 9568            this.select_to_end_of_line(
 9569                &SelectToEndOfLine {
 9570                    stop_at_soft_wraps: false,
 9571                },
 9572                window,
 9573                cx,
 9574            );
 9575            this.delete(&Delete, window, cx);
 9576        });
 9577    }
 9578
 9579    pub fn cut_to_end_of_line(
 9580        &mut self,
 9581        _: &CutToEndOfLine,
 9582        window: &mut Window,
 9583        cx: &mut Context<Self>,
 9584    ) {
 9585        self.transact(window, cx, |this, window, cx| {
 9586            this.select_to_end_of_line(
 9587                &SelectToEndOfLine {
 9588                    stop_at_soft_wraps: false,
 9589                },
 9590                window,
 9591                cx,
 9592            );
 9593            this.cut(&Cut, window, cx);
 9594        });
 9595    }
 9596
 9597    pub fn move_to_start_of_paragraph(
 9598        &mut self,
 9599        _: &MoveToStartOfParagraph,
 9600        window: &mut Window,
 9601        cx: &mut Context<Self>,
 9602    ) {
 9603        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9604            cx.propagate();
 9605            return;
 9606        }
 9607
 9608        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9609            s.move_with(|map, selection| {
 9610                selection.collapse_to(
 9611                    movement::start_of_paragraph(map, selection.head(), 1),
 9612                    SelectionGoal::None,
 9613                )
 9614            });
 9615        })
 9616    }
 9617
 9618    pub fn move_to_end_of_paragraph(
 9619        &mut self,
 9620        _: &MoveToEndOfParagraph,
 9621        window: &mut Window,
 9622        cx: &mut Context<Self>,
 9623    ) {
 9624        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9625            cx.propagate();
 9626            return;
 9627        }
 9628
 9629        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9630            s.move_with(|map, selection| {
 9631                selection.collapse_to(
 9632                    movement::end_of_paragraph(map, selection.head(), 1),
 9633                    SelectionGoal::None,
 9634                )
 9635            });
 9636        })
 9637    }
 9638
 9639    pub fn select_to_start_of_paragraph(
 9640        &mut self,
 9641        _: &SelectToStartOfParagraph,
 9642        window: &mut Window,
 9643        cx: &mut Context<Self>,
 9644    ) {
 9645        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9646            cx.propagate();
 9647            return;
 9648        }
 9649
 9650        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9651            s.move_heads_with(|map, head, _| {
 9652                (
 9653                    movement::start_of_paragraph(map, head, 1),
 9654                    SelectionGoal::None,
 9655                )
 9656            });
 9657        })
 9658    }
 9659
 9660    pub fn select_to_end_of_paragraph(
 9661        &mut self,
 9662        _: &SelectToEndOfParagraph,
 9663        window: &mut Window,
 9664        cx: &mut Context<Self>,
 9665    ) {
 9666        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9667            cx.propagate();
 9668            return;
 9669        }
 9670
 9671        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9672            s.move_heads_with(|map, head, _| {
 9673                (
 9674                    movement::end_of_paragraph(map, head, 1),
 9675                    SelectionGoal::None,
 9676                )
 9677            });
 9678        })
 9679    }
 9680
 9681    pub fn move_to_start_of_excerpt(
 9682        &mut self,
 9683        _: &MoveToStartOfExcerpt,
 9684        window: &mut Window,
 9685        cx: &mut Context<Self>,
 9686    ) {
 9687        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9688            cx.propagate();
 9689            return;
 9690        }
 9691
 9692        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9693            s.move_with(|map, selection| {
 9694                selection.collapse_to(
 9695                    movement::start_of_excerpt(
 9696                        map,
 9697                        selection.head(),
 9698                        workspace::searchable::Direction::Prev,
 9699                    ),
 9700                    SelectionGoal::None,
 9701                )
 9702            });
 9703        })
 9704    }
 9705
 9706    pub fn move_to_end_of_excerpt(
 9707        &mut self,
 9708        _: &MoveToEndOfExcerpt,
 9709        window: &mut Window,
 9710        cx: &mut Context<Self>,
 9711    ) {
 9712        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9713            cx.propagate();
 9714            return;
 9715        }
 9716
 9717        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9718            s.move_with(|map, selection| {
 9719                selection.collapse_to(
 9720                    movement::end_of_excerpt(
 9721                        map,
 9722                        selection.head(),
 9723                        workspace::searchable::Direction::Next,
 9724                    ),
 9725                    SelectionGoal::None,
 9726                )
 9727            });
 9728        })
 9729    }
 9730
 9731    pub fn select_to_start_of_excerpt(
 9732        &mut self,
 9733        _: &SelectToStartOfExcerpt,
 9734        window: &mut Window,
 9735        cx: &mut Context<Self>,
 9736    ) {
 9737        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9738            cx.propagate();
 9739            return;
 9740        }
 9741
 9742        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9743            s.move_heads_with(|map, head, _| {
 9744                (
 9745                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
 9746                    SelectionGoal::None,
 9747                )
 9748            });
 9749        })
 9750    }
 9751
 9752    pub fn select_to_end_of_excerpt(
 9753        &mut self,
 9754        _: &SelectToEndOfExcerpt,
 9755        window: &mut Window,
 9756        cx: &mut Context<Self>,
 9757    ) {
 9758        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9759            cx.propagate();
 9760            return;
 9761        }
 9762
 9763        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9764            s.move_heads_with(|map, head, _| {
 9765                (
 9766                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
 9767                    SelectionGoal::None,
 9768                )
 9769            });
 9770        })
 9771    }
 9772
 9773    pub fn move_to_beginning(
 9774        &mut self,
 9775        _: &MoveToBeginning,
 9776        window: &mut Window,
 9777        cx: &mut Context<Self>,
 9778    ) {
 9779        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9780            cx.propagate();
 9781            return;
 9782        }
 9783
 9784        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9785            s.select_ranges(vec![0..0]);
 9786        });
 9787    }
 9788
 9789    pub fn select_to_beginning(
 9790        &mut self,
 9791        _: &SelectToBeginning,
 9792        window: &mut Window,
 9793        cx: &mut Context<Self>,
 9794    ) {
 9795        let mut selection = self.selections.last::<Point>(cx);
 9796        selection.set_head(Point::zero(), SelectionGoal::None);
 9797
 9798        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9799            s.select(vec![selection]);
 9800        });
 9801    }
 9802
 9803    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9804        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9805            cx.propagate();
 9806            return;
 9807        }
 9808
 9809        let cursor = self.buffer.read(cx).read(cx).len();
 9810        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9811            s.select_ranges(vec![cursor..cursor])
 9812        });
 9813    }
 9814
 9815    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9816        self.nav_history = nav_history;
 9817    }
 9818
 9819    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9820        self.nav_history.as_ref()
 9821    }
 9822
 9823    fn push_to_nav_history(
 9824        &mut self,
 9825        cursor_anchor: Anchor,
 9826        new_position: Option<Point>,
 9827        cx: &mut Context<Self>,
 9828    ) {
 9829        if let Some(nav_history) = self.nav_history.as_mut() {
 9830            let buffer = self.buffer.read(cx).read(cx);
 9831            let cursor_position = cursor_anchor.to_point(&buffer);
 9832            let scroll_state = self.scroll_manager.anchor();
 9833            let scroll_top_row = scroll_state.top_row(&buffer);
 9834            drop(buffer);
 9835
 9836            if let Some(new_position) = new_position {
 9837                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9838                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9839                    return;
 9840                }
 9841            }
 9842
 9843            nav_history.push(
 9844                Some(NavigationData {
 9845                    cursor_anchor,
 9846                    cursor_position,
 9847                    scroll_anchor: scroll_state,
 9848                    scroll_top_row,
 9849                }),
 9850                cx,
 9851            );
 9852        }
 9853    }
 9854
 9855    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9856        let buffer = self.buffer.read(cx).snapshot(cx);
 9857        let mut selection = self.selections.first::<usize>(cx);
 9858        selection.set_head(buffer.len(), SelectionGoal::None);
 9859        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9860            s.select(vec![selection]);
 9861        });
 9862    }
 9863
 9864    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9865        let end = self.buffer.read(cx).read(cx).len();
 9866        self.change_selections(None, window, cx, |s| {
 9867            s.select_ranges(vec![0..end]);
 9868        });
 9869    }
 9870
 9871    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9872        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9873        let mut selections = self.selections.all::<Point>(cx);
 9874        let max_point = display_map.buffer_snapshot.max_point();
 9875        for selection in &mut selections {
 9876            let rows = selection.spanned_rows(true, &display_map);
 9877            selection.start = Point::new(rows.start.0, 0);
 9878            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9879            selection.reversed = false;
 9880        }
 9881        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9882            s.select(selections);
 9883        });
 9884    }
 9885
 9886    pub fn split_selection_into_lines(
 9887        &mut self,
 9888        _: &SplitSelectionIntoLines,
 9889        window: &mut Window,
 9890        cx: &mut Context<Self>,
 9891    ) {
 9892        let selections = self
 9893            .selections
 9894            .all::<Point>(cx)
 9895            .into_iter()
 9896            .map(|selection| selection.start..selection.end)
 9897            .collect::<Vec<_>>();
 9898        self.unfold_ranges(&selections, true, true, cx);
 9899
 9900        let mut new_selection_ranges = Vec::new();
 9901        {
 9902            let buffer = self.buffer.read(cx).read(cx);
 9903            for selection in selections {
 9904                for row in selection.start.row..selection.end.row {
 9905                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9906                    new_selection_ranges.push(cursor..cursor);
 9907                }
 9908
 9909                let is_multiline_selection = selection.start.row != selection.end.row;
 9910                // Don't insert last one if it's a multi-line selection ending at the start of a line,
 9911                // so this action feels more ergonomic when paired with other selection operations
 9912                let should_skip_last = is_multiline_selection && selection.end.column == 0;
 9913                if !should_skip_last {
 9914                    new_selection_ranges.push(selection.end..selection.end);
 9915                }
 9916            }
 9917        }
 9918        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9919            s.select_ranges(new_selection_ranges);
 9920        });
 9921    }
 9922
 9923    pub fn add_selection_above(
 9924        &mut self,
 9925        _: &AddSelectionAbove,
 9926        window: &mut Window,
 9927        cx: &mut Context<Self>,
 9928    ) {
 9929        self.add_selection(true, window, cx);
 9930    }
 9931
 9932    pub fn add_selection_below(
 9933        &mut self,
 9934        _: &AddSelectionBelow,
 9935        window: &mut Window,
 9936        cx: &mut Context<Self>,
 9937    ) {
 9938        self.add_selection(false, window, cx);
 9939    }
 9940
 9941    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9942        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9943        let mut selections = self.selections.all::<Point>(cx);
 9944        let text_layout_details = self.text_layout_details(window);
 9945        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9946            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9947            let range = oldest_selection.display_range(&display_map).sorted();
 9948
 9949            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9950            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9951            let positions = start_x.min(end_x)..start_x.max(end_x);
 9952
 9953            selections.clear();
 9954            let mut stack = Vec::new();
 9955            for row in range.start.row().0..=range.end.row().0 {
 9956                if let Some(selection) = self.selections.build_columnar_selection(
 9957                    &display_map,
 9958                    DisplayRow(row),
 9959                    &positions,
 9960                    oldest_selection.reversed,
 9961                    &text_layout_details,
 9962                ) {
 9963                    stack.push(selection.id);
 9964                    selections.push(selection);
 9965                }
 9966            }
 9967
 9968            if above {
 9969                stack.reverse();
 9970            }
 9971
 9972            AddSelectionsState { above, stack }
 9973        });
 9974
 9975        let last_added_selection = *state.stack.last().unwrap();
 9976        let mut new_selections = Vec::new();
 9977        if above == state.above {
 9978            let end_row = if above {
 9979                DisplayRow(0)
 9980            } else {
 9981                display_map.max_point().row()
 9982            };
 9983
 9984            'outer: for selection in selections {
 9985                if selection.id == last_added_selection {
 9986                    let range = selection.display_range(&display_map).sorted();
 9987                    debug_assert_eq!(range.start.row(), range.end.row());
 9988                    let mut row = range.start.row();
 9989                    let positions =
 9990                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9991                            px(start)..px(end)
 9992                        } else {
 9993                            let start_x =
 9994                                display_map.x_for_display_point(range.start, &text_layout_details);
 9995                            let end_x =
 9996                                display_map.x_for_display_point(range.end, &text_layout_details);
 9997                            start_x.min(end_x)..start_x.max(end_x)
 9998                        };
 9999
10000                    while row != end_row {
10001                        if above {
10002                            row.0 -= 1;
10003                        } else {
10004                            row.0 += 1;
10005                        }
10006
10007                        if let Some(new_selection) = self.selections.build_columnar_selection(
10008                            &display_map,
10009                            row,
10010                            &positions,
10011                            selection.reversed,
10012                            &text_layout_details,
10013                        ) {
10014                            state.stack.push(new_selection.id);
10015                            if above {
10016                                new_selections.push(new_selection);
10017                                new_selections.push(selection);
10018                            } else {
10019                                new_selections.push(selection);
10020                                new_selections.push(new_selection);
10021                            }
10022
10023                            continue 'outer;
10024                        }
10025                    }
10026                }
10027
10028                new_selections.push(selection);
10029            }
10030        } else {
10031            new_selections = selections;
10032            new_selections.retain(|s| s.id != last_added_selection);
10033            state.stack.pop();
10034        }
10035
10036        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10037            s.select(new_selections);
10038        });
10039        if state.stack.len() > 1 {
10040            self.add_selections_state = Some(state);
10041        }
10042    }
10043
10044    pub fn select_next_match_internal(
10045        &mut self,
10046        display_map: &DisplaySnapshot,
10047        replace_newest: bool,
10048        autoscroll: Option<Autoscroll>,
10049        window: &mut Window,
10050        cx: &mut Context<Self>,
10051    ) -> Result<()> {
10052        fn select_next_match_ranges(
10053            this: &mut Editor,
10054            range: Range<usize>,
10055            replace_newest: bool,
10056            auto_scroll: Option<Autoscroll>,
10057            window: &mut Window,
10058            cx: &mut Context<Editor>,
10059        ) {
10060            this.unfold_ranges(&[range.clone()], false, true, cx);
10061            this.change_selections(auto_scroll, window, cx, |s| {
10062                if replace_newest {
10063                    s.delete(s.newest_anchor().id);
10064                }
10065                s.insert_range(range.clone());
10066            });
10067        }
10068
10069        let buffer = &display_map.buffer_snapshot;
10070        let mut selections = self.selections.all::<usize>(cx);
10071        if let Some(mut select_next_state) = self.select_next_state.take() {
10072            let query = &select_next_state.query;
10073            if !select_next_state.done {
10074                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10075                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10076                let mut next_selected_range = None;
10077
10078                let bytes_after_last_selection =
10079                    buffer.bytes_in_range(last_selection.end..buffer.len());
10080                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10081                let query_matches = query
10082                    .stream_find_iter(bytes_after_last_selection)
10083                    .map(|result| (last_selection.end, result))
10084                    .chain(
10085                        query
10086                            .stream_find_iter(bytes_before_first_selection)
10087                            .map(|result| (0, result)),
10088                    );
10089
10090                for (start_offset, query_match) in query_matches {
10091                    let query_match = query_match.unwrap(); // can only fail due to I/O
10092                    let offset_range =
10093                        start_offset + query_match.start()..start_offset + query_match.end();
10094                    let display_range = offset_range.start.to_display_point(display_map)
10095                        ..offset_range.end.to_display_point(display_map);
10096
10097                    if !select_next_state.wordwise
10098                        || (!movement::is_inside_word(display_map, display_range.start)
10099                            && !movement::is_inside_word(display_map, display_range.end))
10100                    {
10101                        // TODO: This is n^2, because we might check all the selections
10102                        if !selections
10103                            .iter()
10104                            .any(|selection| selection.range().overlaps(&offset_range))
10105                        {
10106                            next_selected_range = Some(offset_range);
10107                            break;
10108                        }
10109                    }
10110                }
10111
10112                if let Some(next_selected_range) = next_selected_range {
10113                    select_next_match_ranges(
10114                        self,
10115                        next_selected_range,
10116                        replace_newest,
10117                        autoscroll,
10118                        window,
10119                        cx,
10120                    );
10121                } else {
10122                    select_next_state.done = true;
10123                }
10124            }
10125
10126            self.select_next_state = Some(select_next_state);
10127        } else {
10128            let mut only_carets = true;
10129            let mut same_text_selected = true;
10130            let mut selected_text = None;
10131
10132            let mut selections_iter = selections.iter().peekable();
10133            while let Some(selection) = selections_iter.next() {
10134                if selection.start != selection.end {
10135                    only_carets = false;
10136                }
10137
10138                if same_text_selected {
10139                    if selected_text.is_none() {
10140                        selected_text =
10141                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10142                    }
10143
10144                    if let Some(next_selection) = selections_iter.peek() {
10145                        if next_selection.range().len() == selection.range().len() {
10146                            let next_selected_text = buffer
10147                                .text_for_range(next_selection.range())
10148                                .collect::<String>();
10149                            if Some(next_selected_text) != selected_text {
10150                                same_text_selected = false;
10151                                selected_text = None;
10152                            }
10153                        } else {
10154                            same_text_selected = false;
10155                            selected_text = None;
10156                        }
10157                    }
10158                }
10159            }
10160
10161            if only_carets {
10162                for selection in &mut selections {
10163                    let word_range = movement::surrounding_word(
10164                        display_map,
10165                        selection.start.to_display_point(display_map),
10166                    );
10167                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
10168                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
10169                    selection.goal = SelectionGoal::None;
10170                    selection.reversed = false;
10171                    select_next_match_ranges(
10172                        self,
10173                        selection.start..selection.end,
10174                        replace_newest,
10175                        autoscroll,
10176                        window,
10177                        cx,
10178                    );
10179                }
10180
10181                if selections.len() == 1 {
10182                    let selection = selections
10183                        .last()
10184                        .expect("ensured that there's only one selection");
10185                    let query = buffer
10186                        .text_for_range(selection.start..selection.end)
10187                        .collect::<String>();
10188                    let is_empty = query.is_empty();
10189                    let select_state = SelectNextState {
10190                        query: AhoCorasick::new(&[query])?,
10191                        wordwise: true,
10192                        done: is_empty,
10193                    };
10194                    self.select_next_state = Some(select_state);
10195                } else {
10196                    self.select_next_state = None;
10197                }
10198            } else if let Some(selected_text) = selected_text {
10199                self.select_next_state = Some(SelectNextState {
10200                    query: AhoCorasick::new(&[selected_text])?,
10201                    wordwise: false,
10202                    done: false,
10203                });
10204                self.select_next_match_internal(
10205                    display_map,
10206                    replace_newest,
10207                    autoscroll,
10208                    window,
10209                    cx,
10210                )?;
10211            }
10212        }
10213        Ok(())
10214    }
10215
10216    pub fn select_all_matches(
10217        &mut self,
10218        _action: &SelectAllMatches,
10219        window: &mut Window,
10220        cx: &mut Context<Self>,
10221    ) -> Result<()> {
10222        self.push_to_selection_history();
10223        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10224
10225        self.select_next_match_internal(&display_map, false, None, window, cx)?;
10226        let Some(select_next_state) = self.select_next_state.as_mut() else {
10227            return Ok(());
10228        };
10229        if select_next_state.done {
10230            return Ok(());
10231        }
10232
10233        let mut new_selections = self.selections.all::<usize>(cx);
10234
10235        let buffer = &display_map.buffer_snapshot;
10236        let query_matches = select_next_state
10237            .query
10238            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10239
10240        for query_match in query_matches {
10241            let query_match = query_match.unwrap(); // can only fail due to I/O
10242            let offset_range = query_match.start()..query_match.end();
10243            let display_range = offset_range.start.to_display_point(&display_map)
10244                ..offset_range.end.to_display_point(&display_map);
10245
10246            if !select_next_state.wordwise
10247                || (!movement::is_inside_word(&display_map, display_range.start)
10248                    && !movement::is_inside_word(&display_map, display_range.end))
10249            {
10250                self.selections.change_with(cx, |selections| {
10251                    new_selections.push(Selection {
10252                        id: selections.new_selection_id(),
10253                        start: offset_range.start,
10254                        end: offset_range.end,
10255                        reversed: false,
10256                        goal: SelectionGoal::None,
10257                    });
10258                });
10259            }
10260        }
10261
10262        new_selections.sort_by_key(|selection| selection.start);
10263        let mut ix = 0;
10264        while ix + 1 < new_selections.len() {
10265            let current_selection = &new_selections[ix];
10266            let next_selection = &new_selections[ix + 1];
10267            if current_selection.range().overlaps(&next_selection.range()) {
10268                if current_selection.id < next_selection.id {
10269                    new_selections.remove(ix + 1);
10270                } else {
10271                    new_selections.remove(ix);
10272                }
10273            } else {
10274                ix += 1;
10275            }
10276        }
10277
10278        let reversed = self.selections.oldest::<usize>(cx).reversed;
10279
10280        for selection in new_selections.iter_mut() {
10281            selection.reversed = reversed;
10282        }
10283
10284        select_next_state.done = true;
10285        self.unfold_ranges(
10286            &new_selections
10287                .iter()
10288                .map(|selection| selection.range())
10289                .collect::<Vec<_>>(),
10290            false,
10291            false,
10292            cx,
10293        );
10294        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10295            selections.select(new_selections)
10296        });
10297
10298        Ok(())
10299    }
10300
10301    pub fn select_next(
10302        &mut self,
10303        action: &SelectNext,
10304        window: &mut Window,
10305        cx: &mut Context<Self>,
10306    ) -> Result<()> {
10307        self.push_to_selection_history();
10308        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10309        self.select_next_match_internal(
10310            &display_map,
10311            action.replace_newest,
10312            Some(Autoscroll::newest()),
10313            window,
10314            cx,
10315        )?;
10316        Ok(())
10317    }
10318
10319    pub fn select_previous(
10320        &mut self,
10321        action: &SelectPrevious,
10322        window: &mut Window,
10323        cx: &mut Context<Self>,
10324    ) -> Result<()> {
10325        self.push_to_selection_history();
10326        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10327        let buffer = &display_map.buffer_snapshot;
10328        let mut selections = self.selections.all::<usize>(cx);
10329        if let Some(mut select_prev_state) = self.select_prev_state.take() {
10330            let query = &select_prev_state.query;
10331            if !select_prev_state.done {
10332                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10333                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10334                let mut next_selected_range = None;
10335                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10336                let bytes_before_last_selection =
10337                    buffer.reversed_bytes_in_range(0..last_selection.start);
10338                let bytes_after_first_selection =
10339                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10340                let query_matches = query
10341                    .stream_find_iter(bytes_before_last_selection)
10342                    .map(|result| (last_selection.start, result))
10343                    .chain(
10344                        query
10345                            .stream_find_iter(bytes_after_first_selection)
10346                            .map(|result| (buffer.len(), result)),
10347                    );
10348                for (end_offset, query_match) in query_matches {
10349                    let query_match = query_match.unwrap(); // can only fail due to I/O
10350                    let offset_range =
10351                        end_offset - query_match.end()..end_offset - query_match.start();
10352                    let display_range = offset_range.start.to_display_point(&display_map)
10353                        ..offset_range.end.to_display_point(&display_map);
10354
10355                    if !select_prev_state.wordwise
10356                        || (!movement::is_inside_word(&display_map, display_range.start)
10357                            && !movement::is_inside_word(&display_map, display_range.end))
10358                    {
10359                        next_selected_range = Some(offset_range);
10360                        break;
10361                    }
10362                }
10363
10364                if let Some(next_selected_range) = next_selected_range {
10365                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10366                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10367                        if action.replace_newest {
10368                            s.delete(s.newest_anchor().id);
10369                        }
10370                        s.insert_range(next_selected_range);
10371                    });
10372                } else {
10373                    select_prev_state.done = true;
10374                }
10375            }
10376
10377            self.select_prev_state = Some(select_prev_state);
10378        } else {
10379            let mut only_carets = true;
10380            let mut same_text_selected = true;
10381            let mut selected_text = None;
10382
10383            let mut selections_iter = selections.iter().peekable();
10384            while let Some(selection) = selections_iter.next() {
10385                if selection.start != selection.end {
10386                    only_carets = false;
10387                }
10388
10389                if same_text_selected {
10390                    if selected_text.is_none() {
10391                        selected_text =
10392                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10393                    }
10394
10395                    if let Some(next_selection) = selections_iter.peek() {
10396                        if next_selection.range().len() == selection.range().len() {
10397                            let next_selected_text = buffer
10398                                .text_for_range(next_selection.range())
10399                                .collect::<String>();
10400                            if Some(next_selected_text) != selected_text {
10401                                same_text_selected = false;
10402                                selected_text = None;
10403                            }
10404                        } else {
10405                            same_text_selected = false;
10406                            selected_text = None;
10407                        }
10408                    }
10409                }
10410            }
10411
10412            if only_carets {
10413                for selection in &mut selections {
10414                    let word_range = movement::surrounding_word(
10415                        &display_map,
10416                        selection.start.to_display_point(&display_map),
10417                    );
10418                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10419                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10420                    selection.goal = SelectionGoal::None;
10421                    selection.reversed = false;
10422                }
10423                if selections.len() == 1 {
10424                    let selection = selections
10425                        .last()
10426                        .expect("ensured that there's only one selection");
10427                    let query = buffer
10428                        .text_for_range(selection.start..selection.end)
10429                        .collect::<String>();
10430                    let is_empty = query.is_empty();
10431                    let select_state = SelectNextState {
10432                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10433                        wordwise: true,
10434                        done: is_empty,
10435                    };
10436                    self.select_prev_state = Some(select_state);
10437                } else {
10438                    self.select_prev_state = None;
10439                }
10440
10441                self.unfold_ranges(
10442                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10443                    false,
10444                    true,
10445                    cx,
10446                );
10447                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10448                    s.select(selections);
10449                });
10450            } else if let Some(selected_text) = selected_text {
10451                self.select_prev_state = Some(SelectNextState {
10452                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10453                    wordwise: false,
10454                    done: false,
10455                });
10456                self.select_previous(action, window, cx)?;
10457            }
10458        }
10459        Ok(())
10460    }
10461
10462    pub fn toggle_comments(
10463        &mut self,
10464        action: &ToggleComments,
10465        window: &mut Window,
10466        cx: &mut Context<Self>,
10467    ) {
10468        if self.read_only(cx) {
10469            return;
10470        }
10471        let text_layout_details = &self.text_layout_details(window);
10472        self.transact(window, cx, |this, window, cx| {
10473            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10474            let mut edits = Vec::new();
10475            let mut selection_edit_ranges = Vec::new();
10476            let mut last_toggled_row = None;
10477            let snapshot = this.buffer.read(cx).read(cx);
10478            let empty_str: Arc<str> = Arc::default();
10479            let mut suffixes_inserted = Vec::new();
10480            let ignore_indent = action.ignore_indent;
10481
10482            fn comment_prefix_range(
10483                snapshot: &MultiBufferSnapshot,
10484                row: MultiBufferRow,
10485                comment_prefix: &str,
10486                comment_prefix_whitespace: &str,
10487                ignore_indent: bool,
10488            ) -> Range<Point> {
10489                let indent_size = if ignore_indent {
10490                    0
10491                } else {
10492                    snapshot.indent_size_for_line(row).len
10493                };
10494
10495                let start = Point::new(row.0, indent_size);
10496
10497                let mut line_bytes = snapshot
10498                    .bytes_in_range(start..snapshot.max_point())
10499                    .flatten()
10500                    .copied();
10501
10502                // If this line currently begins with the line comment prefix, then record
10503                // the range containing the prefix.
10504                if line_bytes
10505                    .by_ref()
10506                    .take(comment_prefix.len())
10507                    .eq(comment_prefix.bytes())
10508                {
10509                    // Include any whitespace that matches the comment prefix.
10510                    let matching_whitespace_len = line_bytes
10511                        .zip(comment_prefix_whitespace.bytes())
10512                        .take_while(|(a, b)| a == b)
10513                        .count() as u32;
10514                    let end = Point::new(
10515                        start.row,
10516                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10517                    );
10518                    start..end
10519                } else {
10520                    start..start
10521                }
10522            }
10523
10524            fn comment_suffix_range(
10525                snapshot: &MultiBufferSnapshot,
10526                row: MultiBufferRow,
10527                comment_suffix: &str,
10528                comment_suffix_has_leading_space: bool,
10529            ) -> Range<Point> {
10530                let end = Point::new(row.0, snapshot.line_len(row));
10531                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10532
10533                let mut line_end_bytes = snapshot
10534                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10535                    .flatten()
10536                    .copied();
10537
10538                let leading_space_len = if suffix_start_column > 0
10539                    && line_end_bytes.next() == Some(b' ')
10540                    && comment_suffix_has_leading_space
10541                {
10542                    1
10543                } else {
10544                    0
10545                };
10546
10547                // If this line currently begins with the line comment prefix, then record
10548                // the range containing the prefix.
10549                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10550                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
10551                    start..end
10552                } else {
10553                    end..end
10554                }
10555            }
10556
10557            // TODO: Handle selections that cross excerpts
10558            for selection in &mut selections {
10559                let start_column = snapshot
10560                    .indent_size_for_line(MultiBufferRow(selection.start.row))
10561                    .len;
10562                let language = if let Some(language) =
10563                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10564                {
10565                    language
10566                } else {
10567                    continue;
10568                };
10569
10570                selection_edit_ranges.clear();
10571
10572                // If multiple selections contain a given row, avoid processing that
10573                // row more than once.
10574                let mut start_row = MultiBufferRow(selection.start.row);
10575                if last_toggled_row == Some(start_row) {
10576                    start_row = start_row.next_row();
10577                }
10578                let end_row =
10579                    if selection.end.row > selection.start.row && selection.end.column == 0 {
10580                        MultiBufferRow(selection.end.row - 1)
10581                    } else {
10582                        MultiBufferRow(selection.end.row)
10583                    };
10584                last_toggled_row = Some(end_row);
10585
10586                if start_row > end_row {
10587                    continue;
10588                }
10589
10590                // If the language has line comments, toggle those.
10591                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10592
10593                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10594                if ignore_indent {
10595                    full_comment_prefixes = full_comment_prefixes
10596                        .into_iter()
10597                        .map(|s| Arc::from(s.trim_end()))
10598                        .collect();
10599                }
10600
10601                if !full_comment_prefixes.is_empty() {
10602                    let first_prefix = full_comment_prefixes
10603                        .first()
10604                        .expect("prefixes is non-empty");
10605                    let prefix_trimmed_lengths = full_comment_prefixes
10606                        .iter()
10607                        .map(|p| p.trim_end_matches(' ').len())
10608                        .collect::<SmallVec<[usize; 4]>>();
10609
10610                    let mut all_selection_lines_are_comments = true;
10611
10612                    for row in start_row.0..=end_row.0 {
10613                        let row = MultiBufferRow(row);
10614                        if start_row < end_row && snapshot.is_line_blank(row) {
10615                            continue;
10616                        }
10617
10618                        let prefix_range = full_comment_prefixes
10619                            .iter()
10620                            .zip(prefix_trimmed_lengths.iter().copied())
10621                            .map(|(prefix, trimmed_prefix_len)| {
10622                                comment_prefix_range(
10623                                    snapshot.deref(),
10624                                    row,
10625                                    &prefix[..trimmed_prefix_len],
10626                                    &prefix[trimmed_prefix_len..],
10627                                    ignore_indent,
10628                                )
10629                            })
10630                            .max_by_key(|range| range.end.column - range.start.column)
10631                            .expect("prefixes is non-empty");
10632
10633                        if prefix_range.is_empty() {
10634                            all_selection_lines_are_comments = false;
10635                        }
10636
10637                        selection_edit_ranges.push(prefix_range);
10638                    }
10639
10640                    if all_selection_lines_are_comments {
10641                        edits.extend(
10642                            selection_edit_ranges
10643                                .iter()
10644                                .cloned()
10645                                .map(|range| (range, empty_str.clone())),
10646                        );
10647                    } else {
10648                        let min_column = selection_edit_ranges
10649                            .iter()
10650                            .map(|range| range.start.column)
10651                            .min()
10652                            .unwrap_or(0);
10653                        edits.extend(selection_edit_ranges.iter().map(|range| {
10654                            let position = Point::new(range.start.row, min_column);
10655                            (position..position, first_prefix.clone())
10656                        }));
10657                    }
10658                } else if let Some((full_comment_prefix, comment_suffix)) =
10659                    language.block_comment_delimiters()
10660                {
10661                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10662                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10663                    let prefix_range = comment_prefix_range(
10664                        snapshot.deref(),
10665                        start_row,
10666                        comment_prefix,
10667                        comment_prefix_whitespace,
10668                        ignore_indent,
10669                    );
10670                    let suffix_range = comment_suffix_range(
10671                        snapshot.deref(),
10672                        end_row,
10673                        comment_suffix.trim_start_matches(' '),
10674                        comment_suffix.starts_with(' '),
10675                    );
10676
10677                    if prefix_range.is_empty() || suffix_range.is_empty() {
10678                        edits.push((
10679                            prefix_range.start..prefix_range.start,
10680                            full_comment_prefix.clone(),
10681                        ));
10682                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10683                        suffixes_inserted.push((end_row, comment_suffix.len()));
10684                    } else {
10685                        edits.push((prefix_range, empty_str.clone()));
10686                        edits.push((suffix_range, empty_str.clone()));
10687                    }
10688                } else {
10689                    continue;
10690                }
10691            }
10692
10693            drop(snapshot);
10694            this.buffer.update(cx, |buffer, cx| {
10695                buffer.edit(edits, None, cx);
10696            });
10697
10698            // Adjust selections so that they end before any comment suffixes that
10699            // were inserted.
10700            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10701            let mut selections = this.selections.all::<Point>(cx);
10702            let snapshot = this.buffer.read(cx).read(cx);
10703            for selection in &mut selections {
10704                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10705                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10706                        Ordering::Less => {
10707                            suffixes_inserted.next();
10708                            continue;
10709                        }
10710                        Ordering::Greater => break,
10711                        Ordering::Equal => {
10712                            if selection.end.column == snapshot.line_len(row) {
10713                                if selection.is_empty() {
10714                                    selection.start.column -= suffix_len as u32;
10715                                }
10716                                selection.end.column -= suffix_len as u32;
10717                            }
10718                            break;
10719                        }
10720                    }
10721                }
10722            }
10723
10724            drop(snapshot);
10725            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10726                s.select(selections)
10727            });
10728
10729            let selections = this.selections.all::<Point>(cx);
10730            let selections_on_single_row = selections.windows(2).all(|selections| {
10731                selections[0].start.row == selections[1].start.row
10732                    && selections[0].end.row == selections[1].end.row
10733                    && selections[0].start.row == selections[0].end.row
10734            });
10735            let selections_selecting = selections
10736                .iter()
10737                .any(|selection| selection.start != selection.end);
10738            let advance_downwards = action.advance_downwards
10739                && selections_on_single_row
10740                && !selections_selecting
10741                && !matches!(this.mode, EditorMode::SingleLine { .. });
10742
10743            if advance_downwards {
10744                let snapshot = this.buffer.read(cx).snapshot(cx);
10745
10746                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10747                    s.move_cursors_with(|display_snapshot, display_point, _| {
10748                        let mut point = display_point.to_point(display_snapshot);
10749                        point.row += 1;
10750                        point = snapshot.clip_point(point, Bias::Left);
10751                        let display_point = point.to_display_point(display_snapshot);
10752                        let goal = SelectionGoal::HorizontalPosition(
10753                            display_snapshot
10754                                .x_for_display_point(display_point, text_layout_details)
10755                                .into(),
10756                        );
10757                        (display_point, goal)
10758                    })
10759                });
10760            }
10761        });
10762    }
10763
10764    pub fn select_enclosing_symbol(
10765        &mut self,
10766        _: &SelectEnclosingSymbol,
10767        window: &mut Window,
10768        cx: &mut Context<Self>,
10769    ) {
10770        let buffer = self.buffer.read(cx).snapshot(cx);
10771        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10772
10773        fn update_selection(
10774            selection: &Selection<usize>,
10775            buffer_snap: &MultiBufferSnapshot,
10776        ) -> Option<Selection<usize>> {
10777            let cursor = selection.head();
10778            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10779            for symbol in symbols.iter().rev() {
10780                let start = symbol.range.start.to_offset(buffer_snap);
10781                let end = symbol.range.end.to_offset(buffer_snap);
10782                let new_range = start..end;
10783                if start < selection.start || end > selection.end {
10784                    return Some(Selection {
10785                        id: selection.id,
10786                        start: new_range.start,
10787                        end: new_range.end,
10788                        goal: SelectionGoal::None,
10789                        reversed: selection.reversed,
10790                    });
10791                }
10792            }
10793            None
10794        }
10795
10796        let mut selected_larger_symbol = false;
10797        let new_selections = old_selections
10798            .iter()
10799            .map(|selection| match update_selection(selection, &buffer) {
10800                Some(new_selection) => {
10801                    if new_selection.range() != selection.range() {
10802                        selected_larger_symbol = true;
10803                    }
10804                    new_selection
10805                }
10806                None => selection.clone(),
10807            })
10808            .collect::<Vec<_>>();
10809
10810        if selected_larger_symbol {
10811            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10812                s.select(new_selections);
10813            });
10814        }
10815    }
10816
10817    pub fn select_larger_syntax_node(
10818        &mut self,
10819        _: &SelectLargerSyntaxNode,
10820        window: &mut Window,
10821        cx: &mut Context<Self>,
10822    ) {
10823        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10824        let buffer = self.buffer.read(cx).snapshot(cx);
10825        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10826
10827        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10828        let mut selected_larger_node = false;
10829        let new_selections = old_selections
10830            .iter()
10831            .map(|selection| {
10832                let old_range = selection.start..selection.end;
10833                let mut new_range = old_range.clone();
10834                let mut new_node = None;
10835                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10836                {
10837                    new_node = Some(node);
10838                    new_range = match containing_range {
10839                        MultiOrSingleBufferOffsetRange::Single(_) => break,
10840                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
10841                    };
10842                    if !display_map.intersects_fold(new_range.start)
10843                        && !display_map.intersects_fold(new_range.end)
10844                    {
10845                        break;
10846                    }
10847                }
10848
10849                if let Some(node) = new_node {
10850                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10851                    // nodes. Parent and grandparent are also logged because this operation will not
10852                    // visit nodes that have the same range as their parent.
10853                    log::info!("Node: {node:?}");
10854                    let parent = node.parent();
10855                    log::info!("Parent: {parent:?}");
10856                    let grandparent = parent.and_then(|x| x.parent());
10857                    log::info!("Grandparent: {grandparent:?}");
10858                }
10859
10860                selected_larger_node |= new_range != old_range;
10861                Selection {
10862                    id: selection.id,
10863                    start: new_range.start,
10864                    end: new_range.end,
10865                    goal: SelectionGoal::None,
10866                    reversed: selection.reversed,
10867                }
10868            })
10869            .collect::<Vec<_>>();
10870
10871        if selected_larger_node {
10872            stack.push(old_selections);
10873            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10874                s.select(new_selections);
10875            });
10876        }
10877        self.select_larger_syntax_node_stack = stack;
10878    }
10879
10880    pub fn select_smaller_syntax_node(
10881        &mut self,
10882        _: &SelectSmallerSyntaxNode,
10883        window: &mut Window,
10884        cx: &mut Context<Self>,
10885    ) {
10886        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10887        if let Some(selections) = stack.pop() {
10888            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10889                s.select(selections.to_vec());
10890            });
10891        }
10892        self.select_larger_syntax_node_stack = stack;
10893    }
10894
10895    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10896        if !EditorSettings::get_global(cx).gutter.runnables {
10897            self.clear_tasks();
10898            return Task::ready(());
10899        }
10900        let project = self.project.as_ref().map(Entity::downgrade);
10901        cx.spawn_in(window, |this, mut cx| async move {
10902            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10903            let Some(project) = project.and_then(|p| p.upgrade()) else {
10904                return;
10905            };
10906            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10907                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10908            }) else {
10909                return;
10910            };
10911
10912            let hide_runnables = project
10913                .update(&mut cx, |project, cx| {
10914                    // Do not display any test indicators in non-dev server remote projects.
10915                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10916                })
10917                .unwrap_or(true);
10918            if hide_runnables {
10919                return;
10920            }
10921            let new_rows =
10922                cx.background_spawn({
10923                    let snapshot = display_snapshot.clone();
10924                    async move {
10925                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10926                    }
10927                })
10928                    .await;
10929
10930            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10931            this.update(&mut cx, |this, _| {
10932                this.clear_tasks();
10933                for (key, value) in rows {
10934                    this.insert_tasks(key, value);
10935                }
10936            })
10937            .ok();
10938        })
10939    }
10940    fn fetch_runnable_ranges(
10941        snapshot: &DisplaySnapshot,
10942        range: Range<Anchor>,
10943    ) -> Vec<language::RunnableRange> {
10944        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10945    }
10946
10947    fn runnable_rows(
10948        project: Entity<Project>,
10949        snapshot: DisplaySnapshot,
10950        runnable_ranges: Vec<RunnableRange>,
10951        mut cx: AsyncWindowContext,
10952    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10953        runnable_ranges
10954            .into_iter()
10955            .filter_map(|mut runnable| {
10956                let tasks = cx
10957                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10958                    .ok()?;
10959                if tasks.is_empty() {
10960                    return None;
10961                }
10962
10963                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10964
10965                let row = snapshot
10966                    .buffer_snapshot
10967                    .buffer_line_for_row(MultiBufferRow(point.row))?
10968                    .1
10969                    .start
10970                    .row;
10971
10972                let context_range =
10973                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10974                Some((
10975                    (runnable.buffer_id, row),
10976                    RunnableTasks {
10977                        templates: tasks,
10978                        offset: snapshot
10979                            .buffer_snapshot
10980                            .anchor_before(runnable.run_range.start),
10981                        context_range,
10982                        column: point.column,
10983                        extra_variables: runnable.extra_captures,
10984                    },
10985                ))
10986            })
10987            .collect()
10988    }
10989
10990    fn templates_with_tags(
10991        project: &Entity<Project>,
10992        runnable: &mut Runnable,
10993        cx: &mut App,
10994    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10995        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10996            let (worktree_id, file) = project
10997                .buffer_for_id(runnable.buffer, cx)
10998                .and_then(|buffer| buffer.read(cx).file())
10999                .map(|file| (file.worktree_id(cx), file.clone()))
11000                .unzip();
11001
11002            (
11003                project.task_store().read(cx).task_inventory().cloned(),
11004                worktree_id,
11005                file,
11006            )
11007        });
11008
11009        let tags = mem::take(&mut runnable.tags);
11010        let mut tags: Vec<_> = tags
11011            .into_iter()
11012            .flat_map(|tag| {
11013                let tag = tag.0.clone();
11014                inventory
11015                    .as_ref()
11016                    .into_iter()
11017                    .flat_map(|inventory| {
11018                        inventory.read(cx).list_tasks(
11019                            file.clone(),
11020                            Some(runnable.language.clone()),
11021                            worktree_id,
11022                            cx,
11023                        )
11024                    })
11025                    .filter(move |(_, template)| {
11026                        template.tags.iter().any(|source_tag| source_tag == &tag)
11027                    })
11028            })
11029            .sorted_by_key(|(kind, _)| kind.to_owned())
11030            .collect();
11031        if let Some((leading_tag_source, _)) = tags.first() {
11032            // Strongest source wins; if we have worktree tag binding, prefer that to
11033            // global and language bindings;
11034            // if we have a global binding, prefer that to language binding.
11035            let first_mismatch = tags
11036                .iter()
11037                .position(|(tag_source, _)| tag_source != leading_tag_source);
11038            if let Some(index) = first_mismatch {
11039                tags.truncate(index);
11040            }
11041        }
11042
11043        tags
11044    }
11045
11046    pub fn move_to_enclosing_bracket(
11047        &mut self,
11048        _: &MoveToEnclosingBracket,
11049        window: &mut Window,
11050        cx: &mut Context<Self>,
11051    ) {
11052        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11053            s.move_offsets_with(|snapshot, selection| {
11054                let Some(enclosing_bracket_ranges) =
11055                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11056                else {
11057                    return;
11058                };
11059
11060                let mut best_length = usize::MAX;
11061                let mut best_inside = false;
11062                let mut best_in_bracket_range = false;
11063                let mut best_destination = None;
11064                for (open, close) in enclosing_bracket_ranges {
11065                    let close = close.to_inclusive();
11066                    let length = close.end() - open.start;
11067                    let inside = selection.start >= open.end && selection.end <= *close.start();
11068                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
11069                        || close.contains(&selection.head());
11070
11071                    // If best is next to a bracket and current isn't, skip
11072                    if !in_bracket_range && best_in_bracket_range {
11073                        continue;
11074                    }
11075
11076                    // Prefer smaller lengths unless best is inside and current isn't
11077                    if length > best_length && (best_inside || !inside) {
11078                        continue;
11079                    }
11080
11081                    best_length = length;
11082                    best_inside = inside;
11083                    best_in_bracket_range = in_bracket_range;
11084                    best_destination = Some(
11085                        if close.contains(&selection.start) && close.contains(&selection.end) {
11086                            if inside {
11087                                open.end
11088                            } else {
11089                                open.start
11090                            }
11091                        } else if inside {
11092                            *close.start()
11093                        } else {
11094                            *close.end()
11095                        },
11096                    );
11097                }
11098
11099                if let Some(destination) = best_destination {
11100                    selection.collapse_to(destination, SelectionGoal::None);
11101                }
11102            })
11103        });
11104    }
11105
11106    pub fn undo_selection(
11107        &mut self,
11108        _: &UndoSelection,
11109        window: &mut Window,
11110        cx: &mut Context<Self>,
11111    ) {
11112        self.end_selection(window, cx);
11113        self.selection_history.mode = SelectionHistoryMode::Undoing;
11114        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11115            self.change_selections(None, window, cx, |s| {
11116                s.select_anchors(entry.selections.to_vec())
11117            });
11118            self.select_next_state = entry.select_next_state;
11119            self.select_prev_state = entry.select_prev_state;
11120            self.add_selections_state = entry.add_selections_state;
11121            self.request_autoscroll(Autoscroll::newest(), cx);
11122        }
11123        self.selection_history.mode = SelectionHistoryMode::Normal;
11124    }
11125
11126    pub fn redo_selection(
11127        &mut self,
11128        _: &RedoSelection,
11129        window: &mut Window,
11130        cx: &mut Context<Self>,
11131    ) {
11132        self.end_selection(window, cx);
11133        self.selection_history.mode = SelectionHistoryMode::Redoing;
11134        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11135            self.change_selections(None, window, cx, |s| {
11136                s.select_anchors(entry.selections.to_vec())
11137            });
11138            self.select_next_state = entry.select_next_state;
11139            self.select_prev_state = entry.select_prev_state;
11140            self.add_selections_state = entry.add_selections_state;
11141            self.request_autoscroll(Autoscroll::newest(), cx);
11142        }
11143        self.selection_history.mode = SelectionHistoryMode::Normal;
11144    }
11145
11146    pub fn expand_excerpts(
11147        &mut self,
11148        action: &ExpandExcerpts,
11149        _: &mut Window,
11150        cx: &mut Context<Self>,
11151    ) {
11152        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11153    }
11154
11155    pub fn expand_excerpts_down(
11156        &mut self,
11157        action: &ExpandExcerptsDown,
11158        _: &mut Window,
11159        cx: &mut Context<Self>,
11160    ) {
11161        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11162    }
11163
11164    pub fn expand_excerpts_up(
11165        &mut self,
11166        action: &ExpandExcerptsUp,
11167        _: &mut Window,
11168        cx: &mut Context<Self>,
11169    ) {
11170        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11171    }
11172
11173    pub fn expand_excerpts_for_direction(
11174        &mut self,
11175        lines: u32,
11176        direction: ExpandExcerptDirection,
11177
11178        cx: &mut Context<Self>,
11179    ) {
11180        let selections = self.selections.disjoint_anchors();
11181
11182        let lines = if lines == 0 {
11183            EditorSettings::get_global(cx).expand_excerpt_lines
11184        } else {
11185            lines
11186        };
11187
11188        self.buffer.update(cx, |buffer, cx| {
11189            let snapshot = buffer.snapshot(cx);
11190            let mut excerpt_ids = selections
11191                .iter()
11192                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11193                .collect::<Vec<_>>();
11194            excerpt_ids.sort();
11195            excerpt_ids.dedup();
11196            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11197        })
11198    }
11199
11200    pub fn expand_excerpt(
11201        &mut self,
11202        excerpt: ExcerptId,
11203        direction: ExpandExcerptDirection,
11204        cx: &mut Context<Self>,
11205    ) {
11206        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11207        self.buffer.update(cx, |buffer, cx| {
11208            buffer.expand_excerpts([excerpt], lines, direction, cx)
11209        })
11210    }
11211
11212    pub fn go_to_singleton_buffer_point(
11213        &mut self,
11214        point: Point,
11215        window: &mut Window,
11216        cx: &mut Context<Self>,
11217    ) {
11218        self.go_to_singleton_buffer_range(point..point, window, cx);
11219    }
11220
11221    pub fn go_to_singleton_buffer_range(
11222        &mut self,
11223        range: Range<Point>,
11224        window: &mut Window,
11225        cx: &mut Context<Self>,
11226    ) {
11227        let multibuffer = self.buffer().read(cx);
11228        let Some(buffer) = multibuffer.as_singleton() else {
11229            return;
11230        };
11231        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11232            return;
11233        };
11234        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11235            return;
11236        };
11237        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11238            s.select_anchor_ranges([start..end])
11239        });
11240    }
11241
11242    fn go_to_diagnostic(
11243        &mut self,
11244        _: &GoToDiagnostic,
11245        window: &mut Window,
11246        cx: &mut Context<Self>,
11247    ) {
11248        self.go_to_diagnostic_impl(Direction::Next, window, cx)
11249    }
11250
11251    fn go_to_prev_diagnostic(
11252        &mut self,
11253        _: &GoToPrevDiagnostic,
11254        window: &mut Window,
11255        cx: &mut Context<Self>,
11256    ) {
11257        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11258    }
11259
11260    pub fn go_to_diagnostic_impl(
11261        &mut self,
11262        direction: Direction,
11263        window: &mut Window,
11264        cx: &mut Context<Self>,
11265    ) {
11266        let buffer = self.buffer.read(cx).snapshot(cx);
11267        let selection = self.selections.newest::<usize>(cx);
11268
11269        // If there is an active Diagnostic Popover jump to its diagnostic instead.
11270        if direction == Direction::Next {
11271            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11272                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11273                    return;
11274                };
11275                self.activate_diagnostics(
11276                    buffer_id,
11277                    popover.local_diagnostic.diagnostic.group_id,
11278                    window,
11279                    cx,
11280                );
11281                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11282                    let primary_range_start = active_diagnostics.primary_range.start;
11283                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11284                        let mut new_selection = s.newest_anchor().clone();
11285                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11286                        s.select_anchors(vec![new_selection.clone()]);
11287                    });
11288                    self.refresh_inline_completion(false, true, window, cx);
11289                }
11290                return;
11291            }
11292        }
11293
11294        let active_group_id = self
11295            .active_diagnostics
11296            .as_ref()
11297            .map(|active_group| active_group.group_id);
11298        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11299            active_diagnostics
11300                .primary_range
11301                .to_offset(&buffer)
11302                .to_inclusive()
11303        });
11304        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11305            if active_primary_range.contains(&selection.head()) {
11306                *active_primary_range.start()
11307            } else {
11308                selection.head()
11309            }
11310        } else {
11311            selection.head()
11312        };
11313
11314        let snapshot = self.snapshot(window, cx);
11315        let primary_diagnostics_before = buffer
11316            .diagnostics_in_range::<usize>(0..search_start)
11317            .filter(|entry| entry.diagnostic.is_primary)
11318            .filter(|entry| entry.range.start != entry.range.end)
11319            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11320            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11321            .collect::<Vec<_>>();
11322        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11323            primary_diagnostics_before
11324                .iter()
11325                .position(|entry| entry.diagnostic.group_id == active_group_id)
11326        });
11327
11328        let primary_diagnostics_after = buffer
11329            .diagnostics_in_range::<usize>(search_start..buffer.len())
11330            .filter(|entry| entry.diagnostic.is_primary)
11331            .filter(|entry| entry.range.start != entry.range.end)
11332            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11333            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11334            .collect::<Vec<_>>();
11335        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11336            primary_diagnostics_after
11337                .iter()
11338                .enumerate()
11339                .rev()
11340                .find_map(|(i, entry)| {
11341                    if entry.diagnostic.group_id == active_group_id {
11342                        Some(i)
11343                    } else {
11344                        None
11345                    }
11346                })
11347        });
11348
11349        let next_primary_diagnostic = match direction {
11350            Direction::Prev => primary_diagnostics_before
11351                .iter()
11352                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11353                .rev()
11354                .next(),
11355            Direction::Next => primary_diagnostics_after
11356                .iter()
11357                .skip(
11358                    last_same_group_diagnostic_after
11359                        .map(|index| index + 1)
11360                        .unwrap_or(0),
11361                )
11362                .next(),
11363        };
11364
11365        // Cycle around to the start of the buffer, potentially moving back to the start of
11366        // the currently active diagnostic.
11367        let cycle_around = || match direction {
11368            Direction::Prev => primary_diagnostics_after
11369                .iter()
11370                .rev()
11371                .chain(primary_diagnostics_before.iter().rev())
11372                .next(),
11373            Direction::Next => primary_diagnostics_before
11374                .iter()
11375                .chain(primary_diagnostics_after.iter())
11376                .next(),
11377        };
11378
11379        if let Some((primary_range, group_id)) = next_primary_diagnostic
11380            .or_else(cycle_around)
11381            .map(|entry| (&entry.range, entry.diagnostic.group_id))
11382        {
11383            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11384                return;
11385            };
11386            self.activate_diagnostics(buffer_id, group_id, window, cx);
11387            if self.active_diagnostics.is_some() {
11388                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11389                    s.select(vec![Selection {
11390                        id: selection.id,
11391                        start: primary_range.start,
11392                        end: primary_range.start,
11393                        reversed: false,
11394                        goal: SelectionGoal::None,
11395                    }]);
11396                });
11397                self.refresh_inline_completion(false, true, window, cx);
11398            }
11399        }
11400    }
11401
11402    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11403        let snapshot = self.snapshot(window, cx);
11404        let selection = self.selections.newest::<Point>(cx);
11405        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
11406    }
11407
11408    fn go_to_hunk_after_position(
11409        &mut self,
11410        snapshot: &EditorSnapshot,
11411        position: Point,
11412        window: &mut Window,
11413        cx: &mut Context<Editor>,
11414    ) -> Option<MultiBufferDiffHunk> {
11415        let mut hunk = snapshot
11416            .buffer_snapshot
11417            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11418            .find(|hunk| hunk.row_range.start.0 > position.row);
11419        if hunk.is_none() {
11420            hunk = snapshot
11421                .buffer_snapshot
11422                .diff_hunks_in_range(Point::zero()..position)
11423                .find(|hunk| hunk.row_range.end.0 < position.row)
11424        }
11425        if let Some(hunk) = &hunk {
11426            let destination = Point::new(hunk.row_range.start.0, 0);
11427            self.unfold_ranges(&[destination..destination], false, false, cx);
11428            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11429                s.select_ranges(vec![destination..destination]);
11430            });
11431        }
11432
11433        hunk
11434    }
11435
11436    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
11437        let snapshot = self.snapshot(window, cx);
11438        let selection = self.selections.newest::<Point>(cx);
11439        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
11440    }
11441
11442    fn go_to_hunk_before_position(
11443        &mut self,
11444        snapshot: &EditorSnapshot,
11445        position: Point,
11446        window: &mut Window,
11447        cx: &mut Context<Editor>,
11448    ) -> Option<MultiBufferDiffHunk> {
11449        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
11450        if hunk.is_none() {
11451            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
11452        }
11453        if let Some(hunk) = &hunk {
11454            let destination = Point::new(hunk.row_range.start.0, 0);
11455            self.unfold_ranges(&[destination..destination], false, false, cx);
11456            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11457                s.select_ranges(vec![destination..destination]);
11458            });
11459        }
11460
11461        hunk
11462    }
11463
11464    pub fn go_to_definition(
11465        &mut self,
11466        _: &GoToDefinition,
11467        window: &mut Window,
11468        cx: &mut Context<Self>,
11469    ) -> Task<Result<Navigated>> {
11470        let definition =
11471            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11472        cx.spawn_in(window, |editor, mut cx| async move {
11473            if definition.await? == Navigated::Yes {
11474                return Ok(Navigated::Yes);
11475            }
11476            match editor.update_in(&mut cx, |editor, window, cx| {
11477                editor.find_all_references(&FindAllReferences, window, cx)
11478            })? {
11479                Some(references) => references.await,
11480                None => Ok(Navigated::No),
11481            }
11482        })
11483    }
11484
11485    pub fn go_to_declaration(
11486        &mut self,
11487        _: &GoToDeclaration,
11488        window: &mut Window,
11489        cx: &mut Context<Self>,
11490    ) -> Task<Result<Navigated>> {
11491        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11492    }
11493
11494    pub fn go_to_declaration_split(
11495        &mut self,
11496        _: &GoToDeclaration,
11497        window: &mut Window,
11498        cx: &mut Context<Self>,
11499    ) -> Task<Result<Navigated>> {
11500        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11501    }
11502
11503    pub fn go_to_implementation(
11504        &mut self,
11505        _: &GoToImplementation,
11506        window: &mut Window,
11507        cx: &mut Context<Self>,
11508    ) -> Task<Result<Navigated>> {
11509        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11510    }
11511
11512    pub fn go_to_implementation_split(
11513        &mut self,
11514        _: &GoToImplementationSplit,
11515        window: &mut Window,
11516        cx: &mut Context<Self>,
11517    ) -> Task<Result<Navigated>> {
11518        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11519    }
11520
11521    pub fn go_to_type_definition(
11522        &mut self,
11523        _: &GoToTypeDefinition,
11524        window: &mut Window,
11525        cx: &mut Context<Self>,
11526    ) -> Task<Result<Navigated>> {
11527        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11528    }
11529
11530    pub fn go_to_definition_split(
11531        &mut self,
11532        _: &GoToDefinitionSplit,
11533        window: &mut Window,
11534        cx: &mut Context<Self>,
11535    ) -> Task<Result<Navigated>> {
11536        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11537    }
11538
11539    pub fn go_to_type_definition_split(
11540        &mut self,
11541        _: &GoToTypeDefinitionSplit,
11542        window: &mut Window,
11543        cx: &mut Context<Self>,
11544    ) -> Task<Result<Navigated>> {
11545        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11546    }
11547
11548    fn go_to_definition_of_kind(
11549        &mut self,
11550        kind: GotoDefinitionKind,
11551        split: bool,
11552        window: &mut Window,
11553        cx: &mut Context<Self>,
11554    ) -> Task<Result<Navigated>> {
11555        let Some(provider) = self.semantics_provider.clone() else {
11556            return Task::ready(Ok(Navigated::No));
11557        };
11558        let head = self.selections.newest::<usize>(cx).head();
11559        let buffer = self.buffer.read(cx);
11560        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11561            text_anchor
11562        } else {
11563            return Task::ready(Ok(Navigated::No));
11564        };
11565
11566        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11567            return Task::ready(Ok(Navigated::No));
11568        };
11569
11570        cx.spawn_in(window, |editor, mut cx| async move {
11571            let definitions = definitions.await?;
11572            let navigated = editor
11573                .update_in(&mut cx, |editor, window, cx| {
11574                    editor.navigate_to_hover_links(
11575                        Some(kind),
11576                        definitions
11577                            .into_iter()
11578                            .filter(|location| {
11579                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11580                            })
11581                            .map(HoverLink::Text)
11582                            .collect::<Vec<_>>(),
11583                        split,
11584                        window,
11585                        cx,
11586                    )
11587                })?
11588                .await?;
11589            anyhow::Ok(navigated)
11590        })
11591    }
11592
11593    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11594        let selection = self.selections.newest_anchor();
11595        let head = selection.head();
11596        let tail = selection.tail();
11597
11598        let Some((buffer, start_position)) =
11599            self.buffer.read(cx).text_anchor_for_position(head, cx)
11600        else {
11601            return;
11602        };
11603
11604        let end_position = if head != tail {
11605            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11606                return;
11607            };
11608            Some(pos)
11609        } else {
11610            None
11611        };
11612
11613        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11614            let url = if let Some(end_pos) = end_position {
11615                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11616            } else {
11617                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11618            };
11619
11620            if let Some(url) = url {
11621                editor.update(&mut cx, |_, cx| {
11622                    cx.open_url(&url);
11623                })
11624            } else {
11625                Ok(())
11626            }
11627        });
11628
11629        url_finder.detach();
11630    }
11631
11632    pub fn open_selected_filename(
11633        &mut self,
11634        _: &OpenSelectedFilename,
11635        window: &mut Window,
11636        cx: &mut Context<Self>,
11637    ) {
11638        let Some(workspace) = self.workspace() else {
11639            return;
11640        };
11641
11642        let position = self.selections.newest_anchor().head();
11643
11644        let Some((buffer, buffer_position)) =
11645            self.buffer.read(cx).text_anchor_for_position(position, cx)
11646        else {
11647            return;
11648        };
11649
11650        let project = self.project.clone();
11651
11652        cx.spawn_in(window, |_, mut cx| async move {
11653            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11654
11655            if let Some((_, path)) = result {
11656                workspace
11657                    .update_in(&mut cx, |workspace, window, cx| {
11658                        workspace.open_resolved_path(path, window, cx)
11659                    })?
11660                    .await?;
11661            }
11662            anyhow::Ok(())
11663        })
11664        .detach();
11665    }
11666
11667    pub(crate) fn navigate_to_hover_links(
11668        &mut self,
11669        kind: Option<GotoDefinitionKind>,
11670        mut definitions: Vec<HoverLink>,
11671        split: bool,
11672        window: &mut Window,
11673        cx: &mut Context<Editor>,
11674    ) -> Task<Result<Navigated>> {
11675        // If there is one definition, just open it directly
11676        if definitions.len() == 1 {
11677            let definition = definitions.pop().unwrap();
11678
11679            enum TargetTaskResult {
11680                Location(Option<Location>),
11681                AlreadyNavigated,
11682            }
11683
11684            let target_task = match definition {
11685                HoverLink::Text(link) => {
11686                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11687                }
11688                HoverLink::InlayHint(lsp_location, server_id) => {
11689                    let computation =
11690                        self.compute_target_location(lsp_location, server_id, window, cx);
11691                    cx.background_spawn(async move {
11692                        let location = computation.await?;
11693                        Ok(TargetTaskResult::Location(location))
11694                    })
11695                }
11696                HoverLink::Url(url) => {
11697                    cx.open_url(&url);
11698                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11699                }
11700                HoverLink::File(path) => {
11701                    if let Some(workspace) = self.workspace() {
11702                        cx.spawn_in(window, |_, mut cx| async move {
11703                            workspace
11704                                .update_in(&mut cx, |workspace, window, cx| {
11705                                    workspace.open_resolved_path(path, window, cx)
11706                                })?
11707                                .await
11708                                .map(|_| TargetTaskResult::AlreadyNavigated)
11709                        })
11710                    } else {
11711                        Task::ready(Ok(TargetTaskResult::Location(None)))
11712                    }
11713                }
11714            };
11715            cx.spawn_in(window, |editor, mut cx| async move {
11716                let target = match target_task.await.context("target resolution task")? {
11717                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11718                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11719                    TargetTaskResult::Location(Some(target)) => target,
11720                };
11721
11722                editor.update_in(&mut cx, |editor, window, cx| {
11723                    let Some(workspace) = editor.workspace() else {
11724                        return Navigated::No;
11725                    };
11726                    let pane = workspace.read(cx).active_pane().clone();
11727
11728                    let range = target.range.to_point(target.buffer.read(cx));
11729                    let range = editor.range_for_match(&range);
11730                    let range = collapse_multiline_range(range);
11731
11732                    if !split
11733                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11734                    {
11735                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11736                    } else {
11737                        window.defer(cx, move |window, cx| {
11738                            let target_editor: Entity<Self> =
11739                                workspace.update(cx, |workspace, cx| {
11740                                    let pane = if split {
11741                                        workspace.adjacent_pane(window, cx)
11742                                    } else {
11743                                        workspace.active_pane().clone()
11744                                    };
11745
11746                                    workspace.open_project_item(
11747                                        pane,
11748                                        target.buffer.clone(),
11749                                        true,
11750                                        true,
11751                                        window,
11752                                        cx,
11753                                    )
11754                                });
11755                            target_editor.update(cx, |target_editor, cx| {
11756                                // When selecting a definition in a different buffer, disable the nav history
11757                                // to avoid creating a history entry at the previous cursor location.
11758                                pane.update(cx, |pane, _| pane.disable_history());
11759                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11760                                pane.update(cx, |pane, _| pane.enable_history());
11761                            });
11762                        });
11763                    }
11764                    Navigated::Yes
11765                })
11766            })
11767        } else if !definitions.is_empty() {
11768            cx.spawn_in(window, |editor, mut cx| async move {
11769                let (title, location_tasks, workspace) = editor
11770                    .update_in(&mut cx, |editor, window, cx| {
11771                        let tab_kind = match kind {
11772                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11773                            _ => "Definitions",
11774                        };
11775                        let title = definitions
11776                            .iter()
11777                            .find_map(|definition| match definition {
11778                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11779                                    let buffer = origin.buffer.read(cx);
11780                                    format!(
11781                                        "{} for {}",
11782                                        tab_kind,
11783                                        buffer
11784                                            .text_for_range(origin.range.clone())
11785                                            .collect::<String>()
11786                                    )
11787                                }),
11788                                HoverLink::InlayHint(_, _) => None,
11789                                HoverLink::Url(_) => None,
11790                                HoverLink::File(_) => None,
11791                            })
11792                            .unwrap_or(tab_kind.to_string());
11793                        let location_tasks = definitions
11794                            .into_iter()
11795                            .map(|definition| match definition {
11796                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11797                                HoverLink::InlayHint(lsp_location, server_id) => editor
11798                                    .compute_target_location(lsp_location, server_id, window, cx),
11799                                HoverLink::Url(_) => Task::ready(Ok(None)),
11800                                HoverLink::File(_) => Task::ready(Ok(None)),
11801                            })
11802                            .collect::<Vec<_>>();
11803                        (title, location_tasks, editor.workspace().clone())
11804                    })
11805                    .context("location tasks preparation")?;
11806
11807                let locations = future::join_all(location_tasks)
11808                    .await
11809                    .into_iter()
11810                    .filter_map(|location| location.transpose())
11811                    .collect::<Result<_>>()
11812                    .context("location tasks")?;
11813
11814                let Some(workspace) = workspace else {
11815                    return Ok(Navigated::No);
11816                };
11817                let opened = workspace
11818                    .update_in(&mut cx, |workspace, window, cx| {
11819                        Self::open_locations_in_multibuffer(
11820                            workspace,
11821                            locations,
11822                            title,
11823                            split,
11824                            MultibufferSelectionMode::First,
11825                            window,
11826                            cx,
11827                        )
11828                    })
11829                    .ok();
11830
11831                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11832            })
11833        } else {
11834            Task::ready(Ok(Navigated::No))
11835        }
11836    }
11837
11838    fn compute_target_location(
11839        &self,
11840        lsp_location: lsp::Location,
11841        server_id: LanguageServerId,
11842        window: &mut Window,
11843        cx: &mut Context<Self>,
11844    ) -> Task<anyhow::Result<Option<Location>>> {
11845        let Some(project) = self.project.clone() else {
11846            return Task::ready(Ok(None));
11847        };
11848
11849        cx.spawn_in(window, move |editor, mut cx| async move {
11850            let location_task = editor.update(&mut cx, |_, cx| {
11851                project.update(cx, |project, cx| {
11852                    let language_server_name = project
11853                        .language_server_statuses(cx)
11854                        .find(|(id, _)| server_id == *id)
11855                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11856                    language_server_name.map(|language_server_name| {
11857                        project.open_local_buffer_via_lsp(
11858                            lsp_location.uri.clone(),
11859                            server_id,
11860                            language_server_name,
11861                            cx,
11862                        )
11863                    })
11864                })
11865            })?;
11866            let location = match location_task {
11867                Some(task) => Some({
11868                    let target_buffer_handle = task.await.context("open local buffer")?;
11869                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11870                        let target_start = target_buffer
11871                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11872                        let target_end = target_buffer
11873                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11874                        target_buffer.anchor_after(target_start)
11875                            ..target_buffer.anchor_before(target_end)
11876                    })?;
11877                    Location {
11878                        buffer: target_buffer_handle,
11879                        range,
11880                    }
11881                }),
11882                None => None,
11883            };
11884            Ok(location)
11885        })
11886    }
11887
11888    pub fn find_all_references(
11889        &mut self,
11890        _: &FindAllReferences,
11891        window: &mut Window,
11892        cx: &mut Context<Self>,
11893    ) -> Option<Task<Result<Navigated>>> {
11894        let selection = self.selections.newest::<usize>(cx);
11895        let multi_buffer = self.buffer.read(cx);
11896        let head = selection.head();
11897
11898        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11899        let head_anchor = multi_buffer_snapshot.anchor_at(
11900            head,
11901            if head < selection.tail() {
11902                Bias::Right
11903            } else {
11904                Bias::Left
11905            },
11906        );
11907
11908        match self
11909            .find_all_references_task_sources
11910            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11911        {
11912            Ok(_) => {
11913                log::info!(
11914                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11915                );
11916                return None;
11917            }
11918            Err(i) => {
11919                self.find_all_references_task_sources.insert(i, head_anchor);
11920            }
11921        }
11922
11923        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11924        let workspace = self.workspace()?;
11925        let project = workspace.read(cx).project().clone();
11926        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11927        Some(cx.spawn_in(window, |editor, mut cx| async move {
11928            let _cleanup = defer({
11929                let mut cx = cx.clone();
11930                move || {
11931                    let _ = editor.update(&mut cx, |editor, _| {
11932                        if let Ok(i) =
11933                            editor
11934                                .find_all_references_task_sources
11935                                .binary_search_by(|anchor| {
11936                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11937                                })
11938                        {
11939                            editor.find_all_references_task_sources.remove(i);
11940                        }
11941                    });
11942                }
11943            });
11944
11945            let locations = references.await?;
11946            if locations.is_empty() {
11947                return anyhow::Ok(Navigated::No);
11948            }
11949
11950            workspace.update_in(&mut cx, |workspace, window, cx| {
11951                let title = locations
11952                    .first()
11953                    .as_ref()
11954                    .map(|location| {
11955                        let buffer = location.buffer.read(cx);
11956                        format!(
11957                            "References to `{}`",
11958                            buffer
11959                                .text_for_range(location.range.clone())
11960                                .collect::<String>()
11961                        )
11962                    })
11963                    .unwrap();
11964                Self::open_locations_in_multibuffer(
11965                    workspace,
11966                    locations,
11967                    title,
11968                    false,
11969                    MultibufferSelectionMode::First,
11970                    window,
11971                    cx,
11972                );
11973                Navigated::Yes
11974            })
11975        }))
11976    }
11977
11978    /// Opens a multibuffer with the given project locations in it
11979    pub fn open_locations_in_multibuffer(
11980        workspace: &mut Workspace,
11981        mut locations: Vec<Location>,
11982        title: String,
11983        split: bool,
11984        multibuffer_selection_mode: MultibufferSelectionMode,
11985        window: &mut Window,
11986        cx: &mut Context<Workspace>,
11987    ) {
11988        // If there are multiple definitions, open them in a multibuffer
11989        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11990        let mut locations = locations.into_iter().peekable();
11991        let mut ranges = Vec::new();
11992        let capability = workspace.project().read(cx).capability();
11993
11994        let excerpt_buffer = cx.new(|cx| {
11995            let mut multibuffer = MultiBuffer::new(capability);
11996            while let Some(location) = locations.next() {
11997                let buffer = location.buffer.read(cx);
11998                let mut ranges_for_buffer = Vec::new();
11999                let range = location.range.to_offset(buffer);
12000                ranges_for_buffer.push(range.clone());
12001
12002                while let Some(next_location) = locations.peek() {
12003                    if next_location.buffer == location.buffer {
12004                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
12005                        locations.next();
12006                    } else {
12007                        break;
12008                    }
12009                }
12010
12011                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12012                ranges.extend(multibuffer.push_excerpts_with_context_lines(
12013                    location.buffer.clone(),
12014                    ranges_for_buffer,
12015                    DEFAULT_MULTIBUFFER_CONTEXT,
12016                    cx,
12017                ))
12018            }
12019
12020            multibuffer.with_title(title)
12021        });
12022
12023        let editor = cx.new(|cx| {
12024            Editor::for_multibuffer(
12025                excerpt_buffer,
12026                Some(workspace.project().clone()),
12027                true,
12028                window,
12029                cx,
12030            )
12031        });
12032        editor.update(cx, |editor, cx| {
12033            match multibuffer_selection_mode {
12034                MultibufferSelectionMode::First => {
12035                    if let Some(first_range) = ranges.first() {
12036                        editor.change_selections(None, window, cx, |selections| {
12037                            selections.clear_disjoint();
12038                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12039                        });
12040                    }
12041                    editor.highlight_background::<Self>(
12042                        &ranges,
12043                        |theme| theme.editor_highlighted_line_background,
12044                        cx,
12045                    );
12046                }
12047                MultibufferSelectionMode::All => {
12048                    editor.change_selections(None, window, cx, |selections| {
12049                        selections.clear_disjoint();
12050                        selections.select_anchor_ranges(ranges);
12051                    });
12052                }
12053            }
12054            editor.register_buffers_with_language_servers(cx);
12055        });
12056
12057        let item = Box::new(editor);
12058        let item_id = item.item_id();
12059
12060        if split {
12061            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12062        } else {
12063            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12064                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12065                    pane.close_current_preview_item(window, cx)
12066                } else {
12067                    None
12068                }
12069            });
12070            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12071        }
12072        workspace.active_pane().update(cx, |pane, cx| {
12073            pane.set_preview_item_id(Some(item_id), cx);
12074        });
12075    }
12076
12077    pub fn rename(
12078        &mut self,
12079        _: &Rename,
12080        window: &mut Window,
12081        cx: &mut Context<Self>,
12082    ) -> Option<Task<Result<()>>> {
12083        use language::ToOffset as _;
12084
12085        let provider = self.semantics_provider.clone()?;
12086        let selection = self.selections.newest_anchor().clone();
12087        let (cursor_buffer, cursor_buffer_position) = self
12088            .buffer
12089            .read(cx)
12090            .text_anchor_for_position(selection.head(), cx)?;
12091        let (tail_buffer, cursor_buffer_position_end) = self
12092            .buffer
12093            .read(cx)
12094            .text_anchor_for_position(selection.tail(), cx)?;
12095        if tail_buffer != cursor_buffer {
12096            return None;
12097        }
12098
12099        let snapshot = cursor_buffer.read(cx).snapshot();
12100        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12101        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12102        let prepare_rename = provider
12103            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12104            .unwrap_or_else(|| Task::ready(Ok(None)));
12105        drop(snapshot);
12106
12107        Some(cx.spawn_in(window, |this, mut cx| async move {
12108            let rename_range = if let Some(range) = prepare_rename.await? {
12109                Some(range)
12110            } else {
12111                this.update(&mut cx, |this, cx| {
12112                    let buffer = this.buffer.read(cx).snapshot(cx);
12113                    let mut buffer_highlights = this
12114                        .document_highlights_for_position(selection.head(), &buffer)
12115                        .filter(|highlight| {
12116                            highlight.start.excerpt_id == selection.head().excerpt_id
12117                                && highlight.end.excerpt_id == selection.head().excerpt_id
12118                        });
12119                    buffer_highlights
12120                        .next()
12121                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12122                })?
12123            };
12124            if let Some(rename_range) = rename_range {
12125                this.update_in(&mut cx, |this, window, cx| {
12126                    let snapshot = cursor_buffer.read(cx).snapshot();
12127                    let rename_buffer_range = rename_range.to_offset(&snapshot);
12128                    let cursor_offset_in_rename_range =
12129                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12130                    let cursor_offset_in_rename_range_end =
12131                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12132
12133                    this.take_rename(false, window, cx);
12134                    let buffer = this.buffer.read(cx).read(cx);
12135                    let cursor_offset = selection.head().to_offset(&buffer);
12136                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12137                    let rename_end = rename_start + rename_buffer_range.len();
12138                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12139                    let mut old_highlight_id = None;
12140                    let old_name: Arc<str> = buffer
12141                        .chunks(rename_start..rename_end, true)
12142                        .map(|chunk| {
12143                            if old_highlight_id.is_none() {
12144                                old_highlight_id = chunk.syntax_highlight_id;
12145                            }
12146                            chunk.text
12147                        })
12148                        .collect::<String>()
12149                        .into();
12150
12151                    drop(buffer);
12152
12153                    // Position the selection in the rename editor so that it matches the current selection.
12154                    this.show_local_selections = false;
12155                    let rename_editor = cx.new(|cx| {
12156                        let mut editor = Editor::single_line(window, cx);
12157                        editor.buffer.update(cx, |buffer, cx| {
12158                            buffer.edit([(0..0, old_name.clone())], None, cx)
12159                        });
12160                        let rename_selection_range = match cursor_offset_in_rename_range
12161                            .cmp(&cursor_offset_in_rename_range_end)
12162                        {
12163                            Ordering::Equal => {
12164                                editor.select_all(&SelectAll, window, cx);
12165                                return editor;
12166                            }
12167                            Ordering::Less => {
12168                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12169                            }
12170                            Ordering::Greater => {
12171                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12172                            }
12173                        };
12174                        if rename_selection_range.end > old_name.len() {
12175                            editor.select_all(&SelectAll, window, cx);
12176                        } else {
12177                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12178                                s.select_ranges([rename_selection_range]);
12179                            });
12180                        }
12181                        editor
12182                    });
12183                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12184                        if e == &EditorEvent::Focused {
12185                            cx.emit(EditorEvent::FocusedIn)
12186                        }
12187                    })
12188                    .detach();
12189
12190                    let write_highlights =
12191                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12192                    let read_highlights =
12193                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
12194                    let ranges = write_highlights
12195                        .iter()
12196                        .flat_map(|(_, ranges)| ranges.iter())
12197                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12198                        .cloned()
12199                        .collect();
12200
12201                    this.highlight_text::<Rename>(
12202                        ranges,
12203                        HighlightStyle {
12204                            fade_out: Some(0.6),
12205                            ..Default::default()
12206                        },
12207                        cx,
12208                    );
12209                    let rename_focus_handle = rename_editor.focus_handle(cx);
12210                    window.focus(&rename_focus_handle);
12211                    let block_id = this.insert_blocks(
12212                        [BlockProperties {
12213                            style: BlockStyle::Flex,
12214                            placement: BlockPlacement::Below(range.start),
12215                            height: 1,
12216                            render: Arc::new({
12217                                let rename_editor = rename_editor.clone();
12218                                move |cx: &mut BlockContext| {
12219                                    let mut text_style = cx.editor_style.text.clone();
12220                                    if let Some(highlight_style) = old_highlight_id
12221                                        .and_then(|h| h.style(&cx.editor_style.syntax))
12222                                    {
12223                                        text_style = text_style.highlight(highlight_style);
12224                                    }
12225                                    div()
12226                                        .block_mouse_down()
12227                                        .pl(cx.anchor_x)
12228                                        .child(EditorElement::new(
12229                                            &rename_editor,
12230                                            EditorStyle {
12231                                                background: cx.theme().system().transparent,
12232                                                local_player: cx.editor_style.local_player,
12233                                                text: text_style,
12234                                                scrollbar_width: cx.editor_style.scrollbar_width,
12235                                                syntax: cx.editor_style.syntax.clone(),
12236                                                status: cx.editor_style.status.clone(),
12237                                                inlay_hints_style: HighlightStyle {
12238                                                    font_weight: Some(FontWeight::BOLD),
12239                                                    ..make_inlay_hints_style(cx.app)
12240                                                },
12241                                                inline_completion_styles: make_suggestion_styles(
12242                                                    cx.app,
12243                                                ),
12244                                                ..EditorStyle::default()
12245                                            },
12246                                        ))
12247                                        .into_any_element()
12248                                }
12249                            }),
12250                            priority: 0,
12251                        }],
12252                        Some(Autoscroll::fit()),
12253                        cx,
12254                    )[0];
12255                    this.pending_rename = Some(RenameState {
12256                        range,
12257                        old_name,
12258                        editor: rename_editor,
12259                        block_id,
12260                    });
12261                })?;
12262            }
12263
12264            Ok(())
12265        }))
12266    }
12267
12268    pub fn confirm_rename(
12269        &mut self,
12270        _: &ConfirmRename,
12271        window: &mut Window,
12272        cx: &mut Context<Self>,
12273    ) -> Option<Task<Result<()>>> {
12274        let rename = self.take_rename(false, window, cx)?;
12275        let workspace = self.workspace()?.downgrade();
12276        let (buffer, start) = self
12277            .buffer
12278            .read(cx)
12279            .text_anchor_for_position(rename.range.start, cx)?;
12280        let (end_buffer, _) = self
12281            .buffer
12282            .read(cx)
12283            .text_anchor_for_position(rename.range.end, cx)?;
12284        if buffer != end_buffer {
12285            return None;
12286        }
12287
12288        let old_name = rename.old_name;
12289        let new_name = rename.editor.read(cx).text(cx);
12290
12291        let rename = self.semantics_provider.as_ref()?.perform_rename(
12292            &buffer,
12293            start,
12294            new_name.clone(),
12295            cx,
12296        )?;
12297
12298        Some(cx.spawn_in(window, |editor, mut cx| async move {
12299            let project_transaction = rename.await?;
12300            Self::open_project_transaction(
12301                &editor,
12302                workspace,
12303                project_transaction,
12304                format!("Rename: {}{}", old_name, new_name),
12305                cx.clone(),
12306            )
12307            .await?;
12308
12309            editor.update(&mut cx, |editor, cx| {
12310                editor.refresh_document_highlights(cx);
12311            })?;
12312            Ok(())
12313        }))
12314    }
12315
12316    fn take_rename(
12317        &mut self,
12318        moving_cursor: bool,
12319        window: &mut Window,
12320        cx: &mut Context<Self>,
12321    ) -> Option<RenameState> {
12322        let rename = self.pending_rename.take()?;
12323        if rename.editor.focus_handle(cx).is_focused(window) {
12324            window.focus(&self.focus_handle);
12325        }
12326
12327        self.remove_blocks(
12328            [rename.block_id].into_iter().collect(),
12329            Some(Autoscroll::fit()),
12330            cx,
12331        );
12332        self.clear_highlights::<Rename>(cx);
12333        self.show_local_selections = true;
12334
12335        if moving_cursor {
12336            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12337                editor.selections.newest::<usize>(cx).head()
12338            });
12339
12340            // Update the selection to match the position of the selection inside
12341            // the rename editor.
12342            let snapshot = self.buffer.read(cx).read(cx);
12343            let rename_range = rename.range.to_offset(&snapshot);
12344            let cursor_in_editor = snapshot
12345                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12346                .min(rename_range.end);
12347            drop(snapshot);
12348
12349            self.change_selections(None, window, cx, |s| {
12350                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12351            });
12352        } else {
12353            self.refresh_document_highlights(cx);
12354        }
12355
12356        Some(rename)
12357    }
12358
12359    pub fn pending_rename(&self) -> Option<&RenameState> {
12360        self.pending_rename.as_ref()
12361    }
12362
12363    fn format(
12364        &mut self,
12365        _: &Format,
12366        window: &mut Window,
12367        cx: &mut Context<Self>,
12368    ) -> Option<Task<Result<()>>> {
12369        let project = match &self.project {
12370            Some(project) => project.clone(),
12371            None => return None,
12372        };
12373
12374        Some(self.perform_format(
12375            project,
12376            FormatTrigger::Manual,
12377            FormatTarget::Buffers,
12378            window,
12379            cx,
12380        ))
12381    }
12382
12383    fn format_selections(
12384        &mut self,
12385        _: &FormatSelections,
12386        window: &mut Window,
12387        cx: &mut Context<Self>,
12388    ) -> Option<Task<Result<()>>> {
12389        let project = match &self.project {
12390            Some(project) => project.clone(),
12391            None => return None,
12392        };
12393
12394        let ranges = self
12395            .selections
12396            .all_adjusted(cx)
12397            .into_iter()
12398            .map(|selection| selection.range())
12399            .collect_vec();
12400
12401        Some(self.perform_format(
12402            project,
12403            FormatTrigger::Manual,
12404            FormatTarget::Ranges(ranges),
12405            window,
12406            cx,
12407        ))
12408    }
12409
12410    fn perform_format(
12411        &mut self,
12412        project: Entity<Project>,
12413        trigger: FormatTrigger,
12414        target: FormatTarget,
12415        window: &mut Window,
12416        cx: &mut Context<Self>,
12417    ) -> Task<Result<()>> {
12418        let buffer = self.buffer.clone();
12419        let (buffers, target) = match target {
12420            FormatTarget::Buffers => {
12421                let mut buffers = buffer.read(cx).all_buffers();
12422                if trigger == FormatTrigger::Save {
12423                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
12424                }
12425                (buffers, LspFormatTarget::Buffers)
12426            }
12427            FormatTarget::Ranges(selection_ranges) => {
12428                let multi_buffer = buffer.read(cx);
12429                let snapshot = multi_buffer.read(cx);
12430                let mut buffers = HashSet::default();
12431                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12432                    BTreeMap::new();
12433                for selection_range in selection_ranges {
12434                    for (buffer, buffer_range, _) in
12435                        snapshot.range_to_buffer_ranges(selection_range)
12436                    {
12437                        let buffer_id = buffer.remote_id();
12438                        let start = buffer.anchor_before(buffer_range.start);
12439                        let end = buffer.anchor_after(buffer_range.end);
12440                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12441                        buffer_id_to_ranges
12442                            .entry(buffer_id)
12443                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12444                            .or_insert_with(|| vec![start..end]);
12445                    }
12446                }
12447                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12448            }
12449        };
12450
12451        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12452        let format = project.update(cx, |project, cx| {
12453            project.format(buffers, target, true, trigger, cx)
12454        });
12455
12456        cx.spawn_in(window, |_, mut cx| async move {
12457            let transaction = futures::select_biased! {
12458                () = timeout => {
12459                    log::warn!("timed out waiting for formatting");
12460                    None
12461                }
12462                transaction = format.log_err().fuse() => transaction,
12463            };
12464
12465            buffer
12466                .update(&mut cx, |buffer, cx| {
12467                    if let Some(transaction) = transaction {
12468                        if !buffer.is_singleton() {
12469                            buffer.push_transaction(&transaction.0, cx);
12470                        }
12471                    }
12472
12473                    cx.notify();
12474                })
12475                .ok();
12476
12477            Ok(())
12478        })
12479    }
12480
12481    fn restart_language_server(
12482        &mut self,
12483        _: &RestartLanguageServer,
12484        _: &mut Window,
12485        cx: &mut Context<Self>,
12486    ) {
12487        if let Some(project) = self.project.clone() {
12488            self.buffer.update(cx, |multi_buffer, cx| {
12489                project.update(cx, |project, cx| {
12490                    project.restart_language_servers_for_buffers(
12491                        multi_buffer.all_buffers().into_iter().collect(),
12492                        cx,
12493                    );
12494                });
12495            })
12496        }
12497    }
12498
12499    fn cancel_language_server_work(
12500        workspace: &mut Workspace,
12501        _: &actions::CancelLanguageServerWork,
12502        _: &mut Window,
12503        cx: &mut Context<Workspace>,
12504    ) {
12505        let project = workspace.project();
12506        let buffers = workspace
12507            .active_item(cx)
12508            .and_then(|item| item.act_as::<Editor>(cx))
12509            .map_or(HashSet::default(), |editor| {
12510                editor.read(cx).buffer.read(cx).all_buffers()
12511            });
12512        project.update(cx, |project, cx| {
12513            project.cancel_language_server_work_for_buffers(buffers, cx);
12514        });
12515    }
12516
12517    fn show_character_palette(
12518        &mut self,
12519        _: &ShowCharacterPalette,
12520        window: &mut Window,
12521        _: &mut Context<Self>,
12522    ) {
12523        window.show_character_palette();
12524    }
12525
12526    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12527        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12528            let buffer = self.buffer.read(cx).snapshot(cx);
12529            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12530            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12531            let is_valid = buffer
12532                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12533                .any(|entry| {
12534                    entry.diagnostic.is_primary
12535                        && !entry.range.is_empty()
12536                        && entry.range.start == primary_range_start
12537                        && entry.diagnostic.message == active_diagnostics.primary_message
12538                });
12539
12540            if is_valid != active_diagnostics.is_valid {
12541                active_diagnostics.is_valid = is_valid;
12542                if is_valid {
12543                    let mut new_styles = HashMap::default();
12544                    for (block_id, diagnostic) in &active_diagnostics.blocks {
12545                        new_styles.insert(
12546                            *block_id,
12547                            diagnostic_block_renderer(diagnostic.clone(), None, true),
12548                        );
12549                    }
12550                    self.display_map.update(cx, |display_map, _cx| {
12551                        display_map.replace_blocks(new_styles);
12552                    });
12553                } else {
12554                    self.dismiss_diagnostics(cx);
12555                }
12556            }
12557        }
12558    }
12559
12560    fn activate_diagnostics(
12561        &mut self,
12562        buffer_id: BufferId,
12563        group_id: usize,
12564        window: &mut Window,
12565        cx: &mut Context<Self>,
12566    ) {
12567        self.dismiss_diagnostics(cx);
12568        let snapshot = self.snapshot(window, cx);
12569        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12570            let buffer = self.buffer.read(cx).snapshot(cx);
12571
12572            let mut primary_range = None;
12573            let mut primary_message = None;
12574            let diagnostic_group = buffer
12575                .diagnostic_group(buffer_id, group_id)
12576                .filter_map(|entry| {
12577                    let start = entry.range.start;
12578                    let end = entry.range.end;
12579                    if snapshot.is_line_folded(MultiBufferRow(start.row))
12580                        && (start.row == end.row
12581                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
12582                    {
12583                        return None;
12584                    }
12585                    if entry.diagnostic.is_primary {
12586                        primary_range = Some(entry.range.clone());
12587                        primary_message = Some(entry.diagnostic.message.clone());
12588                    }
12589                    Some(entry)
12590                })
12591                .collect::<Vec<_>>();
12592            let primary_range = primary_range?;
12593            let primary_message = primary_message?;
12594
12595            let blocks = display_map
12596                .insert_blocks(
12597                    diagnostic_group.iter().map(|entry| {
12598                        let diagnostic = entry.diagnostic.clone();
12599                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12600                        BlockProperties {
12601                            style: BlockStyle::Fixed,
12602                            placement: BlockPlacement::Below(
12603                                buffer.anchor_after(entry.range.start),
12604                            ),
12605                            height: message_height,
12606                            render: diagnostic_block_renderer(diagnostic, None, true),
12607                            priority: 0,
12608                        }
12609                    }),
12610                    cx,
12611                )
12612                .into_iter()
12613                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12614                .collect();
12615
12616            Some(ActiveDiagnosticGroup {
12617                primary_range: buffer.anchor_before(primary_range.start)
12618                    ..buffer.anchor_after(primary_range.end),
12619                primary_message,
12620                group_id,
12621                blocks,
12622                is_valid: true,
12623            })
12624        });
12625    }
12626
12627    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12628        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12629            self.display_map.update(cx, |display_map, cx| {
12630                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12631            });
12632            cx.notify();
12633        }
12634    }
12635
12636    /// Disable inline diagnostics rendering for this editor.
12637    pub fn disable_inline_diagnostics(&mut self) {
12638        self.inline_diagnostics_enabled = false;
12639        self.inline_diagnostics_update = Task::ready(());
12640        self.inline_diagnostics.clear();
12641    }
12642
12643    pub fn inline_diagnostics_enabled(&self) -> bool {
12644        self.inline_diagnostics_enabled
12645    }
12646
12647    pub fn show_inline_diagnostics(&self) -> bool {
12648        self.show_inline_diagnostics
12649    }
12650
12651    pub fn toggle_inline_diagnostics(
12652        &mut self,
12653        _: &ToggleInlineDiagnostics,
12654        window: &mut Window,
12655        cx: &mut Context<'_, Editor>,
12656    ) {
12657        self.show_inline_diagnostics = !self.show_inline_diagnostics;
12658        self.refresh_inline_diagnostics(false, window, cx);
12659    }
12660
12661    fn refresh_inline_diagnostics(
12662        &mut self,
12663        debounce: bool,
12664        window: &mut Window,
12665        cx: &mut Context<Self>,
12666    ) {
12667        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12668            self.inline_diagnostics_update = Task::ready(());
12669            self.inline_diagnostics.clear();
12670            return;
12671        }
12672
12673        let debounce_ms = ProjectSettings::get_global(cx)
12674            .diagnostics
12675            .inline
12676            .update_debounce_ms;
12677        let debounce = if debounce && debounce_ms > 0 {
12678            Some(Duration::from_millis(debounce_ms))
12679        } else {
12680            None
12681        };
12682        self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12683            if let Some(debounce) = debounce {
12684                cx.background_executor().timer(debounce).await;
12685            }
12686            let Some(snapshot) = editor
12687                .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12688                .ok()
12689            else {
12690                return;
12691            };
12692
12693            let new_inline_diagnostics = cx
12694                .background_spawn(async move {
12695                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12696                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12697                        let message = diagnostic_entry
12698                            .diagnostic
12699                            .message
12700                            .split_once('\n')
12701                            .map(|(line, _)| line)
12702                            .map(SharedString::new)
12703                            .unwrap_or_else(|| {
12704                                SharedString::from(diagnostic_entry.diagnostic.message)
12705                            });
12706                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12707                        let (Ok(i) | Err(i)) = inline_diagnostics
12708                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12709                        inline_diagnostics.insert(
12710                            i,
12711                            (
12712                                start_anchor,
12713                                InlineDiagnostic {
12714                                    message,
12715                                    group_id: diagnostic_entry.diagnostic.group_id,
12716                                    start: diagnostic_entry.range.start.to_point(&snapshot),
12717                                    is_primary: diagnostic_entry.diagnostic.is_primary,
12718                                    severity: diagnostic_entry.diagnostic.severity,
12719                                },
12720                            ),
12721                        );
12722                    }
12723                    inline_diagnostics
12724                })
12725                .await;
12726
12727            editor
12728                .update(&mut cx, |editor, cx| {
12729                    editor.inline_diagnostics = new_inline_diagnostics;
12730                    cx.notify();
12731                })
12732                .ok();
12733        });
12734    }
12735
12736    pub fn set_selections_from_remote(
12737        &mut self,
12738        selections: Vec<Selection<Anchor>>,
12739        pending_selection: Option<Selection<Anchor>>,
12740        window: &mut Window,
12741        cx: &mut Context<Self>,
12742    ) {
12743        let old_cursor_position = self.selections.newest_anchor().head();
12744        self.selections.change_with(cx, |s| {
12745            s.select_anchors(selections);
12746            if let Some(pending_selection) = pending_selection {
12747                s.set_pending(pending_selection, SelectMode::Character);
12748            } else {
12749                s.clear_pending();
12750            }
12751        });
12752        self.selections_did_change(false, &old_cursor_position, true, window, cx);
12753    }
12754
12755    fn push_to_selection_history(&mut self) {
12756        self.selection_history.push(SelectionHistoryEntry {
12757            selections: self.selections.disjoint_anchors(),
12758            select_next_state: self.select_next_state.clone(),
12759            select_prev_state: self.select_prev_state.clone(),
12760            add_selections_state: self.add_selections_state.clone(),
12761        });
12762    }
12763
12764    pub fn transact(
12765        &mut self,
12766        window: &mut Window,
12767        cx: &mut Context<Self>,
12768        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12769    ) -> Option<TransactionId> {
12770        self.start_transaction_at(Instant::now(), window, cx);
12771        update(self, window, cx);
12772        self.end_transaction_at(Instant::now(), cx)
12773    }
12774
12775    pub fn start_transaction_at(
12776        &mut self,
12777        now: Instant,
12778        window: &mut Window,
12779        cx: &mut Context<Self>,
12780    ) {
12781        self.end_selection(window, cx);
12782        if let Some(tx_id) = self
12783            .buffer
12784            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12785        {
12786            self.selection_history
12787                .insert_transaction(tx_id, self.selections.disjoint_anchors());
12788            cx.emit(EditorEvent::TransactionBegun {
12789                transaction_id: tx_id,
12790            })
12791        }
12792    }
12793
12794    pub fn end_transaction_at(
12795        &mut self,
12796        now: Instant,
12797        cx: &mut Context<Self>,
12798    ) -> Option<TransactionId> {
12799        if let Some(transaction_id) = self
12800            .buffer
12801            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12802        {
12803            if let Some((_, end_selections)) =
12804                self.selection_history.transaction_mut(transaction_id)
12805            {
12806                *end_selections = Some(self.selections.disjoint_anchors());
12807            } else {
12808                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12809            }
12810
12811            cx.emit(EditorEvent::Edited { transaction_id });
12812            Some(transaction_id)
12813        } else {
12814            None
12815        }
12816    }
12817
12818    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12819        if self.selection_mark_mode {
12820            self.change_selections(None, window, cx, |s| {
12821                s.move_with(|_, sel| {
12822                    sel.collapse_to(sel.head(), SelectionGoal::None);
12823                });
12824            })
12825        }
12826        self.selection_mark_mode = true;
12827        cx.notify();
12828    }
12829
12830    pub fn swap_selection_ends(
12831        &mut self,
12832        _: &actions::SwapSelectionEnds,
12833        window: &mut Window,
12834        cx: &mut Context<Self>,
12835    ) {
12836        self.change_selections(None, window, cx, |s| {
12837            s.move_with(|_, sel| {
12838                if sel.start != sel.end {
12839                    sel.reversed = !sel.reversed
12840                }
12841            });
12842        });
12843        self.request_autoscroll(Autoscroll::newest(), cx);
12844        cx.notify();
12845    }
12846
12847    pub fn toggle_fold(
12848        &mut self,
12849        _: &actions::ToggleFold,
12850        window: &mut Window,
12851        cx: &mut Context<Self>,
12852    ) {
12853        if self.is_singleton(cx) {
12854            let selection = self.selections.newest::<Point>(cx);
12855
12856            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12857            let range = if selection.is_empty() {
12858                let point = selection.head().to_display_point(&display_map);
12859                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12860                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12861                    .to_point(&display_map);
12862                start..end
12863            } else {
12864                selection.range()
12865            };
12866            if display_map.folds_in_range(range).next().is_some() {
12867                self.unfold_lines(&Default::default(), window, cx)
12868            } else {
12869                self.fold(&Default::default(), window, cx)
12870            }
12871        } else {
12872            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12873            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12874                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12875                .map(|(snapshot, _, _)| snapshot.remote_id())
12876                .collect();
12877
12878            for buffer_id in buffer_ids {
12879                if self.is_buffer_folded(buffer_id, cx) {
12880                    self.unfold_buffer(buffer_id, cx);
12881                } else {
12882                    self.fold_buffer(buffer_id, cx);
12883                }
12884            }
12885        }
12886    }
12887
12888    pub fn toggle_fold_recursive(
12889        &mut self,
12890        _: &actions::ToggleFoldRecursive,
12891        window: &mut Window,
12892        cx: &mut Context<Self>,
12893    ) {
12894        let selection = self.selections.newest::<Point>(cx);
12895
12896        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12897        let range = if selection.is_empty() {
12898            let point = selection.head().to_display_point(&display_map);
12899            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12900            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12901                .to_point(&display_map);
12902            start..end
12903        } else {
12904            selection.range()
12905        };
12906        if display_map.folds_in_range(range).next().is_some() {
12907            self.unfold_recursive(&Default::default(), window, cx)
12908        } else {
12909            self.fold_recursive(&Default::default(), window, cx)
12910        }
12911    }
12912
12913    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12914        if self.is_singleton(cx) {
12915            let mut to_fold = Vec::new();
12916            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12917            let selections = self.selections.all_adjusted(cx);
12918
12919            for selection in selections {
12920                let range = selection.range().sorted();
12921                let buffer_start_row = range.start.row;
12922
12923                if range.start.row != range.end.row {
12924                    let mut found = false;
12925                    let mut row = range.start.row;
12926                    while row <= range.end.row {
12927                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12928                        {
12929                            found = true;
12930                            row = crease.range().end.row + 1;
12931                            to_fold.push(crease);
12932                        } else {
12933                            row += 1
12934                        }
12935                    }
12936                    if found {
12937                        continue;
12938                    }
12939                }
12940
12941                for row in (0..=range.start.row).rev() {
12942                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12943                        if crease.range().end.row >= buffer_start_row {
12944                            to_fold.push(crease);
12945                            if row <= range.start.row {
12946                                break;
12947                            }
12948                        }
12949                    }
12950                }
12951            }
12952
12953            self.fold_creases(to_fold, true, window, cx);
12954        } else {
12955            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12956
12957            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12958                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12959                .map(|(snapshot, _, _)| snapshot.remote_id())
12960                .collect();
12961            for buffer_id in buffer_ids {
12962                self.fold_buffer(buffer_id, cx);
12963            }
12964        }
12965    }
12966
12967    fn fold_at_level(
12968        &mut self,
12969        fold_at: &FoldAtLevel,
12970        window: &mut Window,
12971        cx: &mut Context<Self>,
12972    ) {
12973        if !self.buffer.read(cx).is_singleton() {
12974            return;
12975        }
12976
12977        let fold_at_level = fold_at.0;
12978        let snapshot = self.buffer.read(cx).snapshot(cx);
12979        let mut to_fold = Vec::new();
12980        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12981
12982        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12983            while start_row < end_row {
12984                match self
12985                    .snapshot(window, cx)
12986                    .crease_for_buffer_row(MultiBufferRow(start_row))
12987                {
12988                    Some(crease) => {
12989                        let nested_start_row = crease.range().start.row + 1;
12990                        let nested_end_row = crease.range().end.row;
12991
12992                        if current_level < fold_at_level {
12993                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12994                        } else if current_level == fold_at_level {
12995                            to_fold.push(crease);
12996                        }
12997
12998                        start_row = nested_end_row + 1;
12999                    }
13000                    None => start_row += 1,
13001                }
13002            }
13003        }
13004
13005        self.fold_creases(to_fold, true, window, cx);
13006    }
13007
13008    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13009        if self.buffer.read(cx).is_singleton() {
13010            let mut fold_ranges = Vec::new();
13011            let snapshot = self.buffer.read(cx).snapshot(cx);
13012
13013            for row in 0..snapshot.max_row().0 {
13014                if let Some(foldable_range) = self
13015                    .snapshot(window, cx)
13016                    .crease_for_buffer_row(MultiBufferRow(row))
13017                {
13018                    fold_ranges.push(foldable_range);
13019                }
13020            }
13021
13022            self.fold_creases(fold_ranges, true, window, cx);
13023        } else {
13024            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13025                editor
13026                    .update_in(&mut cx, |editor, _, cx| {
13027                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13028                            editor.fold_buffer(buffer_id, cx);
13029                        }
13030                    })
13031                    .ok();
13032            });
13033        }
13034    }
13035
13036    pub fn fold_function_bodies(
13037        &mut self,
13038        _: &actions::FoldFunctionBodies,
13039        window: &mut Window,
13040        cx: &mut Context<Self>,
13041    ) {
13042        let snapshot = self.buffer.read(cx).snapshot(cx);
13043
13044        let ranges = snapshot
13045            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13046            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13047            .collect::<Vec<_>>();
13048
13049        let creases = ranges
13050            .into_iter()
13051            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13052            .collect();
13053
13054        self.fold_creases(creases, true, window, cx);
13055    }
13056
13057    pub fn fold_recursive(
13058        &mut self,
13059        _: &actions::FoldRecursive,
13060        window: &mut Window,
13061        cx: &mut Context<Self>,
13062    ) {
13063        let mut to_fold = Vec::new();
13064        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13065        let selections = self.selections.all_adjusted(cx);
13066
13067        for selection in selections {
13068            let range = selection.range().sorted();
13069            let buffer_start_row = range.start.row;
13070
13071            if range.start.row != range.end.row {
13072                let mut found = false;
13073                for row in range.start.row..=range.end.row {
13074                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13075                        found = true;
13076                        to_fold.push(crease);
13077                    }
13078                }
13079                if found {
13080                    continue;
13081                }
13082            }
13083
13084            for row in (0..=range.start.row).rev() {
13085                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13086                    if crease.range().end.row >= buffer_start_row {
13087                        to_fold.push(crease);
13088                    } else {
13089                        break;
13090                    }
13091                }
13092            }
13093        }
13094
13095        self.fold_creases(to_fold, true, window, cx);
13096    }
13097
13098    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13099        let buffer_row = fold_at.buffer_row;
13100        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13101
13102        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13103            let autoscroll = self
13104                .selections
13105                .all::<Point>(cx)
13106                .iter()
13107                .any(|selection| crease.range().overlaps(&selection.range()));
13108
13109            self.fold_creases(vec![crease], autoscroll, window, cx);
13110        }
13111    }
13112
13113    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13114        if self.is_singleton(cx) {
13115            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13116            let buffer = &display_map.buffer_snapshot;
13117            let selections = self.selections.all::<Point>(cx);
13118            let ranges = selections
13119                .iter()
13120                .map(|s| {
13121                    let range = s.display_range(&display_map).sorted();
13122                    let mut start = range.start.to_point(&display_map);
13123                    let mut end = range.end.to_point(&display_map);
13124                    start.column = 0;
13125                    end.column = buffer.line_len(MultiBufferRow(end.row));
13126                    start..end
13127                })
13128                .collect::<Vec<_>>();
13129
13130            self.unfold_ranges(&ranges, true, true, cx);
13131        } else {
13132            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13133            let buffer_ids: HashSet<_> = multi_buffer_snapshot
13134                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
13135                .map(|(snapshot, _, _)| snapshot.remote_id())
13136                .collect();
13137            for buffer_id in buffer_ids {
13138                self.unfold_buffer(buffer_id, cx);
13139            }
13140        }
13141    }
13142
13143    pub fn unfold_recursive(
13144        &mut self,
13145        _: &UnfoldRecursive,
13146        _window: &mut Window,
13147        cx: &mut Context<Self>,
13148    ) {
13149        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13150        let selections = self.selections.all::<Point>(cx);
13151        let ranges = selections
13152            .iter()
13153            .map(|s| {
13154                let mut range = s.display_range(&display_map).sorted();
13155                *range.start.column_mut() = 0;
13156                *range.end.column_mut() = display_map.line_len(range.end.row());
13157                let start = range.start.to_point(&display_map);
13158                let end = range.end.to_point(&display_map);
13159                start..end
13160            })
13161            .collect::<Vec<_>>();
13162
13163        self.unfold_ranges(&ranges, true, true, cx);
13164    }
13165
13166    pub fn unfold_at(
13167        &mut self,
13168        unfold_at: &UnfoldAt,
13169        _window: &mut Window,
13170        cx: &mut Context<Self>,
13171    ) {
13172        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13173
13174        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13175            ..Point::new(
13176                unfold_at.buffer_row.0,
13177                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13178            );
13179
13180        let autoscroll = self
13181            .selections
13182            .all::<Point>(cx)
13183            .iter()
13184            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13185
13186        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13187    }
13188
13189    pub fn unfold_all(
13190        &mut self,
13191        _: &actions::UnfoldAll,
13192        _window: &mut Window,
13193        cx: &mut Context<Self>,
13194    ) {
13195        if self.buffer.read(cx).is_singleton() {
13196            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13197            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13198        } else {
13199            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13200                editor
13201                    .update(&mut cx, |editor, cx| {
13202                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13203                            editor.unfold_buffer(buffer_id, cx);
13204                        }
13205                    })
13206                    .ok();
13207            });
13208        }
13209    }
13210
13211    pub fn fold_selected_ranges(
13212        &mut self,
13213        _: &FoldSelectedRanges,
13214        window: &mut Window,
13215        cx: &mut Context<Self>,
13216    ) {
13217        let selections = self.selections.all::<Point>(cx);
13218        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13219        let line_mode = self.selections.line_mode;
13220        let ranges = selections
13221            .into_iter()
13222            .map(|s| {
13223                if line_mode {
13224                    let start = Point::new(s.start.row, 0);
13225                    let end = Point::new(
13226                        s.end.row,
13227                        display_map
13228                            .buffer_snapshot
13229                            .line_len(MultiBufferRow(s.end.row)),
13230                    );
13231                    Crease::simple(start..end, display_map.fold_placeholder.clone())
13232                } else {
13233                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13234                }
13235            })
13236            .collect::<Vec<_>>();
13237        self.fold_creases(ranges, true, window, cx);
13238    }
13239
13240    pub fn fold_ranges<T: ToOffset + Clone>(
13241        &mut self,
13242        ranges: Vec<Range<T>>,
13243        auto_scroll: bool,
13244        window: &mut Window,
13245        cx: &mut Context<Self>,
13246    ) {
13247        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13248        let ranges = ranges
13249            .into_iter()
13250            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13251            .collect::<Vec<_>>();
13252        self.fold_creases(ranges, auto_scroll, window, cx);
13253    }
13254
13255    pub fn fold_creases<T: ToOffset + Clone>(
13256        &mut self,
13257        creases: Vec<Crease<T>>,
13258        auto_scroll: bool,
13259        window: &mut Window,
13260        cx: &mut Context<Self>,
13261    ) {
13262        if creases.is_empty() {
13263            return;
13264        }
13265
13266        let mut buffers_affected = HashSet::default();
13267        let multi_buffer = self.buffer().read(cx);
13268        for crease in &creases {
13269            if let Some((_, buffer, _)) =
13270                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13271            {
13272                buffers_affected.insert(buffer.read(cx).remote_id());
13273            };
13274        }
13275
13276        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13277
13278        if auto_scroll {
13279            self.request_autoscroll(Autoscroll::fit(), cx);
13280        }
13281
13282        cx.notify();
13283
13284        if let Some(active_diagnostics) = self.active_diagnostics.take() {
13285            // Clear diagnostics block when folding a range that contains it.
13286            let snapshot = self.snapshot(window, cx);
13287            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13288                drop(snapshot);
13289                self.active_diagnostics = Some(active_diagnostics);
13290                self.dismiss_diagnostics(cx);
13291            } else {
13292                self.active_diagnostics = Some(active_diagnostics);
13293            }
13294        }
13295
13296        self.scrollbar_marker_state.dirty = true;
13297    }
13298
13299    /// Removes any folds whose ranges intersect any of the given ranges.
13300    pub fn unfold_ranges<T: ToOffset + Clone>(
13301        &mut self,
13302        ranges: &[Range<T>],
13303        inclusive: bool,
13304        auto_scroll: bool,
13305        cx: &mut Context<Self>,
13306    ) {
13307        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13308            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13309        });
13310    }
13311
13312    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13313        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13314            return;
13315        }
13316        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13317        self.display_map
13318            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
13319        cx.emit(EditorEvent::BufferFoldToggled {
13320            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13321            folded: true,
13322        });
13323        cx.notify();
13324    }
13325
13326    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13327        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13328            return;
13329        }
13330        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13331        self.display_map.update(cx, |display_map, cx| {
13332            display_map.unfold_buffer(buffer_id, cx);
13333        });
13334        cx.emit(EditorEvent::BufferFoldToggled {
13335            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13336            folded: false,
13337        });
13338        cx.notify();
13339    }
13340
13341    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13342        self.display_map.read(cx).is_buffer_folded(buffer)
13343    }
13344
13345    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13346        self.display_map.read(cx).folded_buffers()
13347    }
13348
13349    /// Removes any folds with the given ranges.
13350    pub fn remove_folds_with_type<T: ToOffset + Clone>(
13351        &mut self,
13352        ranges: &[Range<T>],
13353        type_id: TypeId,
13354        auto_scroll: bool,
13355        cx: &mut Context<Self>,
13356    ) {
13357        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13358            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13359        });
13360    }
13361
13362    fn remove_folds_with<T: ToOffset + Clone>(
13363        &mut self,
13364        ranges: &[Range<T>],
13365        auto_scroll: bool,
13366        cx: &mut Context<Self>,
13367        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13368    ) {
13369        if ranges.is_empty() {
13370            return;
13371        }
13372
13373        let mut buffers_affected = HashSet::default();
13374        let multi_buffer = self.buffer().read(cx);
13375        for range in ranges {
13376            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13377                buffers_affected.insert(buffer.read(cx).remote_id());
13378            };
13379        }
13380
13381        self.display_map.update(cx, update);
13382
13383        if auto_scroll {
13384            self.request_autoscroll(Autoscroll::fit(), cx);
13385        }
13386
13387        cx.notify();
13388        self.scrollbar_marker_state.dirty = true;
13389        self.active_indent_guides_state.dirty = true;
13390    }
13391
13392    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13393        self.display_map.read(cx).fold_placeholder.clone()
13394    }
13395
13396    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13397        self.buffer.update(cx, |buffer, cx| {
13398            buffer.set_all_diff_hunks_expanded(cx);
13399        });
13400    }
13401
13402    pub fn expand_all_diff_hunks(
13403        &mut self,
13404        _: &ExpandAllDiffHunks,
13405        _window: &mut Window,
13406        cx: &mut Context<Self>,
13407    ) {
13408        self.buffer.update(cx, |buffer, cx| {
13409            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13410        });
13411    }
13412
13413    pub fn toggle_selected_diff_hunks(
13414        &mut self,
13415        _: &ToggleSelectedDiffHunks,
13416        _window: &mut Window,
13417        cx: &mut Context<Self>,
13418    ) {
13419        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13420        self.toggle_diff_hunks_in_ranges(ranges, cx);
13421    }
13422
13423    pub fn diff_hunks_in_ranges<'a>(
13424        &'a self,
13425        ranges: &'a [Range<Anchor>],
13426        buffer: &'a MultiBufferSnapshot,
13427    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13428        ranges.iter().flat_map(move |range| {
13429            let end_excerpt_id = range.end.excerpt_id;
13430            let range = range.to_point(buffer);
13431            let mut peek_end = range.end;
13432            if range.end.row < buffer.max_row().0 {
13433                peek_end = Point::new(range.end.row + 1, 0);
13434            }
13435            buffer
13436                .diff_hunks_in_range(range.start..peek_end)
13437                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13438        })
13439    }
13440
13441    pub fn has_stageable_diff_hunks_in_ranges(
13442        &self,
13443        ranges: &[Range<Anchor>],
13444        snapshot: &MultiBufferSnapshot,
13445    ) -> bool {
13446        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13447        hunks.any(|hunk| hunk.secondary_status != DiffHunkSecondaryStatus::None)
13448    }
13449
13450    pub fn toggle_staged_selected_diff_hunks(
13451        &mut self,
13452        _: &::git::ToggleStaged,
13453        window: &mut Window,
13454        cx: &mut Context<Self>,
13455    ) {
13456        let snapshot = self.buffer.read(cx).snapshot(cx);
13457        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13458        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13459        self.stage_or_unstage_diff_hunks(stage, &ranges, window, cx);
13460    }
13461
13462    pub fn stage_and_next(
13463        &mut self,
13464        _: &::git::StageAndNext,
13465        window: &mut Window,
13466        cx: &mut Context<Self>,
13467    ) {
13468        self.do_stage_or_unstage_and_next(true, window, cx);
13469    }
13470
13471    pub fn unstage_and_next(
13472        &mut self,
13473        _: &::git::UnstageAndNext,
13474        window: &mut Window,
13475        cx: &mut Context<Self>,
13476    ) {
13477        self.do_stage_or_unstage_and_next(false, window, cx);
13478    }
13479
13480    pub fn stage_or_unstage_diff_hunks(
13481        &mut self,
13482        stage: bool,
13483        ranges: &[Range<Anchor>],
13484        window: &mut Window,
13485        cx: &mut Context<Self>,
13486    ) {
13487        let snapshot = self.buffer.read(cx).snapshot(cx);
13488        let Some(project) = &self.project else {
13489            return;
13490        };
13491
13492        let chunk_by = self
13493            .diff_hunks_in_ranges(&ranges, &snapshot)
13494            .chunk_by(|hunk| hunk.buffer_id);
13495        for (buffer_id, hunks) in &chunk_by {
13496            Self::do_stage_or_unstage(project, stage, buffer_id, hunks, &snapshot, window, cx);
13497        }
13498    }
13499
13500    fn do_stage_or_unstage_and_next(
13501        &mut self,
13502        stage: bool,
13503        window: &mut Window,
13504        cx: &mut Context<Self>,
13505    ) {
13506        let mut ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13507        if ranges.iter().any(|range| range.start != range.end) {
13508            self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13509            return;
13510        }
13511
13512        if !self.buffer().read(cx).is_singleton() {
13513            if let Some((excerpt_id, buffer, range)) = self.active_excerpt(cx) {
13514                if buffer.read(cx).is_empty() {
13515                    let buffer = buffer.read(cx);
13516                    let Some(file) = buffer.file() else {
13517                        return;
13518                    };
13519                    let project_path = project::ProjectPath {
13520                        worktree_id: file.worktree_id(cx),
13521                        path: file.path().clone(),
13522                    };
13523                    let Some(project) = self.project.as_ref() else {
13524                        return;
13525                    };
13526                    let project = project.read(cx);
13527
13528                    let Some(repo) = project.git_store().read(cx).active_repository() else {
13529                        return;
13530                    };
13531
13532                    repo.update(cx, |repo, cx| {
13533                        let Some(repo_path) = repo.project_path_to_repo_path(&project_path) else {
13534                            return;
13535                        };
13536                        let Some(status) = repo.repository_entry.status_for_path(&repo_path) else {
13537                            return;
13538                        };
13539                        if stage && status.status == FileStatus::Untracked {
13540                            repo.stage_entries(vec![repo_path], cx)
13541                                .detach_and_log_err(cx);
13542                            return;
13543                        }
13544                    })
13545                }
13546                ranges = vec![multi_buffer::Anchor::range_in_buffer(
13547                    excerpt_id,
13548                    buffer.read(cx).remote_id(),
13549                    range,
13550                )];
13551                self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13552                let snapshot = self.buffer().read(cx).snapshot(cx);
13553                let mut point = ranges.last().unwrap().end.to_point(&snapshot);
13554                if point.row < snapshot.max_row().0 {
13555                    point.row += 1;
13556                    point.column = 0;
13557                    point = snapshot.clip_point(point, Bias::Right);
13558                    self.change_selections(Some(Autoscroll::top_relative(6)), window, cx, |s| {
13559                        s.select_ranges([point..point]);
13560                    })
13561                }
13562                return;
13563            }
13564        }
13565        self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13566        self.go_to_next_hunk(&Default::default(), window, cx);
13567    }
13568
13569    fn do_stage_or_unstage(
13570        project: &Entity<Project>,
13571        stage: bool,
13572        buffer_id: BufferId,
13573        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13574        snapshot: &MultiBufferSnapshot,
13575        window: &mut Window,
13576        cx: &mut App,
13577    ) {
13578        let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
13579            log::debug!("no buffer for id");
13580            return;
13581        };
13582        let buffer_snapshot = buffer.read(cx).snapshot();
13583        let file_exists = buffer_snapshot
13584            .file()
13585            .is_some_and(|file| file.disk_state().exists());
13586        let Some((repo, path)) = project
13587            .read(cx)
13588            .repository_and_path_for_buffer_id(buffer_id, cx)
13589        else {
13590            log::debug!("no git repo for buffer id");
13591            return;
13592        };
13593        let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
13594            log::debug!("no diff for buffer id");
13595            return;
13596        };
13597
13598        let new_index_text = if !stage && diff.is_single_insertion || stage && !file_exists {
13599            log::debug!("removing from index");
13600            None
13601        } else {
13602            diff.new_secondary_text_for_stage_or_unstage(
13603                stage,
13604                hunks.filter_map(|hunk| {
13605                    if stage && hunk.secondary_status == DiffHunkSecondaryStatus::None {
13606                        return None;
13607                    } else if !stage
13608                        && hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
13609                    {
13610                        return None;
13611                    }
13612                    Some((hunk.buffer_range.clone(), hunk.diff_base_byte_range.clone()))
13613                }),
13614                &buffer_snapshot,
13615                cx,
13616            )
13617        };
13618        if file_exists {
13619            let buffer_store = project.read(cx).buffer_store().clone();
13620            buffer_store
13621                .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
13622                .detach_and_log_err(cx);
13623        }
13624        let recv = repo
13625            .read(cx)
13626            .set_index_text(&path, new_index_text.map(|rope| rope.to_string()));
13627
13628        cx.background_spawn(async move { recv.await? })
13629            .detach_and_notify_err(window, cx);
13630    }
13631
13632    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13633        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13634        self.buffer
13635            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13636    }
13637
13638    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13639        self.buffer.update(cx, |buffer, cx| {
13640            let ranges = vec![Anchor::min()..Anchor::max()];
13641            if !buffer.all_diff_hunks_expanded()
13642                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13643            {
13644                buffer.collapse_diff_hunks(ranges, cx);
13645                true
13646            } else {
13647                false
13648            }
13649        })
13650    }
13651
13652    fn toggle_diff_hunks_in_ranges(
13653        &mut self,
13654        ranges: Vec<Range<Anchor>>,
13655        cx: &mut Context<'_, Editor>,
13656    ) {
13657        self.buffer.update(cx, |buffer, cx| {
13658            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13659            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13660        })
13661    }
13662
13663    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13664        self.buffer.update(cx, |buffer, cx| {
13665            let snapshot = buffer.snapshot(cx);
13666            let excerpt_id = range.end.excerpt_id;
13667            let point_range = range.to_point(&snapshot);
13668            let expand = !buffer.single_hunk_is_expanded(range, cx);
13669            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13670        })
13671    }
13672
13673    pub(crate) fn apply_all_diff_hunks(
13674        &mut self,
13675        _: &ApplyAllDiffHunks,
13676        window: &mut Window,
13677        cx: &mut Context<Self>,
13678    ) {
13679        let buffers = self.buffer.read(cx).all_buffers();
13680        for branch_buffer in buffers {
13681            branch_buffer.update(cx, |branch_buffer, cx| {
13682                branch_buffer.merge_into_base(Vec::new(), cx);
13683            });
13684        }
13685
13686        if let Some(project) = self.project.clone() {
13687            self.save(true, project, window, cx).detach_and_log_err(cx);
13688        }
13689    }
13690
13691    pub(crate) fn apply_selected_diff_hunks(
13692        &mut self,
13693        _: &ApplyDiffHunk,
13694        window: &mut Window,
13695        cx: &mut Context<Self>,
13696    ) {
13697        let snapshot = self.snapshot(window, cx);
13698        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
13699        let mut ranges_by_buffer = HashMap::default();
13700        self.transact(window, cx, |editor, _window, cx| {
13701            for hunk in hunks {
13702                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13703                    ranges_by_buffer
13704                        .entry(buffer.clone())
13705                        .or_insert_with(Vec::new)
13706                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13707                }
13708            }
13709
13710            for (buffer, ranges) in ranges_by_buffer {
13711                buffer.update(cx, |buffer, cx| {
13712                    buffer.merge_into_base(ranges, cx);
13713                });
13714            }
13715        });
13716
13717        if let Some(project) = self.project.clone() {
13718            self.save(true, project, window, cx).detach_and_log_err(cx);
13719        }
13720    }
13721
13722    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13723        if hovered != self.gutter_hovered {
13724            self.gutter_hovered = hovered;
13725            cx.notify();
13726        }
13727    }
13728
13729    pub fn insert_blocks(
13730        &mut self,
13731        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13732        autoscroll: Option<Autoscroll>,
13733        cx: &mut Context<Self>,
13734    ) -> Vec<CustomBlockId> {
13735        let blocks = self
13736            .display_map
13737            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13738        if let Some(autoscroll) = autoscroll {
13739            self.request_autoscroll(autoscroll, cx);
13740        }
13741        cx.notify();
13742        blocks
13743    }
13744
13745    pub fn resize_blocks(
13746        &mut self,
13747        heights: HashMap<CustomBlockId, u32>,
13748        autoscroll: Option<Autoscroll>,
13749        cx: &mut Context<Self>,
13750    ) {
13751        self.display_map
13752            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13753        if let Some(autoscroll) = autoscroll {
13754            self.request_autoscroll(autoscroll, cx);
13755        }
13756        cx.notify();
13757    }
13758
13759    pub fn replace_blocks(
13760        &mut self,
13761        renderers: HashMap<CustomBlockId, RenderBlock>,
13762        autoscroll: Option<Autoscroll>,
13763        cx: &mut Context<Self>,
13764    ) {
13765        self.display_map
13766            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13767        if let Some(autoscroll) = autoscroll {
13768            self.request_autoscroll(autoscroll, cx);
13769        }
13770        cx.notify();
13771    }
13772
13773    pub fn remove_blocks(
13774        &mut self,
13775        block_ids: HashSet<CustomBlockId>,
13776        autoscroll: Option<Autoscroll>,
13777        cx: &mut Context<Self>,
13778    ) {
13779        self.display_map.update(cx, |display_map, cx| {
13780            display_map.remove_blocks(block_ids, cx)
13781        });
13782        if let Some(autoscroll) = autoscroll {
13783            self.request_autoscroll(autoscroll, cx);
13784        }
13785        cx.notify();
13786    }
13787
13788    pub fn row_for_block(
13789        &self,
13790        block_id: CustomBlockId,
13791        cx: &mut Context<Self>,
13792    ) -> Option<DisplayRow> {
13793        self.display_map
13794            .update(cx, |map, cx| map.row_for_block(block_id, cx))
13795    }
13796
13797    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13798        self.focused_block = Some(focused_block);
13799    }
13800
13801    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13802        self.focused_block.take()
13803    }
13804
13805    pub fn insert_creases(
13806        &mut self,
13807        creases: impl IntoIterator<Item = Crease<Anchor>>,
13808        cx: &mut Context<Self>,
13809    ) -> Vec<CreaseId> {
13810        self.display_map
13811            .update(cx, |map, cx| map.insert_creases(creases, cx))
13812    }
13813
13814    pub fn remove_creases(
13815        &mut self,
13816        ids: impl IntoIterator<Item = CreaseId>,
13817        cx: &mut Context<Self>,
13818    ) {
13819        self.display_map
13820            .update(cx, |map, cx| map.remove_creases(ids, cx));
13821    }
13822
13823    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13824        self.display_map
13825            .update(cx, |map, cx| map.snapshot(cx))
13826            .longest_row()
13827    }
13828
13829    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13830        self.display_map
13831            .update(cx, |map, cx| map.snapshot(cx))
13832            .max_point()
13833    }
13834
13835    pub fn text(&self, cx: &App) -> String {
13836        self.buffer.read(cx).read(cx).text()
13837    }
13838
13839    pub fn is_empty(&self, cx: &App) -> bool {
13840        self.buffer.read(cx).read(cx).is_empty()
13841    }
13842
13843    pub fn text_option(&self, cx: &App) -> Option<String> {
13844        let text = self.text(cx);
13845        let text = text.trim();
13846
13847        if text.is_empty() {
13848            return None;
13849        }
13850
13851        Some(text.to_string())
13852    }
13853
13854    pub fn set_text(
13855        &mut self,
13856        text: impl Into<Arc<str>>,
13857        window: &mut Window,
13858        cx: &mut Context<Self>,
13859    ) {
13860        self.transact(window, cx, |this, _, cx| {
13861            this.buffer
13862                .read(cx)
13863                .as_singleton()
13864                .expect("you can only call set_text on editors for singleton buffers")
13865                .update(cx, |buffer, cx| buffer.set_text(text, cx));
13866        });
13867    }
13868
13869    pub fn display_text(&self, cx: &mut App) -> String {
13870        self.display_map
13871            .update(cx, |map, cx| map.snapshot(cx))
13872            .text()
13873    }
13874
13875    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
13876        let mut wrap_guides = smallvec::smallvec![];
13877
13878        if self.show_wrap_guides == Some(false) {
13879            return wrap_guides;
13880        }
13881
13882        let settings = self.buffer.read(cx).settings_at(0, cx);
13883        if settings.show_wrap_guides {
13884            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
13885                wrap_guides.push((soft_wrap as usize, true));
13886            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
13887                wrap_guides.push((soft_wrap as usize, true));
13888            }
13889            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
13890        }
13891
13892        wrap_guides
13893    }
13894
13895    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
13896        let settings = self.buffer.read(cx).settings_at(0, cx);
13897        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
13898        match mode {
13899            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
13900                SoftWrap::None
13901            }
13902            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13903            language_settings::SoftWrap::PreferredLineLength => {
13904                SoftWrap::Column(settings.preferred_line_length)
13905            }
13906            language_settings::SoftWrap::Bounded => {
13907                SoftWrap::Bounded(settings.preferred_line_length)
13908            }
13909        }
13910    }
13911
13912    pub fn set_soft_wrap_mode(
13913        &mut self,
13914        mode: language_settings::SoftWrap,
13915
13916        cx: &mut Context<Self>,
13917    ) {
13918        self.soft_wrap_mode_override = Some(mode);
13919        cx.notify();
13920    }
13921
13922    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13923        self.text_style_refinement = Some(style);
13924    }
13925
13926    /// called by the Element so we know what style we were most recently rendered with.
13927    pub(crate) fn set_style(
13928        &mut self,
13929        style: EditorStyle,
13930        window: &mut Window,
13931        cx: &mut Context<Self>,
13932    ) {
13933        let rem_size = window.rem_size();
13934        self.display_map.update(cx, |map, cx| {
13935            map.set_font(
13936                style.text.font(),
13937                style.text.font_size.to_pixels(rem_size),
13938                cx,
13939            )
13940        });
13941        self.style = Some(style);
13942    }
13943
13944    pub fn style(&self) -> Option<&EditorStyle> {
13945        self.style.as_ref()
13946    }
13947
13948    // Called by the element. This method is not designed to be called outside of the editor
13949    // element's layout code because it does not notify when rewrapping is computed synchronously.
13950    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13951        self.display_map
13952            .update(cx, |map, cx| map.set_wrap_width(width, cx))
13953    }
13954
13955    pub fn set_soft_wrap(&mut self) {
13956        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13957    }
13958
13959    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13960        if self.soft_wrap_mode_override.is_some() {
13961            self.soft_wrap_mode_override.take();
13962        } else {
13963            let soft_wrap = match self.soft_wrap_mode(cx) {
13964                SoftWrap::GitDiff => return,
13965                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13966                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13967                    language_settings::SoftWrap::None
13968                }
13969            };
13970            self.soft_wrap_mode_override = Some(soft_wrap);
13971        }
13972        cx.notify();
13973    }
13974
13975    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13976        let Some(workspace) = self.workspace() else {
13977            return;
13978        };
13979        let fs = workspace.read(cx).app_state().fs.clone();
13980        let current_show = TabBarSettings::get_global(cx).show;
13981        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13982            setting.show = Some(!current_show);
13983        });
13984    }
13985
13986    pub fn toggle_indent_guides(
13987        &mut self,
13988        _: &ToggleIndentGuides,
13989        _: &mut Window,
13990        cx: &mut Context<Self>,
13991    ) {
13992        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13993            self.buffer
13994                .read(cx)
13995                .settings_at(0, cx)
13996                .indent_guides
13997                .enabled
13998        });
13999        self.show_indent_guides = Some(!currently_enabled);
14000        cx.notify();
14001    }
14002
14003    fn should_show_indent_guides(&self) -> Option<bool> {
14004        self.show_indent_guides
14005    }
14006
14007    pub fn toggle_line_numbers(
14008        &mut self,
14009        _: &ToggleLineNumbers,
14010        _: &mut Window,
14011        cx: &mut Context<Self>,
14012    ) {
14013        let mut editor_settings = EditorSettings::get_global(cx).clone();
14014        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14015        EditorSettings::override_global(editor_settings, cx);
14016    }
14017
14018    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14019        self.use_relative_line_numbers
14020            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14021    }
14022
14023    pub fn toggle_relative_line_numbers(
14024        &mut self,
14025        _: &ToggleRelativeLineNumbers,
14026        _: &mut Window,
14027        cx: &mut Context<Self>,
14028    ) {
14029        let is_relative = self.should_use_relative_line_numbers(cx);
14030        self.set_relative_line_number(Some(!is_relative), cx)
14031    }
14032
14033    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14034        self.use_relative_line_numbers = is_relative;
14035        cx.notify();
14036    }
14037
14038    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14039        self.show_gutter = show_gutter;
14040        cx.notify();
14041    }
14042
14043    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14044        self.show_scrollbars = show_scrollbars;
14045        cx.notify();
14046    }
14047
14048    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14049        self.show_line_numbers = Some(show_line_numbers);
14050        cx.notify();
14051    }
14052
14053    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14054        self.show_git_diff_gutter = Some(show_git_diff_gutter);
14055        cx.notify();
14056    }
14057
14058    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14059        self.show_code_actions = Some(show_code_actions);
14060        cx.notify();
14061    }
14062
14063    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14064        self.show_runnables = Some(show_runnables);
14065        cx.notify();
14066    }
14067
14068    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14069        if self.display_map.read(cx).masked != masked {
14070            self.display_map.update(cx, |map, _| map.masked = masked);
14071        }
14072        cx.notify()
14073    }
14074
14075    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14076        self.show_wrap_guides = Some(show_wrap_guides);
14077        cx.notify();
14078    }
14079
14080    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14081        self.show_indent_guides = Some(show_indent_guides);
14082        cx.notify();
14083    }
14084
14085    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14086        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14087            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14088                if let Some(dir) = file.abs_path(cx).parent() {
14089                    return Some(dir.to_owned());
14090                }
14091            }
14092
14093            if let Some(project_path) = buffer.read(cx).project_path(cx) {
14094                return Some(project_path.path.to_path_buf());
14095            }
14096        }
14097
14098        None
14099    }
14100
14101    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14102        self.active_excerpt(cx)?
14103            .1
14104            .read(cx)
14105            .file()
14106            .and_then(|f| f.as_local())
14107    }
14108
14109    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14110        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14111            let buffer = buffer.read(cx);
14112            if let Some(project_path) = buffer.project_path(cx) {
14113                let project = self.project.as_ref()?.read(cx);
14114                project.absolute_path(&project_path, cx)
14115            } else {
14116                buffer
14117                    .file()
14118                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14119            }
14120        })
14121    }
14122
14123    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14124        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14125            let project_path = buffer.read(cx).project_path(cx)?;
14126            let project = self.project.as_ref()?.read(cx);
14127            let entry = project.entry_for_path(&project_path, cx)?;
14128            let path = entry.path.to_path_buf();
14129            Some(path)
14130        })
14131    }
14132
14133    pub fn reveal_in_finder(
14134        &mut self,
14135        _: &RevealInFileManager,
14136        _window: &mut Window,
14137        cx: &mut Context<Self>,
14138    ) {
14139        if let Some(target) = self.target_file(cx) {
14140            cx.reveal_path(&target.abs_path(cx));
14141        }
14142    }
14143
14144    pub fn copy_path(
14145        &mut self,
14146        _: &zed_actions::workspace::CopyPath,
14147        _window: &mut Window,
14148        cx: &mut Context<Self>,
14149    ) {
14150        if let Some(path) = self.target_file_abs_path(cx) {
14151            if let Some(path) = path.to_str() {
14152                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14153            }
14154        }
14155    }
14156
14157    pub fn copy_relative_path(
14158        &mut self,
14159        _: &zed_actions::workspace::CopyRelativePath,
14160        _window: &mut Window,
14161        cx: &mut Context<Self>,
14162    ) {
14163        if let Some(path) = self.target_file_path(cx) {
14164            if let Some(path) = path.to_str() {
14165                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14166            }
14167        }
14168    }
14169
14170    pub fn copy_file_name_without_extension(
14171        &mut self,
14172        _: &CopyFileNameWithoutExtension,
14173        _: &mut Window,
14174        cx: &mut Context<Self>,
14175    ) {
14176        if let Some(file) = self.target_file(cx) {
14177            if let Some(file_stem) = file.path().file_stem() {
14178                if let Some(name) = file_stem.to_str() {
14179                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14180                }
14181            }
14182        }
14183    }
14184
14185    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14186        if let Some(file) = self.target_file(cx) {
14187            if let Some(file_name) = file.path().file_name() {
14188                if let Some(name) = file_name.to_str() {
14189                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14190                }
14191            }
14192        }
14193    }
14194
14195    pub fn toggle_git_blame(
14196        &mut self,
14197        _: &ToggleGitBlame,
14198        window: &mut Window,
14199        cx: &mut Context<Self>,
14200    ) {
14201        self.show_git_blame_gutter = !self.show_git_blame_gutter;
14202
14203        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14204            self.start_git_blame(true, window, cx);
14205        }
14206
14207        cx.notify();
14208    }
14209
14210    pub fn toggle_git_blame_inline(
14211        &mut self,
14212        _: &ToggleGitBlameInline,
14213        window: &mut Window,
14214        cx: &mut Context<Self>,
14215    ) {
14216        self.toggle_git_blame_inline_internal(true, window, cx);
14217        cx.notify();
14218    }
14219
14220    pub fn git_blame_inline_enabled(&self) -> bool {
14221        self.git_blame_inline_enabled
14222    }
14223
14224    pub fn toggle_selection_menu(
14225        &mut self,
14226        _: &ToggleSelectionMenu,
14227        _: &mut Window,
14228        cx: &mut Context<Self>,
14229    ) {
14230        self.show_selection_menu = self
14231            .show_selection_menu
14232            .map(|show_selections_menu| !show_selections_menu)
14233            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14234
14235        cx.notify();
14236    }
14237
14238    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14239        self.show_selection_menu
14240            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14241    }
14242
14243    fn start_git_blame(
14244        &mut self,
14245        user_triggered: bool,
14246        window: &mut Window,
14247        cx: &mut Context<Self>,
14248    ) {
14249        if let Some(project) = self.project.as_ref() {
14250            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14251                return;
14252            };
14253
14254            if buffer.read(cx).file().is_none() {
14255                return;
14256            }
14257
14258            let focused = self.focus_handle(cx).contains_focused(window, cx);
14259
14260            let project = project.clone();
14261            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14262            self.blame_subscription =
14263                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14264            self.blame = Some(blame);
14265        }
14266    }
14267
14268    fn toggle_git_blame_inline_internal(
14269        &mut self,
14270        user_triggered: bool,
14271        window: &mut Window,
14272        cx: &mut Context<Self>,
14273    ) {
14274        if self.git_blame_inline_enabled {
14275            self.git_blame_inline_enabled = false;
14276            self.show_git_blame_inline = false;
14277            self.show_git_blame_inline_delay_task.take();
14278        } else {
14279            self.git_blame_inline_enabled = true;
14280            self.start_git_blame_inline(user_triggered, window, cx);
14281        }
14282
14283        cx.notify();
14284    }
14285
14286    fn start_git_blame_inline(
14287        &mut self,
14288        user_triggered: bool,
14289        window: &mut Window,
14290        cx: &mut Context<Self>,
14291    ) {
14292        self.start_git_blame(user_triggered, window, cx);
14293
14294        if ProjectSettings::get_global(cx)
14295            .git
14296            .inline_blame_delay()
14297            .is_some()
14298        {
14299            self.start_inline_blame_timer(window, cx);
14300        } else {
14301            self.show_git_blame_inline = true
14302        }
14303    }
14304
14305    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14306        self.blame.as_ref()
14307    }
14308
14309    pub fn show_git_blame_gutter(&self) -> bool {
14310        self.show_git_blame_gutter
14311    }
14312
14313    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14314        self.show_git_blame_gutter && self.has_blame_entries(cx)
14315    }
14316
14317    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14318        self.show_git_blame_inline
14319            && (self.focus_handle.is_focused(window)
14320                || self
14321                    .git_blame_inline_tooltip
14322                    .as_ref()
14323                    .and_then(|t| t.upgrade())
14324                    .is_some())
14325            && !self.newest_selection_head_on_empty_line(cx)
14326            && self.has_blame_entries(cx)
14327    }
14328
14329    fn has_blame_entries(&self, cx: &App) -> bool {
14330        self.blame()
14331            .map_or(false, |blame| blame.read(cx).has_generated_entries())
14332    }
14333
14334    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14335        let cursor_anchor = self.selections.newest_anchor().head();
14336
14337        let snapshot = self.buffer.read(cx).snapshot(cx);
14338        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14339
14340        snapshot.line_len(buffer_row) == 0
14341    }
14342
14343    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14344        let buffer_and_selection = maybe!({
14345            let selection = self.selections.newest::<Point>(cx);
14346            let selection_range = selection.range();
14347
14348            let multi_buffer = self.buffer().read(cx);
14349            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14350            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14351
14352            let (buffer, range, _) = if selection.reversed {
14353                buffer_ranges.first()
14354            } else {
14355                buffer_ranges.last()
14356            }?;
14357
14358            let selection = text::ToPoint::to_point(&range.start, &buffer).row
14359                ..text::ToPoint::to_point(&range.end, &buffer).row;
14360            Some((
14361                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14362                selection,
14363            ))
14364        });
14365
14366        let Some((buffer, selection)) = buffer_and_selection else {
14367            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14368        };
14369
14370        let Some(project) = self.project.as_ref() else {
14371            return Task::ready(Err(anyhow!("editor does not have project")));
14372        };
14373
14374        project.update(cx, |project, cx| {
14375            project.get_permalink_to_line(&buffer, selection, cx)
14376        })
14377    }
14378
14379    pub fn copy_permalink_to_line(
14380        &mut self,
14381        _: &CopyPermalinkToLine,
14382        window: &mut Window,
14383        cx: &mut Context<Self>,
14384    ) {
14385        let permalink_task = self.get_permalink_to_line(cx);
14386        let workspace = self.workspace();
14387
14388        cx.spawn_in(window, |_, mut cx| async move {
14389            match permalink_task.await {
14390                Ok(permalink) => {
14391                    cx.update(|_, cx| {
14392                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14393                    })
14394                    .ok();
14395                }
14396                Err(err) => {
14397                    let message = format!("Failed to copy permalink: {err}");
14398
14399                    Err::<(), anyhow::Error>(err).log_err();
14400
14401                    if let Some(workspace) = workspace {
14402                        workspace
14403                            .update_in(&mut cx, |workspace, _, cx| {
14404                                struct CopyPermalinkToLine;
14405
14406                                workspace.show_toast(
14407                                    Toast::new(
14408                                        NotificationId::unique::<CopyPermalinkToLine>(),
14409                                        message,
14410                                    ),
14411                                    cx,
14412                                )
14413                            })
14414                            .ok();
14415                    }
14416                }
14417            }
14418        })
14419        .detach();
14420    }
14421
14422    pub fn copy_file_location(
14423        &mut self,
14424        _: &CopyFileLocation,
14425        _: &mut Window,
14426        cx: &mut Context<Self>,
14427    ) {
14428        let selection = self.selections.newest::<Point>(cx).start.row + 1;
14429        if let Some(file) = self.target_file(cx) {
14430            if let Some(path) = file.path().to_str() {
14431                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14432            }
14433        }
14434    }
14435
14436    pub fn open_permalink_to_line(
14437        &mut self,
14438        _: &OpenPermalinkToLine,
14439        window: &mut Window,
14440        cx: &mut Context<Self>,
14441    ) {
14442        let permalink_task = self.get_permalink_to_line(cx);
14443        let workspace = self.workspace();
14444
14445        cx.spawn_in(window, |_, mut cx| async move {
14446            match permalink_task.await {
14447                Ok(permalink) => {
14448                    cx.update(|_, cx| {
14449                        cx.open_url(permalink.as_ref());
14450                    })
14451                    .ok();
14452                }
14453                Err(err) => {
14454                    let message = format!("Failed to open permalink: {err}");
14455
14456                    Err::<(), anyhow::Error>(err).log_err();
14457
14458                    if let Some(workspace) = workspace {
14459                        workspace
14460                            .update(&mut cx, |workspace, cx| {
14461                                struct OpenPermalinkToLine;
14462
14463                                workspace.show_toast(
14464                                    Toast::new(
14465                                        NotificationId::unique::<OpenPermalinkToLine>(),
14466                                        message,
14467                                    ),
14468                                    cx,
14469                                )
14470                            })
14471                            .ok();
14472                    }
14473                }
14474            }
14475        })
14476        .detach();
14477    }
14478
14479    pub fn insert_uuid_v4(
14480        &mut self,
14481        _: &InsertUuidV4,
14482        window: &mut Window,
14483        cx: &mut Context<Self>,
14484    ) {
14485        self.insert_uuid(UuidVersion::V4, window, cx);
14486    }
14487
14488    pub fn insert_uuid_v7(
14489        &mut self,
14490        _: &InsertUuidV7,
14491        window: &mut Window,
14492        cx: &mut Context<Self>,
14493    ) {
14494        self.insert_uuid(UuidVersion::V7, window, cx);
14495    }
14496
14497    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14498        self.transact(window, cx, |this, window, cx| {
14499            let edits = this
14500                .selections
14501                .all::<Point>(cx)
14502                .into_iter()
14503                .map(|selection| {
14504                    let uuid = match version {
14505                        UuidVersion::V4 => uuid::Uuid::new_v4(),
14506                        UuidVersion::V7 => uuid::Uuid::now_v7(),
14507                    };
14508
14509                    (selection.range(), uuid.to_string())
14510                });
14511            this.edit(edits, cx);
14512            this.refresh_inline_completion(true, false, window, cx);
14513        });
14514    }
14515
14516    pub fn open_selections_in_multibuffer(
14517        &mut self,
14518        _: &OpenSelectionsInMultibuffer,
14519        window: &mut Window,
14520        cx: &mut Context<Self>,
14521    ) {
14522        let multibuffer = self.buffer.read(cx);
14523
14524        let Some(buffer) = multibuffer.as_singleton() else {
14525            return;
14526        };
14527
14528        let Some(workspace) = self.workspace() else {
14529            return;
14530        };
14531
14532        let locations = self
14533            .selections
14534            .disjoint_anchors()
14535            .iter()
14536            .map(|range| Location {
14537                buffer: buffer.clone(),
14538                range: range.start.text_anchor..range.end.text_anchor,
14539            })
14540            .collect::<Vec<_>>();
14541
14542        let title = multibuffer.title(cx).to_string();
14543
14544        cx.spawn_in(window, |_, mut cx| async move {
14545            workspace.update_in(&mut cx, |workspace, window, cx| {
14546                Self::open_locations_in_multibuffer(
14547                    workspace,
14548                    locations,
14549                    format!("Selections for '{title}'"),
14550                    false,
14551                    MultibufferSelectionMode::All,
14552                    window,
14553                    cx,
14554                );
14555            })
14556        })
14557        .detach();
14558    }
14559
14560    /// Adds a row highlight for the given range. If a row has multiple highlights, the
14561    /// last highlight added will be used.
14562    ///
14563    /// If the range ends at the beginning of a line, then that line will not be highlighted.
14564    pub fn highlight_rows<T: 'static>(
14565        &mut self,
14566        range: Range<Anchor>,
14567        color: Hsla,
14568        should_autoscroll: bool,
14569        cx: &mut Context<Self>,
14570    ) {
14571        let snapshot = self.buffer().read(cx).snapshot(cx);
14572        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14573        let ix = row_highlights.binary_search_by(|highlight| {
14574            Ordering::Equal
14575                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14576                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14577        });
14578
14579        if let Err(mut ix) = ix {
14580            let index = post_inc(&mut self.highlight_order);
14581
14582            // If this range intersects with the preceding highlight, then merge it with
14583            // the preceding highlight. Otherwise insert a new highlight.
14584            let mut merged = false;
14585            if ix > 0 {
14586                let prev_highlight = &mut row_highlights[ix - 1];
14587                if prev_highlight
14588                    .range
14589                    .end
14590                    .cmp(&range.start, &snapshot)
14591                    .is_ge()
14592                {
14593                    ix -= 1;
14594                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14595                        prev_highlight.range.end = range.end;
14596                    }
14597                    merged = true;
14598                    prev_highlight.index = index;
14599                    prev_highlight.color = color;
14600                    prev_highlight.should_autoscroll = should_autoscroll;
14601                }
14602            }
14603
14604            if !merged {
14605                row_highlights.insert(
14606                    ix,
14607                    RowHighlight {
14608                        range: range.clone(),
14609                        index,
14610                        color,
14611                        should_autoscroll,
14612                    },
14613                );
14614            }
14615
14616            // If any of the following highlights intersect with this one, merge them.
14617            while let Some(next_highlight) = row_highlights.get(ix + 1) {
14618                let highlight = &row_highlights[ix];
14619                if next_highlight
14620                    .range
14621                    .start
14622                    .cmp(&highlight.range.end, &snapshot)
14623                    .is_le()
14624                {
14625                    if next_highlight
14626                        .range
14627                        .end
14628                        .cmp(&highlight.range.end, &snapshot)
14629                        .is_gt()
14630                    {
14631                        row_highlights[ix].range.end = next_highlight.range.end;
14632                    }
14633                    row_highlights.remove(ix + 1);
14634                } else {
14635                    break;
14636                }
14637            }
14638        }
14639    }
14640
14641    /// Remove any highlighted row ranges of the given type that intersect the
14642    /// given ranges.
14643    pub fn remove_highlighted_rows<T: 'static>(
14644        &mut self,
14645        ranges_to_remove: Vec<Range<Anchor>>,
14646        cx: &mut Context<Self>,
14647    ) {
14648        let snapshot = self.buffer().read(cx).snapshot(cx);
14649        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14650        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14651        row_highlights.retain(|highlight| {
14652            while let Some(range_to_remove) = ranges_to_remove.peek() {
14653                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14654                    Ordering::Less | Ordering::Equal => {
14655                        ranges_to_remove.next();
14656                    }
14657                    Ordering::Greater => {
14658                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14659                            Ordering::Less | Ordering::Equal => {
14660                                return false;
14661                            }
14662                            Ordering::Greater => break,
14663                        }
14664                    }
14665                }
14666            }
14667
14668            true
14669        })
14670    }
14671
14672    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14673    pub fn clear_row_highlights<T: 'static>(&mut self) {
14674        self.highlighted_rows.remove(&TypeId::of::<T>());
14675    }
14676
14677    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14678    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14679        self.highlighted_rows
14680            .get(&TypeId::of::<T>())
14681            .map_or(&[] as &[_], |vec| vec.as_slice())
14682            .iter()
14683            .map(|highlight| (highlight.range.clone(), highlight.color))
14684    }
14685
14686    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14687    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14688    /// Allows to ignore certain kinds of highlights.
14689    pub fn highlighted_display_rows(
14690        &self,
14691        window: &mut Window,
14692        cx: &mut App,
14693    ) -> BTreeMap<DisplayRow, Background> {
14694        let snapshot = self.snapshot(window, cx);
14695        let mut used_highlight_orders = HashMap::default();
14696        self.highlighted_rows
14697            .iter()
14698            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14699            .fold(
14700                BTreeMap::<DisplayRow, Background>::new(),
14701                |mut unique_rows, highlight| {
14702                    let start = highlight.range.start.to_display_point(&snapshot);
14703                    let end = highlight.range.end.to_display_point(&snapshot);
14704                    let start_row = start.row().0;
14705                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14706                        && end.column() == 0
14707                    {
14708                        end.row().0.saturating_sub(1)
14709                    } else {
14710                        end.row().0
14711                    };
14712                    for row in start_row..=end_row {
14713                        let used_index =
14714                            used_highlight_orders.entry(row).or_insert(highlight.index);
14715                        if highlight.index >= *used_index {
14716                            *used_index = highlight.index;
14717                            unique_rows.insert(DisplayRow(row), highlight.color.into());
14718                        }
14719                    }
14720                    unique_rows
14721                },
14722            )
14723    }
14724
14725    pub fn highlighted_display_row_for_autoscroll(
14726        &self,
14727        snapshot: &DisplaySnapshot,
14728    ) -> Option<DisplayRow> {
14729        self.highlighted_rows
14730            .values()
14731            .flat_map(|highlighted_rows| highlighted_rows.iter())
14732            .filter_map(|highlight| {
14733                if highlight.should_autoscroll {
14734                    Some(highlight.range.start.to_display_point(snapshot).row())
14735                } else {
14736                    None
14737                }
14738            })
14739            .min()
14740    }
14741
14742    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14743        self.highlight_background::<SearchWithinRange>(
14744            ranges,
14745            |colors| colors.editor_document_highlight_read_background,
14746            cx,
14747        )
14748    }
14749
14750    pub fn set_breadcrumb_header(&mut self, new_header: String) {
14751        self.breadcrumb_header = Some(new_header);
14752    }
14753
14754    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14755        self.clear_background_highlights::<SearchWithinRange>(cx);
14756    }
14757
14758    pub fn highlight_background<T: 'static>(
14759        &mut self,
14760        ranges: &[Range<Anchor>],
14761        color_fetcher: fn(&ThemeColors) -> Hsla,
14762        cx: &mut Context<Self>,
14763    ) {
14764        self.background_highlights
14765            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14766        self.scrollbar_marker_state.dirty = true;
14767        cx.notify();
14768    }
14769
14770    pub fn clear_background_highlights<T: 'static>(
14771        &mut self,
14772        cx: &mut Context<Self>,
14773    ) -> Option<BackgroundHighlight> {
14774        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14775        if !text_highlights.1.is_empty() {
14776            self.scrollbar_marker_state.dirty = true;
14777            cx.notify();
14778        }
14779        Some(text_highlights)
14780    }
14781
14782    pub fn highlight_gutter<T: 'static>(
14783        &mut self,
14784        ranges: &[Range<Anchor>],
14785        color_fetcher: fn(&App) -> Hsla,
14786        cx: &mut Context<Self>,
14787    ) {
14788        self.gutter_highlights
14789            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14790        cx.notify();
14791    }
14792
14793    pub fn clear_gutter_highlights<T: 'static>(
14794        &mut self,
14795        cx: &mut Context<Self>,
14796    ) -> Option<GutterHighlight> {
14797        cx.notify();
14798        self.gutter_highlights.remove(&TypeId::of::<T>())
14799    }
14800
14801    #[cfg(feature = "test-support")]
14802    pub fn all_text_background_highlights(
14803        &self,
14804        window: &mut Window,
14805        cx: &mut Context<Self>,
14806    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14807        let snapshot = self.snapshot(window, cx);
14808        let buffer = &snapshot.buffer_snapshot;
14809        let start = buffer.anchor_before(0);
14810        let end = buffer.anchor_after(buffer.len());
14811        let theme = cx.theme().colors();
14812        self.background_highlights_in_range(start..end, &snapshot, theme)
14813    }
14814
14815    #[cfg(feature = "test-support")]
14816    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14817        let snapshot = self.buffer().read(cx).snapshot(cx);
14818
14819        let highlights = self
14820            .background_highlights
14821            .get(&TypeId::of::<items::BufferSearchHighlights>());
14822
14823        if let Some((_color, ranges)) = highlights {
14824            ranges
14825                .iter()
14826                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14827                .collect_vec()
14828        } else {
14829            vec![]
14830        }
14831    }
14832
14833    fn document_highlights_for_position<'a>(
14834        &'a self,
14835        position: Anchor,
14836        buffer: &'a MultiBufferSnapshot,
14837    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
14838        let read_highlights = self
14839            .background_highlights
14840            .get(&TypeId::of::<DocumentHighlightRead>())
14841            .map(|h| &h.1);
14842        let write_highlights = self
14843            .background_highlights
14844            .get(&TypeId::of::<DocumentHighlightWrite>())
14845            .map(|h| &h.1);
14846        let left_position = position.bias_left(buffer);
14847        let right_position = position.bias_right(buffer);
14848        read_highlights
14849            .into_iter()
14850            .chain(write_highlights)
14851            .flat_map(move |ranges| {
14852                let start_ix = match ranges.binary_search_by(|probe| {
14853                    let cmp = probe.end.cmp(&left_position, buffer);
14854                    if cmp.is_ge() {
14855                        Ordering::Greater
14856                    } else {
14857                        Ordering::Less
14858                    }
14859                }) {
14860                    Ok(i) | Err(i) => i,
14861                };
14862
14863                ranges[start_ix..]
14864                    .iter()
14865                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
14866            })
14867    }
14868
14869    pub fn has_background_highlights<T: 'static>(&self) -> bool {
14870        self.background_highlights
14871            .get(&TypeId::of::<T>())
14872            .map_or(false, |(_, highlights)| !highlights.is_empty())
14873    }
14874
14875    pub fn background_highlights_in_range(
14876        &self,
14877        search_range: Range<Anchor>,
14878        display_snapshot: &DisplaySnapshot,
14879        theme: &ThemeColors,
14880    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14881        let mut results = Vec::new();
14882        for (color_fetcher, ranges) in self.background_highlights.values() {
14883            let color = color_fetcher(theme);
14884            let start_ix = match ranges.binary_search_by(|probe| {
14885                let cmp = probe
14886                    .end
14887                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14888                if cmp.is_gt() {
14889                    Ordering::Greater
14890                } else {
14891                    Ordering::Less
14892                }
14893            }) {
14894                Ok(i) | Err(i) => i,
14895            };
14896            for range in &ranges[start_ix..] {
14897                if range
14898                    .start
14899                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14900                    .is_ge()
14901                {
14902                    break;
14903                }
14904
14905                let start = range.start.to_display_point(display_snapshot);
14906                let end = range.end.to_display_point(display_snapshot);
14907                results.push((start..end, color))
14908            }
14909        }
14910        results
14911    }
14912
14913    pub fn background_highlight_row_ranges<T: 'static>(
14914        &self,
14915        search_range: Range<Anchor>,
14916        display_snapshot: &DisplaySnapshot,
14917        count: usize,
14918    ) -> Vec<RangeInclusive<DisplayPoint>> {
14919        let mut results = Vec::new();
14920        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14921            return vec![];
14922        };
14923
14924        let start_ix = match ranges.binary_search_by(|probe| {
14925            let cmp = probe
14926                .end
14927                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14928            if cmp.is_gt() {
14929                Ordering::Greater
14930            } else {
14931                Ordering::Less
14932            }
14933        }) {
14934            Ok(i) | Err(i) => i,
14935        };
14936        let mut push_region = |start: Option<Point>, end: Option<Point>| {
14937            if let (Some(start_display), Some(end_display)) = (start, end) {
14938                results.push(
14939                    start_display.to_display_point(display_snapshot)
14940                        ..=end_display.to_display_point(display_snapshot),
14941                );
14942            }
14943        };
14944        let mut start_row: Option<Point> = None;
14945        let mut end_row: Option<Point> = None;
14946        if ranges.len() > count {
14947            return Vec::new();
14948        }
14949        for range in &ranges[start_ix..] {
14950            if range
14951                .start
14952                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14953                .is_ge()
14954            {
14955                break;
14956            }
14957            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14958            if let Some(current_row) = &end_row {
14959                if end.row == current_row.row {
14960                    continue;
14961                }
14962            }
14963            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14964            if start_row.is_none() {
14965                assert_eq!(end_row, None);
14966                start_row = Some(start);
14967                end_row = Some(end);
14968                continue;
14969            }
14970            if let Some(current_end) = end_row.as_mut() {
14971                if start.row > current_end.row + 1 {
14972                    push_region(start_row, end_row);
14973                    start_row = Some(start);
14974                    end_row = Some(end);
14975                } else {
14976                    // Merge two hunks.
14977                    *current_end = end;
14978                }
14979            } else {
14980                unreachable!();
14981            }
14982        }
14983        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14984        push_region(start_row, end_row);
14985        results
14986    }
14987
14988    pub fn gutter_highlights_in_range(
14989        &self,
14990        search_range: Range<Anchor>,
14991        display_snapshot: &DisplaySnapshot,
14992        cx: &App,
14993    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14994        let mut results = Vec::new();
14995        for (color_fetcher, ranges) in self.gutter_highlights.values() {
14996            let color = color_fetcher(cx);
14997            let start_ix = match ranges.binary_search_by(|probe| {
14998                let cmp = probe
14999                    .end
15000                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15001                if cmp.is_gt() {
15002                    Ordering::Greater
15003                } else {
15004                    Ordering::Less
15005                }
15006            }) {
15007                Ok(i) | Err(i) => i,
15008            };
15009            for range in &ranges[start_ix..] {
15010                if range
15011                    .start
15012                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15013                    .is_ge()
15014                {
15015                    break;
15016                }
15017
15018                let start = range.start.to_display_point(display_snapshot);
15019                let end = range.end.to_display_point(display_snapshot);
15020                results.push((start..end, color))
15021            }
15022        }
15023        results
15024    }
15025
15026    /// Get the text ranges corresponding to the redaction query
15027    pub fn redacted_ranges(
15028        &self,
15029        search_range: Range<Anchor>,
15030        display_snapshot: &DisplaySnapshot,
15031        cx: &App,
15032    ) -> Vec<Range<DisplayPoint>> {
15033        display_snapshot
15034            .buffer_snapshot
15035            .redacted_ranges(search_range, |file| {
15036                if let Some(file) = file {
15037                    file.is_private()
15038                        && EditorSettings::get(
15039                            Some(SettingsLocation {
15040                                worktree_id: file.worktree_id(cx),
15041                                path: file.path().as_ref(),
15042                            }),
15043                            cx,
15044                        )
15045                        .redact_private_values
15046                } else {
15047                    false
15048                }
15049            })
15050            .map(|range| {
15051                range.start.to_display_point(display_snapshot)
15052                    ..range.end.to_display_point(display_snapshot)
15053            })
15054            .collect()
15055    }
15056
15057    pub fn highlight_text<T: 'static>(
15058        &mut self,
15059        ranges: Vec<Range<Anchor>>,
15060        style: HighlightStyle,
15061        cx: &mut Context<Self>,
15062    ) {
15063        self.display_map.update(cx, |map, _| {
15064            map.highlight_text(TypeId::of::<T>(), ranges, style)
15065        });
15066        cx.notify();
15067    }
15068
15069    pub(crate) fn highlight_inlays<T: 'static>(
15070        &mut self,
15071        highlights: Vec<InlayHighlight>,
15072        style: HighlightStyle,
15073        cx: &mut Context<Self>,
15074    ) {
15075        self.display_map.update(cx, |map, _| {
15076            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15077        });
15078        cx.notify();
15079    }
15080
15081    pub fn text_highlights<'a, T: 'static>(
15082        &'a self,
15083        cx: &'a App,
15084    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15085        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15086    }
15087
15088    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15089        let cleared = self
15090            .display_map
15091            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15092        if cleared {
15093            cx.notify();
15094        }
15095    }
15096
15097    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15098        (self.read_only(cx) || self.blink_manager.read(cx).visible())
15099            && self.focus_handle.is_focused(window)
15100    }
15101
15102    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15103        self.show_cursor_when_unfocused = is_enabled;
15104        cx.notify();
15105    }
15106
15107    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15108        cx.notify();
15109    }
15110
15111    fn on_buffer_event(
15112        &mut self,
15113        multibuffer: &Entity<MultiBuffer>,
15114        event: &multi_buffer::Event,
15115        window: &mut Window,
15116        cx: &mut Context<Self>,
15117    ) {
15118        match event {
15119            multi_buffer::Event::Edited {
15120                singleton_buffer_edited,
15121                edited_buffer: buffer_edited,
15122            } => {
15123                self.scrollbar_marker_state.dirty = true;
15124                self.active_indent_guides_state.dirty = true;
15125                self.refresh_active_diagnostics(cx);
15126                self.refresh_code_actions(window, cx);
15127                if self.has_active_inline_completion() {
15128                    self.update_visible_inline_completion(window, cx);
15129                }
15130                if let Some(buffer) = buffer_edited {
15131                    let buffer_id = buffer.read(cx).remote_id();
15132                    if !self.registered_buffers.contains_key(&buffer_id) {
15133                        if let Some(project) = self.project.as_ref() {
15134                            project.update(cx, |project, cx| {
15135                                self.registered_buffers.insert(
15136                                    buffer_id,
15137                                    project.register_buffer_with_language_servers(&buffer, cx),
15138                                );
15139                            })
15140                        }
15141                    }
15142                }
15143                cx.emit(EditorEvent::BufferEdited);
15144                cx.emit(SearchEvent::MatchesInvalidated);
15145                if *singleton_buffer_edited {
15146                    if let Some(project) = &self.project {
15147                        #[allow(clippy::mutable_key_type)]
15148                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15149                            multibuffer
15150                                .all_buffers()
15151                                .into_iter()
15152                                .filter_map(|buffer| {
15153                                    buffer.update(cx, |buffer, cx| {
15154                                        let language = buffer.language()?;
15155                                        let should_discard = project.update(cx, |project, cx| {
15156                                            project.is_local()
15157                                                && !project.has_language_servers_for(buffer, cx)
15158                                        });
15159                                        should_discard.not().then_some(language.clone())
15160                                    })
15161                                })
15162                                .collect::<HashSet<_>>()
15163                        });
15164                        if !languages_affected.is_empty() {
15165                            self.refresh_inlay_hints(
15166                                InlayHintRefreshReason::BufferEdited(languages_affected),
15167                                cx,
15168                            );
15169                        }
15170                    }
15171                }
15172
15173                let Some(project) = &self.project else { return };
15174                let (telemetry, is_via_ssh) = {
15175                    let project = project.read(cx);
15176                    let telemetry = project.client().telemetry().clone();
15177                    let is_via_ssh = project.is_via_ssh();
15178                    (telemetry, is_via_ssh)
15179                };
15180                refresh_linked_ranges(self, window, cx);
15181                telemetry.log_edit_event("editor", is_via_ssh);
15182            }
15183            multi_buffer::Event::ExcerptsAdded {
15184                buffer,
15185                predecessor,
15186                excerpts,
15187            } => {
15188                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15189                let buffer_id = buffer.read(cx).remote_id();
15190                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15191                    if let Some(project) = &self.project {
15192                        get_uncommitted_diff_for_buffer(
15193                            project,
15194                            [buffer.clone()],
15195                            self.buffer.clone(),
15196                            cx,
15197                        )
15198                        .detach();
15199                    }
15200                }
15201                cx.emit(EditorEvent::ExcerptsAdded {
15202                    buffer: buffer.clone(),
15203                    predecessor: *predecessor,
15204                    excerpts: excerpts.clone(),
15205                });
15206                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15207            }
15208            multi_buffer::Event::ExcerptsRemoved { ids } => {
15209                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15210                let buffer = self.buffer.read(cx);
15211                self.registered_buffers
15212                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15213                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15214            }
15215            multi_buffer::Event::ExcerptsEdited { ids } => {
15216                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
15217            }
15218            multi_buffer::Event::ExcerptsExpanded { ids } => {
15219                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15220                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15221            }
15222            multi_buffer::Event::Reparsed(buffer_id) => {
15223                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15224
15225                cx.emit(EditorEvent::Reparsed(*buffer_id));
15226            }
15227            multi_buffer::Event::DiffHunksToggled => {
15228                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15229            }
15230            multi_buffer::Event::LanguageChanged(buffer_id) => {
15231                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15232                cx.emit(EditorEvent::Reparsed(*buffer_id));
15233                cx.notify();
15234            }
15235            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15236            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15237            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15238                cx.emit(EditorEvent::TitleChanged)
15239            }
15240            // multi_buffer::Event::DiffBaseChanged => {
15241            //     self.scrollbar_marker_state.dirty = true;
15242            //     cx.emit(EditorEvent::DiffBaseChanged);
15243            //     cx.notify();
15244            // }
15245            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15246            multi_buffer::Event::DiagnosticsUpdated => {
15247                self.refresh_active_diagnostics(cx);
15248                self.refresh_inline_diagnostics(true, window, cx);
15249                self.scrollbar_marker_state.dirty = true;
15250                cx.notify();
15251            }
15252            _ => {}
15253        };
15254    }
15255
15256    fn on_display_map_changed(
15257        &mut self,
15258        _: Entity<DisplayMap>,
15259        _: &mut Window,
15260        cx: &mut Context<Self>,
15261    ) {
15262        cx.notify();
15263    }
15264
15265    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15266        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15267        self.update_edit_prediction_settings(cx);
15268        self.refresh_inline_completion(true, false, window, cx);
15269        self.refresh_inlay_hints(
15270            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15271                self.selections.newest_anchor().head(),
15272                &self.buffer.read(cx).snapshot(cx),
15273                cx,
15274            )),
15275            cx,
15276        );
15277
15278        let old_cursor_shape = self.cursor_shape;
15279
15280        {
15281            let editor_settings = EditorSettings::get_global(cx);
15282            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15283            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15284            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15285        }
15286
15287        if old_cursor_shape != self.cursor_shape {
15288            cx.emit(EditorEvent::CursorShapeChanged);
15289        }
15290
15291        let project_settings = ProjectSettings::get_global(cx);
15292        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15293
15294        if self.mode == EditorMode::Full {
15295            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15296            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15297            if self.show_inline_diagnostics != show_inline_diagnostics {
15298                self.show_inline_diagnostics = show_inline_diagnostics;
15299                self.refresh_inline_diagnostics(false, window, cx);
15300            }
15301
15302            if self.git_blame_inline_enabled != inline_blame_enabled {
15303                self.toggle_git_blame_inline_internal(false, window, cx);
15304            }
15305        }
15306
15307        cx.notify();
15308    }
15309
15310    pub fn set_searchable(&mut self, searchable: bool) {
15311        self.searchable = searchable;
15312    }
15313
15314    pub fn searchable(&self) -> bool {
15315        self.searchable
15316    }
15317
15318    fn open_proposed_changes_editor(
15319        &mut self,
15320        _: &OpenProposedChangesEditor,
15321        window: &mut Window,
15322        cx: &mut Context<Self>,
15323    ) {
15324        let Some(workspace) = self.workspace() else {
15325            cx.propagate();
15326            return;
15327        };
15328
15329        let selections = self.selections.all::<usize>(cx);
15330        let multi_buffer = self.buffer.read(cx);
15331        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15332        let mut new_selections_by_buffer = HashMap::default();
15333        for selection in selections {
15334            for (buffer, range, _) in
15335                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15336            {
15337                let mut range = range.to_point(buffer);
15338                range.start.column = 0;
15339                range.end.column = buffer.line_len(range.end.row);
15340                new_selections_by_buffer
15341                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15342                    .or_insert(Vec::new())
15343                    .push(range)
15344            }
15345        }
15346
15347        let proposed_changes_buffers = new_selections_by_buffer
15348            .into_iter()
15349            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15350            .collect::<Vec<_>>();
15351        let proposed_changes_editor = cx.new(|cx| {
15352            ProposedChangesEditor::new(
15353                "Proposed changes",
15354                proposed_changes_buffers,
15355                self.project.clone(),
15356                window,
15357                cx,
15358            )
15359        });
15360
15361        window.defer(cx, move |window, cx| {
15362            workspace.update(cx, |workspace, cx| {
15363                workspace.active_pane().update(cx, |pane, cx| {
15364                    pane.add_item(
15365                        Box::new(proposed_changes_editor),
15366                        true,
15367                        true,
15368                        None,
15369                        window,
15370                        cx,
15371                    );
15372                });
15373            });
15374        });
15375    }
15376
15377    pub fn open_excerpts_in_split(
15378        &mut self,
15379        _: &OpenExcerptsSplit,
15380        window: &mut Window,
15381        cx: &mut Context<Self>,
15382    ) {
15383        self.open_excerpts_common(None, true, window, cx)
15384    }
15385
15386    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15387        self.open_excerpts_common(None, false, window, cx)
15388    }
15389
15390    fn open_excerpts_common(
15391        &mut self,
15392        jump_data: Option<JumpData>,
15393        split: bool,
15394        window: &mut Window,
15395        cx: &mut Context<Self>,
15396    ) {
15397        let Some(workspace) = self.workspace() else {
15398            cx.propagate();
15399            return;
15400        };
15401
15402        if self.buffer.read(cx).is_singleton() {
15403            cx.propagate();
15404            return;
15405        }
15406
15407        let mut new_selections_by_buffer = HashMap::default();
15408        match &jump_data {
15409            Some(JumpData::MultiBufferPoint {
15410                excerpt_id,
15411                position,
15412                anchor,
15413                line_offset_from_top,
15414            }) => {
15415                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15416                if let Some(buffer) = multi_buffer_snapshot
15417                    .buffer_id_for_excerpt(*excerpt_id)
15418                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15419                {
15420                    let buffer_snapshot = buffer.read(cx).snapshot();
15421                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15422                        language::ToPoint::to_point(anchor, &buffer_snapshot)
15423                    } else {
15424                        buffer_snapshot.clip_point(*position, Bias::Left)
15425                    };
15426                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15427                    new_selections_by_buffer.insert(
15428                        buffer,
15429                        (
15430                            vec![jump_to_offset..jump_to_offset],
15431                            Some(*line_offset_from_top),
15432                        ),
15433                    );
15434                }
15435            }
15436            Some(JumpData::MultiBufferRow {
15437                row,
15438                line_offset_from_top,
15439            }) => {
15440                let point = MultiBufferPoint::new(row.0, 0);
15441                if let Some((buffer, buffer_point, _)) =
15442                    self.buffer.read(cx).point_to_buffer_point(point, cx)
15443                {
15444                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15445                    new_selections_by_buffer
15446                        .entry(buffer)
15447                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
15448                        .0
15449                        .push(buffer_offset..buffer_offset)
15450                }
15451            }
15452            None => {
15453                let selections = self.selections.all::<usize>(cx);
15454                let multi_buffer = self.buffer.read(cx);
15455                for selection in selections {
15456                    for (snapshot, range, _, anchor) in multi_buffer
15457                        .snapshot(cx)
15458                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15459                    {
15460                        if let Some(anchor) = anchor {
15461                            // selection is in a deleted hunk
15462                            let Some(buffer_id) = anchor.buffer_id else {
15463                                continue;
15464                            };
15465                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15466                                continue;
15467                            };
15468                            let offset = text::ToOffset::to_offset(
15469                                &anchor.text_anchor,
15470                                &buffer_handle.read(cx).snapshot(),
15471                            );
15472                            let range = offset..offset;
15473                            new_selections_by_buffer
15474                                .entry(buffer_handle)
15475                                .or_insert((Vec::new(), None))
15476                                .0
15477                                .push(range)
15478                        } else {
15479                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15480                            else {
15481                                continue;
15482                            };
15483                            new_selections_by_buffer
15484                                .entry(buffer_handle)
15485                                .or_insert((Vec::new(), None))
15486                                .0
15487                                .push(range)
15488                        }
15489                    }
15490                }
15491            }
15492        }
15493
15494        if new_selections_by_buffer.is_empty() {
15495            return;
15496        }
15497
15498        // We defer the pane interaction because we ourselves are a workspace item
15499        // and activating a new item causes the pane to call a method on us reentrantly,
15500        // which panics if we're on the stack.
15501        window.defer(cx, move |window, cx| {
15502            workspace.update(cx, |workspace, cx| {
15503                let pane = if split {
15504                    workspace.adjacent_pane(window, cx)
15505                } else {
15506                    workspace.active_pane().clone()
15507                };
15508
15509                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15510                    let editor = buffer
15511                        .read(cx)
15512                        .file()
15513                        .is_none()
15514                        .then(|| {
15515                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15516                            // so `workspace.open_project_item` will never find them, always opening a new editor.
15517                            // Instead, we try to activate the existing editor in the pane first.
15518                            let (editor, pane_item_index) =
15519                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
15520                                    let editor = item.downcast::<Editor>()?;
15521                                    let singleton_buffer =
15522                                        editor.read(cx).buffer().read(cx).as_singleton()?;
15523                                    if singleton_buffer == buffer {
15524                                        Some((editor, i))
15525                                    } else {
15526                                        None
15527                                    }
15528                                })?;
15529                            pane.update(cx, |pane, cx| {
15530                                pane.activate_item(pane_item_index, true, true, window, cx)
15531                            });
15532                            Some(editor)
15533                        })
15534                        .flatten()
15535                        .unwrap_or_else(|| {
15536                            workspace.open_project_item::<Self>(
15537                                pane.clone(),
15538                                buffer,
15539                                true,
15540                                true,
15541                                window,
15542                                cx,
15543                            )
15544                        });
15545
15546                    editor.update(cx, |editor, cx| {
15547                        let autoscroll = match scroll_offset {
15548                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15549                            None => Autoscroll::newest(),
15550                        };
15551                        let nav_history = editor.nav_history.take();
15552                        editor.change_selections(Some(autoscroll), window, cx, |s| {
15553                            s.select_ranges(ranges);
15554                        });
15555                        editor.nav_history = nav_history;
15556                    });
15557                }
15558            })
15559        });
15560    }
15561
15562    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15563        let snapshot = self.buffer.read(cx).read(cx);
15564        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15565        Some(
15566            ranges
15567                .iter()
15568                .map(move |range| {
15569                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15570                })
15571                .collect(),
15572        )
15573    }
15574
15575    fn selection_replacement_ranges(
15576        &self,
15577        range: Range<OffsetUtf16>,
15578        cx: &mut App,
15579    ) -> Vec<Range<OffsetUtf16>> {
15580        let selections = self.selections.all::<OffsetUtf16>(cx);
15581        let newest_selection = selections
15582            .iter()
15583            .max_by_key(|selection| selection.id)
15584            .unwrap();
15585        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15586        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15587        let snapshot = self.buffer.read(cx).read(cx);
15588        selections
15589            .into_iter()
15590            .map(|mut selection| {
15591                selection.start.0 =
15592                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
15593                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15594                snapshot.clip_offset_utf16(selection.start, Bias::Left)
15595                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15596            })
15597            .collect()
15598    }
15599
15600    fn report_editor_event(
15601        &self,
15602        event_type: &'static str,
15603        file_extension: Option<String>,
15604        cx: &App,
15605    ) {
15606        if cfg!(any(test, feature = "test-support")) {
15607            return;
15608        }
15609
15610        let Some(project) = &self.project else { return };
15611
15612        // If None, we are in a file without an extension
15613        let file = self
15614            .buffer
15615            .read(cx)
15616            .as_singleton()
15617            .and_then(|b| b.read(cx).file());
15618        let file_extension = file_extension.or(file
15619            .as_ref()
15620            .and_then(|file| Path::new(file.file_name(cx)).extension())
15621            .and_then(|e| e.to_str())
15622            .map(|a| a.to_string()));
15623
15624        let vim_mode = cx
15625            .global::<SettingsStore>()
15626            .raw_user_settings()
15627            .get("vim_mode")
15628            == Some(&serde_json::Value::Bool(true));
15629
15630        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15631        let copilot_enabled = edit_predictions_provider
15632            == language::language_settings::EditPredictionProvider::Copilot;
15633        let copilot_enabled_for_language = self
15634            .buffer
15635            .read(cx)
15636            .settings_at(0, cx)
15637            .show_edit_predictions;
15638
15639        let project = project.read(cx);
15640        telemetry::event!(
15641            event_type,
15642            file_extension,
15643            vim_mode,
15644            copilot_enabled,
15645            copilot_enabled_for_language,
15646            edit_predictions_provider,
15647            is_via_ssh = project.is_via_ssh(),
15648        );
15649    }
15650
15651    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15652    /// with each line being an array of {text, highlight} objects.
15653    fn copy_highlight_json(
15654        &mut self,
15655        _: &CopyHighlightJson,
15656        window: &mut Window,
15657        cx: &mut Context<Self>,
15658    ) {
15659        #[derive(Serialize)]
15660        struct Chunk<'a> {
15661            text: String,
15662            highlight: Option<&'a str>,
15663        }
15664
15665        let snapshot = self.buffer.read(cx).snapshot(cx);
15666        let range = self
15667            .selected_text_range(false, window, cx)
15668            .and_then(|selection| {
15669                if selection.range.is_empty() {
15670                    None
15671                } else {
15672                    Some(selection.range)
15673                }
15674            })
15675            .unwrap_or_else(|| 0..snapshot.len());
15676
15677        let chunks = snapshot.chunks(range, true);
15678        let mut lines = Vec::new();
15679        let mut line: VecDeque<Chunk> = VecDeque::new();
15680
15681        let Some(style) = self.style.as_ref() else {
15682            return;
15683        };
15684
15685        for chunk in chunks {
15686            let highlight = chunk
15687                .syntax_highlight_id
15688                .and_then(|id| id.name(&style.syntax));
15689            let mut chunk_lines = chunk.text.split('\n').peekable();
15690            while let Some(text) = chunk_lines.next() {
15691                let mut merged_with_last_token = false;
15692                if let Some(last_token) = line.back_mut() {
15693                    if last_token.highlight == highlight {
15694                        last_token.text.push_str(text);
15695                        merged_with_last_token = true;
15696                    }
15697                }
15698
15699                if !merged_with_last_token {
15700                    line.push_back(Chunk {
15701                        text: text.into(),
15702                        highlight,
15703                    });
15704                }
15705
15706                if chunk_lines.peek().is_some() {
15707                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
15708                        line.pop_front();
15709                    }
15710                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
15711                        line.pop_back();
15712                    }
15713
15714                    lines.push(mem::take(&mut line));
15715                }
15716            }
15717        }
15718
15719        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15720            return;
15721        };
15722        cx.write_to_clipboard(ClipboardItem::new_string(lines));
15723    }
15724
15725    pub fn open_context_menu(
15726        &mut self,
15727        _: &OpenContextMenu,
15728        window: &mut Window,
15729        cx: &mut Context<Self>,
15730    ) {
15731        self.request_autoscroll(Autoscroll::newest(), cx);
15732        let position = self.selections.newest_display(cx).start;
15733        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15734    }
15735
15736    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15737        &self.inlay_hint_cache
15738    }
15739
15740    pub fn replay_insert_event(
15741        &mut self,
15742        text: &str,
15743        relative_utf16_range: Option<Range<isize>>,
15744        window: &mut Window,
15745        cx: &mut Context<Self>,
15746    ) {
15747        if !self.input_enabled {
15748            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15749            return;
15750        }
15751        if let Some(relative_utf16_range) = relative_utf16_range {
15752            let selections = self.selections.all::<OffsetUtf16>(cx);
15753            self.change_selections(None, window, cx, |s| {
15754                let new_ranges = selections.into_iter().map(|range| {
15755                    let start = OffsetUtf16(
15756                        range
15757                            .head()
15758                            .0
15759                            .saturating_add_signed(relative_utf16_range.start),
15760                    );
15761                    let end = OffsetUtf16(
15762                        range
15763                            .head()
15764                            .0
15765                            .saturating_add_signed(relative_utf16_range.end),
15766                    );
15767                    start..end
15768                });
15769                s.select_ranges(new_ranges);
15770            });
15771        }
15772
15773        self.handle_input(text, window, cx);
15774    }
15775
15776    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15777        let Some(provider) = self.semantics_provider.as_ref() else {
15778            return false;
15779        };
15780
15781        let mut supports = false;
15782        self.buffer().update(cx, |this, cx| {
15783            this.for_each_buffer(|buffer| {
15784                supports |= provider.supports_inlay_hints(buffer, cx);
15785            });
15786        });
15787
15788        supports
15789    }
15790
15791    pub fn is_focused(&self, window: &Window) -> bool {
15792        self.focus_handle.is_focused(window)
15793    }
15794
15795    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15796        cx.emit(EditorEvent::Focused);
15797
15798        if let Some(descendant) = self
15799            .last_focused_descendant
15800            .take()
15801            .and_then(|descendant| descendant.upgrade())
15802        {
15803            window.focus(&descendant);
15804        } else {
15805            if let Some(blame) = self.blame.as_ref() {
15806                blame.update(cx, GitBlame::focus)
15807            }
15808
15809            self.blink_manager.update(cx, BlinkManager::enable);
15810            self.show_cursor_names(window, cx);
15811            self.buffer.update(cx, |buffer, cx| {
15812                buffer.finalize_last_transaction(cx);
15813                if self.leader_peer_id.is_none() {
15814                    buffer.set_active_selections(
15815                        &self.selections.disjoint_anchors(),
15816                        self.selections.line_mode,
15817                        self.cursor_shape,
15818                        cx,
15819                    );
15820                }
15821            });
15822        }
15823    }
15824
15825    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15826        cx.emit(EditorEvent::FocusedIn)
15827    }
15828
15829    fn handle_focus_out(
15830        &mut self,
15831        event: FocusOutEvent,
15832        _window: &mut Window,
15833        _cx: &mut Context<Self>,
15834    ) {
15835        if event.blurred != self.focus_handle {
15836            self.last_focused_descendant = Some(event.blurred);
15837        }
15838    }
15839
15840    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15841        self.blink_manager.update(cx, BlinkManager::disable);
15842        self.buffer
15843            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
15844
15845        if let Some(blame) = self.blame.as_ref() {
15846            blame.update(cx, GitBlame::blur)
15847        }
15848        if !self.hover_state.focused(window, cx) {
15849            hide_hover(self, cx);
15850        }
15851        if !self
15852            .context_menu
15853            .borrow()
15854            .as_ref()
15855            .is_some_and(|context_menu| context_menu.focused(window, cx))
15856        {
15857            self.hide_context_menu(window, cx);
15858        }
15859        self.discard_inline_completion(false, cx);
15860        cx.emit(EditorEvent::Blurred);
15861        cx.notify();
15862    }
15863
15864    pub fn register_action<A: Action>(
15865        &mut self,
15866        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
15867    ) -> Subscription {
15868        let id = self.next_editor_action_id.post_inc();
15869        let listener = Arc::new(listener);
15870        self.editor_actions.borrow_mut().insert(
15871            id,
15872            Box::new(move |window, _| {
15873                let listener = listener.clone();
15874                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
15875                    let action = action.downcast_ref().unwrap();
15876                    if phase == DispatchPhase::Bubble {
15877                        listener(action, window, cx)
15878                    }
15879                })
15880            }),
15881        );
15882
15883        let editor_actions = self.editor_actions.clone();
15884        Subscription::new(move || {
15885            editor_actions.borrow_mut().remove(&id);
15886        })
15887    }
15888
15889    pub fn file_header_size(&self) -> u32 {
15890        FILE_HEADER_HEIGHT
15891    }
15892
15893    pub fn restore(
15894        &mut self,
15895        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
15896        window: &mut Window,
15897        cx: &mut Context<Self>,
15898    ) {
15899        let workspace = self.workspace();
15900        let project = self.project.as_ref();
15901        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
15902            let mut tasks = Vec::new();
15903            for (buffer_id, changes) in revert_changes {
15904                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
15905                    buffer.update(cx, |buffer, cx| {
15906                        buffer.edit(
15907                            changes.into_iter().map(|(range, text)| {
15908                                (range, text.to_string().map(Arc::<str>::from))
15909                            }),
15910                            None,
15911                            cx,
15912                        );
15913                    });
15914
15915                    if let Some(project) =
15916                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
15917                    {
15918                        project.update(cx, |project, cx| {
15919                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
15920                        })
15921                    }
15922                }
15923            }
15924            tasks
15925        });
15926        cx.spawn_in(window, |_, mut cx| async move {
15927            for (buffer, task) in save_tasks {
15928                let result = task.await;
15929                if result.is_err() {
15930                    let Some(path) = buffer
15931                        .read_with(&cx, |buffer, cx| buffer.project_path(cx))
15932                        .ok()
15933                    else {
15934                        continue;
15935                    };
15936                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
15937                        let Some(task) = cx
15938                            .update_window_entity(&workspace, |workspace, window, cx| {
15939                                workspace
15940                                    .open_path_preview(path, None, false, false, false, window, cx)
15941                            })
15942                            .ok()
15943                        else {
15944                            continue;
15945                        };
15946                        task.await.log_err();
15947                    }
15948                }
15949            }
15950        })
15951        .detach();
15952        self.change_selections(None, window, cx, |selections| selections.refresh());
15953    }
15954
15955    pub fn to_pixel_point(
15956        &self,
15957        source: multi_buffer::Anchor,
15958        editor_snapshot: &EditorSnapshot,
15959        window: &mut Window,
15960    ) -> Option<gpui::Point<Pixels>> {
15961        let source_point = source.to_display_point(editor_snapshot);
15962        self.display_to_pixel_point(source_point, editor_snapshot, window)
15963    }
15964
15965    pub fn display_to_pixel_point(
15966        &self,
15967        source: DisplayPoint,
15968        editor_snapshot: &EditorSnapshot,
15969        window: &mut Window,
15970    ) -> Option<gpui::Point<Pixels>> {
15971        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15972        let text_layout_details = self.text_layout_details(window);
15973        let scroll_top = text_layout_details
15974            .scroll_anchor
15975            .scroll_position(editor_snapshot)
15976            .y;
15977
15978        if source.row().as_f32() < scroll_top.floor() {
15979            return None;
15980        }
15981        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15982        let source_y = line_height * (source.row().as_f32() - scroll_top);
15983        Some(gpui::Point::new(source_x, source_y))
15984    }
15985
15986    pub fn has_visible_completions_menu(&self) -> bool {
15987        !self.edit_prediction_preview_is_active()
15988            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15989                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15990            })
15991    }
15992
15993    pub fn register_addon<T: Addon>(&mut self, instance: T) {
15994        self.addons
15995            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15996    }
15997
15998    pub fn unregister_addon<T: Addon>(&mut self) {
15999        self.addons.remove(&std::any::TypeId::of::<T>());
16000    }
16001
16002    pub fn addon<T: Addon>(&self) -> Option<&T> {
16003        let type_id = std::any::TypeId::of::<T>();
16004        self.addons
16005            .get(&type_id)
16006            .and_then(|item| item.to_any().downcast_ref::<T>())
16007    }
16008
16009    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16010        let text_layout_details = self.text_layout_details(window);
16011        let style = &text_layout_details.editor_style;
16012        let font_id = window.text_system().resolve_font(&style.text.font());
16013        let font_size = style.text.font_size.to_pixels(window.rem_size());
16014        let line_height = style.text.line_height_in_pixels(window.rem_size());
16015        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16016
16017        gpui::Size::new(em_width, line_height)
16018    }
16019
16020    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16021        self.load_diff_task.clone()
16022    }
16023
16024    fn read_selections_from_db(
16025        &mut self,
16026        item_id: u64,
16027        workspace_id: WorkspaceId,
16028        window: &mut Window,
16029        cx: &mut Context<Editor>,
16030    ) {
16031        if !self.is_singleton(cx)
16032            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16033        {
16034            return;
16035        }
16036        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16037            return;
16038        };
16039        if selections.is_empty() {
16040            return;
16041        }
16042
16043        let snapshot = self.buffer.read(cx).snapshot(cx);
16044        self.change_selections(None, window, cx, |s| {
16045            s.select_ranges(selections.into_iter().map(|(start, end)| {
16046                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16047            }));
16048        });
16049    }
16050}
16051
16052fn insert_extra_newline_brackets(
16053    buffer: &MultiBufferSnapshot,
16054    range: Range<usize>,
16055    language: &language::LanguageScope,
16056) -> bool {
16057    let leading_whitespace_len = buffer
16058        .reversed_chars_at(range.start)
16059        .take_while(|c| c.is_whitespace() && *c != '\n')
16060        .map(|c| c.len_utf8())
16061        .sum::<usize>();
16062    let trailing_whitespace_len = buffer
16063        .chars_at(range.end)
16064        .take_while(|c| c.is_whitespace() && *c != '\n')
16065        .map(|c| c.len_utf8())
16066        .sum::<usize>();
16067    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16068
16069    language.brackets().any(|(pair, enabled)| {
16070        let pair_start = pair.start.trim_end();
16071        let pair_end = pair.end.trim_start();
16072
16073        enabled
16074            && pair.newline
16075            && buffer.contains_str_at(range.end, pair_end)
16076            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16077    })
16078}
16079
16080fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16081    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16082        [(buffer, range, _)] => (*buffer, range.clone()),
16083        _ => return false,
16084    };
16085    let pair = {
16086        let mut result: Option<BracketMatch> = None;
16087
16088        for pair in buffer
16089            .all_bracket_ranges(range.clone())
16090            .filter(move |pair| {
16091                pair.open_range.start <= range.start && pair.close_range.end >= range.end
16092            })
16093        {
16094            let len = pair.close_range.end - pair.open_range.start;
16095
16096            if let Some(existing) = &result {
16097                let existing_len = existing.close_range.end - existing.open_range.start;
16098                if len > existing_len {
16099                    continue;
16100                }
16101            }
16102
16103            result = Some(pair);
16104        }
16105
16106        result
16107    };
16108    let Some(pair) = pair else {
16109        return false;
16110    };
16111    pair.newline_only
16112        && buffer
16113            .chars_for_range(pair.open_range.end..range.start)
16114            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16115            .all(|c| c.is_whitespace() && c != '\n')
16116}
16117
16118fn get_uncommitted_diff_for_buffer(
16119    project: &Entity<Project>,
16120    buffers: impl IntoIterator<Item = Entity<Buffer>>,
16121    buffer: Entity<MultiBuffer>,
16122    cx: &mut App,
16123) -> Task<()> {
16124    let mut tasks = Vec::new();
16125    project.update(cx, |project, cx| {
16126        for buffer in buffers {
16127            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16128        }
16129    });
16130    cx.spawn(|mut cx| async move {
16131        let diffs = futures::future::join_all(tasks).await;
16132        buffer
16133            .update(&mut cx, |buffer, cx| {
16134                for diff in diffs.into_iter().flatten() {
16135                    buffer.add_diff(diff, cx);
16136                }
16137            })
16138            .ok();
16139    })
16140}
16141
16142fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16143    let tab_size = tab_size.get() as usize;
16144    let mut width = offset;
16145
16146    for ch in text.chars() {
16147        width += if ch == '\t' {
16148            tab_size - (width % tab_size)
16149        } else {
16150            1
16151        };
16152    }
16153
16154    width - offset
16155}
16156
16157#[cfg(test)]
16158mod tests {
16159    use super::*;
16160
16161    #[test]
16162    fn test_string_size_with_expanded_tabs() {
16163        let nz = |val| NonZeroU32::new(val).unwrap();
16164        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16165        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16166        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16167        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16168        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16169        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16170        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16171        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16172    }
16173}
16174
16175/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16176struct WordBreakingTokenizer<'a> {
16177    input: &'a str,
16178}
16179
16180impl<'a> WordBreakingTokenizer<'a> {
16181    fn new(input: &'a str) -> Self {
16182        Self { input }
16183    }
16184}
16185
16186fn is_char_ideographic(ch: char) -> bool {
16187    use unicode_script::Script::*;
16188    use unicode_script::UnicodeScript;
16189    matches!(ch.script(), Han | Tangut | Yi)
16190}
16191
16192fn is_grapheme_ideographic(text: &str) -> bool {
16193    text.chars().any(is_char_ideographic)
16194}
16195
16196fn is_grapheme_whitespace(text: &str) -> bool {
16197    text.chars().any(|x| x.is_whitespace())
16198}
16199
16200fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16201    text.chars().next().map_or(false, |ch| {
16202        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16203    })
16204}
16205
16206#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16207struct WordBreakToken<'a> {
16208    token: &'a str,
16209    grapheme_len: usize,
16210    is_whitespace: bool,
16211}
16212
16213impl<'a> Iterator for WordBreakingTokenizer<'a> {
16214    /// Yields a span, the count of graphemes in the token, and whether it was
16215    /// whitespace. Note that it also breaks at word boundaries.
16216    type Item = WordBreakToken<'a>;
16217
16218    fn next(&mut self) -> Option<Self::Item> {
16219        use unicode_segmentation::UnicodeSegmentation;
16220        if self.input.is_empty() {
16221            return None;
16222        }
16223
16224        let mut iter = self.input.graphemes(true).peekable();
16225        let mut offset = 0;
16226        let mut graphemes = 0;
16227        if let Some(first_grapheme) = iter.next() {
16228            let is_whitespace = is_grapheme_whitespace(first_grapheme);
16229            offset += first_grapheme.len();
16230            graphemes += 1;
16231            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16232                if let Some(grapheme) = iter.peek().copied() {
16233                    if should_stay_with_preceding_ideograph(grapheme) {
16234                        offset += grapheme.len();
16235                        graphemes += 1;
16236                    }
16237                }
16238            } else {
16239                let mut words = self.input[offset..].split_word_bound_indices().peekable();
16240                let mut next_word_bound = words.peek().copied();
16241                if next_word_bound.map_or(false, |(i, _)| i == 0) {
16242                    next_word_bound = words.next();
16243                }
16244                while let Some(grapheme) = iter.peek().copied() {
16245                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
16246                        break;
16247                    };
16248                    if is_grapheme_whitespace(grapheme) != is_whitespace {
16249                        break;
16250                    };
16251                    offset += grapheme.len();
16252                    graphemes += 1;
16253                    iter.next();
16254                }
16255            }
16256            let token = &self.input[..offset];
16257            self.input = &self.input[offset..];
16258            if is_whitespace {
16259                Some(WordBreakToken {
16260                    token: " ",
16261                    grapheme_len: 1,
16262                    is_whitespace: true,
16263                })
16264            } else {
16265                Some(WordBreakToken {
16266                    token,
16267                    grapheme_len: graphemes,
16268                    is_whitespace: false,
16269                })
16270            }
16271        } else {
16272            None
16273        }
16274    }
16275}
16276
16277#[test]
16278fn test_word_breaking_tokenizer() {
16279    let tests: &[(&str, &[(&str, usize, bool)])] = &[
16280        ("", &[]),
16281        ("  ", &[(" ", 1, true)]),
16282        ("Ʒ", &[("Ʒ", 1, false)]),
16283        ("Ǽ", &[("Ǽ", 1, false)]),
16284        ("", &[("", 1, false)]),
16285        ("⋑⋑", &[("⋑⋑", 2, false)]),
16286        (
16287            "原理,进而",
16288            &[
16289                ("", 1, false),
16290                ("理,", 2, false),
16291                ("", 1, false),
16292                ("", 1, false),
16293            ],
16294        ),
16295        (
16296            "hello world",
16297            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16298        ),
16299        (
16300            "hello, world",
16301            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16302        ),
16303        (
16304            "  hello world",
16305            &[
16306                (" ", 1, true),
16307                ("hello", 5, false),
16308                (" ", 1, true),
16309                ("world", 5, false),
16310            ],
16311        ),
16312        (
16313            "这是什么 \n 钢笔",
16314            &[
16315                ("", 1, false),
16316                ("", 1, false),
16317                ("", 1, false),
16318                ("", 1, false),
16319                (" ", 1, true),
16320                ("", 1, false),
16321                ("", 1, false),
16322            ],
16323        ),
16324        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16325    ];
16326
16327    for (input, result) in tests {
16328        assert_eq!(
16329            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16330            result
16331                .iter()
16332                .copied()
16333                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16334                    token,
16335                    grapheme_len,
16336                    is_whitespace,
16337                })
16338                .collect::<Vec<_>>()
16339        );
16340    }
16341}
16342
16343fn wrap_with_prefix(
16344    line_prefix: String,
16345    unwrapped_text: String,
16346    wrap_column: usize,
16347    tab_size: NonZeroU32,
16348) -> String {
16349    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16350    let mut wrapped_text = String::new();
16351    let mut current_line = line_prefix.clone();
16352
16353    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16354    let mut current_line_len = line_prefix_len;
16355    for WordBreakToken {
16356        token,
16357        grapheme_len,
16358        is_whitespace,
16359    } in tokenizer
16360    {
16361        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16362            wrapped_text.push_str(current_line.trim_end());
16363            wrapped_text.push('\n');
16364            current_line.truncate(line_prefix.len());
16365            current_line_len = line_prefix_len;
16366            if !is_whitespace {
16367                current_line.push_str(token);
16368                current_line_len += grapheme_len;
16369            }
16370        } else if !is_whitespace {
16371            current_line.push_str(token);
16372            current_line_len += grapheme_len;
16373        } else if current_line_len != line_prefix_len {
16374            current_line.push(' ');
16375            current_line_len += 1;
16376        }
16377    }
16378
16379    if !current_line.is_empty() {
16380        wrapped_text.push_str(&current_line);
16381    }
16382    wrapped_text
16383}
16384
16385#[test]
16386fn test_wrap_with_prefix() {
16387    assert_eq!(
16388        wrap_with_prefix(
16389            "# ".to_string(),
16390            "abcdefg".to_string(),
16391            4,
16392            NonZeroU32::new(4).unwrap()
16393        ),
16394        "# abcdefg"
16395    );
16396    assert_eq!(
16397        wrap_with_prefix(
16398            "".to_string(),
16399            "\thello world".to_string(),
16400            8,
16401            NonZeroU32::new(4).unwrap()
16402        ),
16403        "hello\nworld"
16404    );
16405    assert_eq!(
16406        wrap_with_prefix(
16407            "// ".to_string(),
16408            "xx \nyy zz aa bb cc".to_string(),
16409            12,
16410            NonZeroU32::new(4).unwrap()
16411        ),
16412        "// xx yy zz\n// aa bb cc"
16413    );
16414    assert_eq!(
16415        wrap_with_prefix(
16416            String::new(),
16417            "这是什么 \n 钢笔".to_string(),
16418            3,
16419            NonZeroU32::new(4).unwrap()
16420        ),
16421        "这是什\n么 钢\n"
16422    );
16423}
16424
16425pub trait CollaborationHub {
16426    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16427    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16428    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16429}
16430
16431impl CollaborationHub for Entity<Project> {
16432    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16433        self.read(cx).collaborators()
16434    }
16435
16436    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16437        self.read(cx).user_store().read(cx).participant_indices()
16438    }
16439
16440    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16441        let this = self.read(cx);
16442        let user_ids = this.collaborators().values().map(|c| c.user_id);
16443        this.user_store().read_with(cx, |user_store, cx| {
16444            user_store.participant_names(user_ids, cx)
16445        })
16446    }
16447}
16448
16449pub trait SemanticsProvider {
16450    fn hover(
16451        &self,
16452        buffer: &Entity<Buffer>,
16453        position: text::Anchor,
16454        cx: &mut App,
16455    ) -> Option<Task<Vec<project::Hover>>>;
16456
16457    fn inlay_hints(
16458        &self,
16459        buffer_handle: Entity<Buffer>,
16460        range: Range<text::Anchor>,
16461        cx: &mut App,
16462    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16463
16464    fn resolve_inlay_hint(
16465        &self,
16466        hint: InlayHint,
16467        buffer_handle: Entity<Buffer>,
16468        server_id: LanguageServerId,
16469        cx: &mut App,
16470    ) -> Option<Task<anyhow::Result<InlayHint>>>;
16471
16472    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16473
16474    fn document_highlights(
16475        &self,
16476        buffer: &Entity<Buffer>,
16477        position: text::Anchor,
16478        cx: &mut App,
16479    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16480
16481    fn definitions(
16482        &self,
16483        buffer: &Entity<Buffer>,
16484        position: text::Anchor,
16485        kind: GotoDefinitionKind,
16486        cx: &mut App,
16487    ) -> Option<Task<Result<Vec<LocationLink>>>>;
16488
16489    fn range_for_rename(
16490        &self,
16491        buffer: &Entity<Buffer>,
16492        position: text::Anchor,
16493        cx: &mut App,
16494    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16495
16496    fn perform_rename(
16497        &self,
16498        buffer: &Entity<Buffer>,
16499        position: text::Anchor,
16500        new_name: String,
16501        cx: &mut App,
16502    ) -> Option<Task<Result<ProjectTransaction>>>;
16503}
16504
16505pub trait CompletionProvider {
16506    fn completions(
16507        &self,
16508        buffer: &Entity<Buffer>,
16509        buffer_position: text::Anchor,
16510        trigger: CompletionContext,
16511        window: &mut Window,
16512        cx: &mut Context<Editor>,
16513    ) -> Task<Result<Vec<Completion>>>;
16514
16515    fn resolve_completions(
16516        &self,
16517        buffer: Entity<Buffer>,
16518        completion_indices: Vec<usize>,
16519        completions: Rc<RefCell<Box<[Completion]>>>,
16520        cx: &mut Context<Editor>,
16521    ) -> Task<Result<bool>>;
16522
16523    fn apply_additional_edits_for_completion(
16524        &self,
16525        _buffer: Entity<Buffer>,
16526        _completions: Rc<RefCell<Box<[Completion]>>>,
16527        _completion_index: usize,
16528        _push_to_history: bool,
16529        _cx: &mut Context<Editor>,
16530    ) -> Task<Result<Option<language::Transaction>>> {
16531        Task::ready(Ok(None))
16532    }
16533
16534    fn is_completion_trigger(
16535        &self,
16536        buffer: &Entity<Buffer>,
16537        position: language::Anchor,
16538        text: &str,
16539        trigger_in_words: bool,
16540        cx: &mut Context<Editor>,
16541    ) -> bool;
16542
16543    fn sort_completions(&self) -> bool {
16544        true
16545    }
16546}
16547
16548pub trait CodeActionProvider {
16549    fn id(&self) -> Arc<str>;
16550
16551    fn code_actions(
16552        &self,
16553        buffer: &Entity<Buffer>,
16554        range: Range<text::Anchor>,
16555        window: &mut Window,
16556        cx: &mut App,
16557    ) -> Task<Result<Vec<CodeAction>>>;
16558
16559    fn apply_code_action(
16560        &self,
16561        buffer_handle: Entity<Buffer>,
16562        action: CodeAction,
16563        excerpt_id: ExcerptId,
16564        push_to_history: bool,
16565        window: &mut Window,
16566        cx: &mut App,
16567    ) -> Task<Result<ProjectTransaction>>;
16568}
16569
16570impl CodeActionProvider for Entity<Project> {
16571    fn id(&self) -> Arc<str> {
16572        "project".into()
16573    }
16574
16575    fn code_actions(
16576        &self,
16577        buffer: &Entity<Buffer>,
16578        range: Range<text::Anchor>,
16579        _window: &mut Window,
16580        cx: &mut App,
16581    ) -> Task<Result<Vec<CodeAction>>> {
16582        self.update(cx, |project, cx| {
16583            project.code_actions(buffer, range, None, cx)
16584        })
16585    }
16586
16587    fn apply_code_action(
16588        &self,
16589        buffer_handle: Entity<Buffer>,
16590        action: CodeAction,
16591        _excerpt_id: ExcerptId,
16592        push_to_history: bool,
16593        _window: &mut Window,
16594        cx: &mut App,
16595    ) -> Task<Result<ProjectTransaction>> {
16596        self.update(cx, |project, cx| {
16597            project.apply_code_action(buffer_handle, action, push_to_history, cx)
16598        })
16599    }
16600}
16601
16602fn snippet_completions(
16603    project: &Project,
16604    buffer: &Entity<Buffer>,
16605    buffer_position: text::Anchor,
16606    cx: &mut App,
16607) -> Task<Result<Vec<Completion>>> {
16608    let language = buffer.read(cx).language_at(buffer_position);
16609    let language_name = language.as_ref().map(|language| language.lsp_id());
16610    let snippet_store = project.snippets().read(cx);
16611    let snippets = snippet_store.snippets_for(language_name, cx);
16612
16613    if snippets.is_empty() {
16614        return Task::ready(Ok(vec![]));
16615    }
16616    let snapshot = buffer.read(cx).text_snapshot();
16617    let chars: String = snapshot
16618        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16619        .collect();
16620
16621    let scope = language.map(|language| language.default_scope());
16622    let executor = cx.background_executor().clone();
16623
16624    cx.background_spawn(async move {
16625        let classifier = CharClassifier::new(scope).for_completion(true);
16626        let mut last_word = chars
16627            .chars()
16628            .take_while(|c| classifier.is_word(*c))
16629            .collect::<String>();
16630        last_word = last_word.chars().rev().collect();
16631
16632        if last_word.is_empty() {
16633            return Ok(vec![]);
16634        }
16635
16636        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16637        let to_lsp = |point: &text::Anchor| {
16638            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16639            point_to_lsp(end)
16640        };
16641        let lsp_end = to_lsp(&buffer_position);
16642
16643        let candidates = snippets
16644            .iter()
16645            .enumerate()
16646            .flat_map(|(ix, snippet)| {
16647                snippet
16648                    .prefix
16649                    .iter()
16650                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16651            })
16652            .collect::<Vec<StringMatchCandidate>>();
16653
16654        let mut matches = fuzzy::match_strings(
16655            &candidates,
16656            &last_word,
16657            last_word.chars().any(|c| c.is_uppercase()),
16658            100,
16659            &Default::default(),
16660            executor,
16661        )
16662        .await;
16663
16664        // Remove all candidates where the query's start does not match the start of any word in the candidate
16665        if let Some(query_start) = last_word.chars().next() {
16666            matches.retain(|string_match| {
16667                split_words(&string_match.string).any(|word| {
16668                    // Check that the first codepoint of the word as lowercase matches the first
16669                    // codepoint of the query as lowercase
16670                    word.chars()
16671                        .flat_map(|codepoint| codepoint.to_lowercase())
16672                        .zip(query_start.to_lowercase())
16673                        .all(|(word_cp, query_cp)| word_cp == query_cp)
16674                })
16675            });
16676        }
16677
16678        let matched_strings = matches
16679            .into_iter()
16680            .map(|m| m.string)
16681            .collect::<HashSet<_>>();
16682
16683        let result: Vec<Completion> = snippets
16684            .into_iter()
16685            .filter_map(|snippet| {
16686                let matching_prefix = snippet
16687                    .prefix
16688                    .iter()
16689                    .find(|prefix| matched_strings.contains(*prefix))?;
16690                let start = as_offset - last_word.len();
16691                let start = snapshot.anchor_before(start);
16692                let range = start..buffer_position;
16693                let lsp_start = to_lsp(&start);
16694                let lsp_range = lsp::Range {
16695                    start: lsp_start,
16696                    end: lsp_end,
16697                };
16698                Some(Completion {
16699                    old_range: range,
16700                    new_text: snippet.body.clone(),
16701                    resolved: false,
16702                    label: CodeLabel {
16703                        text: matching_prefix.clone(),
16704                        runs: vec![],
16705                        filter_range: 0..matching_prefix.len(),
16706                    },
16707                    server_id: LanguageServerId(usize::MAX),
16708                    documentation: snippet
16709                        .description
16710                        .clone()
16711                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
16712                    lsp_completion: lsp::CompletionItem {
16713                        label: snippet.prefix.first().unwrap().clone(),
16714                        kind: Some(CompletionItemKind::SNIPPET),
16715                        label_details: snippet.description.as_ref().map(|description| {
16716                            lsp::CompletionItemLabelDetails {
16717                                detail: Some(description.clone()),
16718                                description: None,
16719                            }
16720                        }),
16721                        insert_text_format: Some(InsertTextFormat::SNIPPET),
16722                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16723                            lsp::InsertReplaceEdit {
16724                                new_text: snippet.body.clone(),
16725                                insert: lsp_range,
16726                                replace: lsp_range,
16727                            },
16728                        )),
16729                        filter_text: Some(snippet.body.clone()),
16730                        sort_text: Some(char::MAX.to_string()),
16731                        ..Default::default()
16732                    },
16733                    confirm: None,
16734                })
16735            })
16736            .collect();
16737
16738        Ok(result)
16739    })
16740}
16741
16742impl CompletionProvider for Entity<Project> {
16743    fn completions(
16744        &self,
16745        buffer: &Entity<Buffer>,
16746        buffer_position: text::Anchor,
16747        options: CompletionContext,
16748        _window: &mut Window,
16749        cx: &mut Context<Editor>,
16750    ) -> Task<Result<Vec<Completion>>> {
16751        self.update(cx, |project, cx| {
16752            let snippets = snippet_completions(project, buffer, buffer_position, cx);
16753            let project_completions = project.completions(buffer, buffer_position, options, cx);
16754            cx.background_spawn(async move {
16755                let mut completions = project_completions.await?;
16756                let snippets_completions = snippets.await?;
16757                completions.extend(snippets_completions);
16758                Ok(completions)
16759            })
16760        })
16761    }
16762
16763    fn resolve_completions(
16764        &self,
16765        buffer: Entity<Buffer>,
16766        completion_indices: Vec<usize>,
16767        completions: Rc<RefCell<Box<[Completion]>>>,
16768        cx: &mut Context<Editor>,
16769    ) -> Task<Result<bool>> {
16770        self.update(cx, |project, cx| {
16771            project.lsp_store().update(cx, |lsp_store, cx| {
16772                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16773            })
16774        })
16775    }
16776
16777    fn apply_additional_edits_for_completion(
16778        &self,
16779        buffer: Entity<Buffer>,
16780        completions: Rc<RefCell<Box<[Completion]>>>,
16781        completion_index: usize,
16782        push_to_history: bool,
16783        cx: &mut Context<Editor>,
16784    ) -> Task<Result<Option<language::Transaction>>> {
16785        self.update(cx, |project, cx| {
16786            project.lsp_store().update(cx, |lsp_store, cx| {
16787                lsp_store.apply_additional_edits_for_completion(
16788                    buffer,
16789                    completions,
16790                    completion_index,
16791                    push_to_history,
16792                    cx,
16793                )
16794            })
16795        })
16796    }
16797
16798    fn is_completion_trigger(
16799        &self,
16800        buffer: &Entity<Buffer>,
16801        position: language::Anchor,
16802        text: &str,
16803        trigger_in_words: bool,
16804        cx: &mut Context<Editor>,
16805    ) -> bool {
16806        let mut chars = text.chars();
16807        let char = if let Some(char) = chars.next() {
16808            char
16809        } else {
16810            return false;
16811        };
16812        if chars.next().is_some() {
16813            return false;
16814        }
16815
16816        let buffer = buffer.read(cx);
16817        let snapshot = buffer.snapshot();
16818        if !snapshot.settings_at(position, cx).show_completions_on_input {
16819            return false;
16820        }
16821        let classifier = snapshot.char_classifier_at(position).for_completion(true);
16822        if trigger_in_words && classifier.is_word(char) {
16823            return true;
16824        }
16825
16826        buffer.completion_triggers().contains(text)
16827    }
16828}
16829
16830impl SemanticsProvider for Entity<Project> {
16831    fn hover(
16832        &self,
16833        buffer: &Entity<Buffer>,
16834        position: text::Anchor,
16835        cx: &mut App,
16836    ) -> Option<Task<Vec<project::Hover>>> {
16837        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
16838    }
16839
16840    fn document_highlights(
16841        &self,
16842        buffer: &Entity<Buffer>,
16843        position: text::Anchor,
16844        cx: &mut App,
16845    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
16846        Some(self.update(cx, |project, cx| {
16847            project.document_highlights(buffer, position, cx)
16848        }))
16849    }
16850
16851    fn definitions(
16852        &self,
16853        buffer: &Entity<Buffer>,
16854        position: text::Anchor,
16855        kind: GotoDefinitionKind,
16856        cx: &mut App,
16857    ) -> Option<Task<Result<Vec<LocationLink>>>> {
16858        Some(self.update(cx, |project, cx| match kind {
16859            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
16860            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
16861            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
16862            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
16863        }))
16864    }
16865
16866    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
16867        // TODO: make this work for remote projects
16868        self.update(cx, |this, cx| {
16869            buffer.update(cx, |buffer, cx| {
16870                this.any_language_server_supports_inlay_hints(buffer, cx)
16871            })
16872        })
16873    }
16874
16875    fn inlay_hints(
16876        &self,
16877        buffer_handle: Entity<Buffer>,
16878        range: Range<text::Anchor>,
16879        cx: &mut App,
16880    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
16881        Some(self.update(cx, |project, cx| {
16882            project.inlay_hints(buffer_handle, range, cx)
16883        }))
16884    }
16885
16886    fn resolve_inlay_hint(
16887        &self,
16888        hint: InlayHint,
16889        buffer_handle: Entity<Buffer>,
16890        server_id: LanguageServerId,
16891        cx: &mut App,
16892    ) -> Option<Task<anyhow::Result<InlayHint>>> {
16893        Some(self.update(cx, |project, cx| {
16894            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
16895        }))
16896    }
16897
16898    fn range_for_rename(
16899        &self,
16900        buffer: &Entity<Buffer>,
16901        position: text::Anchor,
16902        cx: &mut App,
16903    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
16904        Some(self.update(cx, |project, cx| {
16905            let buffer = buffer.clone();
16906            let task = project.prepare_rename(buffer.clone(), position, cx);
16907            cx.spawn(|_, mut cx| async move {
16908                Ok(match task.await? {
16909                    PrepareRenameResponse::Success(range) => Some(range),
16910                    PrepareRenameResponse::InvalidPosition => None,
16911                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
16912                        // Fallback on using TreeSitter info to determine identifier range
16913                        buffer.update(&mut cx, |buffer, _| {
16914                            let snapshot = buffer.snapshot();
16915                            let (range, kind) = snapshot.surrounding_word(position);
16916                            if kind != Some(CharKind::Word) {
16917                                return None;
16918                            }
16919                            Some(
16920                                snapshot.anchor_before(range.start)
16921                                    ..snapshot.anchor_after(range.end),
16922                            )
16923                        })?
16924                    }
16925                })
16926            })
16927        }))
16928    }
16929
16930    fn perform_rename(
16931        &self,
16932        buffer: &Entity<Buffer>,
16933        position: text::Anchor,
16934        new_name: String,
16935        cx: &mut App,
16936    ) -> Option<Task<Result<ProjectTransaction>>> {
16937        Some(self.update(cx, |project, cx| {
16938            project.perform_rename(buffer.clone(), position, new_name, cx)
16939        }))
16940    }
16941}
16942
16943fn inlay_hint_settings(
16944    location: Anchor,
16945    snapshot: &MultiBufferSnapshot,
16946    cx: &mut Context<Editor>,
16947) -> InlayHintSettings {
16948    let file = snapshot.file_at(location);
16949    let language = snapshot.language_at(location).map(|l| l.name());
16950    language_settings(language, file, cx).inlay_hints
16951}
16952
16953fn consume_contiguous_rows(
16954    contiguous_row_selections: &mut Vec<Selection<Point>>,
16955    selection: &Selection<Point>,
16956    display_map: &DisplaySnapshot,
16957    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
16958) -> (MultiBufferRow, MultiBufferRow) {
16959    contiguous_row_selections.push(selection.clone());
16960    let start_row = MultiBufferRow(selection.start.row);
16961    let mut end_row = ending_row(selection, display_map);
16962
16963    while let Some(next_selection) = selections.peek() {
16964        if next_selection.start.row <= end_row.0 {
16965            end_row = ending_row(next_selection, display_map);
16966            contiguous_row_selections.push(selections.next().unwrap().clone());
16967        } else {
16968            break;
16969        }
16970    }
16971    (start_row, end_row)
16972}
16973
16974fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
16975    if next_selection.end.column > 0 || next_selection.is_empty() {
16976        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
16977    } else {
16978        MultiBufferRow(next_selection.end.row)
16979    }
16980}
16981
16982impl EditorSnapshot {
16983    pub fn remote_selections_in_range<'a>(
16984        &'a self,
16985        range: &'a Range<Anchor>,
16986        collaboration_hub: &dyn CollaborationHub,
16987        cx: &'a App,
16988    ) -> impl 'a + Iterator<Item = RemoteSelection> {
16989        let participant_names = collaboration_hub.user_names(cx);
16990        let participant_indices = collaboration_hub.user_participant_indices(cx);
16991        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
16992        let collaborators_by_replica_id = collaborators_by_peer_id
16993            .iter()
16994            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
16995            .collect::<HashMap<_, _>>();
16996        self.buffer_snapshot
16997            .selections_in_range(range, false)
16998            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
16999                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17000                let participant_index = participant_indices.get(&collaborator.user_id).copied();
17001                let user_name = participant_names.get(&collaborator.user_id).cloned();
17002                Some(RemoteSelection {
17003                    replica_id,
17004                    selection,
17005                    cursor_shape,
17006                    line_mode,
17007                    participant_index,
17008                    peer_id: collaborator.peer_id,
17009                    user_name,
17010                })
17011            })
17012    }
17013
17014    pub fn hunks_for_ranges(
17015        &self,
17016        ranges: impl Iterator<Item = Range<Point>>,
17017    ) -> Vec<MultiBufferDiffHunk> {
17018        let mut hunks = Vec::new();
17019        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17020            HashMap::default();
17021        for query_range in ranges {
17022            let query_rows =
17023                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17024            for hunk in self.buffer_snapshot.diff_hunks_in_range(
17025                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17026            ) {
17027                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
17028                // when the caret is just above or just below the deleted hunk.
17029                let allow_adjacent = hunk.status().is_deleted();
17030                let related_to_selection = if allow_adjacent {
17031                    hunk.row_range.overlaps(&query_rows)
17032                        || hunk.row_range.start == query_rows.end
17033                        || hunk.row_range.end == query_rows.start
17034                } else {
17035                    hunk.row_range.overlaps(&query_rows)
17036                };
17037                if related_to_selection {
17038                    if !processed_buffer_rows
17039                        .entry(hunk.buffer_id)
17040                        .or_default()
17041                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17042                    {
17043                        continue;
17044                    }
17045                    hunks.push(hunk);
17046                }
17047            }
17048        }
17049
17050        hunks
17051    }
17052
17053    fn display_diff_hunks_for_rows<'a>(
17054        &'a self,
17055        display_rows: Range<DisplayRow>,
17056        folded_buffers: &'a HashSet<BufferId>,
17057    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17058        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17059        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17060
17061        self.buffer_snapshot
17062            .diff_hunks_in_range(buffer_start..buffer_end)
17063            .filter_map(|hunk| {
17064                if folded_buffers.contains(&hunk.buffer_id) {
17065                    return None;
17066                }
17067
17068                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17069                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17070
17071                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17072                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17073
17074                let display_hunk = if hunk_display_start.column() != 0 {
17075                    DisplayDiffHunk::Folded {
17076                        display_row: hunk_display_start.row(),
17077                    }
17078                } else {
17079                    let mut end_row = hunk_display_end.row();
17080                    if hunk_display_end.column() > 0 {
17081                        end_row.0 += 1;
17082                    }
17083                    DisplayDiffHunk::Unfolded {
17084                        status: hunk.status(),
17085                        diff_base_byte_range: hunk.diff_base_byte_range,
17086                        display_row_range: hunk_display_start.row()..end_row,
17087                        multi_buffer_range: Anchor::range_in_buffer(
17088                            hunk.excerpt_id,
17089                            hunk.buffer_id,
17090                            hunk.buffer_range,
17091                        ),
17092                    }
17093                };
17094
17095                Some(display_hunk)
17096            })
17097    }
17098
17099    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17100        self.display_snapshot.buffer_snapshot.language_at(position)
17101    }
17102
17103    pub fn is_focused(&self) -> bool {
17104        self.is_focused
17105    }
17106
17107    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17108        self.placeholder_text.as_ref()
17109    }
17110
17111    pub fn scroll_position(&self) -> gpui::Point<f32> {
17112        self.scroll_anchor.scroll_position(&self.display_snapshot)
17113    }
17114
17115    fn gutter_dimensions(
17116        &self,
17117        font_id: FontId,
17118        font_size: Pixels,
17119        max_line_number_width: Pixels,
17120        cx: &App,
17121    ) -> Option<GutterDimensions> {
17122        if !self.show_gutter {
17123            return None;
17124        }
17125
17126        let descent = cx.text_system().descent(font_id, font_size);
17127        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17128        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17129
17130        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17131            matches!(
17132                ProjectSettings::get_global(cx).git.git_gutter,
17133                Some(GitGutterSetting::TrackedFiles)
17134            )
17135        });
17136        let gutter_settings = EditorSettings::get_global(cx).gutter;
17137        let show_line_numbers = self
17138            .show_line_numbers
17139            .unwrap_or(gutter_settings.line_numbers);
17140        let line_gutter_width = if show_line_numbers {
17141            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17142            let min_width_for_number_on_gutter = em_advance * 4.0;
17143            max_line_number_width.max(min_width_for_number_on_gutter)
17144        } else {
17145            0.0.into()
17146        };
17147
17148        let show_code_actions = self
17149            .show_code_actions
17150            .unwrap_or(gutter_settings.code_actions);
17151
17152        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17153
17154        let git_blame_entries_width =
17155            self.git_blame_gutter_max_author_length
17156                .map(|max_author_length| {
17157                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17158
17159                    /// The number of characters to dedicate to gaps and margins.
17160                    const SPACING_WIDTH: usize = 4;
17161
17162                    let max_char_count = max_author_length
17163                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17164                        + ::git::SHORT_SHA_LENGTH
17165                        + MAX_RELATIVE_TIMESTAMP.len()
17166                        + SPACING_WIDTH;
17167
17168                    em_advance * max_char_count
17169                });
17170
17171        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17172        left_padding += if show_code_actions || show_runnables {
17173            em_width * 3.0
17174        } else if show_git_gutter && show_line_numbers {
17175            em_width * 2.0
17176        } else if show_git_gutter || show_line_numbers {
17177            em_width
17178        } else {
17179            px(0.)
17180        };
17181
17182        let right_padding = if gutter_settings.folds && show_line_numbers {
17183            em_width * 4.0
17184        } else if gutter_settings.folds {
17185            em_width * 3.0
17186        } else if show_line_numbers {
17187            em_width
17188        } else {
17189            px(0.)
17190        };
17191
17192        Some(GutterDimensions {
17193            left_padding,
17194            right_padding,
17195            width: line_gutter_width + left_padding + right_padding,
17196            margin: -descent,
17197            git_blame_entries_width,
17198        })
17199    }
17200
17201    pub fn render_crease_toggle(
17202        &self,
17203        buffer_row: MultiBufferRow,
17204        row_contains_cursor: bool,
17205        editor: Entity<Editor>,
17206        window: &mut Window,
17207        cx: &mut App,
17208    ) -> Option<AnyElement> {
17209        let folded = self.is_line_folded(buffer_row);
17210        let mut is_foldable = false;
17211
17212        if let Some(crease) = self
17213            .crease_snapshot
17214            .query_row(buffer_row, &self.buffer_snapshot)
17215        {
17216            is_foldable = true;
17217            match crease {
17218                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17219                    if let Some(render_toggle) = render_toggle {
17220                        let toggle_callback =
17221                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17222                                if folded {
17223                                    editor.update(cx, |editor, cx| {
17224                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17225                                    });
17226                                } else {
17227                                    editor.update(cx, |editor, cx| {
17228                                        editor.unfold_at(
17229                                            &crate::UnfoldAt { buffer_row },
17230                                            window,
17231                                            cx,
17232                                        )
17233                                    });
17234                                }
17235                            });
17236                        return Some((render_toggle)(
17237                            buffer_row,
17238                            folded,
17239                            toggle_callback,
17240                            window,
17241                            cx,
17242                        ));
17243                    }
17244                }
17245            }
17246        }
17247
17248        is_foldable |= self.starts_indent(buffer_row);
17249
17250        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17251            Some(
17252                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17253                    .toggle_state(folded)
17254                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17255                        if folded {
17256                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17257                        } else {
17258                            this.fold_at(&FoldAt { buffer_row }, window, cx);
17259                        }
17260                    }))
17261                    .into_any_element(),
17262            )
17263        } else {
17264            None
17265        }
17266    }
17267
17268    pub fn render_crease_trailer(
17269        &self,
17270        buffer_row: MultiBufferRow,
17271        window: &mut Window,
17272        cx: &mut App,
17273    ) -> Option<AnyElement> {
17274        let folded = self.is_line_folded(buffer_row);
17275        if let Crease::Inline { render_trailer, .. } = self
17276            .crease_snapshot
17277            .query_row(buffer_row, &self.buffer_snapshot)?
17278        {
17279            let render_trailer = render_trailer.as_ref()?;
17280            Some(render_trailer(buffer_row, folded, window, cx))
17281        } else {
17282            None
17283        }
17284    }
17285}
17286
17287impl Deref for EditorSnapshot {
17288    type Target = DisplaySnapshot;
17289
17290    fn deref(&self) -> &Self::Target {
17291        &self.display_snapshot
17292    }
17293}
17294
17295#[derive(Clone, Debug, PartialEq, Eq)]
17296pub enum EditorEvent {
17297    InputIgnored {
17298        text: Arc<str>,
17299    },
17300    InputHandled {
17301        utf16_range_to_replace: Option<Range<isize>>,
17302        text: Arc<str>,
17303    },
17304    ExcerptsAdded {
17305        buffer: Entity<Buffer>,
17306        predecessor: ExcerptId,
17307        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17308    },
17309    ExcerptsRemoved {
17310        ids: Vec<ExcerptId>,
17311    },
17312    BufferFoldToggled {
17313        ids: Vec<ExcerptId>,
17314        folded: bool,
17315    },
17316    ExcerptsEdited {
17317        ids: Vec<ExcerptId>,
17318    },
17319    ExcerptsExpanded {
17320        ids: Vec<ExcerptId>,
17321    },
17322    BufferEdited,
17323    Edited {
17324        transaction_id: clock::Lamport,
17325    },
17326    Reparsed(BufferId),
17327    Focused,
17328    FocusedIn,
17329    Blurred,
17330    DirtyChanged,
17331    Saved,
17332    TitleChanged,
17333    DiffBaseChanged,
17334    SelectionsChanged {
17335        local: bool,
17336    },
17337    ScrollPositionChanged {
17338        local: bool,
17339        autoscroll: bool,
17340    },
17341    Closed,
17342    TransactionUndone {
17343        transaction_id: clock::Lamport,
17344    },
17345    TransactionBegun {
17346        transaction_id: clock::Lamport,
17347    },
17348    Reloaded,
17349    CursorShapeChanged,
17350}
17351
17352impl EventEmitter<EditorEvent> for Editor {}
17353
17354impl Focusable for Editor {
17355    fn focus_handle(&self, _cx: &App) -> FocusHandle {
17356        self.focus_handle.clone()
17357    }
17358}
17359
17360impl Render for Editor {
17361    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
17362        let settings = ThemeSettings::get_global(cx);
17363
17364        let mut text_style = match self.mode {
17365            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17366                color: cx.theme().colors().editor_foreground,
17367                font_family: settings.ui_font.family.clone(),
17368                font_features: settings.ui_font.features.clone(),
17369                font_fallbacks: settings.ui_font.fallbacks.clone(),
17370                font_size: rems(0.875).into(),
17371                font_weight: settings.ui_font.weight,
17372                line_height: relative(settings.buffer_line_height.value()),
17373                ..Default::default()
17374            },
17375            EditorMode::Full => TextStyle {
17376                color: cx.theme().colors().editor_foreground,
17377                font_family: settings.buffer_font.family.clone(),
17378                font_features: settings.buffer_font.features.clone(),
17379                font_fallbacks: settings.buffer_font.fallbacks.clone(),
17380                font_size: settings.buffer_font_size(cx).into(),
17381                font_weight: settings.buffer_font.weight,
17382                line_height: relative(settings.buffer_line_height.value()),
17383                ..Default::default()
17384            },
17385        };
17386        if let Some(text_style_refinement) = &self.text_style_refinement {
17387            text_style.refine(text_style_refinement)
17388        }
17389
17390        let background = match self.mode {
17391            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17392            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17393            EditorMode::Full => cx.theme().colors().editor_background,
17394        };
17395
17396        EditorElement::new(
17397            &cx.entity(),
17398            EditorStyle {
17399                background,
17400                local_player: cx.theme().players().local(),
17401                text: text_style,
17402                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17403                syntax: cx.theme().syntax().clone(),
17404                status: cx.theme().status().clone(),
17405                inlay_hints_style: make_inlay_hints_style(cx),
17406                inline_completion_styles: make_suggestion_styles(cx),
17407                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17408            },
17409        )
17410    }
17411}
17412
17413impl EntityInputHandler for Editor {
17414    fn text_for_range(
17415        &mut self,
17416        range_utf16: Range<usize>,
17417        adjusted_range: &mut Option<Range<usize>>,
17418        _: &mut Window,
17419        cx: &mut Context<Self>,
17420    ) -> Option<String> {
17421        let snapshot = self.buffer.read(cx).read(cx);
17422        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17423        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17424        if (start.0..end.0) != range_utf16 {
17425            adjusted_range.replace(start.0..end.0);
17426        }
17427        Some(snapshot.text_for_range(start..end).collect())
17428    }
17429
17430    fn selected_text_range(
17431        &mut self,
17432        ignore_disabled_input: bool,
17433        _: &mut Window,
17434        cx: &mut Context<Self>,
17435    ) -> Option<UTF16Selection> {
17436        // Prevent the IME menu from appearing when holding down an alphabetic key
17437        // while input is disabled.
17438        if !ignore_disabled_input && !self.input_enabled {
17439            return None;
17440        }
17441
17442        let selection = self.selections.newest::<OffsetUtf16>(cx);
17443        let range = selection.range();
17444
17445        Some(UTF16Selection {
17446            range: range.start.0..range.end.0,
17447            reversed: selection.reversed,
17448        })
17449    }
17450
17451    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17452        let snapshot = self.buffer.read(cx).read(cx);
17453        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17454        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17455    }
17456
17457    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17458        self.clear_highlights::<InputComposition>(cx);
17459        self.ime_transaction.take();
17460    }
17461
17462    fn replace_text_in_range(
17463        &mut self,
17464        range_utf16: Option<Range<usize>>,
17465        text: &str,
17466        window: &mut Window,
17467        cx: &mut Context<Self>,
17468    ) {
17469        if !self.input_enabled {
17470            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17471            return;
17472        }
17473
17474        self.transact(window, cx, |this, window, cx| {
17475            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17476                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17477                Some(this.selection_replacement_ranges(range_utf16, cx))
17478            } else {
17479                this.marked_text_ranges(cx)
17480            };
17481
17482            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17483                let newest_selection_id = this.selections.newest_anchor().id;
17484                this.selections
17485                    .all::<OffsetUtf16>(cx)
17486                    .iter()
17487                    .zip(ranges_to_replace.iter())
17488                    .find_map(|(selection, range)| {
17489                        if selection.id == newest_selection_id {
17490                            Some(
17491                                (range.start.0 as isize - selection.head().0 as isize)
17492                                    ..(range.end.0 as isize - selection.head().0 as isize),
17493                            )
17494                        } else {
17495                            None
17496                        }
17497                    })
17498            });
17499
17500            cx.emit(EditorEvent::InputHandled {
17501                utf16_range_to_replace: range_to_replace,
17502                text: text.into(),
17503            });
17504
17505            if let Some(new_selected_ranges) = new_selected_ranges {
17506                this.change_selections(None, window, cx, |selections| {
17507                    selections.select_ranges(new_selected_ranges)
17508                });
17509                this.backspace(&Default::default(), window, cx);
17510            }
17511
17512            this.handle_input(text, window, cx);
17513        });
17514
17515        if let Some(transaction) = self.ime_transaction {
17516            self.buffer.update(cx, |buffer, cx| {
17517                buffer.group_until_transaction(transaction, cx);
17518            });
17519        }
17520
17521        self.unmark_text(window, cx);
17522    }
17523
17524    fn replace_and_mark_text_in_range(
17525        &mut self,
17526        range_utf16: Option<Range<usize>>,
17527        text: &str,
17528        new_selected_range_utf16: Option<Range<usize>>,
17529        window: &mut Window,
17530        cx: &mut Context<Self>,
17531    ) {
17532        if !self.input_enabled {
17533            return;
17534        }
17535
17536        let transaction = self.transact(window, cx, |this, window, cx| {
17537            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17538                let snapshot = this.buffer.read(cx).read(cx);
17539                if let Some(relative_range_utf16) = range_utf16.as_ref() {
17540                    for marked_range in &mut marked_ranges {
17541                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17542                        marked_range.start.0 += relative_range_utf16.start;
17543                        marked_range.start =
17544                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17545                        marked_range.end =
17546                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17547                    }
17548                }
17549                Some(marked_ranges)
17550            } else if let Some(range_utf16) = range_utf16 {
17551                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17552                Some(this.selection_replacement_ranges(range_utf16, cx))
17553            } else {
17554                None
17555            };
17556
17557            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17558                let newest_selection_id = this.selections.newest_anchor().id;
17559                this.selections
17560                    .all::<OffsetUtf16>(cx)
17561                    .iter()
17562                    .zip(ranges_to_replace.iter())
17563                    .find_map(|(selection, range)| {
17564                        if selection.id == newest_selection_id {
17565                            Some(
17566                                (range.start.0 as isize - selection.head().0 as isize)
17567                                    ..(range.end.0 as isize - selection.head().0 as isize),
17568                            )
17569                        } else {
17570                            None
17571                        }
17572                    })
17573            });
17574
17575            cx.emit(EditorEvent::InputHandled {
17576                utf16_range_to_replace: range_to_replace,
17577                text: text.into(),
17578            });
17579
17580            if let Some(ranges) = ranges_to_replace {
17581                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17582            }
17583
17584            let marked_ranges = {
17585                let snapshot = this.buffer.read(cx).read(cx);
17586                this.selections
17587                    .disjoint_anchors()
17588                    .iter()
17589                    .map(|selection| {
17590                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17591                    })
17592                    .collect::<Vec<_>>()
17593            };
17594
17595            if text.is_empty() {
17596                this.unmark_text(window, cx);
17597            } else {
17598                this.highlight_text::<InputComposition>(
17599                    marked_ranges.clone(),
17600                    HighlightStyle {
17601                        underline: Some(UnderlineStyle {
17602                            thickness: px(1.),
17603                            color: None,
17604                            wavy: false,
17605                        }),
17606                        ..Default::default()
17607                    },
17608                    cx,
17609                );
17610            }
17611
17612            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17613            let use_autoclose = this.use_autoclose;
17614            let use_auto_surround = this.use_auto_surround;
17615            this.set_use_autoclose(false);
17616            this.set_use_auto_surround(false);
17617            this.handle_input(text, window, cx);
17618            this.set_use_autoclose(use_autoclose);
17619            this.set_use_auto_surround(use_auto_surround);
17620
17621            if let Some(new_selected_range) = new_selected_range_utf16 {
17622                let snapshot = this.buffer.read(cx).read(cx);
17623                let new_selected_ranges = marked_ranges
17624                    .into_iter()
17625                    .map(|marked_range| {
17626                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17627                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17628                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17629                        snapshot.clip_offset_utf16(new_start, Bias::Left)
17630                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17631                    })
17632                    .collect::<Vec<_>>();
17633
17634                drop(snapshot);
17635                this.change_selections(None, window, cx, |selections| {
17636                    selections.select_ranges(new_selected_ranges)
17637                });
17638            }
17639        });
17640
17641        self.ime_transaction = self.ime_transaction.or(transaction);
17642        if let Some(transaction) = self.ime_transaction {
17643            self.buffer.update(cx, |buffer, cx| {
17644                buffer.group_until_transaction(transaction, cx);
17645            });
17646        }
17647
17648        if self.text_highlights::<InputComposition>(cx).is_none() {
17649            self.ime_transaction.take();
17650        }
17651    }
17652
17653    fn bounds_for_range(
17654        &mut self,
17655        range_utf16: Range<usize>,
17656        element_bounds: gpui::Bounds<Pixels>,
17657        window: &mut Window,
17658        cx: &mut Context<Self>,
17659    ) -> Option<gpui::Bounds<Pixels>> {
17660        let text_layout_details = self.text_layout_details(window);
17661        let gpui::Size {
17662            width: em_width,
17663            height: line_height,
17664        } = self.character_size(window);
17665
17666        let snapshot = self.snapshot(window, cx);
17667        let scroll_position = snapshot.scroll_position();
17668        let scroll_left = scroll_position.x * em_width;
17669
17670        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17671        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17672            + self.gutter_dimensions.width
17673            + self.gutter_dimensions.margin;
17674        let y = line_height * (start.row().as_f32() - scroll_position.y);
17675
17676        Some(Bounds {
17677            origin: element_bounds.origin + point(x, y),
17678            size: size(em_width, line_height),
17679        })
17680    }
17681
17682    fn character_index_for_point(
17683        &mut self,
17684        point: gpui::Point<Pixels>,
17685        _window: &mut Window,
17686        _cx: &mut Context<Self>,
17687    ) -> Option<usize> {
17688        let position_map = self.last_position_map.as_ref()?;
17689        if !position_map.text_hitbox.contains(&point) {
17690            return None;
17691        }
17692        let display_point = position_map.point_for_position(point).previous_valid;
17693        let anchor = position_map
17694            .snapshot
17695            .display_point_to_anchor(display_point, Bias::Left);
17696        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17697        Some(utf16_offset.0)
17698    }
17699}
17700
17701trait SelectionExt {
17702    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17703    fn spanned_rows(
17704        &self,
17705        include_end_if_at_line_start: bool,
17706        map: &DisplaySnapshot,
17707    ) -> Range<MultiBufferRow>;
17708}
17709
17710impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17711    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17712        let start = self
17713            .start
17714            .to_point(&map.buffer_snapshot)
17715            .to_display_point(map);
17716        let end = self
17717            .end
17718            .to_point(&map.buffer_snapshot)
17719            .to_display_point(map);
17720        if self.reversed {
17721            end..start
17722        } else {
17723            start..end
17724        }
17725    }
17726
17727    fn spanned_rows(
17728        &self,
17729        include_end_if_at_line_start: bool,
17730        map: &DisplaySnapshot,
17731    ) -> Range<MultiBufferRow> {
17732        let start = self.start.to_point(&map.buffer_snapshot);
17733        let mut end = self.end.to_point(&map.buffer_snapshot);
17734        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17735            end.row -= 1;
17736        }
17737
17738        let buffer_start = map.prev_line_boundary(start).0;
17739        let buffer_end = map.next_line_boundary(end).0;
17740        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17741    }
17742}
17743
17744impl<T: InvalidationRegion> InvalidationStack<T> {
17745    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17746    where
17747        S: Clone + ToOffset,
17748    {
17749        while let Some(region) = self.last() {
17750            let all_selections_inside_invalidation_ranges =
17751                if selections.len() == region.ranges().len() {
17752                    selections
17753                        .iter()
17754                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17755                        .all(|(selection, invalidation_range)| {
17756                            let head = selection.head().to_offset(buffer);
17757                            invalidation_range.start <= head && invalidation_range.end >= head
17758                        })
17759                } else {
17760                    false
17761                };
17762
17763            if all_selections_inside_invalidation_ranges {
17764                break;
17765            } else {
17766                self.pop();
17767            }
17768        }
17769    }
17770}
17771
17772impl<T> Default for InvalidationStack<T> {
17773    fn default() -> Self {
17774        Self(Default::default())
17775    }
17776}
17777
17778impl<T> Deref for InvalidationStack<T> {
17779    type Target = Vec<T>;
17780
17781    fn deref(&self) -> &Self::Target {
17782        &self.0
17783    }
17784}
17785
17786impl<T> DerefMut for InvalidationStack<T> {
17787    fn deref_mut(&mut self) -> &mut Self::Target {
17788        &mut self.0
17789    }
17790}
17791
17792impl InvalidationRegion for SnippetState {
17793    fn ranges(&self) -> &[Range<Anchor>] {
17794        &self.ranges[self.active_index]
17795    }
17796}
17797
17798pub fn diagnostic_block_renderer(
17799    diagnostic: Diagnostic,
17800    max_message_rows: Option<u8>,
17801    allow_closing: bool,
17802) -> RenderBlock {
17803    let (text_without_backticks, code_ranges) =
17804        highlight_diagnostic_message(&diagnostic, max_message_rows);
17805
17806    Arc::new(move |cx: &mut BlockContext| {
17807        let group_id: SharedString = cx.block_id.to_string().into();
17808
17809        let mut text_style = cx.window.text_style().clone();
17810        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17811        let theme_settings = ThemeSettings::get_global(cx);
17812        text_style.font_family = theme_settings.buffer_font.family.clone();
17813        text_style.font_style = theme_settings.buffer_font.style;
17814        text_style.font_features = theme_settings.buffer_font.features.clone();
17815        text_style.font_weight = theme_settings.buffer_font.weight;
17816
17817        let multi_line_diagnostic = diagnostic.message.contains('\n');
17818
17819        let buttons = |diagnostic: &Diagnostic| {
17820            if multi_line_diagnostic {
17821                v_flex()
17822            } else {
17823                h_flex()
17824            }
17825            .when(allow_closing, |div| {
17826                div.children(diagnostic.is_primary.then(|| {
17827                    IconButton::new("close-block", IconName::XCircle)
17828                        .icon_color(Color::Muted)
17829                        .size(ButtonSize::Compact)
17830                        .style(ButtonStyle::Transparent)
17831                        .visible_on_hover(group_id.clone())
17832                        .on_click(move |_click, window, cx| {
17833                            window.dispatch_action(Box::new(Cancel), cx)
17834                        })
17835                        .tooltip(|window, cx| {
17836                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
17837                        })
17838                }))
17839            })
17840            .child(
17841                IconButton::new("copy-block", IconName::Copy)
17842                    .icon_color(Color::Muted)
17843                    .size(ButtonSize::Compact)
17844                    .style(ButtonStyle::Transparent)
17845                    .visible_on_hover(group_id.clone())
17846                    .on_click({
17847                        let message = diagnostic.message.clone();
17848                        move |_click, _, cx| {
17849                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
17850                        }
17851                    })
17852                    .tooltip(Tooltip::text("Copy diagnostic message")),
17853            )
17854        };
17855
17856        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
17857            AvailableSpace::min_size(),
17858            cx.window,
17859            cx.app,
17860        );
17861
17862        h_flex()
17863            .id(cx.block_id)
17864            .group(group_id.clone())
17865            .relative()
17866            .size_full()
17867            .block_mouse_down()
17868            .pl(cx.gutter_dimensions.width)
17869            .w(cx.max_width - cx.gutter_dimensions.full_width())
17870            .child(
17871                div()
17872                    .flex()
17873                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
17874                    .flex_shrink(),
17875            )
17876            .child(buttons(&diagnostic))
17877            .child(div().flex().flex_shrink_0().child(
17878                StyledText::new(text_without_backticks.clone()).with_highlights(
17879                    &text_style,
17880                    code_ranges.iter().map(|range| {
17881                        (
17882                            range.clone(),
17883                            HighlightStyle {
17884                                font_weight: Some(FontWeight::BOLD),
17885                                ..Default::default()
17886                            },
17887                        )
17888                    }),
17889                ),
17890            ))
17891            .into_any_element()
17892    })
17893}
17894
17895fn inline_completion_edit_text(
17896    current_snapshot: &BufferSnapshot,
17897    edits: &[(Range<Anchor>, String)],
17898    edit_preview: &EditPreview,
17899    include_deletions: bool,
17900    cx: &App,
17901) -> HighlightedText {
17902    let edits = edits
17903        .iter()
17904        .map(|(anchor, text)| {
17905            (
17906                anchor.start.text_anchor..anchor.end.text_anchor,
17907                text.clone(),
17908            )
17909        })
17910        .collect::<Vec<_>>();
17911
17912    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
17913}
17914
17915pub fn highlight_diagnostic_message(
17916    diagnostic: &Diagnostic,
17917    mut max_message_rows: Option<u8>,
17918) -> (SharedString, Vec<Range<usize>>) {
17919    let mut text_without_backticks = String::new();
17920    let mut code_ranges = Vec::new();
17921
17922    if let Some(source) = &diagnostic.source {
17923        text_without_backticks.push_str(source);
17924        code_ranges.push(0..source.len());
17925        text_without_backticks.push_str(": ");
17926    }
17927
17928    let mut prev_offset = 0;
17929    let mut in_code_block = false;
17930    let has_row_limit = max_message_rows.is_some();
17931    let mut newline_indices = diagnostic
17932        .message
17933        .match_indices('\n')
17934        .filter(|_| has_row_limit)
17935        .map(|(ix, _)| ix)
17936        .fuse()
17937        .peekable();
17938
17939    for (quote_ix, _) in diagnostic
17940        .message
17941        .match_indices('`')
17942        .chain([(diagnostic.message.len(), "")])
17943    {
17944        let mut first_newline_ix = None;
17945        let mut last_newline_ix = None;
17946        while let Some(newline_ix) = newline_indices.peek() {
17947            if *newline_ix < quote_ix {
17948                if first_newline_ix.is_none() {
17949                    first_newline_ix = Some(*newline_ix);
17950                }
17951                last_newline_ix = Some(*newline_ix);
17952
17953                if let Some(rows_left) = &mut max_message_rows {
17954                    if *rows_left == 0 {
17955                        break;
17956                    } else {
17957                        *rows_left -= 1;
17958                    }
17959                }
17960                let _ = newline_indices.next();
17961            } else {
17962                break;
17963            }
17964        }
17965        let prev_len = text_without_backticks.len();
17966        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
17967        text_without_backticks.push_str(new_text);
17968        if in_code_block {
17969            code_ranges.push(prev_len..text_without_backticks.len());
17970        }
17971        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
17972        in_code_block = !in_code_block;
17973        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
17974            text_without_backticks.push_str("...");
17975            break;
17976        }
17977    }
17978
17979    (text_without_backticks.into(), code_ranges)
17980}
17981
17982fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
17983    match severity {
17984        DiagnosticSeverity::ERROR => colors.error,
17985        DiagnosticSeverity::WARNING => colors.warning,
17986        DiagnosticSeverity::INFORMATION => colors.info,
17987        DiagnosticSeverity::HINT => colors.info,
17988        _ => colors.ignored,
17989    }
17990}
17991
17992pub fn styled_runs_for_code_label<'a>(
17993    label: &'a CodeLabel,
17994    syntax_theme: &'a theme::SyntaxTheme,
17995) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
17996    let fade_out = HighlightStyle {
17997        fade_out: Some(0.35),
17998        ..Default::default()
17999    };
18000
18001    let mut prev_end = label.filter_range.end;
18002    label
18003        .runs
18004        .iter()
18005        .enumerate()
18006        .flat_map(move |(ix, (range, highlight_id))| {
18007            let style = if let Some(style) = highlight_id.style(syntax_theme) {
18008                style
18009            } else {
18010                return Default::default();
18011            };
18012            let mut muted_style = style;
18013            muted_style.highlight(fade_out);
18014
18015            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18016            if range.start >= label.filter_range.end {
18017                if range.start > prev_end {
18018                    runs.push((prev_end..range.start, fade_out));
18019                }
18020                runs.push((range.clone(), muted_style));
18021            } else if range.end <= label.filter_range.end {
18022                runs.push((range.clone(), style));
18023            } else {
18024                runs.push((range.start..label.filter_range.end, style));
18025                runs.push((label.filter_range.end..range.end, muted_style));
18026            }
18027            prev_end = cmp::max(prev_end, range.end);
18028
18029            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18030                runs.push((prev_end..label.text.len(), fade_out));
18031            }
18032
18033            runs
18034        })
18035}
18036
18037pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18038    let mut prev_index = 0;
18039    let mut prev_codepoint: Option<char> = None;
18040    text.char_indices()
18041        .chain([(text.len(), '\0')])
18042        .filter_map(move |(index, codepoint)| {
18043            let prev_codepoint = prev_codepoint.replace(codepoint)?;
18044            let is_boundary = index == text.len()
18045                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18046                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18047            if is_boundary {
18048                let chunk = &text[prev_index..index];
18049                prev_index = index;
18050                Some(chunk)
18051            } else {
18052                None
18053            }
18054        })
18055}
18056
18057pub trait RangeToAnchorExt: Sized {
18058    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18059
18060    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18061        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18062        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18063    }
18064}
18065
18066impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18067    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18068        let start_offset = self.start.to_offset(snapshot);
18069        let end_offset = self.end.to_offset(snapshot);
18070        if start_offset == end_offset {
18071            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18072        } else {
18073            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18074        }
18075    }
18076}
18077
18078pub trait RowExt {
18079    fn as_f32(&self) -> f32;
18080
18081    fn next_row(&self) -> Self;
18082
18083    fn previous_row(&self) -> Self;
18084
18085    fn minus(&self, other: Self) -> u32;
18086}
18087
18088impl RowExt for DisplayRow {
18089    fn as_f32(&self) -> f32 {
18090        self.0 as f32
18091    }
18092
18093    fn next_row(&self) -> Self {
18094        Self(self.0 + 1)
18095    }
18096
18097    fn previous_row(&self) -> Self {
18098        Self(self.0.saturating_sub(1))
18099    }
18100
18101    fn minus(&self, other: Self) -> u32 {
18102        self.0 - other.0
18103    }
18104}
18105
18106impl RowExt for MultiBufferRow {
18107    fn as_f32(&self) -> f32 {
18108        self.0 as f32
18109    }
18110
18111    fn next_row(&self) -> Self {
18112        Self(self.0 + 1)
18113    }
18114
18115    fn previous_row(&self) -> Self {
18116        Self(self.0.saturating_sub(1))
18117    }
18118
18119    fn minus(&self, other: Self) -> u32 {
18120        self.0 - other.0
18121    }
18122}
18123
18124trait RowRangeExt {
18125    type Row;
18126
18127    fn len(&self) -> usize;
18128
18129    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18130}
18131
18132impl RowRangeExt for Range<MultiBufferRow> {
18133    type Row = MultiBufferRow;
18134
18135    fn len(&self) -> usize {
18136        (self.end.0 - self.start.0) as usize
18137    }
18138
18139    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18140        (self.start.0..self.end.0).map(MultiBufferRow)
18141    }
18142}
18143
18144impl RowRangeExt for Range<DisplayRow> {
18145    type Row = DisplayRow;
18146
18147    fn len(&self) -> usize {
18148        (self.end.0 - self.start.0) as usize
18149    }
18150
18151    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18152        (self.start.0..self.end.0).map(DisplayRow)
18153    }
18154}
18155
18156/// If select range has more than one line, we
18157/// just point the cursor to range.start.
18158fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18159    if range.start.row == range.end.row {
18160        range
18161    } else {
18162        range.start..range.start
18163    }
18164}
18165pub struct KillRing(ClipboardItem);
18166impl Global for KillRing {}
18167
18168const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18169
18170fn all_edits_insertions_or_deletions(
18171    edits: &Vec<(Range<Anchor>, String)>,
18172    snapshot: &MultiBufferSnapshot,
18173) -> bool {
18174    let mut all_insertions = true;
18175    let mut all_deletions = true;
18176
18177    for (range, new_text) in edits.iter() {
18178        let range_is_empty = range.to_offset(&snapshot).is_empty();
18179        let text_is_empty = new_text.is_empty();
18180
18181        if range_is_empty != text_is_empty {
18182            if range_is_empty {
18183                all_deletions = false;
18184            } else {
18185                all_insertions = false;
18186            }
18187        } else {
18188            return false;
18189        }
18190
18191        if !all_insertions && !all_deletions {
18192            return false;
18193        }
18194    }
18195    all_insertions || all_deletions
18196}