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)]
  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::Auto;
 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.revert(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                let mut new_styles = HashMap::default();
12543                for (block_id, diagnostic) in &active_diagnostics.blocks {
12544                    new_styles.insert(
12545                        *block_id,
12546                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
12547                    );
12548                }
12549                self.display_map.update(cx, |display_map, _cx| {
12550                    display_map.replace_blocks(new_styles)
12551                });
12552            }
12553        }
12554    }
12555
12556    fn activate_diagnostics(
12557        &mut self,
12558        buffer_id: BufferId,
12559        group_id: usize,
12560        window: &mut Window,
12561        cx: &mut Context<Self>,
12562    ) {
12563        self.dismiss_diagnostics(cx);
12564        let snapshot = self.snapshot(window, cx);
12565        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12566            let buffer = self.buffer.read(cx).snapshot(cx);
12567
12568            let mut primary_range = None;
12569            let mut primary_message = None;
12570            let diagnostic_group = buffer
12571                .diagnostic_group(buffer_id, group_id)
12572                .filter_map(|entry| {
12573                    let start = entry.range.start;
12574                    let end = entry.range.end;
12575                    if snapshot.is_line_folded(MultiBufferRow(start.row))
12576                        && (start.row == end.row
12577                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
12578                    {
12579                        return None;
12580                    }
12581                    if entry.diagnostic.is_primary {
12582                        primary_range = Some(entry.range.clone());
12583                        primary_message = Some(entry.diagnostic.message.clone());
12584                    }
12585                    Some(entry)
12586                })
12587                .collect::<Vec<_>>();
12588            let primary_range = primary_range?;
12589            let primary_message = primary_message?;
12590
12591            let blocks = display_map
12592                .insert_blocks(
12593                    diagnostic_group.iter().map(|entry| {
12594                        let diagnostic = entry.diagnostic.clone();
12595                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12596                        BlockProperties {
12597                            style: BlockStyle::Fixed,
12598                            placement: BlockPlacement::Below(
12599                                buffer.anchor_after(entry.range.start),
12600                            ),
12601                            height: message_height,
12602                            render: diagnostic_block_renderer(diagnostic, None, true, true),
12603                            priority: 0,
12604                        }
12605                    }),
12606                    cx,
12607                )
12608                .into_iter()
12609                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12610                .collect();
12611
12612            Some(ActiveDiagnosticGroup {
12613                primary_range: buffer.anchor_before(primary_range.start)
12614                    ..buffer.anchor_after(primary_range.end),
12615                primary_message,
12616                group_id,
12617                blocks,
12618                is_valid: true,
12619            })
12620        });
12621    }
12622
12623    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12624        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12625            self.display_map.update(cx, |display_map, cx| {
12626                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12627            });
12628            cx.notify();
12629        }
12630    }
12631
12632    /// Disable inline diagnostics rendering for this editor.
12633    pub fn disable_inline_diagnostics(&mut self) {
12634        self.inline_diagnostics_enabled = false;
12635        self.inline_diagnostics_update = Task::ready(());
12636        self.inline_diagnostics.clear();
12637    }
12638
12639    pub fn inline_diagnostics_enabled(&self) -> bool {
12640        self.inline_diagnostics_enabled
12641    }
12642
12643    pub fn show_inline_diagnostics(&self) -> bool {
12644        self.show_inline_diagnostics
12645    }
12646
12647    pub fn toggle_inline_diagnostics(
12648        &mut self,
12649        _: &ToggleInlineDiagnostics,
12650        window: &mut Window,
12651        cx: &mut Context<'_, Editor>,
12652    ) {
12653        self.show_inline_diagnostics = !self.show_inline_diagnostics;
12654        self.refresh_inline_diagnostics(false, window, cx);
12655    }
12656
12657    fn refresh_inline_diagnostics(
12658        &mut self,
12659        debounce: bool,
12660        window: &mut Window,
12661        cx: &mut Context<Self>,
12662    ) {
12663        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12664            self.inline_diagnostics_update = Task::ready(());
12665            self.inline_diagnostics.clear();
12666            return;
12667        }
12668
12669        let debounce_ms = ProjectSettings::get_global(cx)
12670            .diagnostics
12671            .inline
12672            .update_debounce_ms;
12673        let debounce = if debounce && debounce_ms > 0 {
12674            Some(Duration::from_millis(debounce_ms))
12675        } else {
12676            None
12677        };
12678        self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12679            if let Some(debounce) = debounce {
12680                cx.background_executor().timer(debounce).await;
12681            }
12682            let Some(snapshot) = editor
12683                .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12684                .ok()
12685            else {
12686                return;
12687            };
12688
12689            let new_inline_diagnostics = cx
12690                .background_spawn(async move {
12691                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12692                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12693                        let message = diagnostic_entry
12694                            .diagnostic
12695                            .message
12696                            .split_once('\n')
12697                            .map(|(line, _)| line)
12698                            .map(SharedString::new)
12699                            .unwrap_or_else(|| {
12700                                SharedString::from(diagnostic_entry.diagnostic.message)
12701                            });
12702                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12703                        let (Ok(i) | Err(i)) = inline_diagnostics
12704                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12705                        inline_diagnostics.insert(
12706                            i,
12707                            (
12708                                start_anchor,
12709                                InlineDiagnostic {
12710                                    message,
12711                                    group_id: diagnostic_entry.diagnostic.group_id,
12712                                    start: diagnostic_entry.range.start.to_point(&snapshot),
12713                                    is_primary: diagnostic_entry.diagnostic.is_primary,
12714                                    severity: diagnostic_entry.diagnostic.severity,
12715                                },
12716                            ),
12717                        );
12718                    }
12719                    inline_diagnostics
12720                })
12721                .await;
12722
12723            editor
12724                .update(&mut cx, |editor, cx| {
12725                    editor.inline_diagnostics = new_inline_diagnostics;
12726                    cx.notify();
12727                })
12728                .ok();
12729        });
12730    }
12731
12732    pub fn set_selections_from_remote(
12733        &mut self,
12734        selections: Vec<Selection<Anchor>>,
12735        pending_selection: Option<Selection<Anchor>>,
12736        window: &mut Window,
12737        cx: &mut Context<Self>,
12738    ) {
12739        let old_cursor_position = self.selections.newest_anchor().head();
12740        self.selections.change_with(cx, |s| {
12741            s.select_anchors(selections);
12742            if let Some(pending_selection) = pending_selection {
12743                s.set_pending(pending_selection, SelectMode::Character);
12744            } else {
12745                s.clear_pending();
12746            }
12747        });
12748        self.selections_did_change(false, &old_cursor_position, true, window, cx);
12749    }
12750
12751    fn push_to_selection_history(&mut self) {
12752        self.selection_history.push(SelectionHistoryEntry {
12753            selections: self.selections.disjoint_anchors(),
12754            select_next_state: self.select_next_state.clone(),
12755            select_prev_state: self.select_prev_state.clone(),
12756            add_selections_state: self.add_selections_state.clone(),
12757        });
12758    }
12759
12760    pub fn transact(
12761        &mut self,
12762        window: &mut Window,
12763        cx: &mut Context<Self>,
12764        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12765    ) -> Option<TransactionId> {
12766        self.start_transaction_at(Instant::now(), window, cx);
12767        update(self, window, cx);
12768        self.end_transaction_at(Instant::now(), cx)
12769    }
12770
12771    pub fn start_transaction_at(
12772        &mut self,
12773        now: Instant,
12774        window: &mut Window,
12775        cx: &mut Context<Self>,
12776    ) {
12777        self.end_selection(window, cx);
12778        if let Some(tx_id) = self
12779            .buffer
12780            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12781        {
12782            self.selection_history
12783                .insert_transaction(tx_id, self.selections.disjoint_anchors());
12784            cx.emit(EditorEvent::TransactionBegun {
12785                transaction_id: tx_id,
12786            })
12787        }
12788    }
12789
12790    pub fn end_transaction_at(
12791        &mut self,
12792        now: Instant,
12793        cx: &mut Context<Self>,
12794    ) -> Option<TransactionId> {
12795        if let Some(transaction_id) = self
12796            .buffer
12797            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12798        {
12799            if let Some((_, end_selections)) =
12800                self.selection_history.transaction_mut(transaction_id)
12801            {
12802                *end_selections = Some(self.selections.disjoint_anchors());
12803            } else {
12804                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12805            }
12806
12807            cx.emit(EditorEvent::Edited { transaction_id });
12808            Some(transaction_id)
12809        } else {
12810            None
12811        }
12812    }
12813
12814    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12815        if self.selection_mark_mode {
12816            self.change_selections(None, window, cx, |s| {
12817                s.move_with(|_, sel| {
12818                    sel.collapse_to(sel.head(), SelectionGoal::None);
12819                });
12820            })
12821        }
12822        self.selection_mark_mode = true;
12823        cx.notify();
12824    }
12825
12826    pub fn swap_selection_ends(
12827        &mut self,
12828        _: &actions::SwapSelectionEnds,
12829        window: &mut Window,
12830        cx: &mut Context<Self>,
12831    ) {
12832        self.change_selections(None, window, cx, |s| {
12833            s.move_with(|_, sel| {
12834                if sel.start != sel.end {
12835                    sel.reversed = !sel.reversed
12836                }
12837            });
12838        });
12839        self.request_autoscroll(Autoscroll::newest(), cx);
12840        cx.notify();
12841    }
12842
12843    pub fn toggle_fold(
12844        &mut self,
12845        _: &actions::ToggleFold,
12846        window: &mut Window,
12847        cx: &mut Context<Self>,
12848    ) {
12849        if self.is_singleton(cx) {
12850            let selection = self.selections.newest::<Point>(cx);
12851
12852            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12853            let range = if selection.is_empty() {
12854                let point = selection.head().to_display_point(&display_map);
12855                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12856                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12857                    .to_point(&display_map);
12858                start..end
12859            } else {
12860                selection.range()
12861            };
12862            if display_map.folds_in_range(range).next().is_some() {
12863                self.unfold_lines(&Default::default(), window, cx)
12864            } else {
12865                self.fold(&Default::default(), window, cx)
12866            }
12867        } else {
12868            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12869            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12870                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12871                .map(|(snapshot, _, _)| snapshot.remote_id())
12872                .collect();
12873
12874            for buffer_id in buffer_ids {
12875                if self.is_buffer_folded(buffer_id, cx) {
12876                    self.unfold_buffer(buffer_id, cx);
12877                } else {
12878                    self.fold_buffer(buffer_id, cx);
12879                }
12880            }
12881        }
12882    }
12883
12884    pub fn toggle_fold_recursive(
12885        &mut self,
12886        _: &actions::ToggleFoldRecursive,
12887        window: &mut Window,
12888        cx: &mut Context<Self>,
12889    ) {
12890        let selection = self.selections.newest::<Point>(cx);
12891
12892        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12893        let range = if selection.is_empty() {
12894            let point = selection.head().to_display_point(&display_map);
12895            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12896            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12897                .to_point(&display_map);
12898            start..end
12899        } else {
12900            selection.range()
12901        };
12902        if display_map.folds_in_range(range).next().is_some() {
12903            self.unfold_recursive(&Default::default(), window, cx)
12904        } else {
12905            self.fold_recursive(&Default::default(), window, cx)
12906        }
12907    }
12908
12909    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12910        if self.is_singleton(cx) {
12911            let mut to_fold = Vec::new();
12912            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12913            let selections = self.selections.all_adjusted(cx);
12914
12915            for selection in selections {
12916                let range = selection.range().sorted();
12917                let buffer_start_row = range.start.row;
12918
12919                if range.start.row != range.end.row {
12920                    let mut found = false;
12921                    let mut row = range.start.row;
12922                    while row <= range.end.row {
12923                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12924                        {
12925                            found = true;
12926                            row = crease.range().end.row + 1;
12927                            to_fold.push(crease);
12928                        } else {
12929                            row += 1
12930                        }
12931                    }
12932                    if found {
12933                        continue;
12934                    }
12935                }
12936
12937                for row in (0..=range.start.row).rev() {
12938                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12939                        if crease.range().end.row >= buffer_start_row {
12940                            to_fold.push(crease);
12941                            if row <= range.start.row {
12942                                break;
12943                            }
12944                        }
12945                    }
12946                }
12947            }
12948
12949            self.fold_creases(to_fold, true, window, cx);
12950        } else {
12951            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12952
12953            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12954                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12955                .map(|(snapshot, _, _)| snapshot.remote_id())
12956                .collect();
12957            for buffer_id in buffer_ids {
12958                self.fold_buffer(buffer_id, cx);
12959            }
12960        }
12961    }
12962
12963    fn fold_at_level(
12964        &mut self,
12965        fold_at: &FoldAtLevel,
12966        window: &mut Window,
12967        cx: &mut Context<Self>,
12968    ) {
12969        if !self.buffer.read(cx).is_singleton() {
12970            return;
12971        }
12972
12973        let fold_at_level = fold_at.0;
12974        let snapshot = self.buffer.read(cx).snapshot(cx);
12975        let mut to_fold = Vec::new();
12976        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12977
12978        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12979            while start_row < end_row {
12980                match self
12981                    .snapshot(window, cx)
12982                    .crease_for_buffer_row(MultiBufferRow(start_row))
12983                {
12984                    Some(crease) => {
12985                        let nested_start_row = crease.range().start.row + 1;
12986                        let nested_end_row = crease.range().end.row;
12987
12988                        if current_level < fold_at_level {
12989                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12990                        } else if current_level == fold_at_level {
12991                            to_fold.push(crease);
12992                        }
12993
12994                        start_row = nested_end_row + 1;
12995                    }
12996                    None => start_row += 1,
12997                }
12998            }
12999        }
13000
13001        self.fold_creases(to_fold, true, window, cx);
13002    }
13003
13004    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13005        if self.buffer.read(cx).is_singleton() {
13006            let mut fold_ranges = Vec::new();
13007            let snapshot = self.buffer.read(cx).snapshot(cx);
13008
13009            for row in 0..snapshot.max_row().0 {
13010                if let Some(foldable_range) = self
13011                    .snapshot(window, cx)
13012                    .crease_for_buffer_row(MultiBufferRow(row))
13013                {
13014                    fold_ranges.push(foldable_range);
13015                }
13016            }
13017
13018            self.fold_creases(fold_ranges, true, window, cx);
13019        } else {
13020            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13021                editor
13022                    .update_in(&mut cx, |editor, _, cx| {
13023                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13024                            editor.fold_buffer(buffer_id, cx);
13025                        }
13026                    })
13027                    .ok();
13028            });
13029        }
13030    }
13031
13032    pub fn fold_function_bodies(
13033        &mut self,
13034        _: &actions::FoldFunctionBodies,
13035        window: &mut Window,
13036        cx: &mut Context<Self>,
13037    ) {
13038        let snapshot = self.buffer.read(cx).snapshot(cx);
13039
13040        let ranges = snapshot
13041            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13042            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13043            .collect::<Vec<_>>();
13044
13045        let creases = ranges
13046            .into_iter()
13047            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13048            .collect();
13049
13050        self.fold_creases(creases, true, window, cx);
13051    }
13052
13053    pub fn fold_recursive(
13054        &mut self,
13055        _: &actions::FoldRecursive,
13056        window: &mut Window,
13057        cx: &mut Context<Self>,
13058    ) {
13059        let mut to_fold = Vec::new();
13060        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13061        let selections = self.selections.all_adjusted(cx);
13062
13063        for selection in selections {
13064            let range = selection.range().sorted();
13065            let buffer_start_row = range.start.row;
13066
13067            if range.start.row != range.end.row {
13068                let mut found = false;
13069                for row in range.start.row..=range.end.row {
13070                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13071                        found = true;
13072                        to_fold.push(crease);
13073                    }
13074                }
13075                if found {
13076                    continue;
13077                }
13078            }
13079
13080            for row in (0..=range.start.row).rev() {
13081                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13082                    if crease.range().end.row >= buffer_start_row {
13083                        to_fold.push(crease);
13084                    } else {
13085                        break;
13086                    }
13087                }
13088            }
13089        }
13090
13091        self.fold_creases(to_fold, true, window, cx);
13092    }
13093
13094    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13095        let buffer_row = fold_at.buffer_row;
13096        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13097
13098        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13099            let autoscroll = self
13100                .selections
13101                .all::<Point>(cx)
13102                .iter()
13103                .any(|selection| crease.range().overlaps(&selection.range()));
13104
13105            self.fold_creases(vec![crease], autoscroll, window, cx);
13106        }
13107    }
13108
13109    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13110        if self.is_singleton(cx) {
13111            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13112            let buffer = &display_map.buffer_snapshot;
13113            let selections = self.selections.all::<Point>(cx);
13114            let ranges = selections
13115                .iter()
13116                .map(|s| {
13117                    let range = s.display_range(&display_map).sorted();
13118                    let mut start = range.start.to_point(&display_map);
13119                    let mut end = range.end.to_point(&display_map);
13120                    start.column = 0;
13121                    end.column = buffer.line_len(MultiBufferRow(end.row));
13122                    start..end
13123                })
13124                .collect::<Vec<_>>();
13125
13126            self.unfold_ranges(&ranges, true, true, cx);
13127        } else {
13128            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13129            let buffer_ids: HashSet<_> = multi_buffer_snapshot
13130                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
13131                .map(|(snapshot, _, _)| snapshot.remote_id())
13132                .collect();
13133            for buffer_id in buffer_ids {
13134                self.unfold_buffer(buffer_id, cx);
13135            }
13136        }
13137    }
13138
13139    pub fn unfold_recursive(
13140        &mut self,
13141        _: &UnfoldRecursive,
13142        _window: &mut Window,
13143        cx: &mut Context<Self>,
13144    ) {
13145        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13146        let selections = self.selections.all::<Point>(cx);
13147        let ranges = selections
13148            .iter()
13149            .map(|s| {
13150                let mut range = s.display_range(&display_map).sorted();
13151                *range.start.column_mut() = 0;
13152                *range.end.column_mut() = display_map.line_len(range.end.row());
13153                let start = range.start.to_point(&display_map);
13154                let end = range.end.to_point(&display_map);
13155                start..end
13156            })
13157            .collect::<Vec<_>>();
13158
13159        self.unfold_ranges(&ranges, true, true, cx);
13160    }
13161
13162    pub fn unfold_at(
13163        &mut self,
13164        unfold_at: &UnfoldAt,
13165        _window: &mut Window,
13166        cx: &mut Context<Self>,
13167    ) {
13168        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13169
13170        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13171            ..Point::new(
13172                unfold_at.buffer_row.0,
13173                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13174            );
13175
13176        let autoscroll = self
13177            .selections
13178            .all::<Point>(cx)
13179            .iter()
13180            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13181
13182        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13183    }
13184
13185    pub fn unfold_all(
13186        &mut self,
13187        _: &actions::UnfoldAll,
13188        _window: &mut Window,
13189        cx: &mut Context<Self>,
13190    ) {
13191        if self.buffer.read(cx).is_singleton() {
13192            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13193            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13194        } else {
13195            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13196                editor
13197                    .update(&mut cx, |editor, cx| {
13198                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13199                            editor.unfold_buffer(buffer_id, cx);
13200                        }
13201                    })
13202                    .ok();
13203            });
13204        }
13205    }
13206
13207    pub fn fold_selected_ranges(
13208        &mut self,
13209        _: &FoldSelectedRanges,
13210        window: &mut Window,
13211        cx: &mut Context<Self>,
13212    ) {
13213        let selections = self.selections.all::<Point>(cx);
13214        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13215        let line_mode = self.selections.line_mode;
13216        let ranges = selections
13217            .into_iter()
13218            .map(|s| {
13219                if line_mode {
13220                    let start = Point::new(s.start.row, 0);
13221                    let end = Point::new(
13222                        s.end.row,
13223                        display_map
13224                            .buffer_snapshot
13225                            .line_len(MultiBufferRow(s.end.row)),
13226                    );
13227                    Crease::simple(start..end, display_map.fold_placeholder.clone())
13228                } else {
13229                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13230                }
13231            })
13232            .collect::<Vec<_>>();
13233        self.fold_creases(ranges, true, window, cx);
13234    }
13235
13236    pub fn fold_ranges<T: ToOffset + Clone>(
13237        &mut self,
13238        ranges: Vec<Range<T>>,
13239        auto_scroll: bool,
13240        window: &mut Window,
13241        cx: &mut Context<Self>,
13242    ) {
13243        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13244        let ranges = ranges
13245            .into_iter()
13246            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13247            .collect::<Vec<_>>();
13248        self.fold_creases(ranges, auto_scroll, window, cx);
13249    }
13250
13251    pub fn fold_creases<T: ToOffset + Clone>(
13252        &mut self,
13253        creases: Vec<Crease<T>>,
13254        auto_scroll: bool,
13255        window: &mut Window,
13256        cx: &mut Context<Self>,
13257    ) {
13258        if creases.is_empty() {
13259            return;
13260        }
13261
13262        let mut buffers_affected = HashSet::default();
13263        let multi_buffer = self.buffer().read(cx);
13264        for crease in &creases {
13265            if let Some((_, buffer, _)) =
13266                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13267            {
13268                buffers_affected.insert(buffer.read(cx).remote_id());
13269            };
13270        }
13271
13272        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13273
13274        if auto_scroll {
13275            self.request_autoscroll(Autoscroll::fit(), cx);
13276        }
13277
13278        cx.notify();
13279
13280        if let Some(active_diagnostics) = self.active_diagnostics.take() {
13281            // Clear diagnostics block when folding a range that contains it.
13282            let snapshot = self.snapshot(window, cx);
13283            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13284                drop(snapshot);
13285                self.active_diagnostics = Some(active_diagnostics);
13286                self.dismiss_diagnostics(cx);
13287            } else {
13288                self.active_diagnostics = Some(active_diagnostics);
13289            }
13290        }
13291
13292        self.scrollbar_marker_state.dirty = true;
13293    }
13294
13295    /// Removes any folds whose ranges intersect any of the given ranges.
13296    pub fn unfold_ranges<T: ToOffset + Clone>(
13297        &mut self,
13298        ranges: &[Range<T>],
13299        inclusive: bool,
13300        auto_scroll: bool,
13301        cx: &mut Context<Self>,
13302    ) {
13303        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13304            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13305        });
13306    }
13307
13308    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13309        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13310            return;
13311        }
13312        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13313        self.display_map
13314            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
13315        cx.emit(EditorEvent::BufferFoldToggled {
13316            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13317            folded: true,
13318        });
13319        cx.notify();
13320    }
13321
13322    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13323        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13324            return;
13325        }
13326        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13327        self.display_map.update(cx, |display_map, cx| {
13328            display_map.unfold_buffer(buffer_id, cx);
13329        });
13330        cx.emit(EditorEvent::BufferFoldToggled {
13331            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13332            folded: false,
13333        });
13334        cx.notify();
13335    }
13336
13337    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13338        self.display_map.read(cx).is_buffer_folded(buffer)
13339    }
13340
13341    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13342        self.display_map.read(cx).folded_buffers()
13343    }
13344
13345    /// Removes any folds with the given ranges.
13346    pub fn remove_folds_with_type<T: ToOffset + Clone>(
13347        &mut self,
13348        ranges: &[Range<T>],
13349        type_id: TypeId,
13350        auto_scroll: bool,
13351        cx: &mut Context<Self>,
13352    ) {
13353        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13354            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13355        });
13356    }
13357
13358    fn remove_folds_with<T: ToOffset + Clone>(
13359        &mut self,
13360        ranges: &[Range<T>],
13361        auto_scroll: bool,
13362        cx: &mut Context<Self>,
13363        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13364    ) {
13365        if ranges.is_empty() {
13366            return;
13367        }
13368
13369        let mut buffers_affected = HashSet::default();
13370        let multi_buffer = self.buffer().read(cx);
13371        for range in ranges {
13372            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13373                buffers_affected.insert(buffer.read(cx).remote_id());
13374            };
13375        }
13376
13377        self.display_map.update(cx, update);
13378
13379        if auto_scroll {
13380            self.request_autoscroll(Autoscroll::fit(), cx);
13381        }
13382
13383        cx.notify();
13384        self.scrollbar_marker_state.dirty = true;
13385        self.active_indent_guides_state.dirty = true;
13386    }
13387
13388    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13389        self.display_map.read(cx).fold_placeholder.clone()
13390    }
13391
13392    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13393        self.buffer.update(cx, |buffer, cx| {
13394            buffer.set_all_diff_hunks_expanded(cx);
13395        });
13396    }
13397
13398    pub fn expand_all_diff_hunks(
13399        &mut self,
13400        _: &ExpandAllDiffHunks,
13401        _window: &mut Window,
13402        cx: &mut Context<Self>,
13403    ) {
13404        self.buffer.update(cx, |buffer, cx| {
13405            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13406        });
13407    }
13408
13409    pub fn toggle_selected_diff_hunks(
13410        &mut self,
13411        _: &ToggleSelectedDiffHunks,
13412        _window: &mut Window,
13413        cx: &mut Context<Self>,
13414    ) {
13415        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13416        self.toggle_diff_hunks_in_ranges(ranges, cx);
13417    }
13418
13419    pub fn diff_hunks_in_ranges<'a>(
13420        &'a self,
13421        ranges: &'a [Range<Anchor>],
13422        buffer: &'a MultiBufferSnapshot,
13423    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13424        ranges.iter().flat_map(move |range| {
13425            let end_excerpt_id = range.end.excerpt_id;
13426            let range = range.to_point(buffer);
13427            let mut peek_end = range.end;
13428            if range.end.row < buffer.max_row().0 {
13429                peek_end = Point::new(range.end.row + 1, 0);
13430            }
13431            buffer
13432                .diff_hunks_in_range(range.start..peek_end)
13433                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13434        })
13435    }
13436
13437    pub fn has_stageable_diff_hunks_in_ranges(
13438        &self,
13439        ranges: &[Range<Anchor>],
13440        snapshot: &MultiBufferSnapshot,
13441    ) -> bool {
13442        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13443        hunks.any(|hunk| hunk.secondary_status != DiffHunkSecondaryStatus::None)
13444    }
13445
13446    pub fn toggle_staged_selected_diff_hunks(
13447        &mut self,
13448        _: &::git::ToggleStaged,
13449        window: &mut Window,
13450        cx: &mut Context<Self>,
13451    ) {
13452        let snapshot = self.buffer.read(cx).snapshot(cx);
13453        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13454        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13455        self.stage_or_unstage_diff_hunks(stage, &ranges, window, cx);
13456    }
13457
13458    pub fn stage_and_next(
13459        &mut self,
13460        _: &::git::StageAndNext,
13461        window: &mut Window,
13462        cx: &mut Context<Self>,
13463    ) {
13464        self.do_stage_or_unstage_and_next(true, window, cx);
13465    }
13466
13467    pub fn unstage_and_next(
13468        &mut self,
13469        _: &::git::UnstageAndNext,
13470        window: &mut Window,
13471        cx: &mut Context<Self>,
13472    ) {
13473        self.do_stage_or_unstage_and_next(false, window, cx);
13474    }
13475
13476    pub fn stage_or_unstage_diff_hunks(
13477        &mut self,
13478        stage: bool,
13479        ranges: &[Range<Anchor>],
13480        window: &mut Window,
13481        cx: &mut Context<Self>,
13482    ) {
13483        let snapshot = self.buffer.read(cx).snapshot(cx);
13484        let Some(project) = &self.project else {
13485            return;
13486        };
13487
13488        let chunk_by = self
13489            .diff_hunks_in_ranges(&ranges, &snapshot)
13490            .chunk_by(|hunk| hunk.buffer_id);
13491        for (buffer_id, hunks) in &chunk_by {
13492            Self::do_stage_or_unstage(project, stage, buffer_id, hunks, &snapshot, window, cx);
13493        }
13494    }
13495
13496    fn do_stage_or_unstage_and_next(
13497        &mut self,
13498        stage: bool,
13499        window: &mut Window,
13500        cx: &mut Context<Self>,
13501    ) {
13502        let mut ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13503        if ranges.iter().any(|range| range.start != range.end) {
13504            self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13505            return;
13506        }
13507
13508        if !self.buffer().read(cx).is_singleton() {
13509            if let Some((excerpt_id, buffer, range)) = self.active_excerpt(cx) {
13510                if buffer.read(cx).is_empty() {
13511                    let buffer = buffer.read(cx);
13512                    let Some(file) = buffer.file() else {
13513                        return;
13514                    };
13515                    let project_path = project::ProjectPath {
13516                        worktree_id: file.worktree_id(cx),
13517                        path: file.path().clone(),
13518                    };
13519                    let Some(project) = self.project.as_ref() else {
13520                        return;
13521                    };
13522                    let project = project.read(cx);
13523
13524                    let Some(repo) = project.git_store().read(cx).active_repository() else {
13525                        return;
13526                    };
13527
13528                    repo.update(cx, |repo, cx| {
13529                        let Some(repo_path) = repo.project_path_to_repo_path(&project_path) else {
13530                            return;
13531                        };
13532                        let Some(status) = repo.repository_entry.status_for_path(&repo_path) else {
13533                            return;
13534                        };
13535                        if stage && status.status == FileStatus::Untracked {
13536                            repo.stage_entries(vec![repo_path], cx)
13537                                .detach_and_log_err(cx);
13538                            return;
13539                        }
13540                    })
13541                }
13542                ranges = vec![multi_buffer::Anchor::range_in_buffer(
13543                    excerpt_id,
13544                    buffer.read(cx).remote_id(),
13545                    range,
13546                )];
13547                self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13548                let snapshot = self.buffer().read(cx).snapshot(cx);
13549                let mut point = ranges.last().unwrap().end.to_point(&snapshot);
13550                if point.row < snapshot.max_row().0 {
13551                    point.row += 1;
13552                    point.column = 0;
13553                    point = snapshot.clip_point(point, Bias::Right);
13554                    self.change_selections(Some(Autoscroll::top_relative(6)), window, cx, |s| {
13555                        s.select_ranges([point..point]);
13556                    })
13557                }
13558                return;
13559            }
13560        }
13561        self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13562        self.go_to_next_hunk(&Default::default(), window, cx);
13563    }
13564
13565    fn do_stage_or_unstage(
13566        project: &Entity<Project>,
13567        stage: bool,
13568        buffer_id: BufferId,
13569        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13570        snapshot: &MultiBufferSnapshot,
13571        window: &mut Window,
13572        cx: &mut App,
13573    ) {
13574        let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
13575            log::debug!("no buffer for id");
13576            return;
13577        };
13578        let buffer_snapshot = buffer.read(cx).snapshot();
13579        let file_exists = buffer_snapshot
13580            .file()
13581            .is_some_and(|file| file.disk_state().exists());
13582        let Some((repo, path)) = project
13583            .read(cx)
13584            .repository_and_path_for_buffer_id(buffer_id, cx)
13585        else {
13586            log::debug!("no git repo for buffer id");
13587            return;
13588        };
13589        let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
13590            log::debug!("no diff for buffer id");
13591            return;
13592        };
13593
13594        let new_index_text = if !stage && diff.is_single_insertion || stage && !file_exists {
13595            log::debug!("removing from index");
13596            None
13597        } else {
13598            diff.new_secondary_text_for_stage_or_unstage(
13599                stage,
13600                hunks.filter_map(|hunk| {
13601                    if stage && hunk.secondary_status == DiffHunkSecondaryStatus::None {
13602                        return None;
13603                    } else if !stage
13604                        && hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
13605                    {
13606                        return None;
13607                    }
13608                    Some((hunk.buffer_range.clone(), hunk.diff_base_byte_range.clone()))
13609                }),
13610                &buffer_snapshot,
13611                cx,
13612            )
13613        };
13614        if file_exists {
13615            let buffer_store = project.read(cx).buffer_store().clone();
13616            buffer_store
13617                .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
13618                .detach_and_log_err(cx);
13619        }
13620        let recv = repo
13621            .read(cx)
13622            .set_index_text(&path, new_index_text.map(|rope| rope.to_string()));
13623
13624        cx.background_spawn(async move { recv.await? })
13625            .detach_and_notify_err(window, cx);
13626    }
13627
13628    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13629        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13630        self.buffer
13631            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13632    }
13633
13634    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13635        self.buffer.update(cx, |buffer, cx| {
13636            let ranges = vec![Anchor::min()..Anchor::max()];
13637            if !buffer.all_diff_hunks_expanded()
13638                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13639            {
13640                buffer.collapse_diff_hunks(ranges, cx);
13641                true
13642            } else {
13643                false
13644            }
13645        })
13646    }
13647
13648    fn toggle_diff_hunks_in_ranges(
13649        &mut self,
13650        ranges: Vec<Range<Anchor>>,
13651        cx: &mut Context<'_, Editor>,
13652    ) {
13653        self.buffer.update(cx, |buffer, cx| {
13654            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13655            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13656        })
13657    }
13658
13659    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13660        self.buffer.update(cx, |buffer, cx| {
13661            let snapshot = buffer.snapshot(cx);
13662            let excerpt_id = range.end.excerpt_id;
13663            let point_range = range.to_point(&snapshot);
13664            let expand = !buffer.single_hunk_is_expanded(range, cx);
13665            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13666        })
13667    }
13668
13669    pub(crate) fn apply_all_diff_hunks(
13670        &mut self,
13671        _: &ApplyAllDiffHunks,
13672        window: &mut Window,
13673        cx: &mut Context<Self>,
13674    ) {
13675        let buffers = self.buffer.read(cx).all_buffers();
13676        for branch_buffer in buffers {
13677            branch_buffer.update(cx, |branch_buffer, cx| {
13678                branch_buffer.merge_into_base(Vec::new(), cx);
13679            });
13680        }
13681
13682        if let Some(project) = self.project.clone() {
13683            self.save(true, project, window, cx).detach_and_log_err(cx);
13684        }
13685    }
13686
13687    pub(crate) fn apply_selected_diff_hunks(
13688        &mut self,
13689        _: &ApplyDiffHunk,
13690        window: &mut Window,
13691        cx: &mut Context<Self>,
13692    ) {
13693        let snapshot = self.snapshot(window, cx);
13694        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
13695        let mut ranges_by_buffer = HashMap::default();
13696        self.transact(window, cx, |editor, _window, cx| {
13697            for hunk in hunks {
13698                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13699                    ranges_by_buffer
13700                        .entry(buffer.clone())
13701                        .or_insert_with(Vec::new)
13702                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13703                }
13704            }
13705
13706            for (buffer, ranges) in ranges_by_buffer {
13707                buffer.update(cx, |buffer, cx| {
13708                    buffer.merge_into_base(ranges, cx);
13709                });
13710            }
13711        });
13712
13713        if let Some(project) = self.project.clone() {
13714            self.save(true, project, window, cx).detach_and_log_err(cx);
13715        }
13716    }
13717
13718    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13719        if hovered != self.gutter_hovered {
13720            self.gutter_hovered = hovered;
13721            cx.notify();
13722        }
13723    }
13724
13725    pub fn insert_blocks(
13726        &mut self,
13727        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13728        autoscroll: Option<Autoscroll>,
13729        cx: &mut Context<Self>,
13730    ) -> Vec<CustomBlockId> {
13731        let blocks = self
13732            .display_map
13733            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13734        if let Some(autoscroll) = autoscroll {
13735            self.request_autoscroll(autoscroll, cx);
13736        }
13737        cx.notify();
13738        blocks
13739    }
13740
13741    pub fn resize_blocks(
13742        &mut self,
13743        heights: HashMap<CustomBlockId, u32>,
13744        autoscroll: Option<Autoscroll>,
13745        cx: &mut Context<Self>,
13746    ) {
13747        self.display_map
13748            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13749        if let Some(autoscroll) = autoscroll {
13750            self.request_autoscroll(autoscroll, cx);
13751        }
13752        cx.notify();
13753    }
13754
13755    pub fn replace_blocks(
13756        &mut self,
13757        renderers: HashMap<CustomBlockId, RenderBlock>,
13758        autoscroll: Option<Autoscroll>,
13759        cx: &mut Context<Self>,
13760    ) {
13761        self.display_map
13762            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13763        if let Some(autoscroll) = autoscroll {
13764            self.request_autoscroll(autoscroll, cx);
13765        }
13766        cx.notify();
13767    }
13768
13769    pub fn remove_blocks(
13770        &mut self,
13771        block_ids: HashSet<CustomBlockId>,
13772        autoscroll: Option<Autoscroll>,
13773        cx: &mut Context<Self>,
13774    ) {
13775        self.display_map.update(cx, |display_map, cx| {
13776            display_map.remove_blocks(block_ids, cx)
13777        });
13778        if let Some(autoscroll) = autoscroll {
13779            self.request_autoscroll(autoscroll, cx);
13780        }
13781        cx.notify();
13782    }
13783
13784    pub fn row_for_block(
13785        &self,
13786        block_id: CustomBlockId,
13787        cx: &mut Context<Self>,
13788    ) -> Option<DisplayRow> {
13789        self.display_map
13790            .update(cx, |map, cx| map.row_for_block(block_id, cx))
13791    }
13792
13793    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13794        self.focused_block = Some(focused_block);
13795    }
13796
13797    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13798        self.focused_block.take()
13799    }
13800
13801    pub fn insert_creases(
13802        &mut self,
13803        creases: impl IntoIterator<Item = Crease<Anchor>>,
13804        cx: &mut Context<Self>,
13805    ) -> Vec<CreaseId> {
13806        self.display_map
13807            .update(cx, |map, cx| map.insert_creases(creases, cx))
13808    }
13809
13810    pub fn remove_creases(
13811        &mut self,
13812        ids: impl IntoIterator<Item = CreaseId>,
13813        cx: &mut Context<Self>,
13814    ) {
13815        self.display_map
13816            .update(cx, |map, cx| map.remove_creases(ids, cx));
13817    }
13818
13819    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13820        self.display_map
13821            .update(cx, |map, cx| map.snapshot(cx))
13822            .longest_row()
13823    }
13824
13825    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13826        self.display_map
13827            .update(cx, |map, cx| map.snapshot(cx))
13828            .max_point()
13829    }
13830
13831    pub fn text(&self, cx: &App) -> String {
13832        self.buffer.read(cx).read(cx).text()
13833    }
13834
13835    pub fn is_empty(&self, cx: &App) -> bool {
13836        self.buffer.read(cx).read(cx).is_empty()
13837    }
13838
13839    pub fn text_option(&self, cx: &App) -> Option<String> {
13840        let text = self.text(cx);
13841        let text = text.trim();
13842
13843        if text.is_empty() {
13844            return None;
13845        }
13846
13847        Some(text.to_string())
13848    }
13849
13850    pub fn set_text(
13851        &mut self,
13852        text: impl Into<Arc<str>>,
13853        window: &mut Window,
13854        cx: &mut Context<Self>,
13855    ) {
13856        self.transact(window, cx, |this, _, cx| {
13857            this.buffer
13858                .read(cx)
13859                .as_singleton()
13860                .expect("you can only call set_text on editors for singleton buffers")
13861                .update(cx, |buffer, cx| buffer.set_text(text, cx));
13862        });
13863    }
13864
13865    pub fn display_text(&self, cx: &mut App) -> String {
13866        self.display_map
13867            .update(cx, |map, cx| map.snapshot(cx))
13868            .text()
13869    }
13870
13871    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
13872        let mut wrap_guides = smallvec::smallvec![];
13873
13874        if self.show_wrap_guides == Some(false) {
13875            return wrap_guides;
13876        }
13877
13878        let settings = self.buffer.read(cx).settings_at(0, cx);
13879        if settings.show_wrap_guides {
13880            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
13881                wrap_guides.push((soft_wrap as usize, true));
13882            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
13883                wrap_guides.push((soft_wrap as usize, true));
13884            }
13885            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
13886        }
13887
13888        wrap_guides
13889    }
13890
13891    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
13892        let settings = self.buffer.read(cx).settings_at(0, cx);
13893        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
13894        match mode {
13895            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
13896                SoftWrap::None
13897            }
13898            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13899            language_settings::SoftWrap::PreferredLineLength => {
13900                SoftWrap::Column(settings.preferred_line_length)
13901            }
13902            language_settings::SoftWrap::Bounded => {
13903                SoftWrap::Bounded(settings.preferred_line_length)
13904            }
13905        }
13906    }
13907
13908    pub fn set_soft_wrap_mode(
13909        &mut self,
13910        mode: language_settings::SoftWrap,
13911
13912        cx: &mut Context<Self>,
13913    ) {
13914        self.soft_wrap_mode_override = Some(mode);
13915        cx.notify();
13916    }
13917
13918    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13919        self.text_style_refinement = Some(style);
13920    }
13921
13922    /// called by the Element so we know what style we were most recently rendered with.
13923    pub(crate) fn set_style(
13924        &mut self,
13925        style: EditorStyle,
13926        window: &mut Window,
13927        cx: &mut Context<Self>,
13928    ) {
13929        let rem_size = window.rem_size();
13930        self.display_map.update(cx, |map, cx| {
13931            map.set_font(
13932                style.text.font(),
13933                style.text.font_size.to_pixels(rem_size),
13934                cx,
13935            )
13936        });
13937        self.style = Some(style);
13938    }
13939
13940    pub fn style(&self) -> Option<&EditorStyle> {
13941        self.style.as_ref()
13942    }
13943
13944    // Called by the element. This method is not designed to be called outside of the editor
13945    // element's layout code because it does not notify when rewrapping is computed synchronously.
13946    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13947        self.display_map
13948            .update(cx, |map, cx| map.set_wrap_width(width, cx))
13949    }
13950
13951    pub fn set_soft_wrap(&mut self) {
13952        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13953    }
13954
13955    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13956        if self.soft_wrap_mode_override.is_some() {
13957            self.soft_wrap_mode_override.take();
13958        } else {
13959            let soft_wrap = match self.soft_wrap_mode(cx) {
13960                SoftWrap::GitDiff => return,
13961                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13962                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13963                    language_settings::SoftWrap::None
13964                }
13965            };
13966            self.soft_wrap_mode_override = Some(soft_wrap);
13967        }
13968        cx.notify();
13969    }
13970
13971    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13972        let Some(workspace) = self.workspace() else {
13973            return;
13974        };
13975        let fs = workspace.read(cx).app_state().fs.clone();
13976        let current_show = TabBarSettings::get_global(cx).show;
13977        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13978            setting.show = Some(!current_show);
13979        });
13980    }
13981
13982    pub fn toggle_indent_guides(
13983        &mut self,
13984        _: &ToggleIndentGuides,
13985        _: &mut Window,
13986        cx: &mut Context<Self>,
13987    ) {
13988        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13989            self.buffer
13990                .read(cx)
13991                .settings_at(0, cx)
13992                .indent_guides
13993                .enabled
13994        });
13995        self.show_indent_guides = Some(!currently_enabled);
13996        cx.notify();
13997    }
13998
13999    fn should_show_indent_guides(&self) -> Option<bool> {
14000        self.show_indent_guides
14001    }
14002
14003    pub fn toggle_line_numbers(
14004        &mut self,
14005        _: &ToggleLineNumbers,
14006        _: &mut Window,
14007        cx: &mut Context<Self>,
14008    ) {
14009        let mut editor_settings = EditorSettings::get_global(cx).clone();
14010        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14011        EditorSettings::override_global(editor_settings, cx);
14012    }
14013
14014    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14015        self.use_relative_line_numbers
14016            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14017    }
14018
14019    pub fn toggle_relative_line_numbers(
14020        &mut self,
14021        _: &ToggleRelativeLineNumbers,
14022        _: &mut Window,
14023        cx: &mut Context<Self>,
14024    ) {
14025        let is_relative = self.should_use_relative_line_numbers(cx);
14026        self.set_relative_line_number(Some(!is_relative), cx)
14027    }
14028
14029    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14030        self.use_relative_line_numbers = is_relative;
14031        cx.notify();
14032    }
14033
14034    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14035        self.show_gutter = show_gutter;
14036        cx.notify();
14037    }
14038
14039    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14040        self.show_scrollbars = show_scrollbars;
14041        cx.notify();
14042    }
14043
14044    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14045        self.show_line_numbers = Some(show_line_numbers);
14046        cx.notify();
14047    }
14048
14049    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14050        self.show_git_diff_gutter = Some(show_git_diff_gutter);
14051        cx.notify();
14052    }
14053
14054    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14055        self.show_code_actions = Some(show_code_actions);
14056        cx.notify();
14057    }
14058
14059    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14060        self.show_runnables = Some(show_runnables);
14061        cx.notify();
14062    }
14063
14064    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14065        if self.display_map.read(cx).masked != masked {
14066            self.display_map.update(cx, |map, _| map.masked = masked);
14067        }
14068        cx.notify()
14069    }
14070
14071    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14072        self.show_wrap_guides = Some(show_wrap_guides);
14073        cx.notify();
14074    }
14075
14076    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14077        self.show_indent_guides = Some(show_indent_guides);
14078        cx.notify();
14079    }
14080
14081    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14082        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14083            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14084                if let Some(dir) = file.abs_path(cx).parent() {
14085                    return Some(dir.to_owned());
14086                }
14087            }
14088
14089            if let Some(project_path) = buffer.read(cx).project_path(cx) {
14090                return Some(project_path.path.to_path_buf());
14091            }
14092        }
14093
14094        None
14095    }
14096
14097    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14098        self.active_excerpt(cx)?
14099            .1
14100            .read(cx)
14101            .file()
14102            .and_then(|f| f.as_local())
14103    }
14104
14105    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14106        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14107            let buffer = buffer.read(cx);
14108            if let Some(project_path) = buffer.project_path(cx) {
14109                let project = self.project.as_ref()?.read(cx);
14110                project.absolute_path(&project_path, cx)
14111            } else {
14112                buffer
14113                    .file()
14114                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14115            }
14116        })
14117    }
14118
14119    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14120        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14121            let project_path = buffer.read(cx).project_path(cx)?;
14122            let project = self.project.as_ref()?.read(cx);
14123            let entry = project.entry_for_path(&project_path, cx)?;
14124            let path = entry.path.to_path_buf();
14125            Some(path)
14126        })
14127    }
14128
14129    pub fn reveal_in_finder(
14130        &mut self,
14131        _: &RevealInFileManager,
14132        _window: &mut Window,
14133        cx: &mut Context<Self>,
14134    ) {
14135        if let Some(target) = self.target_file(cx) {
14136            cx.reveal_path(&target.abs_path(cx));
14137        }
14138    }
14139
14140    pub fn copy_path(
14141        &mut self,
14142        _: &zed_actions::workspace::CopyPath,
14143        _window: &mut Window,
14144        cx: &mut Context<Self>,
14145    ) {
14146        if let Some(path) = self.target_file_abs_path(cx) {
14147            if let Some(path) = path.to_str() {
14148                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14149            }
14150        }
14151    }
14152
14153    pub fn copy_relative_path(
14154        &mut self,
14155        _: &zed_actions::workspace::CopyRelativePath,
14156        _window: &mut Window,
14157        cx: &mut Context<Self>,
14158    ) {
14159        if let Some(path) = self.target_file_path(cx) {
14160            if let Some(path) = path.to_str() {
14161                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14162            }
14163        }
14164    }
14165
14166    pub fn copy_file_name_without_extension(
14167        &mut self,
14168        _: &CopyFileNameWithoutExtension,
14169        _: &mut Window,
14170        cx: &mut Context<Self>,
14171    ) {
14172        if let Some(file) = self.target_file(cx) {
14173            if let Some(file_stem) = file.path().file_stem() {
14174                if let Some(name) = file_stem.to_str() {
14175                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14176                }
14177            }
14178        }
14179    }
14180
14181    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14182        if let Some(file) = self.target_file(cx) {
14183            if let Some(file_name) = file.path().file_name() {
14184                if let Some(name) = file_name.to_str() {
14185                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14186                }
14187            }
14188        }
14189    }
14190
14191    pub fn toggle_git_blame(
14192        &mut self,
14193        _: &ToggleGitBlame,
14194        window: &mut Window,
14195        cx: &mut Context<Self>,
14196    ) {
14197        self.show_git_blame_gutter = !self.show_git_blame_gutter;
14198
14199        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14200            self.start_git_blame(true, window, cx);
14201        }
14202
14203        cx.notify();
14204    }
14205
14206    pub fn toggle_git_blame_inline(
14207        &mut self,
14208        _: &ToggleGitBlameInline,
14209        window: &mut Window,
14210        cx: &mut Context<Self>,
14211    ) {
14212        self.toggle_git_blame_inline_internal(true, window, cx);
14213        cx.notify();
14214    }
14215
14216    pub fn git_blame_inline_enabled(&self) -> bool {
14217        self.git_blame_inline_enabled
14218    }
14219
14220    pub fn toggle_selection_menu(
14221        &mut self,
14222        _: &ToggleSelectionMenu,
14223        _: &mut Window,
14224        cx: &mut Context<Self>,
14225    ) {
14226        self.show_selection_menu = self
14227            .show_selection_menu
14228            .map(|show_selections_menu| !show_selections_menu)
14229            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14230
14231        cx.notify();
14232    }
14233
14234    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14235        self.show_selection_menu
14236            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14237    }
14238
14239    fn start_git_blame(
14240        &mut self,
14241        user_triggered: bool,
14242        window: &mut Window,
14243        cx: &mut Context<Self>,
14244    ) {
14245        if let Some(project) = self.project.as_ref() {
14246            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14247                return;
14248            };
14249
14250            if buffer.read(cx).file().is_none() {
14251                return;
14252            }
14253
14254            let focused = self.focus_handle(cx).contains_focused(window, cx);
14255
14256            let project = project.clone();
14257            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14258            self.blame_subscription =
14259                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14260            self.blame = Some(blame);
14261        }
14262    }
14263
14264    fn toggle_git_blame_inline_internal(
14265        &mut self,
14266        user_triggered: bool,
14267        window: &mut Window,
14268        cx: &mut Context<Self>,
14269    ) {
14270        if self.git_blame_inline_enabled {
14271            self.git_blame_inline_enabled = false;
14272            self.show_git_blame_inline = false;
14273            self.show_git_blame_inline_delay_task.take();
14274        } else {
14275            self.git_blame_inline_enabled = true;
14276            self.start_git_blame_inline(user_triggered, window, cx);
14277        }
14278
14279        cx.notify();
14280    }
14281
14282    fn start_git_blame_inline(
14283        &mut self,
14284        user_triggered: bool,
14285        window: &mut Window,
14286        cx: &mut Context<Self>,
14287    ) {
14288        self.start_git_blame(user_triggered, window, cx);
14289
14290        if ProjectSettings::get_global(cx)
14291            .git
14292            .inline_blame_delay()
14293            .is_some()
14294        {
14295            self.start_inline_blame_timer(window, cx);
14296        } else {
14297            self.show_git_blame_inline = true
14298        }
14299    }
14300
14301    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14302        self.blame.as_ref()
14303    }
14304
14305    pub fn show_git_blame_gutter(&self) -> bool {
14306        self.show_git_blame_gutter
14307    }
14308
14309    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14310        self.show_git_blame_gutter && self.has_blame_entries(cx)
14311    }
14312
14313    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14314        self.show_git_blame_inline
14315            && (self.focus_handle.is_focused(window)
14316                || self
14317                    .git_blame_inline_tooltip
14318                    .as_ref()
14319                    .and_then(|t| t.upgrade())
14320                    .is_some())
14321            && !self.newest_selection_head_on_empty_line(cx)
14322            && self.has_blame_entries(cx)
14323    }
14324
14325    fn has_blame_entries(&self, cx: &App) -> bool {
14326        self.blame()
14327            .map_or(false, |blame| blame.read(cx).has_generated_entries())
14328    }
14329
14330    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14331        let cursor_anchor = self.selections.newest_anchor().head();
14332
14333        let snapshot = self.buffer.read(cx).snapshot(cx);
14334        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14335
14336        snapshot.line_len(buffer_row) == 0
14337    }
14338
14339    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14340        let buffer_and_selection = maybe!({
14341            let selection = self.selections.newest::<Point>(cx);
14342            let selection_range = selection.range();
14343
14344            let multi_buffer = self.buffer().read(cx);
14345            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14346            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14347
14348            let (buffer, range, _) = if selection.reversed {
14349                buffer_ranges.first()
14350            } else {
14351                buffer_ranges.last()
14352            }?;
14353
14354            let selection = text::ToPoint::to_point(&range.start, &buffer).row
14355                ..text::ToPoint::to_point(&range.end, &buffer).row;
14356            Some((
14357                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14358                selection,
14359            ))
14360        });
14361
14362        let Some((buffer, selection)) = buffer_and_selection else {
14363            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14364        };
14365
14366        let Some(project) = self.project.as_ref() else {
14367            return Task::ready(Err(anyhow!("editor does not have project")));
14368        };
14369
14370        project.update(cx, |project, cx| {
14371            project.get_permalink_to_line(&buffer, selection, cx)
14372        })
14373    }
14374
14375    pub fn copy_permalink_to_line(
14376        &mut self,
14377        _: &CopyPermalinkToLine,
14378        window: &mut Window,
14379        cx: &mut Context<Self>,
14380    ) {
14381        let permalink_task = self.get_permalink_to_line(cx);
14382        let workspace = self.workspace();
14383
14384        cx.spawn_in(window, |_, mut cx| async move {
14385            match permalink_task.await {
14386                Ok(permalink) => {
14387                    cx.update(|_, cx| {
14388                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14389                    })
14390                    .ok();
14391                }
14392                Err(err) => {
14393                    let message = format!("Failed to copy permalink: {err}");
14394
14395                    Err::<(), anyhow::Error>(err).log_err();
14396
14397                    if let Some(workspace) = workspace {
14398                        workspace
14399                            .update_in(&mut cx, |workspace, _, cx| {
14400                                struct CopyPermalinkToLine;
14401
14402                                workspace.show_toast(
14403                                    Toast::new(
14404                                        NotificationId::unique::<CopyPermalinkToLine>(),
14405                                        message,
14406                                    ),
14407                                    cx,
14408                                )
14409                            })
14410                            .ok();
14411                    }
14412                }
14413            }
14414        })
14415        .detach();
14416    }
14417
14418    pub fn copy_file_location(
14419        &mut self,
14420        _: &CopyFileLocation,
14421        _: &mut Window,
14422        cx: &mut Context<Self>,
14423    ) {
14424        let selection = self.selections.newest::<Point>(cx).start.row + 1;
14425        if let Some(file) = self.target_file(cx) {
14426            if let Some(path) = file.path().to_str() {
14427                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14428            }
14429        }
14430    }
14431
14432    pub fn open_permalink_to_line(
14433        &mut self,
14434        _: &OpenPermalinkToLine,
14435        window: &mut Window,
14436        cx: &mut Context<Self>,
14437    ) {
14438        let permalink_task = self.get_permalink_to_line(cx);
14439        let workspace = self.workspace();
14440
14441        cx.spawn_in(window, |_, mut cx| async move {
14442            match permalink_task.await {
14443                Ok(permalink) => {
14444                    cx.update(|_, cx| {
14445                        cx.open_url(permalink.as_ref());
14446                    })
14447                    .ok();
14448                }
14449                Err(err) => {
14450                    let message = format!("Failed to open permalink: {err}");
14451
14452                    Err::<(), anyhow::Error>(err).log_err();
14453
14454                    if let Some(workspace) = workspace {
14455                        workspace
14456                            .update(&mut cx, |workspace, cx| {
14457                                struct OpenPermalinkToLine;
14458
14459                                workspace.show_toast(
14460                                    Toast::new(
14461                                        NotificationId::unique::<OpenPermalinkToLine>(),
14462                                        message,
14463                                    ),
14464                                    cx,
14465                                )
14466                            })
14467                            .ok();
14468                    }
14469                }
14470            }
14471        })
14472        .detach();
14473    }
14474
14475    pub fn insert_uuid_v4(
14476        &mut self,
14477        _: &InsertUuidV4,
14478        window: &mut Window,
14479        cx: &mut Context<Self>,
14480    ) {
14481        self.insert_uuid(UuidVersion::V4, window, cx);
14482    }
14483
14484    pub fn insert_uuid_v7(
14485        &mut self,
14486        _: &InsertUuidV7,
14487        window: &mut Window,
14488        cx: &mut Context<Self>,
14489    ) {
14490        self.insert_uuid(UuidVersion::V7, window, cx);
14491    }
14492
14493    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14494        self.transact(window, cx, |this, window, cx| {
14495            let edits = this
14496                .selections
14497                .all::<Point>(cx)
14498                .into_iter()
14499                .map(|selection| {
14500                    let uuid = match version {
14501                        UuidVersion::V4 => uuid::Uuid::new_v4(),
14502                        UuidVersion::V7 => uuid::Uuid::now_v7(),
14503                    };
14504
14505                    (selection.range(), uuid.to_string())
14506                });
14507            this.edit(edits, cx);
14508            this.refresh_inline_completion(true, false, window, cx);
14509        });
14510    }
14511
14512    pub fn open_selections_in_multibuffer(
14513        &mut self,
14514        _: &OpenSelectionsInMultibuffer,
14515        window: &mut Window,
14516        cx: &mut Context<Self>,
14517    ) {
14518        let multibuffer = self.buffer.read(cx);
14519
14520        let Some(buffer) = multibuffer.as_singleton() else {
14521            return;
14522        };
14523
14524        let Some(workspace) = self.workspace() else {
14525            return;
14526        };
14527
14528        let locations = self
14529            .selections
14530            .disjoint_anchors()
14531            .iter()
14532            .map(|range| Location {
14533                buffer: buffer.clone(),
14534                range: range.start.text_anchor..range.end.text_anchor,
14535            })
14536            .collect::<Vec<_>>();
14537
14538        let title = multibuffer.title(cx).to_string();
14539
14540        cx.spawn_in(window, |_, mut cx| async move {
14541            workspace.update_in(&mut cx, |workspace, window, cx| {
14542                Self::open_locations_in_multibuffer(
14543                    workspace,
14544                    locations,
14545                    format!("Selections for '{title}'"),
14546                    false,
14547                    MultibufferSelectionMode::All,
14548                    window,
14549                    cx,
14550                );
14551            })
14552        })
14553        .detach();
14554    }
14555
14556    /// Adds a row highlight for the given range. If a row has multiple highlights, the
14557    /// last highlight added will be used.
14558    ///
14559    /// If the range ends at the beginning of a line, then that line will not be highlighted.
14560    pub fn highlight_rows<T: 'static>(
14561        &mut self,
14562        range: Range<Anchor>,
14563        color: Hsla,
14564        should_autoscroll: bool,
14565        cx: &mut Context<Self>,
14566    ) {
14567        let snapshot = self.buffer().read(cx).snapshot(cx);
14568        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14569        let ix = row_highlights.binary_search_by(|highlight| {
14570            Ordering::Equal
14571                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14572                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14573        });
14574
14575        if let Err(mut ix) = ix {
14576            let index = post_inc(&mut self.highlight_order);
14577
14578            // If this range intersects with the preceding highlight, then merge it with
14579            // the preceding highlight. Otherwise insert a new highlight.
14580            let mut merged = false;
14581            if ix > 0 {
14582                let prev_highlight = &mut row_highlights[ix - 1];
14583                if prev_highlight
14584                    .range
14585                    .end
14586                    .cmp(&range.start, &snapshot)
14587                    .is_ge()
14588                {
14589                    ix -= 1;
14590                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14591                        prev_highlight.range.end = range.end;
14592                    }
14593                    merged = true;
14594                    prev_highlight.index = index;
14595                    prev_highlight.color = color;
14596                    prev_highlight.should_autoscroll = should_autoscroll;
14597                }
14598            }
14599
14600            if !merged {
14601                row_highlights.insert(
14602                    ix,
14603                    RowHighlight {
14604                        range: range.clone(),
14605                        index,
14606                        color,
14607                        should_autoscroll,
14608                    },
14609                );
14610            }
14611
14612            // If any of the following highlights intersect with this one, merge them.
14613            while let Some(next_highlight) = row_highlights.get(ix + 1) {
14614                let highlight = &row_highlights[ix];
14615                if next_highlight
14616                    .range
14617                    .start
14618                    .cmp(&highlight.range.end, &snapshot)
14619                    .is_le()
14620                {
14621                    if next_highlight
14622                        .range
14623                        .end
14624                        .cmp(&highlight.range.end, &snapshot)
14625                        .is_gt()
14626                    {
14627                        row_highlights[ix].range.end = next_highlight.range.end;
14628                    }
14629                    row_highlights.remove(ix + 1);
14630                } else {
14631                    break;
14632                }
14633            }
14634        }
14635    }
14636
14637    /// Remove any highlighted row ranges of the given type that intersect the
14638    /// given ranges.
14639    pub fn remove_highlighted_rows<T: 'static>(
14640        &mut self,
14641        ranges_to_remove: Vec<Range<Anchor>>,
14642        cx: &mut Context<Self>,
14643    ) {
14644        let snapshot = self.buffer().read(cx).snapshot(cx);
14645        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14646        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14647        row_highlights.retain(|highlight| {
14648            while let Some(range_to_remove) = ranges_to_remove.peek() {
14649                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14650                    Ordering::Less | Ordering::Equal => {
14651                        ranges_to_remove.next();
14652                    }
14653                    Ordering::Greater => {
14654                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14655                            Ordering::Less | Ordering::Equal => {
14656                                return false;
14657                            }
14658                            Ordering::Greater => break,
14659                        }
14660                    }
14661                }
14662            }
14663
14664            true
14665        })
14666    }
14667
14668    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14669    pub fn clear_row_highlights<T: 'static>(&mut self) {
14670        self.highlighted_rows.remove(&TypeId::of::<T>());
14671    }
14672
14673    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14674    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14675        self.highlighted_rows
14676            .get(&TypeId::of::<T>())
14677            .map_or(&[] as &[_], |vec| vec.as_slice())
14678            .iter()
14679            .map(|highlight| (highlight.range.clone(), highlight.color))
14680    }
14681
14682    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14683    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14684    /// Allows to ignore certain kinds of highlights.
14685    pub fn highlighted_display_rows(
14686        &self,
14687        window: &mut Window,
14688        cx: &mut App,
14689    ) -> BTreeMap<DisplayRow, Background> {
14690        let snapshot = self.snapshot(window, cx);
14691        let mut used_highlight_orders = HashMap::default();
14692        self.highlighted_rows
14693            .iter()
14694            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14695            .fold(
14696                BTreeMap::<DisplayRow, Background>::new(),
14697                |mut unique_rows, highlight| {
14698                    let start = highlight.range.start.to_display_point(&snapshot);
14699                    let end = highlight.range.end.to_display_point(&snapshot);
14700                    let start_row = start.row().0;
14701                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14702                        && end.column() == 0
14703                    {
14704                        end.row().0.saturating_sub(1)
14705                    } else {
14706                        end.row().0
14707                    };
14708                    for row in start_row..=end_row {
14709                        let used_index =
14710                            used_highlight_orders.entry(row).or_insert(highlight.index);
14711                        if highlight.index >= *used_index {
14712                            *used_index = highlight.index;
14713                            unique_rows.insert(DisplayRow(row), highlight.color.into());
14714                        }
14715                    }
14716                    unique_rows
14717                },
14718            )
14719    }
14720
14721    pub fn highlighted_display_row_for_autoscroll(
14722        &self,
14723        snapshot: &DisplaySnapshot,
14724    ) -> Option<DisplayRow> {
14725        self.highlighted_rows
14726            .values()
14727            .flat_map(|highlighted_rows| highlighted_rows.iter())
14728            .filter_map(|highlight| {
14729                if highlight.should_autoscroll {
14730                    Some(highlight.range.start.to_display_point(snapshot).row())
14731                } else {
14732                    None
14733                }
14734            })
14735            .min()
14736    }
14737
14738    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14739        self.highlight_background::<SearchWithinRange>(
14740            ranges,
14741            |colors| colors.editor_document_highlight_read_background,
14742            cx,
14743        )
14744    }
14745
14746    pub fn set_breadcrumb_header(&mut self, new_header: String) {
14747        self.breadcrumb_header = Some(new_header);
14748    }
14749
14750    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14751        self.clear_background_highlights::<SearchWithinRange>(cx);
14752    }
14753
14754    pub fn highlight_background<T: 'static>(
14755        &mut self,
14756        ranges: &[Range<Anchor>],
14757        color_fetcher: fn(&ThemeColors) -> Hsla,
14758        cx: &mut Context<Self>,
14759    ) {
14760        self.background_highlights
14761            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14762        self.scrollbar_marker_state.dirty = true;
14763        cx.notify();
14764    }
14765
14766    pub fn clear_background_highlights<T: 'static>(
14767        &mut self,
14768        cx: &mut Context<Self>,
14769    ) -> Option<BackgroundHighlight> {
14770        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14771        if !text_highlights.1.is_empty() {
14772            self.scrollbar_marker_state.dirty = true;
14773            cx.notify();
14774        }
14775        Some(text_highlights)
14776    }
14777
14778    pub fn highlight_gutter<T: 'static>(
14779        &mut self,
14780        ranges: &[Range<Anchor>],
14781        color_fetcher: fn(&App) -> Hsla,
14782        cx: &mut Context<Self>,
14783    ) {
14784        self.gutter_highlights
14785            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14786        cx.notify();
14787    }
14788
14789    pub fn clear_gutter_highlights<T: 'static>(
14790        &mut self,
14791        cx: &mut Context<Self>,
14792    ) -> Option<GutterHighlight> {
14793        cx.notify();
14794        self.gutter_highlights.remove(&TypeId::of::<T>())
14795    }
14796
14797    #[cfg(feature = "test-support")]
14798    pub fn all_text_background_highlights(
14799        &self,
14800        window: &mut Window,
14801        cx: &mut Context<Self>,
14802    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14803        let snapshot = self.snapshot(window, cx);
14804        let buffer = &snapshot.buffer_snapshot;
14805        let start = buffer.anchor_before(0);
14806        let end = buffer.anchor_after(buffer.len());
14807        let theme = cx.theme().colors();
14808        self.background_highlights_in_range(start..end, &snapshot, theme)
14809    }
14810
14811    #[cfg(feature = "test-support")]
14812    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14813        let snapshot = self.buffer().read(cx).snapshot(cx);
14814
14815        let highlights = self
14816            .background_highlights
14817            .get(&TypeId::of::<items::BufferSearchHighlights>());
14818
14819        if let Some((_color, ranges)) = highlights {
14820            ranges
14821                .iter()
14822                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14823                .collect_vec()
14824        } else {
14825            vec![]
14826        }
14827    }
14828
14829    fn document_highlights_for_position<'a>(
14830        &'a self,
14831        position: Anchor,
14832        buffer: &'a MultiBufferSnapshot,
14833    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
14834        let read_highlights = self
14835            .background_highlights
14836            .get(&TypeId::of::<DocumentHighlightRead>())
14837            .map(|h| &h.1);
14838        let write_highlights = self
14839            .background_highlights
14840            .get(&TypeId::of::<DocumentHighlightWrite>())
14841            .map(|h| &h.1);
14842        let left_position = position.bias_left(buffer);
14843        let right_position = position.bias_right(buffer);
14844        read_highlights
14845            .into_iter()
14846            .chain(write_highlights)
14847            .flat_map(move |ranges| {
14848                let start_ix = match ranges.binary_search_by(|probe| {
14849                    let cmp = probe.end.cmp(&left_position, buffer);
14850                    if cmp.is_ge() {
14851                        Ordering::Greater
14852                    } else {
14853                        Ordering::Less
14854                    }
14855                }) {
14856                    Ok(i) | Err(i) => i,
14857                };
14858
14859                ranges[start_ix..]
14860                    .iter()
14861                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
14862            })
14863    }
14864
14865    pub fn has_background_highlights<T: 'static>(&self) -> bool {
14866        self.background_highlights
14867            .get(&TypeId::of::<T>())
14868            .map_or(false, |(_, highlights)| !highlights.is_empty())
14869    }
14870
14871    pub fn background_highlights_in_range(
14872        &self,
14873        search_range: Range<Anchor>,
14874        display_snapshot: &DisplaySnapshot,
14875        theme: &ThemeColors,
14876    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14877        let mut results = Vec::new();
14878        for (color_fetcher, ranges) in self.background_highlights.values() {
14879            let color = color_fetcher(theme);
14880            let start_ix = match ranges.binary_search_by(|probe| {
14881                let cmp = probe
14882                    .end
14883                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14884                if cmp.is_gt() {
14885                    Ordering::Greater
14886                } else {
14887                    Ordering::Less
14888                }
14889            }) {
14890                Ok(i) | Err(i) => i,
14891            };
14892            for range in &ranges[start_ix..] {
14893                if range
14894                    .start
14895                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14896                    .is_ge()
14897                {
14898                    break;
14899                }
14900
14901                let start = range.start.to_display_point(display_snapshot);
14902                let end = range.end.to_display_point(display_snapshot);
14903                results.push((start..end, color))
14904            }
14905        }
14906        results
14907    }
14908
14909    pub fn background_highlight_row_ranges<T: 'static>(
14910        &self,
14911        search_range: Range<Anchor>,
14912        display_snapshot: &DisplaySnapshot,
14913        count: usize,
14914    ) -> Vec<RangeInclusive<DisplayPoint>> {
14915        let mut results = Vec::new();
14916        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14917            return vec![];
14918        };
14919
14920        let start_ix = match ranges.binary_search_by(|probe| {
14921            let cmp = probe
14922                .end
14923                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14924            if cmp.is_gt() {
14925                Ordering::Greater
14926            } else {
14927                Ordering::Less
14928            }
14929        }) {
14930            Ok(i) | Err(i) => i,
14931        };
14932        let mut push_region = |start: Option<Point>, end: Option<Point>| {
14933            if let (Some(start_display), Some(end_display)) = (start, end) {
14934                results.push(
14935                    start_display.to_display_point(display_snapshot)
14936                        ..=end_display.to_display_point(display_snapshot),
14937                );
14938            }
14939        };
14940        let mut start_row: Option<Point> = None;
14941        let mut end_row: Option<Point> = None;
14942        if ranges.len() > count {
14943            return Vec::new();
14944        }
14945        for range in &ranges[start_ix..] {
14946            if range
14947                .start
14948                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14949                .is_ge()
14950            {
14951                break;
14952            }
14953            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14954            if let Some(current_row) = &end_row {
14955                if end.row == current_row.row {
14956                    continue;
14957                }
14958            }
14959            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14960            if start_row.is_none() {
14961                assert_eq!(end_row, None);
14962                start_row = Some(start);
14963                end_row = Some(end);
14964                continue;
14965            }
14966            if let Some(current_end) = end_row.as_mut() {
14967                if start.row > current_end.row + 1 {
14968                    push_region(start_row, end_row);
14969                    start_row = Some(start);
14970                    end_row = Some(end);
14971                } else {
14972                    // Merge two hunks.
14973                    *current_end = end;
14974                }
14975            } else {
14976                unreachable!();
14977            }
14978        }
14979        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14980        push_region(start_row, end_row);
14981        results
14982    }
14983
14984    pub fn gutter_highlights_in_range(
14985        &self,
14986        search_range: Range<Anchor>,
14987        display_snapshot: &DisplaySnapshot,
14988        cx: &App,
14989    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14990        let mut results = Vec::new();
14991        for (color_fetcher, ranges) in self.gutter_highlights.values() {
14992            let color = color_fetcher(cx);
14993            let start_ix = match ranges.binary_search_by(|probe| {
14994                let cmp = probe
14995                    .end
14996                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14997                if cmp.is_gt() {
14998                    Ordering::Greater
14999                } else {
15000                    Ordering::Less
15001                }
15002            }) {
15003                Ok(i) | Err(i) => i,
15004            };
15005            for range in &ranges[start_ix..] {
15006                if range
15007                    .start
15008                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15009                    .is_ge()
15010                {
15011                    break;
15012                }
15013
15014                let start = range.start.to_display_point(display_snapshot);
15015                let end = range.end.to_display_point(display_snapshot);
15016                results.push((start..end, color))
15017            }
15018        }
15019        results
15020    }
15021
15022    /// Get the text ranges corresponding to the redaction query
15023    pub fn redacted_ranges(
15024        &self,
15025        search_range: Range<Anchor>,
15026        display_snapshot: &DisplaySnapshot,
15027        cx: &App,
15028    ) -> Vec<Range<DisplayPoint>> {
15029        display_snapshot
15030            .buffer_snapshot
15031            .redacted_ranges(search_range, |file| {
15032                if let Some(file) = file {
15033                    file.is_private()
15034                        && EditorSettings::get(
15035                            Some(SettingsLocation {
15036                                worktree_id: file.worktree_id(cx),
15037                                path: file.path().as_ref(),
15038                            }),
15039                            cx,
15040                        )
15041                        .redact_private_values
15042                } else {
15043                    false
15044                }
15045            })
15046            .map(|range| {
15047                range.start.to_display_point(display_snapshot)
15048                    ..range.end.to_display_point(display_snapshot)
15049            })
15050            .collect()
15051    }
15052
15053    pub fn highlight_text<T: 'static>(
15054        &mut self,
15055        ranges: Vec<Range<Anchor>>,
15056        style: HighlightStyle,
15057        cx: &mut Context<Self>,
15058    ) {
15059        self.display_map.update(cx, |map, _| {
15060            map.highlight_text(TypeId::of::<T>(), ranges, style)
15061        });
15062        cx.notify();
15063    }
15064
15065    pub(crate) fn highlight_inlays<T: 'static>(
15066        &mut self,
15067        highlights: Vec<InlayHighlight>,
15068        style: HighlightStyle,
15069        cx: &mut Context<Self>,
15070    ) {
15071        self.display_map.update(cx, |map, _| {
15072            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15073        });
15074        cx.notify();
15075    }
15076
15077    pub fn text_highlights<'a, T: 'static>(
15078        &'a self,
15079        cx: &'a App,
15080    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15081        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15082    }
15083
15084    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15085        let cleared = self
15086            .display_map
15087            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15088        if cleared {
15089            cx.notify();
15090        }
15091    }
15092
15093    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15094        (self.read_only(cx) || self.blink_manager.read(cx).visible())
15095            && self.focus_handle.is_focused(window)
15096    }
15097
15098    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15099        self.show_cursor_when_unfocused = is_enabled;
15100        cx.notify();
15101    }
15102
15103    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15104        cx.notify();
15105    }
15106
15107    fn on_buffer_event(
15108        &mut self,
15109        multibuffer: &Entity<MultiBuffer>,
15110        event: &multi_buffer::Event,
15111        window: &mut Window,
15112        cx: &mut Context<Self>,
15113    ) {
15114        match event {
15115            multi_buffer::Event::Edited {
15116                singleton_buffer_edited,
15117                edited_buffer: buffer_edited,
15118            } => {
15119                self.scrollbar_marker_state.dirty = true;
15120                self.active_indent_guides_state.dirty = true;
15121                self.refresh_active_diagnostics(cx);
15122                self.refresh_code_actions(window, cx);
15123                if self.has_active_inline_completion() {
15124                    self.update_visible_inline_completion(window, cx);
15125                }
15126                if let Some(buffer) = buffer_edited {
15127                    let buffer_id = buffer.read(cx).remote_id();
15128                    if !self.registered_buffers.contains_key(&buffer_id) {
15129                        if let Some(project) = self.project.as_ref() {
15130                            project.update(cx, |project, cx| {
15131                                self.registered_buffers.insert(
15132                                    buffer_id,
15133                                    project.register_buffer_with_language_servers(&buffer, cx),
15134                                );
15135                            })
15136                        }
15137                    }
15138                }
15139                cx.emit(EditorEvent::BufferEdited);
15140                cx.emit(SearchEvent::MatchesInvalidated);
15141                if *singleton_buffer_edited {
15142                    if let Some(project) = &self.project {
15143                        #[allow(clippy::mutable_key_type)]
15144                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15145                            multibuffer
15146                                .all_buffers()
15147                                .into_iter()
15148                                .filter_map(|buffer| {
15149                                    buffer.update(cx, |buffer, cx| {
15150                                        let language = buffer.language()?;
15151                                        let should_discard = project.update(cx, |project, cx| {
15152                                            project.is_local()
15153                                                && !project.has_language_servers_for(buffer, cx)
15154                                        });
15155                                        should_discard.not().then_some(language.clone())
15156                                    })
15157                                })
15158                                .collect::<HashSet<_>>()
15159                        });
15160                        if !languages_affected.is_empty() {
15161                            self.refresh_inlay_hints(
15162                                InlayHintRefreshReason::BufferEdited(languages_affected),
15163                                cx,
15164                            );
15165                        }
15166                    }
15167                }
15168
15169                let Some(project) = &self.project else { return };
15170                let (telemetry, is_via_ssh) = {
15171                    let project = project.read(cx);
15172                    let telemetry = project.client().telemetry().clone();
15173                    let is_via_ssh = project.is_via_ssh();
15174                    (telemetry, is_via_ssh)
15175                };
15176                refresh_linked_ranges(self, window, cx);
15177                telemetry.log_edit_event("editor", is_via_ssh);
15178            }
15179            multi_buffer::Event::ExcerptsAdded {
15180                buffer,
15181                predecessor,
15182                excerpts,
15183            } => {
15184                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15185                let buffer_id = buffer.read(cx).remote_id();
15186                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15187                    if let Some(project) = &self.project {
15188                        get_uncommitted_diff_for_buffer(
15189                            project,
15190                            [buffer.clone()],
15191                            self.buffer.clone(),
15192                            cx,
15193                        )
15194                        .detach();
15195                    }
15196                }
15197                cx.emit(EditorEvent::ExcerptsAdded {
15198                    buffer: buffer.clone(),
15199                    predecessor: *predecessor,
15200                    excerpts: excerpts.clone(),
15201                });
15202                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15203            }
15204            multi_buffer::Event::ExcerptsRemoved { ids } => {
15205                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15206                let buffer = self.buffer.read(cx);
15207                self.registered_buffers
15208                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15209                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15210            }
15211            multi_buffer::Event::ExcerptsEdited { ids } => {
15212                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
15213            }
15214            multi_buffer::Event::ExcerptsExpanded { ids } => {
15215                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15216                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15217            }
15218            multi_buffer::Event::Reparsed(buffer_id) => {
15219                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15220
15221                cx.emit(EditorEvent::Reparsed(*buffer_id));
15222            }
15223            multi_buffer::Event::DiffHunksToggled => {
15224                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15225            }
15226            multi_buffer::Event::LanguageChanged(buffer_id) => {
15227                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15228                cx.emit(EditorEvent::Reparsed(*buffer_id));
15229                cx.notify();
15230            }
15231            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15232            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15233            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15234                cx.emit(EditorEvent::TitleChanged)
15235            }
15236            // multi_buffer::Event::DiffBaseChanged => {
15237            //     self.scrollbar_marker_state.dirty = true;
15238            //     cx.emit(EditorEvent::DiffBaseChanged);
15239            //     cx.notify();
15240            // }
15241            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15242            multi_buffer::Event::DiagnosticsUpdated => {
15243                self.refresh_active_diagnostics(cx);
15244                self.refresh_inline_diagnostics(true, window, cx);
15245                self.scrollbar_marker_state.dirty = true;
15246                cx.notify();
15247            }
15248            _ => {}
15249        };
15250    }
15251
15252    fn on_display_map_changed(
15253        &mut self,
15254        _: Entity<DisplayMap>,
15255        _: &mut Window,
15256        cx: &mut Context<Self>,
15257    ) {
15258        cx.notify();
15259    }
15260
15261    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15262        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15263        self.update_edit_prediction_settings(cx);
15264        self.refresh_inline_completion(true, false, window, cx);
15265        self.refresh_inlay_hints(
15266            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15267                self.selections.newest_anchor().head(),
15268                &self.buffer.read(cx).snapshot(cx),
15269                cx,
15270            )),
15271            cx,
15272        );
15273
15274        let old_cursor_shape = self.cursor_shape;
15275
15276        {
15277            let editor_settings = EditorSettings::get_global(cx);
15278            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15279            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15280            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15281        }
15282
15283        if old_cursor_shape != self.cursor_shape {
15284            cx.emit(EditorEvent::CursorShapeChanged);
15285        }
15286
15287        let project_settings = ProjectSettings::get_global(cx);
15288        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15289
15290        if self.mode == EditorMode::Full {
15291            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15292            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15293            if self.show_inline_diagnostics != show_inline_diagnostics {
15294                self.show_inline_diagnostics = show_inline_diagnostics;
15295                self.refresh_inline_diagnostics(false, window, cx);
15296            }
15297
15298            if self.git_blame_inline_enabled != inline_blame_enabled {
15299                self.toggle_git_blame_inline_internal(false, window, cx);
15300            }
15301        }
15302
15303        cx.notify();
15304    }
15305
15306    pub fn set_searchable(&mut self, searchable: bool) {
15307        self.searchable = searchable;
15308    }
15309
15310    pub fn searchable(&self) -> bool {
15311        self.searchable
15312    }
15313
15314    fn open_proposed_changes_editor(
15315        &mut self,
15316        _: &OpenProposedChangesEditor,
15317        window: &mut Window,
15318        cx: &mut Context<Self>,
15319    ) {
15320        let Some(workspace) = self.workspace() else {
15321            cx.propagate();
15322            return;
15323        };
15324
15325        let selections = self.selections.all::<usize>(cx);
15326        let multi_buffer = self.buffer.read(cx);
15327        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15328        let mut new_selections_by_buffer = HashMap::default();
15329        for selection in selections {
15330            for (buffer, range, _) in
15331                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15332            {
15333                let mut range = range.to_point(buffer);
15334                range.start.column = 0;
15335                range.end.column = buffer.line_len(range.end.row);
15336                new_selections_by_buffer
15337                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15338                    .or_insert(Vec::new())
15339                    .push(range)
15340            }
15341        }
15342
15343        let proposed_changes_buffers = new_selections_by_buffer
15344            .into_iter()
15345            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15346            .collect::<Vec<_>>();
15347        let proposed_changes_editor = cx.new(|cx| {
15348            ProposedChangesEditor::new(
15349                "Proposed changes",
15350                proposed_changes_buffers,
15351                self.project.clone(),
15352                window,
15353                cx,
15354            )
15355        });
15356
15357        window.defer(cx, move |window, cx| {
15358            workspace.update(cx, |workspace, cx| {
15359                workspace.active_pane().update(cx, |pane, cx| {
15360                    pane.add_item(
15361                        Box::new(proposed_changes_editor),
15362                        true,
15363                        true,
15364                        None,
15365                        window,
15366                        cx,
15367                    );
15368                });
15369            });
15370        });
15371    }
15372
15373    pub fn open_excerpts_in_split(
15374        &mut self,
15375        _: &OpenExcerptsSplit,
15376        window: &mut Window,
15377        cx: &mut Context<Self>,
15378    ) {
15379        self.open_excerpts_common(None, true, window, cx)
15380    }
15381
15382    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15383        self.open_excerpts_common(None, false, window, cx)
15384    }
15385
15386    fn open_excerpts_common(
15387        &mut self,
15388        jump_data: Option<JumpData>,
15389        split: bool,
15390        window: &mut Window,
15391        cx: &mut Context<Self>,
15392    ) {
15393        let Some(workspace) = self.workspace() else {
15394            cx.propagate();
15395            return;
15396        };
15397
15398        if self.buffer.read(cx).is_singleton() {
15399            cx.propagate();
15400            return;
15401        }
15402
15403        let mut new_selections_by_buffer = HashMap::default();
15404        match &jump_data {
15405            Some(JumpData::MultiBufferPoint {
15406                excerpt_id,
15407                position,
15408                anchor,
15409                line_offset_from_top,
15410            }) => {
15411                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15412                if let Some(buffer) = multi_buffer_snapshot
15413                    .buffer_id_for_excerpt(*excerpt_id)
15414                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15415                {
15416                    let buffer_snapshot = buffer.read(cx).snapshot();
15417                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15418                        language::ToPoint::to_point(anchor, &buffer_snapshot)
15419                    } else {
15420                        buffer_snapshot.clip_point(*position, Bias::Left)
15421                    };
15422                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15423                    new_selections_by_buffer.insert(
15424                        buffer,
15425                        (
15426                            vec![jump_to_offset..jump_to_offset],
15427                            Some(*line_offset_from_top),
15428                        ),
15429                    );
15430                }
15431            }
15432            Some(JumpData::MultiBufferRow {
15433                row,
15434                line_offset_from_top,
15435            }) => {
15436                let point = MultiBufferPoint::new(row.0, 0);
15437                if let Some((buffer, buffer_point, _)) =
15438                    self.buffer.read(cx).point_to_buffer_point(point, cx)
15439                {
15440                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15441                    new_selections_by_buffer
15442                        .entry(buffer)
15443                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
15444                        .0
15445                        .push(buffer_offset..buffer_offset)
15446                }
15447            }
15448            None => {
15449                let selections = self.selections.all::<usize>(cx);
15450                let multi_buffer = self.buffer.read(cx);
15451                for selection in selections {
15452                    for (snapshot, range, _, anchor) in multi_buffer
15453                        .snapshot(cx)
15454                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15455                    {
15456                        if let Some(anchor) = anchor {
15457                            // selection is in a deleted hunk
15458                            let Some(buffer_id) = anchor.buffer_id else {
15459                                continue;
15460                            };
15461                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15462                                continue;
15463                            };
15464                            let offset = text::ToOffset::to_offset(
15465                                &anchor.text_anchor,
15466                                &buffer_handle.read(cx).snapshot(),
15467                            );
15468                            let range = offset..offset;
15469                            new_selections_by_buffer
15470                                .entry(buffer_handle)
15471                                .or_insert((Vec::new(), None))
15472                                .0
15473                                .push(range)
15474                        } else {
15475                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15476                            else {
15477                                continue;
15478                            };
15479                            new_selections_by_buffer
15480                                .entry(buffer_handle)
15481                                .or_insert((Vec::new(), None))
15482                                .0
15483                                .push(range)
15484                        }
15485                    }
15486                }
15487            }
15488        }
15489
15490        if new_selections_by_buffer.is_empty() {
15491            return;
15492        }
15493
15494        // We defer the pane interaction because we ourselves are a workspace item
15495        // and activating a new item causes the pane to call a method on us reentrantly,
15496        // which panics if we're on the stack.
15497        window.defer(cx, move |window, cx| {
15498            workspace.update(cx, |workspace, cx| {
15499                let pane = if split {
15500                    workspace.adjacent_pane(window, cx)
15501                } else {
15502                    workspace.active_pane().clone()
15503                };
15504
15505                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15506                    let editor = buffer
15507                        .read(cx)
15508                        .file()
15509                        .is_none()
15510                        .then(|| {
15511                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15512                            // so `workspace.open_project_item` will never find them, always opening a new editor.
15513                            // Instead, we try to activate the existing editor in the pane first.
15514                            let (editor, pane_item_index) =
15515                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
15516                                    let editor = item.downcast::<Editor>()?;
15517                                    let singleton_buffer =
15518                                        editor.read(cx).buffer().read(cx).as_singleton()?;
15519                                    if singleton_buffer == buffer {
15520                                        Some((editor, i))
15521                                    } else {
15522                                        None
15523                                    }
15524                                })?;
15525                            pane.update(cx, |pane, cx| {
15526                                pane.activate_item(pane_item_index, true, true, window, cx)
15527                            });
15528                            Some(editor)
15529                        })
15530                        .flatten()
15531                        .unwrap_or_else(|| {
15532                            workspace.open_project_item::<Self>(
15533                                pane.clone(),
15534                                buffer,
15535                                true,
15536                                true,
15537                                window,
15538                                cx,
15539                            )
15540                        });
15541
15542                    editor.update(cx, |editor, cx| {
15543                        let autoscroll = match scroll_offset {
15544                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15545                            None => Autoscroll::newest(),
15546                        };
15547                        let nav_history = editor.nav_history.take();
15548                        editor.change_selections(Some(autoscroll), window, cx, |s| {
15549                            s.select_ranges(ranges);
15550                        });
15551                        editor.nav_history = nav_history;
15552                    });
15553                }
15554            })
15555        });
15556    }
15557
15558    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15559        let snapshot = self.buffer.read(cx).read(cx);
15560        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15561        Some(
15562            ranges
15563                .iter()
15564                .map(move |range| {
15565                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15566                })
15567                .collect(),
15568        )
15569    }
15570
15571    fn selection_replacement_ranges(
15572        &self,
15573        range: Range<OffsetUtf16>,
15574        cx: &mut App,
15575    ) -> Vec<Range<OffsetUtf16>> {
15576        let selections = self.selections.all::<OffsetUtf16>(cx);
15577        let newest_selection = selections
15578            .iter()
15579            .max_by_key(|selection| selection.id)
15580            .unwrap();
15581        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15582        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15583        let snapshot = self.buffer.read(cx).read(cx);
15584        selections
15585            .into_iter()
15586            .map(|mut selection| {
15587                selection.start.0 =
15588                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
15589                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15590                snapshot.clip_offset_utf16(selection.start, Bias::Left)
15591                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15592            })
15593            .collect()
15594    }
15595
15596    fn report_editor_event(
15597        &self,
15598        event_type: &'static str,
15599        file_extension: Option<String>,
15600        cx: &App,
15601    ) {
15602        if cfg!(any(test, feature = "test-support")) {
15603            return;
15604        }
15605
15606        let Some(project) = &self.project else { return };
15607
15608        // If None, we are in a file without an extension
15609        let file = self
15610            .buffer
15611            .read(cx)
15612            .as_singleton()
15613            .and_then(|b| b.read(cx).file());
15614        let file_extension = file_extension.or(file
15615            .as_ref()
15616            .and_then(|file| Path::new(file.file_name(cx)).extension())
15617            .and_then(|e| e.to_str())
15618            .map(|a| a.to_string()));
15619
15620        let vim_mode = cx
15621            .global::<SettingsStore>()
15622            .raw_user_settings()
15623            .get("vim_mode")
15624            == Some(&serde_json::Value::Bool(true));
15625
15626        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15627        let copilot_enabled = edit_predictions_provider
15628            == language::language_settings::EditPredictionProvider::Copilot;
15629        let copilot_enabled_for_language = self
15630            .buffer
15631            .read(cx)
15632            .settings_at(0, cx)
15633            .show_edit_predictions;
15634
15635        let project = project.read(cx);
15636        telemetry::event!(
15637            event_type,
15638            file_extension,
15639            vim_mode,
15640            copilot_enabled,
15641            copilot_enabled_for_language,
15642            edit_predictions_provider,
15643            is_via_ssh = project.is_via_ssh(),
15644        );
15645    }
15646
15647    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15648    /// with each line being an array of {text, highlight} objects.
15649    fn copy_highlight_json(
15650        &mut self,
15651        _: &CopyHighlightJson,
15652        window: &mut Window,
15653        cx: &mut Context<Self>,
15654    ) {
15655        #[derive(Serialize)]
15656        struct Chunk<'a> {
15657            text: String,
15658            highlight: Option<&'a str>,
15659        }
15660
15661        let snapshot = self.buffer.read(cx).snapshot(cx);
15662        let range = self
15663            .selected_text_range(false, window, cx)
15664            .and_then(|selection| {
15665                if selection.range.is_empty() {
15666                    None
15667                } else {
15668                    Some(selection.range)
15669                }
15670            })
15671            .unwrap_or_else(|| 0..snapshot.len());
15672
15673        let chunks = snapshot.chunks(range, true);
15674        let mut lines = Vec::new();
15675        let mut line: VecDeque<Chunk> = VecDeque::new();
15676
15677        let Some(style) = self.style.as_ref() else {
15678            return;
15679        };
15680
15681        for chunk in chunks {
15682            let highlight = chunk
15683                .syntax_highlight_id
15684                .and_then(|id| id.name(&style.syntax));
15685            let mut chunk_lines = chunk.text.split('\n').peekable();
15686            while let Some(text) = chunk_lines.next() {
15687                let mut merged_with_last_token = false;
15688                if let Some(last_token) = line.back_mut() {
15689                    if last_token.highlight == highlight {
15690                        last_token.text.push_str(text);
15691                        merged_with_last_token = true;
15692                    }
15693                }
15694
15695                if !merged_with_last_token {
15696                    line.push_back(Chunk {
15697                        text: text.into(),
15698                        highlight,
15699                    });
15700                }
15701
15702                if chunk_lines.peek().is_some() {
15703                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
15704                        line.pop_front();
15705                    }
15706                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
15707                        line.pop_back();
15708                    }
15709
15710                    lines.push(mem::take(&mut line));
15711                }
15712            }
15713        }
15714
15715        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15716            return;
15717        };
15718        cx.write_to_clipboard(ClipboardItem::new_string(lines));
15719    }
15720
15721    pub fn open_context_menu(
15722        &mut self,
15723        _: &OpenContextMenu,
15724        window: &mut Window,
15725        cx: &mut Context<Self>,
15726    ) {
15727        self.request_autoscroll(Autoscroll::newest(), cx);
15728        let position = self.selections.newest_display(cx).start;
15729        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15730    }
15731
15732    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15733        &self.inlay_hint_cache
15734    }
15735
15736    pub fn replay_insert_event(
15737        &mut self,
15738        text: &str,
15739        relative_utf16_range: Option<Range<isize>>,
15740        window: &mut Window,
15741        cx: &mut Context<Self>,
15742    ) {
15743        if !self.input_enabled {
15744            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15745            return;
15746        }
15747        if let Some(relative_utf16_range) = relative_utf16_range {
15748            let selections = self.selections.all::<OffsetUtf16>(cx);
15749            self.change_selections(None, window, cx, |s| {
15750                let new_ranges = selections.into_iter().map(|range| {
15751                    let start = OffsetUtf16(
15752                        range
15753                            .head()
15754                            .0
15755                            .saturating_add_signed(relative_utf16_range.start),
15756                    );
15757                    let end = OffsetUtf16(
15758                        range
15759                            .head()
15760                            .0
15761                            .saturating_add_signed(relative_utf16_range.end),
15762                    );
15763                    start..end
15764                });
15765                s.select_ranges(new_ranges);
15766            });
15767        }
15768
15769        self.handle_input(text, window, cx);
15770    }
15771
15772    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15773        let Some(provider) = self.semantics_provider.as_ref() else {
15774            return false;
15775        };
15776
15777        let mut supports = false;
15778        self.buffer().update(cx, |this, cx| {
15779            this.for_each_buffer(|buffer| {
15780                supports |= provider.supports_inlay_hints(buffer, cx);
15781            });
15782        });
15783
15784        supports
15785    }
15786
15787    pub fn is_focused(&self, window: &Window) -> bool {
15788        self.focus_handle.is_focused(window)
15789    }
15790
15791    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15792        cx.emit(EditorEvent::Focused);
15793
15794        if let Some(descendant) = self
15795            .last_focused_descendant
15796            .take()
15797            .and_then(|descendant| descendant.upgrade())
15798        {
15799            window.focus(&descendant);
15800        } else {
15801            if let Some(blame) = self.blame.as_ref() {
15802                blame.update(cx, GitBlame::focus)
15803            }
15804
15805            self.blink_manager.update(cx, BlinkManager::enable);
15806            self.show_cursor_names(window, cx);
15807            self.buffer.update(cx, |buffer, cx| {
15808                buffer.finalize_last_transaction(cx);
15809                if self.leader_peer_id.is_none() {
15810                    buffer.set_active_selections(
15811                        &self.selections.disjoint_anchors(),
15812                        self.selections.line_mode,
15813                        self.cursor_shape,
15814                        cx,
15815                    );
15816                }
15817            });
15818        }
15819    }
15820
15821    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15822        cx.emit(EditorEvent::FocusedIn)
15823    }
15824
15825    fn handle_focus_out(
15826        &mut self,
15827        event: FocusOutEvent,
15828        _window: &mut Window,
15829        _cx: &mut Context<Self>,
15830    ) {
15831        if event.blurred != self.focus_handle {
15832            self.last_focused_descendant = Some(event.blurred);
15833        }
15834    }
15835
15836    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15837        self.blink_manager.update(cx, BlinkManager::disable);
15838        self.buffer
15839            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
15840
15841        if let Some(blame) = self.blame.as_ref() {
15842            blame.update(cx, GitBlame::blur)
15843        }
15844        if !self.hover_state.focused(window, cx) {
15845            hide_hover(self, cx);
15846        }
15847        if !self
15848            .context_menu
15849            .borrow()
15850            .as_ref()
15851            .is_some_and(|context_menu| context_menu.focused(window, cx))
15852        {
15853            self.hide_context_menu(window, cx);
15854        }
15855        self.discard_inline_completion(false, cx);
15856        cx.emit(EditorEvent::Blurred);
15857        cx.notify();
15858    }
15859
15860    pub fn register_action<A: Action>(
15861        &mut self,
15862        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
15863    ) -> Subscription {
15864        let id = self.next_editor_action_id.post_inc();
15865        let listener = Arc::new(listener);
15866        self.editor_actions.borrow_mut().insert(
15867            id,
15868            Box::new(move |window, _| {
15869                let listener = listener.clone();
15870                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
15871                    let action = action.downcast_ref().unwrap();
15872                    if phase == DispatchPhase::Bubble {
15873                        listener(action, window, cx)
15874                    }
15875                })
15876            }),
15877        );
15878
15879        let editor_actions = self.editor_actions.clone();
15880        Subscription::new(move || {
15881            editor_actions.borrow_mut().remove(&id);
15882        })
15883    }
15884
15885    pub fn file_header_size(&self) -> u32 {
15886        FILE_HEADER_HEIGHT
15887    }
15888
15889    pub fn revert(
15890        &mut self,
15891        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
15892        window: &mut Window,
15893        cx: &mut Context<Self>,
15894    ) {
15895        self.buffer().update(cx, |multi_buffer, cx| {
15896            for (buffer_id, changes) in revert_changes {
15897                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
15898                    buffer.update(cx, |buffer, cx| {
15899                        buffer.edit(
15900                            changes.into_iter().map(|(range, text)| {
15901                                (range, text.to_string().map(Arc::<str>::from))
15902                            }),
15903                            None,
15904                            cx,
15905                        );
15906                    });
15907                }
15908            }
15909        });
15910        self.change_selections(None, window, cx, |selections| selections.refresh());
15911    }
15912
15913    pub fn to_pixel_point(
15914        &self,
15915        source: multi_buffer::Anchor,
15916        editor_snapshot: &EditorSnapshot,
15917        window: &mut Window,
15918    ) -> Option<gpui::Point<Pixels>> {
15919        let source_point = source.to_display_point(editor_snapshot);
15920        self.display_to_pixel_point(source_point, editor_snapshot, window)
15921    }
15922
15923    pub fn display_to_pixel_point(
15924        &self,
15925        source: DisplayPoint,
15926        editor_snapshot: &EditorSnapshot,
15927        window: &mut Window,
15928    ) -> Option<gpui::Point<Pixels>> {
15929        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15930        let text_layout_details = self.text_layout_details(window);
15931        let scroll_top = text_layout_details
15932            .scroll_anchor
15933            .scroll_position(editor_snapshot)
15934            .y;
15935
15936        if source.row().as_f32() < scroll_top.floor() {
15937            return None;
15938        }
15939        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15940        let source_y = line_height * (source.row().as_f32() - scroll_top);
15941        Some(gpui::Point::new(source_x, source_y))
15942    }
15943
15944    pub fn has_visible_completions_menu(&self) -> bool {
15945        !self.edit_prediction_preview_is_active()
15946            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15947                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15948            })
15949    }
15950
15951    pub fn register_addon<T: Addon>(&mut self, instance: T) {
15952        self.addons
15953            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15954    }
15955
15956    pub fn unregister_addon<T: Addon>(&mut self) {
15957        self.addons.remove(&std::any::TypeId::of::<T>());
15958    }
15959
15960    pub fn addon<T: Addon>(&self) -> Option<&T> {
15961        let type_id = std::any::TypeId::of::<T>();
15962        self.addons
15963            .get(&type_id)
15964            .and_then(|item| item.to_any().downcast_ref::<T>())
15965    }
15966
15967    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15968        let text_layout_details = self.text_layout_details(window);
15969        let style = &text_layout_details.editor_style;
15970        let font_id = window.text_system().resolve_font(&style.text.font());
15971        let font_size = style.text.font_size.to_pixels(window.rem_size());
15972        let line_height = style.text.line_height_in_pixels(window.rem_size());
15973        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15974
15975        gpui::Size::new(em_width, line_height)
15976    }
15977
15978    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15979        self.load_diff_task.clone()
15980    }
15981
15982    fn read_selections_from_db(
15983        &mut self,
15984        item_id: u64,
15985        workspace_id: WorkspaceId,
15986        window: &mut Window,
15987        cx: &mut Context<Editor>,
15988    ) {
15989        if !self.is_singleton(cx)
15990            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15991        {
15992            return;
15993        }
15994        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15995            return;
15996        };
15997        if selections.is_empty() {
15998            return;
15999        }
16000
16001        let snapshot = self.buffer.read(cx).snapshot(cx);
16002        self.change_selections(None, window, cx, |s| {
16003            s.select_ranges(selections.into_iter().map(|(start, end)| {
16004                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16005            }));
16006        });
16007    }
16008}
16009
16010fn insert_extra_newline_brackets(
16011    buffer: &MultiBufferSnapshot,
16012    range: Range<usize>,
16013    language: &language::LanguageScope,
16014) -> bool {
16015    let leading_whitespace_len = buffer
16016        .reversed_chars_at(range.start)
16017        .take_while(|c| c.is_whitespace() && *c != '\n')
16018        .map(|c| c.len_utf8())
16019        .sum::<usize>();
16020    let trailing_whitespace_len = buffer
16021        .chars_at(range.end)
16022        .take_while(|c| c.is_whitespace() && *c != '\n')
16023        .map(|c| c.len_utf8())
16024        .sum::<usize>();
16025    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16026
16027    language.brackets().any(|(pair, enabled)| {
16028        let pair_start = pair.start.trim_end();
16029        let pair_end = pair.end.trim_start();
16030
16031        enabled
16032            && pair.newline
16033            && buffer.contains_str_at(range.end, pair_end)
16034            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16035    })
16036}
16037
16038fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16039    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16040        [(buffer, range, _)] => (*buffer, range.clone()),
16041        _ => return false,
16042    };
16043    let pair = {
16044        let mut result: Option<BracketMatch> = None;
16045
16046        for pair in buffer
16047            .all_bracket_ranges(range.clone())
16048            .filter(move |pair| {
16049                pair.open_range.start <= range.start && pair.close_range.end >= range.end
16050            })
16051        {
16052            let len = pair.close_range.end - pair.open_range.start;
16053
16054            if let Some(existing) = &result {
16055                let existing_len = existing.close_range.end - existing.open_range.start;
16056                if len > existing_len {
16057                    continue;
16058                }
16059            }
16060
16061            result = Some(pair);
16062        }
16063
16064        result
16065    };
16066    let Some(pair) = pair else {
16067        return false;
16068    };
16069    pair.newline_only
16070        && buffer
16071            .chars_for_range(pair.open_range.end..range.start)
16072            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16073            .all(|c| c.is_whitespace() && c != '\n')
16074}
16075
16076fn get_uncommitted_diff_for_buffer(
16077    project: &Entity<Project>,
16078    buffers: impl IntoIterator<Item = Entity<Buffer>>,
16079    buffer: Entity<MultiBuffer>,
16080    cx: &mut App,
16081) -> Task<()> {
16082    let mut tasks = Vec::new();
16083    project.update(cx, |project, cx| {
16084        for buffer in buffers {
16085            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16086        }
16087    });
16088    cx.spawn(|mut cx| async move {
16089        let diffs = futures::future::join_all(tasks).await;
16090        buffer
16091            .update(&mut cx, |buffer, cx| {
16092                for diff in diffs.into_iter().flatten() {
16093                    buffer.add_diff(diff, cx);
16094                }
16095            })
16096            .ok();
16097    })
16098}
16099
16100fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16101    let tab_size = tab_size.get() as usize;
16102    let mut width = offset;
16103
16104    for ch in text.chars() {
16105        width += if ch == '\t' {
16106            tab_size - (width % tab_size)
16107        } else {
16108            1
16109        };
16110    }
16111
16112    width - offset
16113}
16114
16115#[cfg(test)]
16116mod tests {
16117    use super::*;
16118
16119    #[test]
16120    fn test_string_size_with_expanded_tabs() {
16121        let nz = |val| NonZeroU32::new(val).unwrap();
16122        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16123        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16124        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16125        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16126        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16127        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16128        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16129        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16130    }
16131}
16132
16133/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16134struct WordBreakingTokenizer<'a> {
16135    input: &'a str,
16136}
16137
16138impl<'a> WordBreakingTokenizer<'a> {
16139    fn new(input: &'a str) -> Self {
16140        Self { input }
16141    }
16142}
16143
16144fn is_char_ideographic(ch: char) -> bool {
16145    use unicode_script::Script::*;
16146    use unicode_script::UnicodeScript;
16147    matches!(ch.script(), Han | Tangut | Yi)
16148}
16149
16150fn is_grapheme_ideographic(text: &str) -> bool {
16151    text.chars().any(is_char_ideographic)
16152}
16153
16154fn is_grapheme_whitespace(text: &str) -> bool {
16155    text.chars().any(|x| x.is_whitespace())
16156}
16157
16158fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16159    text.chars().next().map_or(false, |ch| {
16160        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16161    })
16162}
16163
16164#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16165struct WordBreakToken<'a> {
16166    token: &'a str,
16167    grapheme_len: usize,
16168    is_whitespace: bool,
16169}
16170
16171impl<'a> Iterator for WordBreakingTokenizer<'a> {
16172    /// Yields a span, the count of graphemes in the token, and whether it was
16173    /// whitespace. Note that it also breaks at word boundaries.
16174    type Item = WordBreakToken<'a>;
16175
16176    fn next(&mut self) -> Option<Self::Item> {
16177        use unicode_segmentation::UnicodeSegmentation;
16178        if self.input.is_empty() {
16179            return None;
16180        }
16181
16182        let mut iter = self.input.graphemes(true).peekable();
16183        let mut offset = 0;
16184        let mut graphemes = 0;
16185        if let Some(first_grapheme) = iter.next() {
16186            let is_whitespace = is_grapheme_whitespace(first_grapheme);
16187            offset += first_grapheme.len();
16188            graphemes += 1;
16189            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16190                if let Some(grapheme) = iter.peek().copied() {
16191                    if should_stay_with_preceding_ideograph(grapheme) {
16192                        offset += grapheme.len();
16193                        graphemes += 1;
16194                    }
16195                }
16196            } else {
16197                let mut words = self.input[offset..].split_word_bound_indices().peekable();
16198                let mut next_word_bound = words.peek().copied();
16199                if next_word_bound.map_or(false, |(i, _)| i == 0) {
16200                    next_word_bound = words.next();
16201                }
16202                while let Some(grapheme) = iter.peek().copied() {
16203                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
16204                        break;
16205                    };
16206                    if is_grapheme_whitespace(grapheme) != is_whitespace {
16207                        break;
16208                    };
16209                    offset += grapheme.len();
16210                    graphemes += 1;
16211                    iter.next();
16212                }
16213            }
16214            let token = &self.input[..offset];
16215            self.input = &self.input[offset..];
16216            if is_whitespace {
16217                Some(WordBreakToken {
16218                    token: " ",
16219                    grapheme_len: 1,
16220                    is_whitespace: true,
16221                })
16222            } else {
16223                Some(WordBreakToken {
16224                    token,
16225                    grapheme_len: graphemes,
16226                    is_whitespace: false,
16227                })
16228            }
16229        } else {
16230            None
16231        }
16232    }
16233}
16234
16235#[test]
16236fn test_word_breaking_tokenizer() {
16237    let tests: &[(&str, &[(&str, usize, bool)])] = &[
16238        ("", &[]),
16239        ("  ", &[(" ", 1, true)]),
16240        ("Ʒ", &[("Ʒ", 1, false)]),
16241        ("Ǽ", &[("Ǽ", 1, false)]),
16242        ("", &[("", 1, false)]),
16243        ("⋑⋑", &[("⋑⋑", 2, false)]),
16244        (
16245            "原理,进而",
16246            &[
16247                ("", 1, false),
16248                ("理,", 2, false),
16249                ("", 1, false),
16250                ("", 1, false),
16251            ],
16252        ),
16253        (
16254            "hello world",
16255            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16256        ),
16257        (
16258            "hello, world",
16259            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16260        ),
16261        (
16262            "  hello world",
16263            &[
16264                (" ", 1, true),
16265                ("hello", 5, false),
16266                (" ", 1, true),
16267                ("world", 5, false),
16268            ],
16269        ),
16270        (
16271            "这是什么 \n 钢笔",
16272            &[
16273                ("", 1, false),
16274                ("", 1, false),
16275                ("", 1, false),
16276                ("", 1, false),
16277                (" ", 1, true),
16278                ("", 1, false),
16279                ("", 1, false),
16280            ],
16281        ),
16282        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16283    ];
16284
16285    for (input, result) in tests {
16286        assert_eq!(
16287            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16288            result
16289                .iter()
16290                .copied()
16291                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16292                    token,
16293                    grapheme_len,
16294                    is_whitespace,
16295                })
16296                .collect::<Vec<_>>()
16297        );
16298    }
16299}
16300
16301fn wrap_with_prefix(
16302    line_prefix: String,
16303    unwrapped_text: String,
16304    wrap_column: usize,
16305    tab_size: NonZeroU32,
16306) -> String {
16307    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16308    let mut wrapped_text = String::new();
16309    let mut current_line = line_prefix.clone();
16310
16311    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16312    let mut current_line_len = line_prefix_len;
16313    for WordBreakToken {
16314        token,
16315        grapheme_len,
16316        is_whitespace,
16317    } in tokenizer
16318    {
16319        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16320            wrapped_text.push_str(current_line.trim_end());
16321            wrapped_text.push('\n');
16322            current_line.truncate(line_prefix.len());
16323            current_line_len = line_prefix_len;
16324            if !is_whitespace {
16325                current_line.push_str(token);
16326                current_line_len += grapheme_len;
16327            }
16328        } else if !is_whitespace {
16329            current_line.push_str(token);
16330            current_line_len += grapheme_len;
16331        } else if current_line_len != line_prefix_len {
16332            current_line.push(' ');
16333            current_line_len += 1;
16334        }
16335    }
16336
16337    if !current_line.is_empty() {
16338        wrapped_text.push_str(&current_line);
16339    }
16340    wrapped_text
16341}
16342
16343#[test]
16344fn test_wrap_with_prefix() {
16345    assert_eq!(
16346        wrap_with_prefix(
16347            "# ".to_string(),
16348            "abcdefg".to_string(),
16349            4,
16350            NonZeroU32::new(4).unwrap()
16351        ),
16352        "# abcdefg"
16353    );
16354    assert_eq!(
16355        wrap_with_prefix(
16356            "".to_string(),
16357            "\thello world".to_string(),
16358            8,
16359            NonZeroU32::new(4).unwrap()
16360        ),
16361        "hello\nworld"
16362    );
16363    assert_eq!(
16364        wrap_with_prefix(
16365            "// ".to_string(),
16366            "xx \nyy zz aa bb cc".to_string(),
16367            12,
16368            NonZeroU32::new(4).unwrap()
16369        ),
16370        "// xx yy zz\n// aa bb cc"
16371    );
16372    assert_eq!(
16373        wrap_with_prefix(
16374            String::new(),
16375            "这是什么 \n 钢笔".to_string(),
16376            3,
16377            NonZeroU32::new(4).unwrap()
16378        ),
16379        "这是什\n么 钢\n"
16380    );
16381}
16382
16383pub trait CollaborationHub {
16384    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16385    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16386    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16387}
16388
16389impl CollaborationHub for Entity<Project> {
16390    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16391        self.read(cx).collaborators()
16392    }
16393
16394    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16395        self.read(cx).user_store().read(cx).participant_indices()
16396    }
16397
16398    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16399        let this = self.read(cx);
16400        let user_ids = this.collaborators().values().map(|c| c.user_id);
16401        this.user_store().read_with(cx, |user_store, cx| {
16402            user_store.participant_names(user_ids, cx)
16403        })
16404    }
16405}
16406
16407pub trait SemanticsProvider {
16408    fn hover(
16409        &self,
16410        buffer: &Entity<Buffer>,
16411        position: text::Anchor,
16412        cx: &mut App,
16413    ) -> Option<Task<Vec<project::Hover>>>;
16414
16415    fn inlay_hints(
16416        &self,
16417        buffer_handle: Entity<Buffer>,
16418        range: Range<text::Anchor>,
16419        cx: &mut App,
16420    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16421
16422    fn resolve_inlay_hint(
16423        &self,
16424        hint: InlayHint,
16425        buffer_handle: Entity<Buffer>,
16426        server_id: LanguageServerId,
16427        cx: &mut App,
16428    ) -> Option<Task<anyhow::Result<InlayHint>>>;
16429
16430    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16431
16432    fn document_highlights(
16433        &self,
16434        buffer: &Entity<Buffer>,
16435        position: text::Anchor,
16436        cx: &mut App,
16437    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16438
16439    fn definitions(
16440        &self,
16441        buffer: &Entity<Buffer>,
16442        position: text::Anchor,
16443        kind: GotoDefinitionKind,
16444        cx: &mut App,
16445    ) -> Option<Task<Result<Vec<LocationLink>>>>;
16446
16447    fn range_for_rename(
16448        &self,
16449        buffer: &Entity<Buffer>,
16450        position: text::Anchor,
16451        cx: &mut App,
16452    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16453
16454    fn perform_rename(
16455        &self,
16456        buffer: &Entity<Buffer>,
16457        position: text::Anchor,
16458        new_name: String,
16459        cx: &mut App,
16460    ) -> Option<Task<Result<ProjectTransaction>>>;
16461}
16462
16463pub trait CompletionProvider {
16464    fn completions(
16465        &self,
16466        buffer: &Entity<Buffer>,
16467        buffer_position: text::Anchor,
16468        trigger: CompletionContext,
16469        window: &mut Window,
16470        cx: &mut Context<Editor>,
16471    ) -> Task<Result<Vec<Completion>>>;
16472
16473    fn resolve_completions(
16474        &self,
16475        buffer: Entity<Buffer>,
16476        completion_indices: Vec<usize>,
16477        completions: Rc<RefCell<Box<[Completion]>>>,
16478        cx: &mut Context<Editor>,
16479    ) -> Task<Result<bool>>;
16480
16481    fn apply_additional_edits_for_completion(
16482        &self,
16483        _buffer: Entity<Buffer>,
16484        _completions: Rc<RefCell<Box<[Completion]>>>,
16485        _completion_index: usize,
16486        _push_to_history: bool,
16487        _cx: &mut Context<Editor>,
16488    ) -> Task<Result<Option<language::Transaction>>> {
16489        Task::ready(Ok(None))
16490    }
16491
16492    fn is_completion_trigger(
16493        &self,
16494        buffer: &Entity<Buffer>,
16495        position: language::Anchor,
16496        text: &str,
16497        trigger_in_words: bool,
16498        cx: &mut Context<Editor>,
16499    ) -> bool;
16500
16501    fn sort_completions(&self) -> bool {
16502        true
16503    }
16504}
16505
16506pub trait CodeActionProvider {
16507    fn id(&self) -> Arc<str>;
16508
16509    fn code_actions(
16510        &self,
16511        buffer: &Entity<Buffer>,
16512        range: Range<text::Anchor>,
16513        window: &mut Window,
16514        cx: &mut App,
16515    ) -> Task<Result<Vec<CodeAction>>>;
16516
16517    fn apply_code_action(
16518        &self,
16519        buffer_handle: Entity<Buffer>,
16520        action: CodeAction,
16521        excerpt_id: ExcerptId,
16522        push_to_history: bool,
16523        window: &mut Window,
16524        cx: &mut App,
16525    ) -> Task<Result<ProjectTransaction>>;
16526}
16527
16528impl CodeActionProvider for Entity<Project> {
16529    fn id(&self) -> Arc<str> {
16530        "project".into()
16531    }
16532
16533    fn code_actions(
16534        &self,
16535        buffer: &Entity<Buffer>,
16536        range: Range<text::Anchor>,
16537        _window: &mut Window,
16538        cx: &mut App,
16539    ) -> Task<Result<Vec<CodeAction>>> {
16540        self.update(cx, |project, cx| {
16541            project.code_actions(buffer, range, None, cx)
16542        })
16543    }
16544
16545    fn apply_code_action(
16546        &self,
16547        buffer_handle: Entity<Buffer>,
16548        action: CodeAction,
16549        _excerpt_id: ExcerptId,
16550        push_to_history: bool,
16551        _window: &mut Window,
16552        cx: &mut App,
16553    ) -> Task<Result<ProjectTransaction>> {
16554        self.update(cx, |project, cx| {
16555            project.apply_code_action(buffer_handle, action, push_to_history, cx)
16556        })
16557    }
16558}
16559
16560fn snippet_completions(
16561    project: &Project,
16562    buffer: &Entity<Buffer>,
16563    buffer_position: text::Anchor,
16564    cx: &mut App,
16565) -> Task<Result<Vec<Completion>>> {
16566    let language = buffer.read(cx).language_at(buffer_position);
16567    let language_name = language.as_ref().map(|language| language.lsp_id());
16568    let snippet_store = project.snippets().read(cx);
16569    let snippets = snippet_store.snippets_for(language_name, cx);
16570
16571    if snippets.is_empty() {
16572        return Task::ready(Ok(vec![]));
16573    }
16574    let snapshot = buffer.read(cx).text_snapshot();
16575    let chars: String = snapshot
16576        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16577        .collect();
16578
16579    let scope = language.map(|language| language.default_scope());
16580    let executor = cx.background_executor().clone();
16581
16582    cx.background_spawn(async move {
16583        let classifier = CharClassifier::new(scope).for_completion(true);
16584        let mut last_word = chars
16585            .chars()
16586            .take_while(|c| classifier.is_word(*c))
16587            .collect::<String>();
16588        last_word = last_word.chars().rev().collect();
16589
16590        if last_word.is_empty() {
16591            return Ok(vec![]);
16592        }
16593
16594        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16595        let to_lsp = |point: &text::Anchor| {
16596            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16597            point_to_lsp(end)
16598        };
16599        let lsp_end = to_lsp(&buffer_position);
16600
16601        let candidates = snippets
16602            .iter()
16603            .enumerate()
16604            .flat_map(|(ix, snippet)| {
16605                snippet
16606                    .prefix
16607                    .iter()
16608                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16609            })
16610            .collect::<Vec<StringMatchCandidate>>();
16611
16612        let mut matches = fuzzy::match_strings(
16613            &candidates,
16614            &last_word,
16615            last_word.chars().any(|c| c.is_uppercase()),
16616            100,
16617            &Default::default(),
16618            executor,
16619        )
16620        .await;
16621
16622        // Remove all candidates where the query's start does not match the start of any word in the candidate
16623        if let Some(query_start) = last_word.chars().next() {
16624            matches.retain(|string_match| {
16625                split_words(&string_match.string).any(|word| {
16626                    // Check that the first codepoint of the word as lowercase matches the first
16627                    // codepoint of the query as lowercase
16628                    word.chars()
16629                        .flat_map(|codepoint| codepoint.to_lowercase())
16630                        .zip(query_start.to_lowercase())
16631                        .all(|(word_cp, query_cp)| word_cp == query_cp)
16632                })
16633            });
16634        }
16635
16636        let matched_strings = matches
16637            .into_iter()
16638            .map(|m| m.string)
16639            .collect::<HashSet<_>>();
16640
16641        let result: Vec<Completion> = snippets
16642            .into_iter()
16643            .filter_map(|snippet| {
16644                let matching_prefix = snippet
16645                    .prefix
16646                    .iter()
16647                    .find(|prefix| matched_strings.contains(*prefix))?;
16648                let start = as_offset - last_word.len();
16649                let start = snapshot.anchor_before(start);
16650                let range = start..buffer_position;
16651                let lsp_start = to_lsp(&start);
16652                let lsp_range = lsp::Range {
16653                    start: lsp_start,
16654                    end: lsp_end,
16655                };
16656                Some(Completion {
16657                    old_range: range,
16658                    new_text: snippet.body.clone(),
16659                    resolved: false,
16660                    label: CodeLabel {
16661                        text: matching_prefix.clone(),
16662                        runs: vec![],
16663                        filter_range: 0..matching_prefix.len(),
16664                    },
16665                    server_id: LanguageServerId(usize::MAX),
16666                    documentation: snippet
16667                        .description
16668                        .clone()
16669                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
16670                    lsp_completion: lsp::CompletionItem {
16671                        label: snippet.prefix.first().unwrap().clone(),
16672                        kind: Some(CompletionItemKind::SNIPPET),
16673                        label_details: snippet.description.as_ref().map(|description| {
16674                            lsp::CompletionItemLabelDetails {
16675                                detail: Some(description.clone()),
16676                                description: None,
16677                            }
16678                        }),
16679                        insert_text_format: Some(InsertTextFormat::SNIPPET),
16680                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16681                            lsp::InsertReplaceEdit {
16682                                new_text: snippet.body.clone(),
16683                                insert: lsp_range,
16684                                replace: lsp_range,
16685                            },
16686                        )),
16687                        filter_text: Some(snippet.body.clone()),
16688                        sort_text: Some(char::MAX.to_string()),
16689                        ..Default::default()
16690                    },
16691                    confirm: None,
16692                })
16693            })
16694            .collect();
16695
16696        Ok(result)
16697    })
16698}
16699
16700impl CompletionProvider for Entity<Project> {
16701    fn completions(
16702        &self,
16703        buffer: &Entity<Buffer>,
16704        buffer_position: text::Anchor,
16705        options: CompletionContext,
16706        _window: &mut Window,
16707        cx: &mut Context<Editor>,
16708    ) -> Task<Result<Vec<Completion>>> {
16709        self.update(cx, |project, cx| {
16710            let snippets = snippet_completions(project, buffer, buffer_position, cx);
16711            let project_completions = project.completions(buffer, buffer_position, options, cx);
16712            cx.background_spawn(async move {
16713                let mut completions = project_completions.await?;
16714                let snippets_completions = snippets.await?;
16715                completions.extend(snippets_completions);
16716                Ok(completions)
16717            })
16718        })
16719    }
16720
16721    fn resolve_completions(
16722        &self,
16723        buffer: Entity<Buffer>,
16724        completion_indices: Vec<usize>,
16725        completions: Rc<RefCell<Box<[Completion]>>>,
16726        cx: &mut Context<Editor>,
16727    ) -> Task<Result<bool>> {
16728        self.update(cx, |project, cx| {
16729            project.lsp_store().update(cx, |lsp_store, cx| {
16730                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16731            })
16732        })
16733    }
16734
16735    fn apply_additional_edits_for_completion(
16736        &self,
16737        buffer: Entity<Buffer>,
16738        completions: Rc<RefCell<Box<[Completion]>>>,
16739        completion_index: usize,
16740        push_to_history: bool,
16741        cx: &mut Context<Editor>,
16742    ) -> Task<Result<Option<language::Transaction>>> {
16743        self.update(cx, |project, cx| {
16744            project.lsp_store().update(cx, |lsp_store, cx| {
16745                lsp_store.apply_additional_edits_for_completion(
16746                    buffer,
16747                    completions,
16748                    completion_index,
16749                    push_to_history,
16750                    cx,
16751                )
16752            })
16753        })
16754    }
16755
16756    fn is_completion_trigger(
16757        &self,
16758        buffer: &Entity<Buffer>,
16759        position: language::Anchor,
16760        text: &str,
16761        trigger_in_words: bool,
16762        cx: &mut Context<Editor>,
16763    ) -> bool {
16764        let mut chars = text.chars();
16765        let char = if let Some(char) = chars.next() {
16766            char
16767        } else {
16768            return false;
16769        };
16770        if chars.next().is_some() {
16771            return false;
16772        }
16773
16774        let buffer = buffer.read(cx);
16775        let snapshot = buffer.snapshot();
16776        if !snapshot.settings_at(position, cx).show_completions_on_input {
16777            return false;
16778        }
16779        let classifier = snapshot.char_classifier_at(position).for_completion(true);
16780        if trigger_in_words && classifier.is_word(char) {
16781            return true;
16782        }
16783
16784        buffer.completion_triggers().contains(text)
16785    }
16786}
16787
16788impl SemanticsProvider for Entity<Project> {
16789    fn hover(
16790        &self,
16791        buffer: &Entity<Buffer>,
16792        position: text::Anchor,
16793        cx: &mut App,
16794    ) -> Option<Task<Vec<project::Hover>>> {
16795        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
16796    }
16797
16798    fn document_highlights(
16799        &self,
16800        buffer: &Entity<Buffer>,
16801        position: text::Anchor,
16802        cx: &mut App,
16803    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
16804        Some(self.update(cx, |project, cx| {
16805            project.document_highlights(buffer, position, cx)
16806        }))
16807    }
16808
16809    fn definitions(
16810        &self,
16811        buffer: &Entity<Buffer>,
16812        position: text::Anchor,
16813        kind: GotoDefinitionKind,
16814        cx: &mut App,
16815    ) -> Option<Task<Result<Vec<LocationLink>>>> {
16816        Some(self.update(cx, |project, cx| match kind {
16817            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
16818            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
16819            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
16820            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
16821        }))
16822    }
16823
16824    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
16825        // TODO: make this work for remote projects
16826        self.update(cx, |this, cx| {
16827            buffer.update(cx, |buffer, cx| {
16828                this.any_language_server_supports_inlay_hints(buffer, cx)
16829            })
16830        })
16831    }
16832
16833    fn inlay_hints(
16834        &self,
16835        buffer_handle: Entity<Buffer>,
16836        range: Range<text::Anchor>,
16837        cx: &mut App,
16838    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
16839        Some(self.update(cx, |project, cx| {
16840            project.inlay_hints(buffer_handle, range, cx)
16841        }))
16842    }
16843
16844    fn resolve_inlay_hint(
16845        &self,
16846        hint: InlayHint,
16847        buffer_handle: Entity<Buffer>,
16848        server_id: LanguageServerId,
16849        cx: &mut App,
16850    ) -> Option<Task<anyhow::Result<InlayHint>>> {
16851        Some(self.update(cx, |project, cx| {
16852            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
16853        }))
16854    }
16855
16856    fn range_for_rename(
16857        &self,
16858        buffer: &Entity<Buffer>,
16859        position: text::Anchor,
16860        cx: &mut App,
16861    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
16862        Some(self.update(cx, |project, cx| {
16863            let buffer = buffer.clone();
16864            let task = project.prepare_rename(buffer.clone(), position, cx);
16865            cx.spawn(|_, mut cx| async move {
16866                Ok(match task.await? {
16867                    PrepareRenameResponse::Success(range) => Some(range),
16868                    PrepareRenameResponse::InvalidPosition => None,
16869                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
16870                        // Fallback on using TreeSitter info to determine identifier range
16871                        buffer.update(&mut cx, |buffer, _| {
16872                            let snapshot = buffer.snapshot();
16873                            let (range, kind) = snapshot.surrounding_word(position);
16874                            if kind != Some(CharKind::Word) {
16875                                return None;
16876                            }
16877                            Some(
16878                                snapshot.anchor_before(range.start)
16879                                    ..snapshot.anchor_after(range.end),
16880                            )
16881                        })?
16882                    }
16883                })
16884            })
16885        }))
16886    }
16887
16888    fn perform_rename(
16889        &self,
16890        buffer: &Entity<Buffer>,
16891        position: text::Anchor,
16892        new_name: String,
16893        cx: &mut App,
16894    ) -> Option<Task<Result<ProjectTransaction>>> {
16895        Some(self.update(cx, |project, cx| {
16896            project.perform_rename(buffer.clone(), position, new_name, cx)
16897        }))
16898    }
16899}
16900
16901fn inlay_hint_settings(
16902    location: Anchor,
16903    snapshot: &MultiBufferSnapshot,
16904    cx: &mut Context<Editor>,
16905) -> InlayHintSettings {
16906    let file = snapshot.file_at(location);
16907    let language = snapshot.language_at(location).map(|l| l.name());
16908    language_settings(language, file, cx).inlay_hints
16909}
16910
16911fn consume_contiguous_rows(
16912    contiguous_row_selections: &mut Vec<Selection<Point>>,
16913    selection: &Selection<Point>,
16914    display_map: &DisplaySnapshot,
16915    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
16916) -> (MultiBufferRow, MultiBufferRow) {
16917    contiguous_row_selections.push(selection.clone());
16918    let start_row = MultiBufferRow(selection.start.row);
16919    let mut end_row = ending_row(selection, display_map);
16920
16921    while let Some(next_selection) = selections.peek() {
16922        if next_selection.start.row <= end_row.0 {
16923            end_row = ending_row(next_selection, display_map);
16924            contiguous_row_selections.push(selections.next().unwrap().clone());
16925        } else {
16926            break;
16927        }
16928    }
16929    (start_row, end_row)
16930}
16931
16932fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
16933    if next_selection.end.column > 0 || next_selection.is_empty() {
16934        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
16935    } else {
16936        MultiBufferRow(next_selection.end.row)
16937    }
16938}
16939
16940impl EditorSnapshot {
16941    pub fn remote_selections_in_range<'a>(
16942        &'a self,
16943        range: &'a Range<Anchor>,
16944        collaboration_hub: &dyn CollaborationHub,
16945        cx: &'a App,
16946    ) -> impl 'a + Iterator<Item = RemoteSelection> {
16947        let participant_names = collaboration_hub.user_names(cx);
16948        let participant_indices = collaboration_hub.user_participant_indices(cx);
16949        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
16950        let collaborators_by_replica_id = collaborators_by_peer_id
16951            .iter()
16952            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
16953            .collect::<HashMap<_, _>>();
16954        self.buffer_snapshot
16955            .selections_in_range(range, false)
16956            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
16957                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
16958                let participant_index = participant_indices.get(&collaborator.user_id).copied();
16959                let user_name = participant_names.get(&collaborator.user_id).cloned();
16960                Some(RemoteSelection {
16961                    replica_id,
16962                    selection,
16963                    cursor_shape,
16964                    line_mode,
16965                    participant_index,
16966                    peer_id: collaborator.peer_id,
16967                    user_name,
16968                })
16969            })
16970    }
16971
16972    pub fn hunks_for_ranges(
16973        &self,
16974        ranges: impl Iterator<Item = Range<Point>>,
16975    ) -> Vec<MultiBufferDiffHunk> {
16976        let mut hunks = Vec::new();
16977        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
16978            HashMap::default();
16979        for query_range in ranges {
16980            let query_rows =
16981                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
16982            for hunk in self.buffer_snapshot.diff_hunks_in_range(
16983                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
16984            ) {
16985                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
16986                // when the caret is just above or just below the deleted hunk.
16987                let allow_adjacent = hunk.status().is_deleted();
16988                let related_to_selection = if allow_adjacent {
16989                    hunk.row_range.overlaps(&query_rows)
16990                        || hunk.row_range.start == query_rows.end
16991                        || hunk.row_range.end == query_rows.start
16992                } else {
16993                    hunk.row_range.overlaps(&query_rows)
16994                };
16995                if related_to_selection {
16996                    if !processed_buffer_rows
16997                        .entry(hunk.buffer_id)
16998                        .or_default()
16999                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17000                    {
17001                        continue;
17002                    }
17003                    hunks.push(hunk);
17004                }
17005            }
17006        }
17007
17008        hunks
17009    }
17010
17011    fn display_diff_hunks_for_rows<'a>(
17012        &'a self,
17013        display_rows: Range<DisplayRow>,
17014        folded_buffers: &'a HashSet<BufferId>,
17015    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17016        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17017        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17018
17019        self.buffer_snapshot
17020            .diff_hunks_in_range(buffer_start..buffer_end)
17021            .filter_map(|hunk| {
17022                if folded_buffers.contains(&hunk.buffer_id) {
17023                    return None;
17024                }
17025
17026                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17027                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17028
17029                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17030                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17031
17032                let display_hunk = if hunk_display_start.column() != 0 {
17033                    DisplayDiffHunk::Folded {
17034                        display_row: hunk_display_start.row(),
17035                    }
17036                } else {
17037                    let mut end_row = hunk_display_end.row();
17038                    if hunk_display_end.column() > 0 {
17039                        end_row.0 += 1;
17040                    }
17041                    DisplayDiffHunk::Unfolded {
17042                        status: hunk.status(),
17043                        diff_base_byte_range: hunk.diff_base_byte_range,
17044                        display_row_range: hunk_display_start.row()..end_row,
17045                        multi_buffer_range: Anchor::range_in_buffer(
17046                            hunk.excerpt_id,
17047                            hunk.buffer_id,
17048                            hunk.buffer_range,
17049                        ),
17050                    }
17051                };
17052
17053                Some(display_hunk)
17054            })
17055    }
17056
17057    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17058        self.display_snapshot.buffer_snapshot.language_at(position)
17059    }
17060
17061    pub fn is_focused(&self) -> bool {
17062        self.is_focused
17063    }
17064
17065    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17066        self.placeholder_text.as_ref()
17067    }
17068
17069    pub fn scroll_position(&self) -> gpui::Point<f32> {
17070        self.scroll_anchor.scroll_position(&self.display_snapshot)
17071    }
17072
17073    fn gutter_dimensions(
17074        &self,
17075        font_id: FontId,
17076        font_size: Pixels,
17077        max_line_number_width: Pixels,
17078        cx: &App,
17079    ) -> Option<GutterDimensions> {
17080        if !self.show_gutter {
17081            return None;
17082        }
17083
17084        let descent = cx.text_system().descent(font_id, font_size);
17085        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17086        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17087
17088        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17089            matches!(
17090                ProjectSettings::get_global(cx).git.git_gutter,
17091                Some(GitGutterSetting::TrackedFiles)
17092            )
17093        });
17094        let gutter_settings = EditorSettings::get_global(cx).gutter;
17095        let show_line_numbers = self
17096            .show_line_numbers
17097            .unwrap_or(gutter_settings.line_numbers);
17098        let line_gutter_width = if show_line_numbers {
17099            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17100            let min_width_for_number_on_gutter = em_advance * 4.0;
17101            max_line_number_width.max(min_width_for_number_on_gutter)
17102        } else {
17103            0.0.into()
17104        };
17105
17106        let show_code_actions = self
17107            .show_code_actions
17108            .unwrap_or(gutter_settings.code_actions);
17109
17110        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17111
17112        let git_blame_entries_width =
17113            self.git_blame_gutter_max_author_length
17114                .map(|max_author_length| {
17115                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17116
17117                    /// The number of characters to dedicate to gaps and margins.
17118                    const SPACING_WIDTH: usize = 4;
17119
17120                    let max_char_count = max_author_length
17121                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17122                        + ::git::SHORT_SHA_LENGTH
17123                        + MAX_RELATIVE_TIMESTAMP.len()
17124                        + SPACING_WIDTH;
17125
17126                    em_advance * max_char_count
17127                });
17128
17129        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17130        left_padding += if show_code_actions || show_runnables {
17131            em_width * 3.0
17132        } else if show_git_gutter && show_line_numbers {
17133            em_width * 2.0
17134        } else if show_git_gutter || show_line_numbers {
17135            em_width
17136        } else {
17137            px(0.)
17138        };
17139
17140        let right_padding = if gutter_settings.folds && show_line_numbers {
17141            em_width * 4.0
17142        } else if gutter_settings.folds {
17143            em_width * 3.0
17144        } else if show_line_numbers {
17145            em_width
17146        } else {
17147            px(0.)
17148        };
17149
17150        Some(GutterDimensions {
17151            left_padding,
17152            right_padding,
17153            width: line_gutter_width + left_padding + right_padding,
17154            margin: -descent,
17155            git_blame_entries_width,
17156        })
17157    }
17158
17159    pub fn render_crease_toggle(
17160        &self,
17161        buffer_row: MultiBufferRow,
17162        row_contains_cursor: bool,
17163        editor: Entity<Editor>,
17164        window: &mut Window,
17165        cx: &mut App,
17166    ) -> Option<AnyElement> {
17167        let folded = self.is_line_folded(buffer_row);
17168        let mut is_foldable = false;
17169
17170        if let Some(crease) = self
17171            .crease_snapshot
17172            .query_row(buffer_row, &self.buffer_snapshot)
17173        {
17174            is_foldable = true;
17175            match crease {
17176                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17177                    if let Some(render_toggle) = render_toggle {
17178                        let toggle_callback =
17179                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17180                                if folded {
17181                                    editor.update(cx, |editor, cx| {
17182                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17183                                    });
17184                                } else {
17185                                    editor.update(cx, |editor, cx| {
17186                                        editor.unfold_at(
17187                                            &crate::UnfoldAt { buffer_row },
17188                                            window,
17189                                            cx,
17190                                        )
17191                                    });
17192                                }
17193                            });
17194                        return Some((render_toggle)(
17195                            buffer_row,
17196                            folded,
17197                            toggle_callback,
17198                            window,
17199                            cx,
17200                        ));
17201                    }
17202                }
17203            }
17204        }
17205
17206        is_foldable |= self.starts_indent(buffer_row);
17207
17208        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17209            Some(
17210                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17211                    .toggle_state(folded)
17212                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17213                        if folded {
17214                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17215                        } else {
17216                            this.fold_at(&FoldAt { buffer_row }, window, cx);
17217                        }
17218                    }))
17219                    .into_any_element(),
17220            )
17221        } else {
17222            None
17223        }
17224    }
17225
17226    pub fn render_crease_trailer(
17227        &self,
17228        buffer_row: MultiBufferRow,
17229        window: &mut Window,
17230        cx: &mut App,
17231    ) -> Option<AnyElement> {
17232        let folded = self.is_line_folded(buffer_row);
17233        if let Crease::Inline { render_trailer, .. } = self
17234            .crease_snapshot
17235            .query_row(buffer_row, &self.buffer_snapshot)?
17236        {
17237            let render_trailer = render_trailer.as_ref()?;
17238            Some(render_trailer(buffer_row, folded, window, cx))
17239        } else {
17240            None
17241        }
17242    }
17243}
17244
17245impl Deref for EditorSnapshot {
17246    type Target = DisplaySnapshot;
17247
17248    fn deref(&self) -> &Self::Target {
17249        &self.display_snapshot
17250    }
17251}
17252
17253#[derive(Clone, Debug, PartialEq, Eq)]
17254pub enum EditorEvent {
17255    InputIgnored {
17256        text: Arc<str>,
17257    },
17258    InputHandled {
17259        utf16_range_to_replace: Option<Range<isize>>,
17260        text: Arc<str>,
17261    },
17262    ExcerptsAdded {
17263        buffer: Entity<Buffer>,
17264        predecessor: ExcerptId,
17265        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17266    },
17267    ExcerptsRemoved {
17268        ids: Vec<ExcerptId>,
17269    },
17270    BufferFoldToggled {
17271        ids: Vec<ExcerptId>,
17272        folded: bool,
17273    },
17274    ExcerptsEdited {
17275        ids: Vec<ExcerptId>,
17276    },
17277    ExcerptsExpanded {
17278        ids: Vec<ExcerptId>,
17279    },
17280    BufferEdited,
17281    Edited {
17282        transaction_id: clock::Lamport,
17283    },
17284    Reparsed(BufferId),
17285    Focused,
17286    FocusedIn,
17287    Blurred,
17288    DirtyChanged,
17289    Saved,
17290    TitleChanged,
17291    DiffBaseChanged,
17292    SelectionsChanged {
17293        local: bool,
17294    },
17295    ScrollPositionChanged {
17296        local: bool,
17297        autoscroll: bool,
17298    },
17299    Closed,
17300    TransactionUndone {
17301        transaction_id: clock::Lamport,
17302    },
17303    TransactionBegun {
17304        transaction_id: clock::Lamport,
17305    },
17306    Reloaded,
17307    CursorShapeChanged,
17308}
17309
17310impl EventEmitter<EditorEvent> for Editor {}
17311
17312impl Focusable for Editor {
17313    fn focus_handle(&self, _cx: &App) -> FocusHandle {
17314        self.focus_handle.clone()
17315    }
17316}
17317
17318impl Render for Editor {
17319    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
17320        let settings = ThemeSettings::get_global(cx);
17321
17322        let mut text_style = match self.mode {
17323            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17324                color: cx.theme().colors().editor_foreground,
17325                font_family: settings.ui_font.family.clone(),
17326                font_features: settings.ui_font.features.clone(),
17327                font_fallbacks: settings.ui_font.fallbacks.clone(),
17328                font_size: rems(0.875).into(),
17329                font_weight: settings.ui_font.weight,
17330                line_height: relative(settings.buffer_line_height.value()),
17331                ..Default::default()
17332            },
17333            EditorMode::Full => TextStyle {
17334                color: cx.theme().colors().editor_foreground,
17335                font_family: settings.buffer_font.family.clone(),
17336                font_features: settings.buffer_font.features.clone(),
17337                font_fallbacks: settings.buffer_font.fallbacks.clone(),
17338                font_size: settings.buffer_font_size(cx).into(),
17339                font_weight: settings.buffer_font.weight,
17340                line_height: relative(settings.buffer_line_height.value()),
17341                ..Default::default()
17342            },
17343        };
17344        if let Some(text_style_refinement) = &self.text_style_refinement {
17345            text_style.refine(text_style_refinement)
17346        }
17347
17348        let background = match self.mode {
17349            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17350            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17351            EditorMode::Full => cx.theme().colors().editor_background,
17352        };
17353
17354        EditorElement::new(
17355            &cx.entity(),
17356            EditorStyle {
17357                background,
17358                local_player: cx.theme().players().local(),
17359                text: text_style,
17360                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17361                syntax: cx.theme().syntax().clone(),
17362                status: cx.theme().status().clone(),
17363                inlay_hints_style: make_inlay_hints_style(cx),
17364                inline_completion_styles: make_suggestion_styles(cx),
17365                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17366            },
17367        )
17368    }
17369}
17370
17371impl EntityInputHandler for Editor {
17372    fn text_for_range(
17373        &mut self,
17374        range_utf16: Range<usize>,
17375        adjusted_range: &mut Option<Range<usize>>,
17376        _: &mut Window,
17377        cx: &mut Context<Self>,
17378    ) -> Option<String> {
17379        let snapshot = self.buffer.read(cx).read(cx);
17380        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17381        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17382        if (start.0..end.0) != range_utf16 {
17383            adjusted_range.replace(start.0..end.0);
17384        }
17385        Some(snapshot.text_for_range(start..end).collect())
17386    }
17387
17388    fn selected_text_range(
17389        &mut self,
17390        ignore_disabled_input: bool,
17391        _: &mut Window,
17392        cx: &mut Context<Self>,
17393    ) -> Option<UTF16Selection> {
17394        // Prevent the IME menu from appearing when holding down an alphabetic key
17395        // while input is disabled.
17396        if !ignore_disabled_input && !self.input_enabled {
17397            return None;
17398        }
17399
17400        let selection = self.selections.newest::<OffsetUtf16>(cx);
17401        let range = selection.range();
17402
17403        Some(UTF16Selection {
17404            range: range.start.0..range.end.0,
17405            reversed: selection.reversed,
17406        })
17407    }
17408
17409    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17410        let snapshot = self.buffer.read(cx).read(cx);
17411        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17412        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17413    }
17414
17415    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17416        self.clear_highlights::<InputComposition>(cx);
17417        self.ime_transaction.take();
17418    }
17419
17420    fn replace_text_in_range(
17421        &mut self,
17422        range_utf16: Option<Range<usize>>,
17423        text: &str,
17424        window: &mut Window,
17425        cx: &mut Context<Self>,
17426    ) {
17427        if !self.input_enabled {
17428            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17429            return;
17430        }
17431
17432        self.transact(window, cx, |this, window, cx| {
17433            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17434                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17435                Some(this.selection_replacement_ranges(range_utf16, cx))
17436            } else {
17437                this.marked_text_ranges(cx)
17438            };
17439
17440            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17441                let newest_selection_id = this.selections.newest_anchor().id;
17442                this.selections
17443                    .all::<OffsetUtf16>(cx)
17444                    .iter()
17445                    .zip(ranges_to_replace.iter())
17446                    .find_map(|(selection, range)| {
17447                        if selection.id == newest_selection_id {
17448                            Some(
17449                                (range.start.0 as isize - selection.head().0 as isize)
17450                                    ..(range.end.0 as isize - selection.head().0 as isize),
17451                            )
17452                        } else {
17453                            None
17454                        }
17455                    })
17456            });
17457
17458            cx.emit(EditorEvent::InputHandled {
17459                utf16_range_to_replace: range_to_replace,
17460                text: text.into(),
17461            });
17462
17463            if let Some(new_selected_ranges) = new_selected_ranges {
17464                this.change_selections(None, window, cx, |selections| {
17465                    selections.select_ranges(new_selected_ranges)
17466                });
17467                this.backspace(&Default::default(), window, cx);
17468            }
17469
17470            this.handle_input(text, window, cx);
17471        });
17472
17473        if let Some(transaction) = self.ime_transaction {
17474            self.buffer.update(cx, |buffer, cx| {
17475                buffer.group_until_transaction(transaction, cx);
17476            });
17477        }
17478
17479        self.unmark_text(window, cx);
17480    }
17481
17482    fn replace_and_mark_text_in_range(
17483        &mut self,
17484        range_utf16: Option<Range<usize>>,
17485        text: &str,
17486        new_selected_range_utf16: Option<Range<usize>>,
17487        window: &mut Window,
17488        cx: &mut Context<Self>,
17489    ) {
17490        if !self.input_enabled {
17491            return;
17492        }
17493
17494        let transaction = self.transact(window, cx, |this, window, cx| {
17495            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17496                let snapshot = this.buffer.read(cx).read(cx);
17497                if let Some(relative_range_utf16) = range_utf16.as_ref() {
17498                    for marked_range in &mut marked_ranges {
17499                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17500                        marked_range.start.0 += relative_range_utf16.start;
17501                        marked_range.start =
17502                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17503                        marked_range.end =
17504                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17505                    }
17506                }
17507                Some(marked_ranges)
17508            } else if let Some(range_utf16) = range_utf16 {
17509                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17510                Some(this.selection_replacement_ranges(range_utf16, cx))
17511            } else {
17512                None
17513            };
17514
17515            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17516                let newest_selection_id = this.selections.newest_anchor().id;
17517                this.selections
17518                    .all::<OffsetUtf16>(cx)
17519                    .iter()
17520                    .zip(ranges_to_replace.iter())
17521                    .find_map(|(selection, range)| {
17522                        if selection.id == newest_selection_id {
17523                            Some(
17524                                (range.start.0 as isize - selection.head().0 as isize)
17525                                    ..(range.end.0 as isize - selection.head().0 as isize),
17526                            )
17527                        } else {
17528                            None
17529                        }
17530                    })
17531            });
17532
17533            cx.emit(EditorEvent::InputHandled {
17534                utf16_range_to_replace: range_to_replace,
17535                text: text.into(),
17536            });
17537
17538            if let Some(ranges) = ranges_to_replace {
17539                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17540            }
17541
17542            let marked_ranges = {
17543                let snapshot = this.buffer.read(cx).read(cx);
17544                this.selections
17545                    .disjoint_anchors()
17546                    .iter()
17547                    .map(|selection| {
17548                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17549                    })
17550                    .collect::<Vec<_>>()
17551            };
17552
17553            if text.is_empty() {
17554                this.unmark_text(window, cx);
17555            } else {
17556                this.highlight_text::<InputComposition>(
17557                    marked_ranges.clone(),
17558                    HighlightStyle {
17559                        underline: Some(UnderlineStyle {
17560                            thickness: px(1.),
17561                            color: None,
17562                            wavy: false,
17563                        }),
17564                        ..Default::default()
17565                    },
17566                    cx,
17567                );
17568            }
17569
17570            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17571            let use_autoclose = this.use_autoclose;
17572            let use_auto_surround = this.use_auto_surround;
17573            this.set_use_autoclose(false);
17574            this.set_use_auto_surround(false);
17575            this.handle_input(text, window, cx);
17576            this.set_use_autoclose(use_autoclose);
17577            this.set_use_auto_surround(use_auto_surround);
17578
17579            if let Some(new_selected_range) = new_selected_range_utf16 {
17580                let snapshot = this.buffer.read(cx).read(cx);
17581                let new_selected_ranges = marked_ranges
17582                    .into_iter()
17583                    .map(|marked_range| {
17584                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17585                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17586                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17587                        snapshot.clip_offset_utf16(new_start, Bias::Left)
17588                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17589                    })
17590                    .collect::<Vec<_>>();
17591
17592                drop(snapshot);
17593                this.change_selections(None, window, cx, |selections| {
17594                    selections.select_ranges(new_selected_ranges)
17595                });
17596            }
17597        });
17598
17599        self.ime_transaction = self.ime_transaction.or(transaction);
17600        if let Some(transaction) = self.ime_transaction {
17601            self.buffer.update(cx, |buffer, cx| {
17602                buffer.group_until_transaction(transaction, cx);
17603            });
17604        }
17605
17606        if self.text_highlights::<InputComposition>(cx).is_none() {
17607            self.ime_transaction.take();
17608        }
17609    }
17610
17611    fn bounds_for_range(
17612        &mut self,
17613        range_utf16: Range<usize>,
17614        element_bounds: gpui::Bounds<Pixels>,
17615        window: &mut Window,
17616        cx: &mut Context<Self>,
17617    ) -> Option<gpui::Bounds<Pixels>> {
17618        let text_layout_details = self.text_layout_details(window);
17619        let gpui::Size {
17620            width: em_width,
17621            height: line_height,
17622        } = self.character_size(window);
17623
17624        let snapshot = self.snapshot(window, cx);
17625        let scroll_position = snapshot.scroll_position();
17626        let scroll_left = scroll_position.x * em_width;
17627
17628        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17629        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17630            + self.gutter_dimensions.width
17631            + self.gutter_dimensions.margin;
17632        let y = line_height * (start.row().as_f32() - scroll_position.y);
17633
17634        Some(Bounds {
17635            origin: element_bounds.origin + point(x, y),
17636            size: size(em_width, line_height),
17637        })
17638    }
17639
17640    fn character_index_for_point(
17641        &mut self,
17642        point: gpui::Point<Pixels>,
17643        _window: &mut Window,
17644        _cx: &mut Context<Self>,
17645    ) -> Option<usize> {
17646        let position_map = self.last_position_map.as_ref()?;
17647        if !position_map.text_hitbox.contains(&point) {
17648            return None;
17649        }
17650        let display_point = position_map.point_for_position(point).previous_valid;
17651        let anchor = position_map
17652            .snapshot
17653            .display_point_to_anchor(display_point, Bias::Left);
17654        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17655        Some(utf16_offset.0)
17656    }
17657}
17658
17659trait SelectionExt {
17660    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17661    fn spanned_rows(
17662        &self,
17663        include_end_if_at_line_start: bool,
17664        map: &DisplaySnapshot,
17665    ) -> Range<MultiBufferRow>;
17666}
17667
17668impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17669    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17670        let start = self
17671            .start
17672            .to_point(&map.buffer_snapshot)
17673            .to_display_point(map);
17674        let end = self
17675            .end
17676            .to_point(&map.buffer_snapshot)
17677            .to_display_point(map);
17678        if self.reversed {
17679            end..start
17680        } else {
17681            start..end
17682        }
17683    }
17684
17685    fn spanned_rows(
17686        &self,
17687        include_end_if_at_line_start: bool,
17688        map: &DisplaySnapshot,
17689    ) -> Range<MultiBufferRow> {
17690        let start = self.start.to_point(&map.buffer_snapshot);
17691        let mut end = self.end.to_point(&map.buffer_snapshot);
17692        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17693            end.row -= 1;
17694        }
17695
17696        let buffer_start = map.prev_line_boundary(start).0;
17697        let buffer_end = map.next_line_boundary(end).0;
17698        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17699    }
17700}
17701
17702impl<T: InvalidationRegion> InvalidationStack<T> {
17703    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17704    where
17705        S: Clone + ToOffset,
17706    {
17707        while let Some(region) = self.last() {
17708            let all_selections_inside_invalidation_ranges =
17709                if selections.len() == region.ranges().len() {
17710                    selections
17711                        .iter()
17712                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17713                        .all(|(selection, invalidation_range)| {
17714                            let head = selection.head().to_offset(buffer);
17715                            invalidation_range.start <= head && invalidation_range.end >= head
17716                        })
17717                } else {
17718                    false
17719                };
17720
17721            if all_selections_inside_invalidation_ranges {
17722                break;
17723            } else {
17724                self.pop();
17725            }
17726        }
17727    }
17728}
17729
17730impl<T> Default for InvalidationStack<T> {
17731    fn default() -> Self {
17732        Self(Default::default())
17733    }
17734}
17735
17736impl<T> Deref for InvalidationStack<T> {
17737    type Target = Vec<T>;
17738
17739    fn deref(&self) -> &Self::Target {
17740        &self.0
17741    }
17742}
17743
17744impl<T> DerefMut for InvalidationStack<T> {
17745    fn deref_mut(&mut self) -> &mut Self::Target {
17746        &mut self.0
17747    }
17748}
17749
17750impl InvalidationRegion for SnippetState {
17751    fn ranges(&self) -> &[Range<Anchor>] {
17752        &self.ranges[self.active_index]
17753    }
17754}
17755
17756pub fn diagnostic_block_renderer(
17757    diagnostic: Diagnostic,
17758    max_message_rows: Option<u8>,
17759    allow_closing: bool,
17760    _is_valid: bool,
17761) -> RenderBlock {
17762    let (text_without_backticks, code_ranges) =
17763        highlight_diagnostic_message(&diagnostic, max_message_rows);
17764
17765    Arc::new(move |cx: &mut BlockContext| {
17766        let group_id: SharedString = cx.block_id.to_string().into();
17767
17768        let mut text_style = cx.window.text_style().clone();
17769        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17770        let theme_settings = ThemeSettings::get_global(cx);
17771        text_style.font_family = theme_settings.buffer_font.family.clone();
17772        text_style.font_style = theme_settings.buffer_font.style;
17773        text_style.font_features = theme_settings.buffer_font.features.clone();
17774        text_style.font_weight = theme_settings.buffer_font.weight;
17775
17776        let multi_line_diagnostic = diagnostic.message.contains('\n');
17777
17778        let buttons = |diagnostic: &Diagnostic| {
17779            if multi_line_diagnostic {
17780                v_flex()
17781            } else {
17782                h_flex()
17783            }
17784            .when(allow_closing, |div| {
17785                div.children(diagnostic.is_primary.then(|| {
17786                    IconButton::new("close-block", IconName::XCircle)
17787                        .icon_color(Color::Muted)
17788                        .size(ButtonSize::Compact)
17789                        .style(ButtonStyle::Transparent)
17790                        .visible_on_hover(group_id.clone())
17791                        .on_click(move |_click, window, cx| {
17792                            window.dispatch_action(Box::new(Cancel), cx)
17793                        })
17794                        .tooltip(|window, cx| {
17795                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
17796                        })
17797                }))
17798            })
17799            .child(
17800                IconButton::new("copy-block", IconName::Copy)
17801                    .icon_color(Color::Muted)
17802                    .size(ButtonSize::Compact)
17803                    .style(ButtonStyle::Transparent)
17804                    .visible_on_hover(group_id.clone())
17805                    .on_click({
17806                        let message = diagnostic.message.clone();
17807                        move |_click, _, cx| {
17808                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
17809                        }
17810                    })
17811                    .tooltip(Tooltip::text("Copy diagnostic message")),
17812            )
17813        };
17814
17815        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
17816            AvailableSpace::min_size(),
17817            cx.window,
17818            cx.app,
17819        );
17820
17821        h_flex()
17822            .id(cx.block_id)
17823            .group(group_id.clone())
17824            .relative()
17825            .size_full()
17826            .block_mouse_down()
17827            .pl(cx.gutter_dimensions.width)
17828            .w(cx.max_width - cx.gutter_dimensions.full_width())
17829            .child(
17830                div()
17831                    .flex()
17832                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
17833                    .flex_shrink(),
17834            )
17835            .child(buttons(&diagnostic))
17836            .child(div().flex().flex_shrink_0().child(
17837                StyledText::new(text_without_backticks.clone()).with_highlights(
17838                    &text_style,
17839                    code_ranges.iter().map(|range| {
17840                        (
17841                            range.clone(),
17842                            HighlightStyle {
17843                                font_weight: Some(FontWeight::BOLD),
17844                                ..Default::default()
17845                            },
17846                        )
17847                    }),
17848                ),
17849            ))
17850            .into_any_element()
17851    })
17852}
17853
17854fn inline_completion_edit_text(
17855    current_snapshot: &BufferSnapshot,
17856    edits: &[(Range<Anchor>, String)],
17857    edit_preview: &EditPreview,
17858    include_deletions: bool,
17859    cx: &App,
17860) -> HighlightedText {
17861    let edits = edits
17862        .iter()
17863        .map(|(anchor, text)| {
17864            (
17865                anchor.start.text_anchor..anchor.end.text_anchor,
17866                text.clone(),
17867            )
17868        })
17869        .collect::<Vec<_>>();
17870
17871    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
17872}
17873
17874pub fn highlight_diagnostic_message(
17875    diagnostic: &Diagnostic,
17876    mut max_message_rows: Option<u8>,
17877) -> (SharedString, Vec<Range<usize>>) {
17878    let mut text_without_backticks = String::new();
17879    let mut code_ranges = Vec::new();
17880
17881    if let Some(source) = &diagnostic.source {
17882        text_without_backticks.push_str(source);
17883        code_ranges.push(0..source.len());
17884        text_without_backticks.push_str(": ");
17885    }
17886
17887    let mut prev_offset = 0;
17888    let mut in_code_block = false;
17889    let has_row_limit = max_message_rows.is_some();
17890    let mut newline_indices = diagnostic
17891        .message
17892        .match_indices('\n')
17893        .filter(|_| has_row_limit)
17894        .map(|(ix, _)| ix)
17895        .fuse()
17896        .peekable();
17897
17898    for (quote_ix, _) in diagnostic
17899        .message
17900        .match_indices('`')
17901        .chain([(diagnostic.message.len(), "")])
17902    {
17903        let mut first_newline_ix = None;
17904        let mut last_newline_ix = None;
17905        while let Some(newline_ix) = newline_indices.peek() {
17906            if *newline_ix < quote_ix {
17907                if first_newline_ix.is_none() {
17908                    first_newline_ix = Some(*newline_ix);
17909                }
17910                last_newline_ix = Some(*newline_ix);
17911
17912                if let Some(rows_left) = &mut max_message_rows {
17913                    if *rows_left == 0 {
17914                        break;
17915                    } else {
17916                        *rows_left -= 1;
17917                    }
17918                }
17919                let _ = newline_indices.next();
17920            } else {
17921                break;
17922            }
17923        }
17924        let prev_len = text_without_backticks.len();
17925        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
17926        text_without_backticks.push_str(new_text);
17927        if in_code_block {
17928            code_ranges.push(prev_len..text_without_backticks.len());
17929        }
17930        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
17931        in_code_block = !in_code_block;
17932        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
17933            text_without_backticks.push_str("...");
17934            break;
17935        }
17936    }
17937
17938    (text_without_backticks.into(), code_ranges)
17939}
17940
17941fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
17942    match severity {
17943        DiagnosticSeverity::ERROR => colors.error,
17944        DiagnosticSeverity::WARNING => colors.warning,
17945        DiagnosticSeverity::INFORMATION => colors.info,
17946        DiagnosticSeverity::HINT => colors.info,
17947        _ => colors.ignored,
17948    }
17949}
17950
17951pub fn styled_runs_for_code_label<'a>(
17952    label: &'a CodeLabel,
17953    syntax_theme: &'a theme::SyntaxTheme,
17954) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
17955    let fade_out = HighlightStyle {
17956        fade_out: Some(0.35),
17957        ..Default::default()
17958    };
17959
17960    let mut prev_end = label.filter_range.end;
17961    label
17962        .runs
17963        .iter()
17964        .enumerate()
17965        .flat_map(move |(ix, (range, highlight_id))| {
17966            let style = if let Some(style) = highlight_id.style(syntax_theme) {
17967                style
17968            } else {
17969                return Default::default();
17970            };
17971            let mut muted_style = style;
17972            muted_style.highlight(fade_out);
17973
17974            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
17975            if range.start >= label.filter_range.end {
17976                if range.start > prev_end {
17977                    runs.push((prev_end..range.start, fade_out));
17978                }
17979                runs.push((range.clone(), muted_style));
17980            } else if range.end <= label.filter_range.end {
17981                runs.push((range.clone(), style));
17982            } else {
17983                runs.push((range.start..label.filter_range.end, style));
17984                runs.push((label.filter_range.end..range.end, muted_style));
17985            }
17986            prev_end = cmp::max(prev_end, range.end);
17987
17988            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
17989                runs.push((prev_end..label.text.len(), fade_out));
17990            }
17991
17992            runs
17993        })
17994}
17995
17996pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
17997    let mut prev_index = 0;
17998    let mut prev_codepoint: Option<char> = None;
17999    text.char_indices()
18000        .chain([(text.len(), '\0')])
18001        .filter_map(move |(index, codepoint)| {
18002            let prev_codepoint = prev_codepoint.replace(codepoint)?;
18003            let is_boundary = index == text.len()
18004                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18005                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18006            if is_boundary {
18007                let chunk = &text[prev_index..index];
18008                prev_index = index;
18009                Some(chunk)
18010            } else {
18011                None
18012            }
18013        })
18014}
18015
18016pub trait RangeToAnchorExt: Sized {
18017    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18018
18019    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18020        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18021        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18022    }
18023}
18024
18025impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18026    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18027        let start_offset = self.start.to_offset(snapshot);
18028        let end_offset = self.end.to_offset(snapshot);
18029        if start_offset == end_offset {
18030            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18031        } else {
18032            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18033        }
18034    }
18035}
18036
18037pub trait RowExt {
18038    fn as_f32(&self) -> f32;
18039
18040    fn next_row(&self) -> Self;
18041
18042    fn previous_row(&self) -> Self;
18043
18044    fn minus(&self, other: Self) -> u32;
18045}
18046
18047impl RowExt for DisplayRow {
18048    fn as_f32(&self) -> f32 {
18049        self.0 as f32
18050    }
18051
18052    fn next_row(&self) -> Self {
18053        Self(self.0 + 1)
18054    }
18055
18056    fn previous_row(&self) -> Self {
18057        Self(self.0.saturating_sub(1))
18058    }
18059
18060    fn minus(&self, other: Self) -> u32 {
18061        self.0 - other.0
18062    }
18063}
18064
18065impl RowExt for MultiBufferRow {
18066    fn as_f32(&self) -> f32 {
18067        self.0 as f32
18068    }
18069
18070    fn next_row(&self) -> Self {
18071        Self(self.0 + 1)
18072    }
18073
18074    fn previous_row(&self) -> Self {
18075        Self(self.0.saturating_sub(1))
18076    }
18077
18078    fn minus(&self, other: Self) -> u32 {
18079        self.0 - other.0
18080    }
18081}
18082
18083trait RowRangeExt {
18084    type Row;
18085
18086    fn len(&self) -> usize;
18087
18088    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18089}
18090
18091impl RowRangeExt for Range<MultiBufferRow> {
18092    type Row = MultiBufferRow;
18093
18094    fn len(&self) -> usize {
18095        (self.end.0 - self.start.0) as usize
18096    }
18097
18098    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18099        (self.start.0..self.end.0).map(MultiBufferRow)
18100    }
18101}
18102
18103impl RowRangeExt for Range<DisplayRow> {
18104    type Row = DisplayRow;
18105
18106    fn len(&self) -> usize {
18107        (self.end.0 - self.start.0) as usize
18108    }
18109
18110    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18111        (self.start.0..self.end.0).map(DisplayRow)
18112    }
18113}
18114
18115/// If select range has more than one line, we
18116/// just point the cursor to range.start.
18117fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18118    if range.start.row == range.end.row {
18119        range
18120    } else {
18121        range.start..range.start
18122    }
18123}
18124pub struct KillRing(ClipboardItem);
18125impl Global for KillRing {}
18126
18127const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18128
18129fn all_edits_insertions_or_deletions(
18130    edits: &Vec<(Range<Anchor>, String)>,
18131    snapshot: &MultiBufferSnapshot,
18132) -> bool {
18133    let mut all_insertions = true;
18134    let mut all_deletions = true;
18135
18136    for (range, new_text) in edits.iter() {
18137        let range_is_empty = range.to_offset(&snapshot).is_empty();
18138        let text_is_empty = new_text.is_empty();
18139
18140        if range_is_empty != text_is_empty {
18141            if range_is_empty {
18142                all_deletions = false;
18143            } else {
18144                all_insertions = false;
18145            }
18146        } else {
18147            return false;
18148        }
18149
18150        if !all_insertions && !all_deletions {
18151            return false;
18152        }
18153    }
18154    all_insertions || all_deletions
18155}